#!/usr/bin/env python3 """Read-only v2 conversation/dance gate; partial-emotion import/publish needs an external Pi pin.""" from pathlib import Path, PurePosixPath from decimal import Decimal from fractions import Fraction import argparse import array import hashlib import importlib.util import json import os import math import re import shutil import subprocess import sys import tempfile import urllib.request import zipfile ROOT=Path(__file__).resolve().parents[1] ASSET_ROOT='avatar/a01-expression-action-v1/' TOOLS=Path('/home/ubuntu/android-build/sdk/build-tools/34.0.0') CERT='b9608336bc1ed1de3269bb4594f9fe718daaa5439511c5187aa385d2b799dcf1' LEGACY_PIN='0a3c4918ba746019cf1df885bec66e5858a8950997dac4f64e7d37094be64dad' ROLLBACK=ROOT/'artifacts/lan-voice-v070-stage-candidate-code16-arm64-debug.apk' RUNTIME_FIX_PIN='987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887' CODE18=ROOT/'artifacts/lan-voice-v070-action-emotion-code18-arm64-debug.apk' CODE18_SHA='ea6ca77c2e4cc995c3ca2c097e71beef092cfcba1f452b18f255bd341e5f8723' ROLLBACK_SHA='687c350ec64d693dd8a0bc6e8f1e249816842631119f17a4cbdd38b0cb1e7336' spec=importlib.util.spec_from_file_location('runtime_gate',ROOT/'scripts/check-avatar-runtime.py') runtime_gate=importlib.util.module_from_spec(spec);spec.loader.exec_module(runtime_gate) require=runtime_gate.require sha=lambda b:hashlib.sha256(b).hexdigest() def file_sha(path): with Path(path).open('rb') as f: return hashlib.file_digest(f,'sha256').hexdigest() def relative(name): require(isinstance(name,str) and re.fullmatch(r'[A-Za-z0-9_./-]+',name),'asset path shape') p=PurePosixPath(name) require(not p.is_absolute() and str(p)==name and all(x not in ('.','..','') for x in name.split('/')),'asset path escape') return name def locate(root,name): p=(root/relative(name)).resolve(strict=True) require(p.is_relative_to(root.resolve()) and p.is_file(),'asset path escape/missing') return p def unique(pairs): result={} for k,v in pairs: require(k not in result,'duplicate manifest key');result[k]=v return result def read_json(path): require(path.stat().st_size<=2_000_000,'manifest byte bound') return json.loads(path.read_bytes(),object_pairs_hook=unique) def probe_clip(path): result=subprocess.run(['/home/ubuntu/miniconda3/envs/gori-speech/bin/ffprobe','-v','error','-show_streams','-show_frames','-of','json',str(path)],capture_output=True,check=True,timeout=60) data=json.loads(result.stdout) require(len(data['streams'])==1,'conversation/bridge must be silent video') v=data['streams'][0] require(v['codec_type']=='video' and v['codec_name']=='h264' and (v['width'],v['height'])==(480,848),'clip codec/shape') us=lambda value:int((Decimal(value)*1_000_000).to_integral_value()) measured={'ptsUs':[us(f['best_effort_timestamp_time']) for f in data['frames']], 'durationUs':us(v['duration']),'fps':Fraction(v['r_frame_rate'])} subprocess.run(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-xerror','-i',str(path),'-map','0:v:0','-f','null','-'],capture_output=True,check=True,timeout=60) return measured def probe_music_clip(path): """Bounded offline decode, including presented AAC samples. No listening claim.""" result=subprocess.run(['/home/ubuntu/miniconda3/envs/gori-speech/bin/ffprobe','-v','error', '-show_streams','-show_frames','-of','json',str(path)],capture_output=True,check=True,timeout=60) data=json.loads(result.stdout);streams=data['streams'] require(len(streams)==2 and sorted(s['codec_type'] for s in streams)==['audio','video'], 'dance requires exactly video+audio, no attached cover') v=next(s for s in streams if s['codec_type']=='video');a=next(s for s in streams if s['codec_type']=='audio') require(v['codec_name']=='h264' and (v['width'],v['height'])==(480,848) and not v.get('disposition',{}).get('attached_pic',0),'dance video codec/shape/cover') require(a['codec_name']=='aac' and a['channels'] in (1,2) and 8000<=int(a['sample_rate'])<=96000,'dance AAC format') us=lambda value:int((Decimal(value)*1_000_000).to_integral_value()) duration=us(v['duration']);require(1_000_000<=duration<=90_000_000,'dance duration bound') frames=[f for f in data['frames'] if f['media_type']=='video'] require(1<=len(frames)<=5400,'dance decoded frame bound') audio=[f for f in data['frames'] if f['media_type']=='audio'] require(audio and us(a.get('start_time','0'))>=0,'dance decoded audio missing/start') decoded_end=max(us(f['best_effort_timestamp_time'])+int(round(int(f['nb_samples'])*1_000_000/int(a['sample_rate']))) for f in audio) # AAC final frames can include encoder padding beyond the MP4 presentation end. audio_end=us(a.get('start_time','0'))+us(a['duration']) require(1<=audio_end<=duration and decoded_end+2>=audio_end,'dance presented audio end') subprocess.run(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-xerror','-i',str(path), '-map','0:v:0','-f','null','-'],capture_output=True,check=True,timeout=60) pcm=subprocess.run(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-xerror','-i',str(path), '-map','0:a:0','-af','atrim=end='+str(Decimal(audio_end)/1_000_000),'-ac','2','-ar','48000', '-f','f32le','-'],capture_output=True,check=True,timeout=60).stdout require(00.00001 and peak<=1.001,'dance silent/out-of-range audio') return {'ptsUs':[us(f['best_effort_timestamp_time']) for f in frames], 'durationUs':duration,'fps':Fraction(v['r_frame_rate']),'audioEndUs':audio_end, 'decodedAudioEndUs':decoded_end,'pcmFrames':len(samples)//2,'audioRms':rms,'audioPeak':peak, 'nearFullScaleSamples':sum(abs(x)>=0.999 for x in samples),'humanListening':'not_run'} def check_bundle(manifest,expected,output): manifest=manifest.resolve(strict=True);root=manifest.parent require(re.fullmatch('[0-9a-f]{64}',expected) and file_sha(manifest)==expected,'candidate index drift') index=read_json(manifest) require(index['schemaVersion']==2 and index['identityId']=='a01' and index['packId']=='a01-expression-action-v1','index identity/schema') actions=index['actions'] require(isinstance(actions,list) and (not actions or len(actions)==2 and {a['id'] for a in actions}=={'asset_01','asset_02'}),'actions require exactly asset_01/asset_02 or []') rows=index['conversationPackages'];require(1<=len(rows)<=12,'package count') files={};measurements={};runtimes=[] def add(name,digest,bound): p=locate(root,name) require(re.fullmatch('[0-9a-f]{64}',digest) and p.stat().st_size<=bound and file_sha(p)==digest,'file hash/byte bound: '+name) row={'sha256':digest,'bytes':p.stat().st_size} require(name not in files or files[name]==row,'conflicting file reference') files[name]=row require(sum(f['bytes'] for f in files.values())<=512_000_000,'bundle byte bound') return p references=[(row['id'],row['runtimeManifest']) for row in rows] references += [('bridge:'+edge['id'],edge['mouthRuntimeManifest']) for edge in index['edges'] if 'mouthRuntimeManifest' in edge] for runtime_id,ref in references: path=add(ref['path'],ref['sha256'],2_000_000) evidence,verified=runtime_gate.check_runtime(path,ref['sha256'],kotlin=False) m=read_json(path);prefix=PurePosixPath(ref['path']).parent for name,digest in verified.items(): add(str(prefix/name),digest,64_000_000 if name.endswith('.mp4') else 256_000) body=m['body'];measurements[str(prefix/body['path'])]={'ptsUs':body['ptsUs'] if m['schemaVersion']==2 else [i*1_000_000//24 for i in range(body['frameCount'])], 'durationUs':body['durationUs'],'fps':Fraction(body['fpsNumerator'],body['fpsDenominator'])} runtimes.append({'package_id':runtime_id,**evidence}) rgba=sum(r['rgba_cache_bytes'] for r in runtimes);require(rgba<=32_000_000,'combined runtime cache bound') require(len(index['edges'])<=100,'edge count bound') for edge in index['edges']: clip=edge['clip'];name=relative(clip['path']);path=add(name,clip['sha256'],64_000_000) require(clip['hasAudio'] is False,'conversation edge cannot have audio') measured=measurements.get(name) if measured is None: measured=measurements[name]=probe_clip(path) require(len(measured['ptsUs'])==clip['frameCount'] and len(clip['ptsUs'])==clip['frameCount'],'decoded clip N mismatch: '+name) require(all(abs(a-b)<=2 for a,b in zip(measured['ptsUs'],clip['ptsUs'])),'decoded clip PTS mismatch: '+name) require(abs(measured['durationUs']-clip['durationUs'])<=2 and measured['fps']==Fraction(clip['fpsNumerator'],clip['fpsDenominator']),'decoded clip timing mismatch: '+name) action_measurements=[] for action in actions: clip=action['clip'];name=relative(clip['path']);path=add(name,clip['sha256'],128_000_000) require(clip['hasAudio'] is True,'dance requires actual audio') measured=probe_music_clip(path) require(len(measured['ptsUs'])==clip['frameCount'] and len(clip['ptsUs'])==clip['frameCount'], 'dance decoded N mismatch: '+name) require(all(abs(a-b)<=2 for a,b in zip(measured['ptsUs'],clip['ptsUs'])),'dance decoded PTS mismatch: '+name) require(abs(measured['durationUs']-clip['durationUs'])<=2 and measured['fps']==Fraction(clip['fpsNumerator'],clip['fpsDenominator']),'dance decoded timing mismatch: '+name) require(abs(measured['audioEndUs']-action['audioEndUs'])<=2,'dance audioEndUs mismatch: '+name) action_measurements.append({'id':action['id'],**{k:v for k,v in measured.items() if k!='fps'}}) # Preview inventory is checked too, but only runtime-referenced files enter APK. declared=index['files'] if isinstance(declared,dict): declared=[dict(v,path=k) for k,v in declared.items()] require(isinstance(declared,list) and len(declared)<=20000,'file inventory shape/bound') table={} for row in declared: name=relative(row['path']);require(name not in table,'duplicate inventory path') p=locate(root,name) require(p.stat().st_size==row['bytes'] and p.stat().st_size<=128_000_000 and file_sha(p)==row['sha256'],'declared file mismatch: '+name) table[name]={'sha256':row['sha256'],'bytes':row['bytes']} require(all(table.get(name)==row for name,row in files.items()),'inventory missing/mismatching referenced file') log=output/'production-index-tests.txt' with log.open('x') as f: result=subprocess.run([sys.executable,str(ROOT/'scripts/check-reply-regressions.py'),'--suite','avatar','--index-manifest',str(manifest)],stdout=f,stderr=subprocess.STDOUT,timeout=180) require(result.returncode==0 and 'PASS: actual exported v2 index parsed' in log.read_text(),'production index admission failed; see '+str(log)) files['manifest.json']={'sha256':expected,'bytes':manifest.stat().st_size} for name,row in files.items(): require(file_sha(locate(root,name))==row['sha256'],'bundle changed during gate') report={'status':'passed','scope':'read_only_machine_gate_no_approval_no_activation','manifest_sha256':expected, 'runtime_packages':runtimes,'combined_rgba_bytes':rgba,'referenced_files':len(files),'preview_files_not_packaged':len(table.keys()-files.keys()), 'edge_count':len(index['edges']),'action_count':len(actions),'dance_available':False, 'candidate_dance_validated':bool(actions),'action_measurements':action_measurements,'production_kotlin_index':'passed', 'naturalness':'not_certified','real_device':'not_run','files':files} (output/'bundle-gate.json').write_text(json.dumps(report,indent=2)+'\n') return report def import_files(root,files,target): require(not target.is_symlink(),'import target symlink') # Preflight every destination before writing; preserve unknown existing bytes. for name,row in files.items(): dest=target/relative(name) require(not dest.exists() or (not dest.is_symlink() and dest.is_file() and file_sha(dest)==row['sha256']),'unknown destination preserved: '+name) require(dest.resolve().is_relative_to(target.resolve()),'import destination escape') require(file_sha(locate(root,name))==row['sha256'],'source drift before import') for name,row in files.items(): dest=target/name;dest.parent.mkdir(parents=True,exist_ok=True) if dest.exists(): continue fd,tmp=tempfile.mkstemp(prefix='.emotion-import-',dir=dest.parent) try: with os.fdopen(fd,'wb') as out,locate(root,name).open('rb') as source: shutil.copyfileobj(source,out) require(file_sha(tmp)==row['sha256'],'source drift during import') os.link(tmp,dest) # Exclusive creation, never replacement. finally: os.unlink(tmp) def replace_known_import(root,files,target,previous_report,previous_pin,backup): """Replace only a completely verified code-owned previous import; retain rollback.""" require(re.fullmatch('[0-9a-f]{64}',previous_pin or ''),'previous exact pin required') require(not target.is_symlink() and target.is_dir(),'previous target directory') old=read_json(previous_report) require(old['status']=='passed' and old['manifest_sha256']==previous_pin,'previous report pin mismatch') previous_manifest=target/'manifest.json' require(file_sha(previous_manifest)==previous_pin,'previous import index drift') inventory=read_json(previous_manifest)['files'] if isinstance(inventory,dict): inventory=[dict(row,path=name) for name,row in inventory.items()] known={relative(row['path']):{'sha256':row['sha256'],'bytes':row['bytes']} for row in inventory} known['manifest.json']={'sha256':previous_pin,'bytes':previous_manifest.stat().st_size} previous=old['files'] require(all(known.get(relative(name))==row for name,row in previous.items()),'previous report not bound to pinned inventory') require(not any(p.is_symlink() for p in target.rglob('*')),'previous import symlink preserved') actual={str(p.relative_to(target)) for p in target.rglob('*') if p.is_file()} require(actual==set(previous),'unknown import files preserved') def verify_previous(): for name,row in previous.items(): p=locate(target,name) require(p.stat().st_size==row['bytes'] and file_sha(p)==row['sha256'],'previous import bytes drift: '+name) verify_previous() require(not backup.exists() and not backup.is_symlink() and not backup.resolve().is_relative_to(target.resolve()),'new external backup required') require(not backup.resolve().is_relative_to(root.resolve()),'backup must not modify asset owner directory') target.parent.mkdir(parents=True,exist_ok=True) staging=Path(tempfile.mkdtemp(prefix='.emotion-stage-',dir=target.parent)) try: import_files(root,files,staging) verify_previous() backup.parent.mkdir(parents=True,exist_ok=True) os.rename(target,backup) try: os.rename(staging,target) except BaseException: os.rename(backup,target);raise finally: if staging.exists(): shutil.rmtree(staging) def badging(path): return subprocess.check_output([str(TOOLS/'aapt'),'dump','badging',str(path)],text=True,stderr=subprocess.STDOUT) def next_version(paths): codes=[int(re.search(r"versionCode='(\d+)'",badging(p))[1]) for p in paths] return max([16,*codes])+1 def reviewed_actions(index,pin,registry): """External pin is necessary but never replaces production media validation.""" require(registry is not None,'dance import/publication requires separately reviewed gateway capability admission; read-only gate supported') table=read_json(registry) expected={row['id']:(row['clip']['durationUs']+999)//1000 for row in index['actions']} require(set(expected)=={'asset_01','asset_02'} and all(row['kind']=='dance' and row['mouthAllowed'] is False for row in index['actions']),'reviewed dance shape') require(table.get(pin)==expected,'reviewed action pin/duration mismatch') return expected def tested_source(full=False): client=json.loads((ROOT/'logs/avatar-safe-061/client-tests.json').read_text()) require(client['status']=='passed' and client['jvm_entry_points']==9,'client regression evidence') for name,digest in client['hashes'].items(): require(file_sha(ROOT/name)==digest,'untested source: '+name) if full: evidence=read_json(ROOT/'logs/action-emotion/full-release/checks.json') require(evidence['gateway_passed']>=97 and evidence['gateway_skipped']==1 and evidence['offline_gles_goldens']==200 and evidence['packaging_passed']>=27,'full release regression evidence') for name,digest in evidence['hashes'].items(): require(file_sha(ROOT/name)==digest,'full release evidence drift: '+name) return evidence=json.loads((ROOT/'logs/action-emotion/bridge-talk/delivery.json').read_text()) require(evidence['gateway_passed']==97 and evidence['gateway_skipped']==1 and evidence['offline_gles_goldens']==40,'gateway/GLES evidence') for name,digest in evidence['source_hashes'].items(): if name.startswith('app/src/'): require(file_sha(ROOT/name)==digest,'media evidence drift: '+name) def packaging_tests_current(): evidence=json.loads((ROOT/'logs/action-emotion/partial-pack/packaging-tests.json').read_text()) require(evidence['status']=='passed','packaging regression evidence') for name,digest in evidence['hashes'].items(): require(file_sha(ROOT/name)==digest,'untested packaging source: '+name) def verify_runtime_fix_assets(built,pin,startup_fix=False): require(pin==RUNTIME_FIX_PIN,'runtime fix must preserve reviewed pin') require(file_sha(CODE18)==CODE18_SHA,'code18 rollback drift') with zipfile.ZipFile(CODE18) as old,zipfile.ZipFile(built) as new: paths=lambda z:{n for n in z.namelist() if n.startswith('assets/avatar/') and not n.endswith('/')} extra={'assets/avatar/startup-white-01/manifest.json','assets/avatar/startup-white-01/poster.png'} if startup_fix else set() require(paths(new)==paths(old)|extra,'runtime fix avatar inventory changed') if startup_fix: basic=read_json(ROOT/'manifests/startup-white-01.json') require(sha(new.read('assets/avatar/startup-white-01/manifest.json'))=='461f5cfc10036de5f10ca3ce765fb8d9998697d3fd035aa9b1862d2ccfc3eaa2','bootstrap exact manifest') require(sha(new.read('assets/avatar/startup-white-01/poster.png'))==basic['posterSha256'],'bootstrap poster SHA') for name in paths(old): require(new.read(name)==old.read(name),'runtime fix asset changed: '+name) require(sha(new.read('assets/'+ASSET_ROOT+'manifest.json'))==pin,'runtime fix packaged pin') return len([p for p in paths(new) if p.startswith('assets/'+ASSET_ROOT)]) def publish(report,output,requested,full=False,runtime_fix=False,playback_diagnostic=False,playback_clock_fix=False,startup_fix=False,presence_candidate=False): require(all(edge.get('nativeLoop') is True or 'mouthRuntimeManifest' in edge for edge in read_json(ROOT/'app/src/main/assets'/ASSET_ROOT/'manifest.json')['edges']), 'live emotion release needs bridge-own TALK runtimes') tested_source(full);packaging_tests_current();require(file_sha(ROLLBACK)==ROLLBACK_SHA,'rollback drift') version=next_version((ROOT/'artifacts').glob('*.apk')) if requested is not None: require(requested>=version,'version code occupied');version=requested require(not full or version>=18,'full candidate needs code >=18') require(not presence_candidate or startup_fix and version>=23,'presence candidate needs startup and fresh code >=23') require(not startup_fix or full and version>=22 and report['manifest_sha256']==RUNTIME_FIX_PIN,'startup fix release shape') if startup_fix: subprocess.run(['python3',str(ROOT/'scripts/prepare-startup-assets.py'),'--verify-only'],check=True) require(not playback_clock_fix or full and version>=21 and report['manifest_sha256']==RUNTIME_FIX_PIN,'playback clock fix release shape') require(not playback_diagnostic or full and version>=20 and report['manifest_sha256']==RUNTIME_FIX_PIN,'playback diagnostic release shape') require(not runtime_fix or full and version>=19 and report['manifest_sha256']==RUNTIME_FIX_PIN,'runtime fix release shape') subprocess.run([str(ROOT/'scripts/build.sh'),'assembleDebug','compileDebugAndroidTestKotlin','-PavatarActionCandidate=true', '-PavatarNatural=true','-PavatarMouthCandidate=true','-PnaturalManifestSha='+LEGACY_PIN, '-PemotionManifestSha='+report['manifest_sha256'],'-PactionVersionCode='+str(version),'-PavatarFullActionCandidate='+str(full).lower(),'-PavatarRuntimeFix='+str(runtime_fix).lower(),'-PavatarPlaybackDiagnostic='+str(playback_diagnostic).lower(),'-PavatarPlaybackClockFix='+str(playback_clock_fix or startup_fix).lower(),'-PavatarStartupFix='+str(startup_fix).lower(),'-PpresenceCandidate='+str(presence_candidate).lower()],check=True,cwd=ROOT) built=ROOT/'app/build/outputs/apk/debug/app-debug.apk';badge=badging(built) version_name='0.7.5' if presence_candidate else '0.7.4' if startup_fix else '0.7.3' if playback_clock_fix else '0.7.2' if playback_diagnostic else '0.7.1' if runtime_fix else ('0.7.0' if full else '0.7.0-emotion-dev') for text in ("name='com.gorios.lanvoice'",f"versionCode='{version}'",f"versionName='{version_name}'","sdkVersion:'26'","targetSdkVersion:'34'"): require(text in badge,'APK metadata: '+text) require(re.search(r'^native-code: (.+)$',badge,re.M)[1].strip()=="'arm64-v8a'",'APK ABI') cert=subprocess.check_output([str(TOOLS/'apksigner'),'verify','--verbose','--print-certs',str(built)],text=True) require(re.search(r'Signer #1 certificate SHA-256 digest: (\w+)',cert)[1]==CERT,'APK certificate') with zipfile.ZipFile(ROLLBACK) as old,zipfile.ZipFile(built) as new: paths=lambda z:{n for n in z.namelist() if n.startswith('assets/avatar/') and not n.endswith('/')} extra={'assets/'+ASSET_ROOT+n for n in report['files']} if startup_fix: extra|={'assets/avatar/startup-white-01/manifest.json','assets/avatar/startup-white-01/poster.png'} require(paths(new)==paths(old)|extra,'APK unreferenced/missing avatar assets') for name in paths(old): require(new.read(name)==old.read(name),'rollback asset changed') for name,row in report['files'].items(): require(sha(new.read('assets/'+ASSET_ROOT+name))==row['sha256'],'APK pack hash') for name in paths(new): if name.endswith('.mp4'): require(new.getinfo(name).compress_type==zipfile.ZIP_STORED,'compressed media') config=ROOT/'app/build/generated/source/buildConfig/debug/com/gorios/lanvoice/BuildConfig.java' require('EMOTION_MANIFEST_SHA = "'+report['manifest_sha256']+'"' in config.read_text(),'compiled index pin mismatch') if startup_fix: require('AVATAR_STARTUP_FIX = true' in config.read_text(),'compiled startup flag mismatch') require(version>=next_version((ROOT/'artifacts').glob('*.apk')),'version became occupied during build') if startup_fix or runtime_fix or playback_diagnostic or playback_clock_fix: require(verify_runtime_fix_assets(built,report['manifest_sha256'],startup_fix)==len(report['files']),'runtime fix file count') stem='presence' if presence_candidate else 'startup-fix' if startup_fix else 'playback-clock-fix' if playback_clock_fix else 'playback-diagnostic' if playback_diagnostic else 'runtime-fix' if runtime_fix else ('action-emotion' if full else 'emotion-candidate') release='v075' if presence_candidate else 'v074' if startup_fix else 'v073' if playback_clock_fix else 'v072' if playback_diagnostic else 'v071' if runtime_fix else 'v070' artifact=ROOT/f'artifacts/lan-voice-{release}-{stem}-code{version}-arm64-debug.apk' with artifact.open('xb') as f,built.open('rb') as source: shutil.copyfileobj(source,f) digest=file_sha(artifact);checksum=f'{digest} {artifact.name}\n'.encode() with artifact.with_suffix('.apk.sha256').open('xb') as f: f.write(checksum) url='http://192.168.31.124:8080/'+artifact.name opener=urllib.request.build_opener(urllib.request.ProxyHandler({})) with opener.open(url,timeout=30) as response: require(response.status==200 and sha(response.read())==digest,'HTTP APK bytes mismatch') with opener.open(url+'.sha256',timeout=15) as response: require(response.status==200 and response.read()==checksum,'HTTP checksum mismatch') require(file_sha(ROLLBACK)==ROLLBACK_SHA,'rollback modified') delivery={'status':'full_action_emotion_candidate' if full else 'partial_emotion_candidate','version_name':version_name,'version_code':version,'url':url,'sha256':digest, 'certificate_sha256':CERT,'manifest_sha256':report['manifest_sha256'],'dance_available':full,'action_count':report['action_count'], 'http_bytes_verified':True,'device':'not_run','naturalness':'not_certified','paid_calls':0, 'gateway_deployed':bool(full and read_json(ROOT/'logs/action-emotion/full-release/checks.json').get('gateway_deployed',False)), 'gateway_deployed_by_packager':False,'runtime_fix':runtime_fix,'diagnostic_only':playback_diagnostic,'playback_clock_fix':playback_clock_fix or startup_fix,'startup_fix':startup_fix,'presence_candidate':presence_candidate,'runtime_files_unchanged_from_code18':len(report['files']) if startup_fix or runtime_fix or playback_diagnostic or playback_clock_fix else None} (output/'delivery.json').write_text(json.dumps(delivery,indent=2)+'\n') return delivery def main(): parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--manifest',type=Path,required=True);parser.add_argument('--sha256',required=True) parser.add_argument('--output',type=Path,required=True,help='New evidence directory outside owner storage') parser.add_argument('--pi-pin',help='External exact Pi pin, required for import/publish') mode=parser.add_mutually_exclusive_group();mode.add_argument('--import-only',action='store_true');mode.add_argument('--publish',action='store_true') parser.add_argument('--previous-import-report',type=Path,help='Verified previous bundle-gate.json; requires --previous-pin and fresh backup') parser.add_argument('--previous-pin') parser.add_argument('--backup',type=Path) parser.add_argument('--action-registry',type=Path,help='Reviewed public gateway registry required for full dance release') parser.add_argument('--version-code',type=int,help='Default max existing APK code+1, minimum17') parser.add_argument('--runtime-fix',action='store_true',help='0.7.1 Android-only repair; all avatar bytes must equal frozen code18') parser.add_argument('--playback-diagnostic',action='store_true',help='0.7.2 diagnostic-only Android build, frozen code18 avatar bytes') parser.add_argument('--playback-clock-fix',action='store_true',help='0.7.3 Android MediaPlayer-output clock fix; exact frozen avatar bytes') parser.add_argument('--startup-fix',action='store_true',help='0.7.4 immediate shell/background strict admission, exact frozen runtime plus tiny derived bootstrap') parser.add_argument('--presence-candidate',action='store_true',help='0.7.5 presence-triggered assistant turns, frozen runtime and startup assets') args=parser.parse_args(); require(sum((args.runtime_fix,args.playback_diagnostic,args.playback_clock_fix,args.startup_fix,args.presence_candidate))<=1,'choose one build purpose') manifest=args.manifest.resolve(strict=True);output=args.output.resolve() require(not output.exists() and not output.is_relative_to(manifest.parent),'new evidence outside owner root required') if args.import_only or args.publish: require(args.pi_pin==args.sha256 and re.fullmatch('[0-9a-f]{64}',args.pi_pin or ''),'external Pi pin required') if args.import_only or args.publish: if read_json(manifest)['actions']: reviewed_actions(read_json(manifest),args.pi_pin,args.action_registry) output.mkdir(parents=True) report=check_bundle(manifest,args.sha256,output) if args.import_only or args.publish: target=ROOT/'app/src/main/assets'/ASSET_ROOT if args.previous_import_report: require(args.previous_pin and args.backup,'previous replacement requires exact pin and backup') replace_known_import(manifest.parent,report['files'],target,args.previous_import_report,args.previous_pin,args.backup) else: require(not args.previous_pin and not args.backup,'previous import report required') import_files(manifest.parent,report['files'],target) (output/'import.json').write_text(json.dumps({'externally_pinned_sha256':args.pi_pin,'files':len(report['files']),'naturalness':'not_certified'})+'\n') result=publish(report,output,args.version_code,bool(report['action_count']),args.runtime_fix,args.playback_diagnostic,args.playback_clock_fix,args.startup_fix or args.presence_candidate,args.presence_candidate) if args.publish else {k:v for k,v in report.items() if k!='files'} print(json.dumps(result,indent=2)) if __name__=='__main__': try: main() except (ValueError,KeyError,TypeError,OSError,subprocess.SubprocessError) as error: print('FAIL: emotion pack: '+str(error),file=sys.stderr);raise SystemExit(1)