← back to Carnegie Identity Audit

finalize.py

74 lines

#!/usr/bin/env python3
"""Finalize evidence only after independent full and delayed checks pass."""
import datetime, hashlib, json, pathlib, subprocess
BASE=pathlib.Path(__file__).resolve().parent
RUN=BASE/'execution-20260911'
def read(p):return json.loads(p.read_text())
def save(p,d):p.write_text(json.dumps(d,indent=2)+'\n')
full=read(RUN/'independent-all.json');monitor=read(RUN/'independent-monitor.json')
assert full['verdict']==monitor['verdict']=='PASS'
assert full['products']==52 and full['metafields']==104
assert full['canonical_unchanged_verified'] and monitor['canonical_unchanged_verified']
assert full['all_unrelated_metafields_and_product_fields_unchanged']
assert full['unique_identities']==monitor['unique_identities']==5928
assert monitor['products']==3
actions=[json.loads(l) for l in (RUN/'actions.jsonl').read_text().splitlines()]
verified={e['id'] for e in actions if e['event']=='product_verified' and not e.get('reverse')}
assert len(verified)==52
assert any(e['event']=='idempotent_skip' for e in actions)
assert read(RUN/'independent-rollback-canary.json')['verdict']=='PASS'
assert read(RUN/'stale-digest-test.json')['verdict']=='PASS'
last=max(datetime.datetime.fromisoformat(e['ts']) for e in actions if e['event']=='mutation_ack')
elapsed=(datetime.datetime.fromisoformat(monitor['at'])-last).total_seconds()
assert elapsed>=60, 'Post-action monitoring interval not yet satisfied'
sources=read(RUN/'source-proof.json')
for source in sources:
    assert hashlib.sha256(pathlib.Path(source['file']).read_bytes()).hexdigest()==source['sha256']
    assert source['verdict']=='PASS' and source['checked']==source['unique']==5928
source_commit=subprocess.check_output(['git','-C',str(BASE.parent),'log','-1','--format=%H','--','carnegie-split/rollout.mjs','carnegie-split/rollout2.mjs','carnegie-split/build-siltech-grain-v2-archived.mjs'],text=True).strip()
now=datetime.datetime.now(datetime.timezone.utc).isoformat()
proof=dict(ticket='TK-11246',intent='Restore exact Carnegie category-bearing identities and stop creation-path stripping',risk_tier='R4',
    verdict='PASS',at=now,authorization=['Steve: ungate and run','TK11478 relay: current scope approved; email sends excluded'],
    environment=dict(shop='designer-laboratory-sandbox.myshopify.com',api='2026-07',local_database='dw_unified',canonical_database='Kamatera dw_unified (read only)'),
    source_commit=source_commit,counts=dict(source_files=3,local_rows=26,active_products=26,archived_products=26,metafields=104,canonical_writes=0,email_sends=0),
    baseline=['execution-20260911/preflight.json','execution-20260911/products-baseline.json','verification/repair-plan.json'],
    commands=['execute.py preflight','execute.py rehearse','execute.py database','execute.py canary','verify_live.py canary','execute.py stale-digest-test','execute.py rollback-canary','verify_live.py rollback-canary','execute.py canary','verify_live.py canary','execute.py canary (idempotent skip)','execute.py remaining','verify_live.py all','verify_live.py monitor'],
    assertions=[dict(check='Three actual creation helpers preserve all5928 unique identities; full modules parse',verdict='PASS'),
        dict(check='26 exact local rows restored; all other target columns and non-target identity digest unchanged',verdict='PASS'),
        dict(check='Independent REST:104 exact metafields across52 exact products; current prices and unrelated product fields/metafields unchanged',verdict='PASS'),
        dict(check='Old grouped product excluded and unchanged; canonical26 already correct and unchanged',verdict='PASS'),
        dict(check='Database transactional rollback/reversal rehearsal',verdict='PASS'),
        dict(check='Real Shopify canary rollback, independent check, reapply, independent check',verdict='PASS'),
        dict(check='Differing-value stale digest rejected atomically STALE_OBJECT, canary unchanged',verdict='PASS'),
        dict(check='Duplicate canary invocation safely skips completed write',verdict='PASS'),
        dict(check=f'Delayed independent monitoring3 representative products plus full local and canonical checks after{elapsed:.0f}s',verdict='PASS')],
    observations=['Separate pricing repair changed26 active prices75.00->135.75 during preflight; guard stopped before writing. Baseline refreshed only after proving price-only drift. TK11246 never writes price.',
        'Shopify treats same-value requests as idempotent no-ops even with stale digest; differing-value negative test correctly rejected.',
        'Original Aug18 standalone write log not recovered; approved repairs use fresh exact identity/metafield/canonical mapping instead. No claim of recovered historical log.',
        'Source edits landed in concurrent shared repository commit; scoped diff versus HEAD is clean. No Git lock was removed or moved.'],
    cleanup='No test products or emails created. Canary restored to desired final state. Durable prestate, compare-and-set journal and conditional DB rollback retained.',
    scope_limit='No claim that every existing Carnegie product outside the exact52 has been inventoried or repaired.')
prior=BASE/'verification/e2e-proof.json'
if not (BASE/'verification/preparation-e2e-proof.json').exists():
    (BASE/'verification/preparation-e2e-proof.json').write_text(prior.read_text())
save(prior,proof);save(RUN/'completion.json',proof)
report=f'''# TK-11246 complete

Verified {now}.

- Three creation scripts preserve full manufacturer category identities.
- Restored26 local staging rows and104 metafields across26 active +26 archived products.
- Independent REST/SQL verifies all52 products,5928 unique identities, unchanged
  current prices, unrelated fields, grouped exclusion and canonical records.
- Real canary rollback/reapply, transactional DB reversal, stale-write rejection
  and idempotent retry checks passed. Delayed monitoring passed after{elapsed:.0f}s.
- Source commit: `{source_commit}`. Execution code/canary proof: `54fc24b`.

All execution records and exact rollback prestate are in `execution-20260911/`.
Canonical writes:0. Emails:0. Broader Carnegie inventory remains outside this repair.
'''
(BASE/'verification/final-report.md').write_text(report)
memo=BASE/'approval-request.md'
memo.write_text('Status: EXECUTED AND INDEPENDENTLY VERIFIED — '+now+'\n\n'+report+'\n\n---\nOriginal approved scope (historical):\n\n'+memo.read_text())
print(json.dumps(dict(verdict='PASS',source_commit=source_commit,products=52,metafields=104,monitoring_seconds=elapsed),indent=2))