#!/usr/bin/env python3 """Copy an exact task index and repair only two idle runtime state clocks, never body/media.""" import argparse import copy import importlib.util import json from pathlib import Path import shutil ROOT=Path(__file__).resolve().parents[1] spec=importlib.util.spec_from_file_location('pack',ROOT/'scripts/package-avatar-emotion.py') pack=importlib.util.module_from_spec(spec);spec.loader.exec_module(pack) IDS={'idle-breathe-01','idle-microshift-01'} def repair_states(runtime): repaired=copy.deepcopy(runtime);changes=[] states=repaired['mouthStates'] pack.require(runtime['schemaVersion']==2 and len(states)==5 and {s['id'] for s in states}=={'idle','opening','talk1','talk2','end-talk'},'known schema2 state contract required') for i,state in enumerate(states): n=len(state['globalAlphaByFrame']);bridge=state['id'] in ('opening','end-talk') pack.require(n==(6 if bridge else 12) and state['fpsNumerator']==24 and state['fpsDenominator']==1 and state['durationMs']==(250 if bridge else 500),'repair only authored 24fps six/twelve-frame curves') pts=[(frame*1_000_000+12)//24 for frame in range(n)] pack.require(n*1_000_000==state['durationMs']*1000*24,'state duration/curve mismatch') for field,value in (('frameCount',n),('ptsUs',pts)): if state[field]!=value: changes.append({'field':f'mouthStates[{i}].{field}','before':state[field],'after':value}) state[field]=value if 'durationUs' in state: pack.require(state['durationUs']==state['durationMs']*1000,'unexpected authored durationUs; no speculative repair') # Body, patches, alpha, routing, anchors and review flags are byte-for-byte JSON values unchanged. for key in runtime.keys()-{'mouthStates'}:pack.require(repaired[key]==runtime[key],'non-state metadata changed') for before,after in zip(runtime['mouthStates'],states): pack.require({k:v for k,v in before.items() if k not in ('frameCount','ptsUs')}== {k:v for k,v in after.items() if k not in ('frameCount','ptsUs')},'authored state content changed') return repaired,changes def write_json(path,value): with path.open('x') as f:json.dump(value,f,ensure_ascii=False,indent=2);f.write('\n') def repair(source,expected,output): source=Path(source).resolve(strict=True);output=Path(output).resolve();root=source.parent pack.require(not output.exists() and not output.is_relative_to(root) and not root.is_relative_to(output),'independent new output required') pack.require(pack.file_sha(source)==expected,'source index drift') original=pack.read_json(source);index=copy.deepcopy(original);files=original['files'] pack.require(original['schemaVersion']==2 and original['packId']=='a01-expression-action-v1' and isinstance(files,list) and len(files)<=20000,'task index/list inventory required') pack.require(len({r['path'] for r in files})==len(files) and all(r['path']!='manifest.json' for r in files),'duplicate/root inventory entry') rows=[r for r in index['conversationPackages'] if r['id'] in IDS] pack.require({r['id'] for r in rows}==IDS and len(rows)==2,'exact two idle rows required') prepared=[] for row in rows: ref=row['runtimeManifest'];path=pack.locate(root,ref['path']) pack.require(pack.file_sha(path)==ref['sha256'],'runtime reference drift') runtime=pack.read_json(path);repaired,changes=repair_states(runtime) pack.require(changes,'source already repaired; no redundant recovery') prepared.append((row,runtime,repaired,changes)) # All source inventory hashes/bytes pass before any output is created. for row in files: path=pack.locate(root,row['path']) pack.require(path.stat().st_size==row['bytes'] and pack.file_sha(path)==row['sha256'],'source indexed drift: '+row['path']) output.mkdir(parents=True) for row in files: dest=output/row['path'];dest.parent.mkdir(parents=True,exist_ok=True) shutil.copyfile(pack.locate(root,row['path']),dest) backup=output/'docs/code-recovery-original-metadata';backup.mkdir(parents=True) shutil.copyfile(source,backup/'candidate03-index.json') repaired_rows=[];changed_paths=set() for row,runtime,repaired,changes in prepared: ref=row['runtimeManifest'];dest=output/ref['path'] shutil.copyfile(pack.locate(root,ref['path']),backup/(row['id']+'-runtime.json')) # These are our independent copied metadata files, never owner files/hardlinks. with dest.open('w') as f:json.dump(repaired,f,ensure_ascii=False,indent=2);f.write('\n') before=ref['sha256'];ref['sha256']=pack.file_sha(dest);changed_paths.add(ref['path']) repaired_rows.append({'id':row['id'],'file':ref['path'],'before_sha256':before,'after_sha256':ref['sha256'], 'body_sha256':runtime['body']['sha256'],'body_frame_count':runtime['body']['frameCount'],'changes':changes}) unchanged=0 for row in files: current=pack.file_sha(output/row['path']) if row['path'] not in changed_paths: pack.require(current==row['sha256'],'copied payload changed: '+row['path']);unchanged+=1 pack.require(pack.file_sha(pack.locate(root,row['path']))==row['sha256'],'owner source drift during copy') pack.require(pack.file_sha(source)==expected,'source index changed during recovery') provenance={'source_index_sha256':expected,'repair_script_sha256':pack.file_sha(Path(__file__)), 'scope':'only two runtime state frameCount/ptsUs and index references/inventory', 'repaired_runtimes':repaired_rows,'original_indexed_files':len(files),'original_files_unchanged':unchanged, 'original_files_changed':sorted(changed_paths),'media_patch_pixels_unchanged':True, 'state_clock_independent_of_body_clock':True,'additional_ai_calls':0,'known_fee_usd':0, 'production_parser':'not_run_by_repair','Pi_pin':'pending_new_exact_index_review','naturalness':'not_certified','device':'not_run'} write_json(output/'docs/code-recovery-repair-report.json',provenance) index['files']=[{'path':str(p.relative_to(output)),'sha256':pack.file_sha(p),'bytes':p.stat().st_size} for p in sorted(output.rglob('*')) if p.is_file()] write_json(output/'manifest.json',index) return {'manifest':str(output/'manifest.json'),'manifest_sha256':pack.file_sha(output/'manifest.json'), 'indexed_files':len(index['files']),**provenance} def main(): parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--source-manifest',type=Path,required=True);parser.add_argument('--source-sha',required=True) parser.add_argument('--output',type=Path,required=True);args=parser.parse_args() result=repair(args.source_manifest,args.source_sha,args.output) print(json.dumps({k:result[k] for k in ('manifest','manifest_sha256','indexed_files','original_files_unchanged','original_files_changed')},indent=2)) if __name__=='__main__':main()