"""Archive local A3 implementation evidence; no external-storage acceptance.""" from pathlib import Path import ast import datetime import hashlib import json import shutil import subprocess import sys import tempfile ROOT=Path.cwd() out=Path(tempfile.mkdtemp(prefix='K2515-archive-local-preparation-',dir='reports/os-implementation')) source=out/'source';source.mkdir() def art(p):return dict(path=str(p),sha256=hashlib.sha256(Path(p).read_bytes()).hexdigest()) files=[];commands=[];mutants=[] def run(name,args,cwd=ROOT,expected=0): r=subprocess.run(list(map(str,args)),cwd=cwd,capture_output=True,text=True,timeout=90) p=out/(name+'.log');p.write_text(r.stdout+r.stderr);a=art(p);files.append(a) commands.append(dict(name=name,argv=list(map(str,args)),exitCode=r.returncode,log=a)) if r.returncode!=expected:raise RuntimeError(name+' unexpected exit; see '+str(p)) return r.stdout+r.stderr report=dict(status='A3_ARCHIVE_LOCAL_PREPARATION_RUNNING',guestAccepted=False,productAccepted=False,externalStorageVerified=False, acceptedMoves=[],pendingMoves=['K2511','K2512','K2513','K2514','K2515'],commands=commands,mutants=mutants,files=files) try: names=['archive.py','test_archive.py','ARCHIVE_CONTRACT.md','README.md','prepare.py'] for name in names: p=source/name;shutil.copyfile(ROOT/'tools/evidence_archive'/name,p);files.append(art(p)) if name.endswith('.py'):ast.parse(p.read_text()) report['sources']=[art(source/name)for name in names] result=run('host-tests',[sys.executable,'-m','unittest','-v','test_archive'],cwd=source.resolve()) assert 'Ran 26 tests'in result and result.rstrip().endswith('OK');report['hostTests']=26 original=(source/'archive.py').read_text() changes=[ ('accept-wrong-selection-hash',"if row['sha256']!=item['sha256']:","if False:",'test_wrong_manifest_hash_and_traversal_rejected',1), ('skip-expected-file-comparison',"if expected is not None and any(row[k]!=expected[k]for k in ['sha256','bytes','mode']):","if False:",'test_existing_restore_content_is_not_overwritten',1), ('allow-local-as-external',"if require_external and not separate:","if False:",'test_same_filesystem_cannot_claim_external_acceptance',2), ('ignore-completion-hash',"if completion_sha256 is not None:","if False:",'test_wrong_completion_digest_and_changed_metadata_are_refused',1), ('allow-archive-inside-source',"if target.path==source.path or source.path in target.path.parents:","if False:",'test_archive_cannot_be_inside_source_tree',1), ('follow-symlinks','os.O_NOFOLLOW','0','test_symlink_source_and_intermediate_directory_are_refused',4), ('omit-writer-lock','try:fcntl.flock(fd,fcntl.LOCK_EX|fcntl.LOCK_NB)','try:pass','test_archive_writer_lock_refuses_second_writer',1), ('skip-final-source-readback',"inspect(source,row['path'],row);inspect(target,","inspect(target,",'test_source_change_before_seal_prevents_completion',1), ] for name,before,after,test,count in changes: assert original.count(before)==count,(name,original.count(before),count) directory=out/'mutants'/name;directory.mkdir(parents=True);code=original.replace(before,after);ast.parse(code) (directory/'archive.py').write_text(code);shutil.copyfile(source/'test_archive.py',directory/'test_archive.py') log=run(name,[sys.executable,'-m','unittest','-v','test_archive.ArchiveTests.'+test],cwd=directory.resolve(),expected=1) assert 'FAIL:'in log and 'AssertionError:'in log and 'ERROR:'not in log,'mutant must fail an assertion, not a loader or syntax error' mutant=dict(name=name,rejected=True,test=test,source=art(directory/'archive.py'),log=commands[-1]['log']);mutants.append(mutant);files.append(mutant['source']) report['sourceMutantsRejected']=len(mutants) # Read only two explicitly named, completed reports. No recursive inventory # and no active checkpoint, image, serial log or coordinator input is copied. paths=['reports/os-implementation/K2100-duration-long-review-sM0wbm/report.json','reports/os-implementation/K2100-duration-window-proof-uqFFpe/report.json'] selection=dict(schema='turkos-archive-selection/v1',storageClass='sealed-evidence',files=[art(p)for p in paths]) p=out/'real-completed-report-selection.json';p.write_text(json.dumps(selection,indent=2)+'\n');files.append(art(p)) text=run('real-source-plan',[sys.executable,str(source/'archive.py'),'plan','--root',str(ROOT),'--selection',str(p)]) plan=json.loads(text);assert plan['status']=='ARCHIVE_PLAN_VERIFIED'and plan['externalStorageVerified']is False p=out/'real-source-plan.json';p.write_text(json.dumps(plan,indent=2)+'\n');files.append(art(p));report['realSourcePlan']=art(p) report.update(status='A3_ARCHIVE_LOCAL_PREPARATION_PASSED',updatedAt=datetime.datetime.now(datetime.timezone.utc).isoformat(), scope='Bounded resumable copy/restore implementation, 26 generated-file host tests and eight rejected source mutants. Read-only plan over two explicitly selected completed real reports passed. No real external destination supplied; no A3 moves admitted and no source reclamation authorized.', realExternalDestinationRequired=True,sourceDeletionImplemented=False) except BaseException: import traceback report.update(status='A3_ARCHIVE_LOCAL_PREPARATION_FAILED',error=traceback.format_exc());raise finally: (out/'report.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n');print(json.dumps(dict(status=report['status'],report=str(out/'report.json'))))