From fcc55b8370d212570fa1d2884bed789f5238eb4f Mon Sep 17 00:00:00 2001 From: zenord Date: Tue, 13 Oct 2026 03:22:55 +0800 Subject: [PATCH] Prepare pinned partial emotion bundle gate and safe candidate packaging --- docs/ACTION_EMOTION_STAGE_070.md | 56 +++++- scripts/check-avatar-runtime.py | 44 +++-- scripts/check-reply-regressions.py | 46 ++++- scripts/package-avatar-emotion.py | 240 ++++++++++++++++++++++++ tests/packaging/test_emotion_package.py | 139 ++++++++++++++ tests/protocol/ProtocolCheck.kt | 9 + 6 files changed, 504 insertions(+), 30 deletions(-) create mode 100644 scripts/package-avatar-emotion.py create mode 100644 tests/packaging/test_emotion_package.py diff --git a/docs/ACTION_EMOTION_STAGE_070.md b/docs/ACTION_EMOTION_STAGE_070.md index eed8c5a..340b42e 100644 --- a/docs/ACTION_EMOTION_STAGE_070.md +++ b/docs/ACTION_EMOTION_STAGE_070.md @@ -84,8 +84,8 @@ Asset-owner update: P1 free amplitude previews completed in its own `.runtime/avatar-imports/a01-expression-action-v1/p1-amplitude-01/`; Pi selected1.1 source pixels for candidate production based on fixed comparisons. Dynamic visual review remains pending. Nearest-level/opacity1/zero-bypass rendering stays intact. -Latest coordinator batch ledger snapshot: **8 submitted**, known video fee **$1.14**, -3 image fees unknown (supersedes earlier snapshots, not an all-time total). +Latest coordinator batch ledger snapshot: **11 submitted** (3 image edits +8 videos), +known video fee **$1.44**, image fees unknown (supersedes earlier snapshots, not an all-time total). sad001 idle rejected for visible opening/strong expression; sad00249-frame revision also rejected for opening around1–1.7s. Targeted sad003 is in its own frame gate. Happy own mouth uses1.1 sourcepx and actual97 source PTS; dynamic12s review pending. First real frame0-to-frame0 entry bridge @@ -186,3 +186,55 @@ N×5 checks and15 invalid graph/cache cases also pass. Local gateway98 tests: 97 passed/1 existing Silero artifact skip.40 offline EGL/GLES goldens passed. Application and Android instrumentation Kotlin compilation passed; instrumentation execution and real device capture/GPU/perception were not run. + + +Partial-emotion release preparation (baseline515d106, no APK build/import): +`scripts/package-avatar-emotion.py` defaults to a read-only full bundle gate. It +checks per-runtime full decode/PTS/own N×5 patches, referenced file SHA/bytes, +actual silent bridge decode, combined cache and production Kotlin index admission. +Only runtime-referenced files enter APK; preview inventory is checked but excluded. +`actions:[]` is required by this P4a packer and never advertises dance. Import/publish +requires an externally supplied exact Pi pin; it cannot replace unknown destination +bytes. Publication picks max existing APK code+1 (minimum17), preserves code16, +verifies package/min26/target34/arm64, certificate, every bundled asset byte, +compiled index pin and HTTP APK/checksum bytes. Dance publication needs its later +real-audio gate; this script does not claim that gate is implemented. + +Candidate-only machine check command: +`python3 scripts/package-avatar-emotion.py --manifest /manifest.json --sha256 --output logs/action-emotion/partial-pack/`. +After Pi's exact pin, add `--pi-pin --publish`; no empty-pack build runs. +14 packaging regressions passed: a real silent runtime plus synthetic neutral-only +index invokes actual production parser; no pin, bad digest/PTS/inventory, unsafe +path/symlink, source drift, unknown destination, exclusive/idempotent import and +version increments are checked. Nine JVM entries and UI source contracts passed +again for the extended index harness and five new HELLO no/unknown/valid action +capability cases. Android/gateway/GLES source is unchanged from515d106; their +previous compile/97-pass1-skip/40-golden evidence is retained, not redundantly rerun. + +sad003 standalone schema2 SHA +`6da7a3e431db28a7021eb1638fc8fecbabe5526bc9c49f7a9fcebe07009454b4` +passed read-only runtime Gate1:49 actual PTS,245 own patches,2.041667s,856,680 RGBA +bytes. Three original runtime textures total4,046,460 bytes; limits remain8MB/runtime +and32MB/index. This is a cache calculation, not physical OOME/GPU validation. + +New candidate index exists at +`.runtime/avatar-imports/a01-expression-action-v1/p4a-combined-01/manifest.json`, +read-only machine-passed SHA +`000d04ea2137748e42a762e170a739c0ea5648fe14703d4980c2cc5811bc5008`. +It includes3 own runtimes97/97/49,4 actual bidirectional bridges and3 native loops; +1,226 referenced files verified,19 preview inventory files excluded from runtime. +The integrated runtime manifest SHAs differ from the standalone exports due to +metadata; exact bodies/patches were independently rechecked without owner writes. +Production parser reports danceAvailable=false, actions empty and4,046,460 RGBA. +Pi approved P4a technical candidate production, not final naturalness or this index +publication pin. The index currently lists expression exits[0,last], whereas the +latest coordinator cursor says expressionlast only; all actual return bridges use +last. These unused0 declarations need coordinator/asset metadata reconciliation +before final pin, not image regeneration. Expression exit waits up to its body +loop plus bridge are separate from mouth response; no expression≤1s claim. + +Ignored evidence: `logs/action-emotion/partial-pack/{packaging-tests.json, +p4a-combined-01-gate/}`, `logs/action-emotion/media-wiring/sad-v2-gate.json`. +No asset import/activation, APK build/publication, gateway deployment/restart, +new live probe or paid call. Code16 rollback remains intact. Handoff marker: +**PARTIAL_EMOTION_PACKER_READY_INDEX_MACHINE_PASSED_AWAIT_EXACT_PI_PIN**. diff --git a/scripts/check-avatar-runtime.py b/scripts/check-avatar-runtime.py index c980ea7..6fddabe 100644 --- a/scripts/check-avatar-runtime.py +++ b/scripts/check-avatar-runtime.py @@ -13,22 +13,15 @@ import sys from PIL import Image ROOT=Path(__file__).resolve().parents[1] -parser=argparse.ArgumentParser(description=__doc__) -parser.add_argument('--manifest',type=Path,required=True) -parser.add_argument('--sha256',required=True,help='Exact candidate hash; this is not a publication approval') -parser.add_argument('--output',type=Path,required=True,help='New evidence file outside owner asset directory') -args=parser.parse_args() def require(value,reason): if not value: raise ValueError(reason) -def main(): - source=args.manifest.resolve(strict=True);directory=source.parent - output=args.output.resolve() - require(not output.exists() and not output.is_relative_to(directory),'evidence must be new and outside owner directory') +def check_runtime(manifest_path, expected_sha, kotlin=True): + source=Path(manifest_path).resolve(strict=True);directory=source.parent require(source.stat().st_size<=2_000_000,'manifest byte bound') raw=source.read_bytes();digest=hashlib.sha256(raw).hexdigest() - require(re.fullmatch('[0-9a-f]{64}',args.sha256) and digest==args.sha256,'candidate manifest drift') + require(re.fullmatch('[0-9a-f]{64}',expected_sha) and digest==expected_sha,'candidate manifest drift') def unique(pairs): result={} for key,value in pairs: @@ -81,21 +74,36 @@ def main(): bitmap.load() rgba+=width*height*4 require(len(set(paths))==len(paths) and rgba<=8_000_000,'unique N levels/cache bound') - result=subprocess.run([sys.executable,str(ROOT/'scripts/check-reply-regressions.py'),'--suite','avatar','--runtime-manifest',str(source)],capture_output=True,text=True,timeout=120) - require(result.returncode==0,'production Kotlin admission failed (candidate format or metadata)') - require('PASS: actual exported runtime manifest parsed' in result.stdout,'actual parser evidence absent') + if kotlin: + result=subprocess.run([sys.executable,str(ROOT/'scripts/check-reply-regressions.py'),'--suite','avatar','--runtime-manifest',str(source)],capture_output=True,text=True,timeout=120) + require(result.returncode==0,'production Kotlin admission failed (candidate format or metadata)') + require('PASS: actual exported runtime manifest parsed' in result.stdout,'actual parser evidence absent') require(source.read_bytes()==raw,'manifest changed during gate') for name,sha in verified.items(): require(hashlib.sha256((directory/name).read_bytes()).hexdigest()==sha,'asset changed during gate') evidence={'status':'passed','scope':'read_only_machine_gate_no_approval_no_activation','manifest_sha256':digest, 'body_sha256':body['sha256'],'schema_version':manifest['schemaVersion'],'actual_frame_count':count, 'actual_pts_count':len(pts),'actual_duration_us':duration,'patch_images':len(paths),'rgba_cache_bytes':rgba, - 'verified_files':len(verified),'full_decode':'passed','production_kotlin_parser':'passed','naturalness':'pending','real_device':'not_run'} + 'verified_files':len(verified),'full_decode':'passed','production_kotlin_parser':'passed' if kotlin else 'checked_by_bundle_parser','naturalness':'pending','real_device':'not_run'} + return evidence, verified + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument('--manifest',type=Path,required=True) + parser.add_argument('--sha256',required=True,help='Exact candidate hash; not a publication approval') + parser.add_argument('--output',type=Path,required=True,help='New evidence outside owner directory') + args=parser.parse_args() + output=args.output.resolve();source=args.manifest.resolve(strict=True) + require(not output.exists() and not output.is_relative_to(source.parent),'evidence must be new and outside owner directory') + evidence,_=check_runtime(source,args.sha256) output.parent.mkdir(parents=True,exist_ok=True) with output.open('x') as target: json.dump(evidence,target,indent=2);target.write('\n') print(json.dumps(evidence)) -try: main() -except (ValueError,KeyError,TypeError,OSError,subprocess.SubprocessError) as error: - print('FAIL: runtime gate: '+str(error),file=sys.stderr) - raise SystemExit(1) + +if __name__=='__main__': + try: main() + except (ValueError,KeyError,TypeError,OSError,subprocess.SubprocessError) as error: + print('FAIL: runtime gate: '+str(error),file=sys.stderr) + raise SystemExit(1) diff --git a/scripts/check-reply-regressions.py b/scripts/check-reply-regressions.py index bcaca6b..b8839e4 100644 --- a/scripts/check-reply-regressions.py +++ b/scripts/check-reply-regressions.py @@ -34,17 +34,19 @@ suites = [ parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--suite', choices=[name for name, _, _ in suites]) parser.add_argument('--runtime-manifest',type=Path,help='Additionally exercise real continuous parser with actual offline manifest metadata') +parser.add_argument('--index-manifest',type=Path,help='Additionally admit an exact offline v2 index and each referenced runtime through production parsers; no activation') args = parser.parse_args() +if args.index_manifest and args.runtime_manifest: parser.error('Choose runtime or index manifest, not both') for name, main, real in suites: if args.suite and name != args.suite: continue with tempfile.TemporaryDirectory(prefix=f'lan-voice-{name}-') as out: files = list((ROOT/'tests'/name).glob('*.kt')) + real - if name == 'avatar' and args.runtime_manifest: + if name == 'avatar' and (args.runtime_manifest or args.index_manifest): definitions=[] def kotlin(value): if value is None: return 'null' if isinstance(value,bool): return str(value).lower() - if isinstance(value,str): return json.dumps(value,ensure_ascii=False).replace('$','\\$') + if isinstance(value,str): return json.dumps(value,ensure_ascii=False).replace('$',chr(92)+'$') if isinstance(value,int): return str(value)+'L' if isinstance(value,float): return repr(value) if isinstance(value,(list,dict)): @@ -58,17 +60,41 @@ for name, main, real in suites: return method+'()' raise TypeError(type(value)) import hashlib - raw=args.runtime_manifest.read_bytes();digest=hashlib.sha256(raw).hexdigest() - extra=Path(out)/'ActualRuntimeCheck.kt' - literal=kotlin(json.loads(raw)) - extra.write_text('import com.gorios.lanvoice.avatar.*\n'+''.join(definitions)+'fun main() {\nval root='+literal+'\n'+ - 'val pack=checkNotNull(ContinuousAvatarManifest.read(root,"'+digest+'","'+digest+'",true,"runtime/"))\n'+ - 'check(pack.patches.size==pack.body.frameCount && pack.curves.size==5)\n'+ - ('check(pack.apertureMode && pack.textureImages.size==pack.body.frameCount*5 && pack.patches.all { it.levels.size==5 })\n' if json.loads(raw)['packId'].endswith('runtime-04') else 'check(!pack.apertureMode && pack.textureImages.size==pack.body.frameCount)\n')+ - 'println("PASS: actual exported runtime manifest parsed by production Kotlin, exact hash '+digest+'; per-body actual frame count/PTS and five authored curves/routing")\n}\n') + if args.runtime_manifest: + raw=args.runtime_manifest.read_bytes();digest=hashlib.sha256(raw).hexdigest() + extra=Path(out)/'ActualRuntimeCheck.kt' + literal=kotlin(json.loads(raw)) + extra.write_text('import com.gorios.lanvoice.avatar.*\n'+''.join(definitions)+'fun main() {\nval root='+literal+'\n'+ + 'val pack=checkNotNull(ContinuousAvatarManifest.read(root,"'+digest+'","'+digest+'",true,"runtime/"))\n'+ + 'check(pack.patches.size==pack.body.frameCount && pack.curves.size==5)\n'+ + ('check(pack.apertureMode && pack.textureImages.size==pack.body.frameCount*5 && pack.patches.all { it.levels.size==5 })\n' if json.loads(raw)['packId'].endswith('runtime-04') else 'check(!pack.apertureMode && pack.textureImages.size==pack.body.frameCount)\n')+ + 'println("PASS: actual exported runtime manifest parsed by production Kotlin, exact hash '+digest+'; per-body actual frame count/PTS and five authored curves/routing")\n}\n') + else: + index_path=args.index_manifest.resolve(strict=True) + raw=index_path.read_bytes();digest=hashlib.sha256(raw).hexdigest() + data=json.loads(raw);runtimes={};hashes={} + for row in data['conversationPackages']: + reference=row['runtimeManifest'];path=reference['path'] + runtime_path=(index_path.parent/path).resolve(strict=True) + if not runtime_path.is_relative_to(index_path.parent): raise ValueError('Runtime path escape') + runtime_raw=runtime_path.read_bytes();runtime_hash=hashlib.sha256(runtime_raw).hexdigest() + if runtime_hash!=reference['sha256']: raise ValueError('Runtime hash drift') + runtimes[path]=json.loads(runtime_raw);hashes[path]=runtime_hash + index_literal=kotlin(data);runtime_literal=kotlin(runtimes);hash_literal=kotlin(hashes) + extra=Path(out)/'ActualIndexCheck.kt' + extra.write_text('import com.gorios.lanvoice.avatar.*\n'+''.join(definitions)+ + 'fun main() {\nval root='+index_literal+'\nval runtimes='+runtime_literal+'\nval hashes='+hash_literal+'\n'+ + 'val index=checkNotNull(EmotionActionManifest.read(root,"'+digest+'","'+digest+'","fixture/") { path,hash ->\n'+ + 'check(hashes[path]==hash)\n@Suppress("UNCHECKED_CAST")\n'+ + 'ContinuousAvatarManifest.read(runtimes[path] as Map,hash,hash,true,"fixture/"+path.substringBeforeLast(47.toChar())+"/")\n})\n'+ + 'check(index.packages.values.all { it.textureImages.size==it.body.frameCount*5 })\n'+ + ('check(index.actionPack==null)\n' if not data['actions'] else 'check(index.actionPack?.assets?.size==2)\n')+ + 'println("PASS: actual exported v2 index parsed by production Kotlin, exact hash '+digest+'; packages="+index.packages.size+" rgbaBytes="+index.packages.values.sumOf { it.rgbaBytes }+" danceAvailable="+(index.actionPack!=null))\n}\n') files.append(extra) subprocess.run([JAVA,'-cp',compiler,'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler','-no-stdlib', '-no-reflect','-jvm-target','17','-nowarn','-classpath',cp,'-d',out, *map(str,files)],check=True,cwd=ROOT) subprocess.run([JAVA,'-cp',out+':'+cp,main],check=True,cwd=ROOT,timeout=30) if name == 'avatar' and args.runtime_manifest: subprocess.run([JAVA,'-cp',out+':'+cp,'ActualRuntimeCheckKt'],check=True,cwd=ROOT,timeout=30) + if name == 'avatar' and args.index_manifest: + subprocess.run([JAVA,'-cp',out+':'+cp,'ActualIndexCheckKt'],check=True,cwd=ROOT,timeout=30) diff --git a/scripts/package-avatar-emotion.py b/scripts/package-avatar-emotion.py new file mode 100644 index 0000000..0e403e3 --- /dev/null +++ b/scripts/package-avatar-emotion.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python3 +"""Read-only partial v2 emotion gate by default; import/publish needs an external Pi pin.""" +from pathlib import Path, PurePosixPath +from decimal import Decimal +from fractions import Fraction +import argparse +import hashlib +import importlib.util +import json +import os +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' +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 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') + require(index['actions']==[],'this partial-emotion packer requires actions:[]; dance needs its separate audio gate') + 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 + for row in rows: + ref=row['runtimeManifest'];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':row['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) + # 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':0,'dance_available':False,'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 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 tested_source(): + 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) + evidence=json.loads((ROOT/'logs/action-emotion/media-wiring/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/'): 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 publish(report,output,requested): + tested_source();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 + 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)],check=True,cwd=ROOT) + built=ROOT/'app/build/outputs/apk/debug/app-debug.apk';badge=badging(built) + for text in ("name='com.gorios.lanvoice'",f"versionCode='{version}'","versionName='0.7.0-stage-dev'","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']} + 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') + require(version>=next_version((ROOT/'artifacts').glob('*.apk')),'version became occupied during build') + artifact=ROOT/f'artifacts/lan-voice-v070-emotion-candidate-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':'partial_emotion_candidate','version_code':version,'url':url,'sha256':digest, + 'certificate_sha256':CERT,'manifest_sha256':report['manifest_sha256'],'dance_available':False,'action_count':0, + 'http_bytes_verified':True,'device':'not_run','naturalness':'not_certified','paid_calls':0,'gateway_deployed':False} + (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('--version-code',type=int,help='Default max existing APK code+1, minimum17') + args=parser.parse_args();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') + output.mkdir(parents=True) + report=check_bundle(manifest,args.sha256,output) + if args.import_only or args.publish: + import_files(manifest.parent,report['files'],ROOT/'app/src/main/assets'/ASSET_ROOT) + (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) 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) diff --git a/tests/packaging/test_emotion_package.py b/tests/packaging/test_emotion_package.py new file mode 100644 index 0000000..cde42d6 --- /dev/null +++ b/tests/packaging/test_emotion_package.py @@ -0,0 +1,139 @@ +"""Release/import safety + one real-parser/silent-media fixture; no Pi approval or APK build.""" +from pathlib import Path +import copy +import hashlib +import importlib.util +import json +import shutil +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +ROOT=Path(__file__).resolve().parents[2] +spec=importlib.util.spec_from_file_location('emotion_package',ROOT/'scripts/package-avatar-emotion.py') +pack=importlib.util.module_from_spec(spec);spec.loader.exec_module(pack) + + +class PackageTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.temp=tempfile.TemporaryDirectory(prefix='baji-package-fixture-') + cls.base=Path(cls.temp.name);cls.source=cls.base/'fixture';cls.source.mkdir() + original=ROOT/'.runtime/avatar-imports/a01-expression-action-v1/packages/neutral-01-v2' + cls.runtime=json.loads((original/'manifest.json').read_bytes()) + names=['manifest.json',cls.runtime['body']['path']] + names += [level['path'] for row in cls.runtime['patches'] for level in row['levels']] + for name in names: + dest=cls.source/'neutral'/name;dest.parent.mkdir(parents=True,exist_ok=True) + shutil.copyfile(original/name,dest) # Never mutate/hardlink owner files. + body=cls.runtime['body'] + cls.index={'schemaVersion':2,'identityId':'a01','packId':'a01-expression-action-v1', + 'fallbackPackageId':'neutral','conversationPackages':[{'id':'neutral','emotion':'neutral','visualIntensity':0, + 'mouthBodySha256':body['sha256'],'runtimeManifest':{'path':'neutral/manifest.json','sha256':pack.file_sha(cls.source/'neutral/manifest.json')}, + 'entryAnchor':'A','exitAnchor':'A','legalExitFrames':[96],'loopEdge':'neutral-loop'}], + 'edges':[{'id':'neutral-loop','from':'neutral','to':'neutral','fromFrame':96,'toFrame':0, + 'fromPtsUs':body['ptsUs'][-1],'toPtsUs':0,'fromAnchor':'A','toAnchor':'A','nativeLoop':True, + 'clip':{**body,'path':'neutral/'+body['path']}}], 'actions':[], + 'files':[{'path':'neutral/'+name,'sha256':pack.file_sha(cls.source/'neutral'/name), + 'bytes':(cls.source/'neutral'/name).stat().st_size} for name in names], + 'fixtureNotice':'Synthetic index declaration, ${noInterpolation}, not Pi review'} + cls.manifest=cls.source/'manifest.json' + + @classmethod + def tearDownClass(cls): cls.temp.cleanup() + + def gate(self,index,folder): + self.manifest.write_text(json.dumps(index)) + output=self.base/folder;output.mkdir() + return pack.check_bundle(self.manifest,pack.file_sha(self.manifest),output) + + def test_actual_partial_index_parser_and_media(self): + result=self.gate(self.index,'actual-gate') + self.assertFalse(result['dance_available']);self.assertEqual(result['action_count'],0) + self.assertEqual(result['combined_rgba_bytes'],1572780) + self.assertEqual(result['runtime_packages'][0]['actual_frame_count'],97) + self.assertEqual(result['referenced_files'],488) + self.assertIn('production_kotlin_index',result) + + def test_candidate_digest_mismatch(self): + self.manifest.write_text(json.dumps(self.index));out=self.base/'hash-gate';out.mkdir() + with self.assertRaisesRegex(ValueError,'index drift'): pack.check_bundle(self.manifest,'0'*64,out) + + def test_real_clip_timeline_mismatch(self): + bad=copy.deepcopy(self.index);bad['edges'][0]['clip']['ptsUs'][1]+=4 + with self.assertRaisesRegex(ValueError,'clip PTS'): self.gate(bad,'pts-gate') + + def test_inventory_omission(self): + bad=copy.deepcopy(self.index);bad['files']=bad['files'][1:] + with self.assertRaisesRegex(ValueError,'inventory missing'): self.gate(bad,'inventory-gate') + + def test_no_dance_in_partial_packer(self): + bad=copy.deepcopy(self.index);bad['actions']=[{'id':'asset_01'}] + with self.assertRaisesRegex(ValueError,'requires actions'): self.gate(bad,'action-gate') + + def test_paths(self): + for name in ('../x','x/../y','x//y','/x','x/./y','https://host/x','x\\y'): + with self.subTest(name=name),self.assertRaises(ValueError): pack.relative(name) + self.assertEqual(pack.relative('packages/neutral-01/body/test.mp4'),'packages/neutral-01/body/test.mp4') + + def test_symlink_read_escape(self): + (self.source/'escape').symlink_to(self.base) + with self.assertRaises(ValueError): pack.locate(self.source,'escape/duplicate.json') + + def test_duplicate_json(self): + p=self.base/'duplicate.json';p.write_text('{"schemaVersion":2,"schemaVersion":1}') + with self.assertRaisesRegex(ValueError,'duplicate'): pack.read_json(p) + + def test_import_idempotent_preserves_unknown(self): + source=self.base/'import-source';source.mkdir();(source/'one').write_bytes(b'first') + target=self.base/'import-target';files={'one':{'sha256':pack.file_sha(source/'one'),'bytes':5}} + pack.import_files(source,files,target);pack.import_files(source,files,target) + (target/'one').write_bytes(b'unknown') + with self.assertRaisesRegex(ValueError,'unknown destination'): pack.import_files(source,files,target) + self.assertEqual((target/'one').read_bytes(),b'unknown') + + def test_import_preflight_no_partial_write(self): + source=self.base/'preflight-source';source.mkdir();target=self.base/'preflight-target';target.mkdir() + for name in ('first','later'): (source/name).write_bytes(b'expected') + (target/'later').write_bytes(b'unknown') + files={name:{'sha256':pack.file_sha(source/name),'bytes':8} for name in ('first','later')} + with self.assertRaises(ValueError): pack.import_files(source,files,target) + self.assertFalse((target/'first').exists()) + + def test_import_broken_target_symlink(self): + target=self.base/'broken-target';target.symlink_to(self.base/'absent-destination') + with self.assertRaisesRegex(ValueError,'target symlink'): pack.import_files(self.source,{},target) + + def test_source_drift_before_import(self): + source=self.base/'drift-source';source.mkdir();(source/'one').write_bytes(b'first') + files={'one':{'sha256':pack.file_sha(source/'one'),'bytes':5}} + (source/'one').write_bytes(b'changed') + target=self.base/'drift-target' + with self.assertRaisesRegex(ValueError,'source drift'): pack.import_files(source,files,target) + self.assertFalse(target.exists()) + + def test_version_increments_existing_apks(self): + with patch.object(pack,'badging',side_effect=["versionCode='16'","versionCode='19'"]): + self.assertEqual(pack.next_version(['one.apk','two.apk']),20) + self.assertEqual(pack.next_version([]),17) + + def test_cli_no_pin_no_import_no_output(self): + self.manifest.write_text(json.dumps(self.index));out=self.base/'no-pin-output' + result=subprocess.run([sys.executable,str(ROOT/'scripts/package-avatar-emotion.py'), + '--manifest',str(self.manifest),'--sha256',pack.file_sha(self.manifest),'--output',str(out),'--import-only'],capture_output=True,text=True) + self.assertNotEqual(result.returncode,0);self.assertIn('external Pi pin required',result.stderr) + self.assertFalse(out.exists()) + + +if __name__=='__main__': + program=unittest.main(verbosity=2,exit=False) + if program.result.wasSuccessful(): + paths=['scripts/package-avatar-emotion.py','scripts/check-avatar-runtime.py', + 'scripts/check-reply-regressions.py','tests/packaging/test_emotion_package.py'] + output=ROOT/'logs/action-emotion/partial-pack';output.mkdir(parents=True,exist_ok=True) + (output/'packaging-tests.json').write_text(json.dumps({'status':'passed','test_count':program.result.testsRun, + 'scope':'read-only real-media index fixture and import/release safety; no approved-pack APK', + 'hashes':{p:pack.file_sha(ROOT/p) for p in paths}},indent=2)+'\n') + raise SystemExit(not program.result.wasSuccessful()) diff --git a/tests/protocol/ProtocolCheck.kt b/tests/protocol/ProtocolCheck.kt index 81bf2ce..2f2d52d 100644 --- a/tests/protocol/ProtocolCheck.kt +++ b/tests/protocol/ProtocolCheck.kt @@ -1,6 +1,15 @@ import com.gorios.lanvoice.net.DialogueProtocol fun main() { + // Partial expression packs provide no reviewed action pack; no dance in HELLO. + for (pin in listOf(null,"","unknown","a".repeat(63))) { + val hello=DialogueProtocol.hello(pin) + check(listOf("action_protocol","action_pack_sha256","action_kinds","dance").none { it in hello }) + check("continuous_voice" in hello) + } + val actionHello=DialogueProtocol.hello("a".repeat(64)) + check("action_protocol" in actionHello && "action_kinds" in actionHello && "dance" in actionHello) + println("PASS: 5 actual HELLO capability cases: partial/no/unknown pack advertises no dance; valid reviewed action SHA retains protocol1") val states = listOf("neutral" to 0) + listOf("happy", "angry", "sad").flatMap { kind -> listOf(kind to 1, kind to 2) } states.forEach { (kind, strength) -> val parsed = checkNotNull(com.gorios.lanvoice.dialogue.ReplyEmotion.fromWire(7L, 10L, kind, strength, "model"))