#!/usr/bin/env python3 """Finite replay of production loader/View/renderer callbacks over exact APK bytes. Android EGL/codec/music/record confirmations are doubles; no device or sockets. """ from pathlib import Path import ast,subprocess,tempfile,json,hashlib import argparse, zipfile parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--apk',type=Path,required=True) parser.add_argument('--sha256',required=True) parser.add_argument('--startup-loader',action='store_true',help='Production background repository over actual APK bytes, isolated private receipt, no rendering/connection') parser.add_argument('--user-asset-candidate',action='store_true',help='Exact user-authorized correct03 APK; this offline replay uses local media callback doubles and does not assert network admission') parser.add_argument('--media-bundle',default='black-correct03',help='Trusted user-debug bundle, when --user-asset-candidate is set') args=parser.parse_args() assert hashlib.sha256(args.apk.read_bytes()).hexdigest()==args.sha256, 'APK hash drift' ROOT=Path(__file__).resolve().parents[1];script=ROOT/'scripts/check-reply-regressions.py' tree=ast.parse(script.read_text());nodes=[] for node in tree.body: if isinstance(node,ast.Assign) and any(isinstance(t,ast.Name) and t.id=='parser' for t in node.targets):break nodes.append(node) ns={'__file__':str(script)};exec(compile(ast.Module(body=nodes,type_ignores=[]),str(script),'exec'),ns) java,compiler,cp=ns['JAVA'],ns['compiler'],ns['cp'];real=next(x[2] for x in ns['suites'] if x[0]=='avatar') json_adapter=r''' package org.json private fun wrap(v: Any?): Any? = when(v) { is Map<*,*> -> JSONObject(v as Map); is List<*> -> JSONArray(v); null -> JSONObject.NULL;else ->v } class JSONObject(private val map: Map) { constructor(raw: String):this(Parser(raw).value() as Map) fun keys()=map.keys.iterator() fun get(k: String): Any? = wrap(map.getValue(k)) fun getString(k: String)=map.getValue(k) as String fun getJSONObject(k: String)=JSONObject(map.getValue(k) as Map) fun getLong(k: String)=(map.getValue(k) as Number).toLong() fun getInt(k: String)=(map.getValue(k) as Number).toInt() fun getBoolean(k: String)=map.getValue(k) as Boolean fun getJSONArray(k: String)=JSONArray(map.getValue(k) as List<*>) companion object { val NULL=Any() } } class JSONArray(private val values: List<*>) { fun length()=values.size fun get(i: Int): Any? =wrap(values[i]) fun getJSONObject(i: Int)=get(i) as JSONObject fun getLong(i: Int)=(values[i] as Number).toLong() } private class Parser(val s: String) { var i=0 fun space() { while(i { i++;space();val m=linkedMapOf();if(s[i]!='}') while(true) { val k=value() as String;space();check(s[i++]==':');m[k]=value();space();if(s[i]!=',')break;i++ };check(s[i++]=='}');m } '[' -> { i++;space();val a=mutableListOf();if(s[i]!=']')while(true) { a.add(value());space();if(s[i]!=',')break;i++ };check(s[i++]==']');a } '"' -> { i++;val b=StringBuilder();while(s[i]!='"') { var c=s[i++];if(c=='\\') { c=s[i++];c=when(c) { 'n'->'\n';'r'->'\r';'t'->'\t';'b'->'\b';'f'->'\u000c';'u'->{ val x=s.substring(i,i+4).toInt(16).toChar();i+=4;x };else->c } };b.append(c) };i++;b.toString() } 't' -> {check(s.substring(i,i+4)=="true");i+=4;true} 'f' -> {check(s.substring(i,i+5)=="false");i+=5;false} 'n' -> {check(s.substring(i,i+4)=="null");i+=4;null} else -> { val start=i;while(i() } object AssetFixture { val paths=mutableMapOf() } class Descriptor(path: String="") : java.io.Closeable { val fileDescriptor=java.io.FileDescriptor();val startOffset=0L;val length=20L init { AssetFixture.paths[fileDescriptor]=path };override fun close() {} } ''' graphics=(ROOT/'tests/avatar/Graphics.kt').read_text();graphics=graphics.replace(' fun decodeStream(input: java.io.InputStream): Bitmap = Bitmap(if(wrongSize) 41 else 40,22)',r''' class Options { var inJustDecodeBounds=false;var outWidth=0;var outHeight=0 } fun decodeStream(input: java.io.InputStream): Bitmap { val image=javax.imageio.ImageIO.read(input);return Bitmap(image.width,image.height) } fun decodeByteArray(bytes: ByteArray,offset: Int,length: Int,options: Options): Bitmap? { val input=java.io.ByteArrayInputStream(bytes,offset,length);val image=javax.imageio.ImageIO.read(input) options.outWidth=image.width;options.outHeight=image.height return if(options.inJustDecodeBounds) null else Bitmap(image.width,image.height) } ''') build='''package com.gorios.lanvoice object BuildConfig { const val STARTUP_POSTER_RES_ID=1;const val AVATAR_STARTUP_FIX=false;const val DEBUG=true;const val AVATAR_NATURAL=true;const val AVATAR_ENGINEERING=true;const val AVATAR_MOUTH_CANDIDATE=true const val EMOTION_MANIFEST_SHA="987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887" const val NATURAL_MANIFEST_SHA="0a3c4918ba746019cf1df885bec66e5858a8950997dac4f64e7d37094be64dad" }''' if args.user_asset_candidate: import importlib.util spec=importlib.util.spec_from_file_location('user_startup',ROOT/'scripts/prepare-user-avatar-startup.py');asset_config=importlib.util.module_from_spec(spec);spec.loader.exec_module(asset_config) media=json.loads((ROOT/'manifests/character-build-profiles.json').read_bytes())['mediaBundles'][args.media_bundle] assert media.get('userAuthorizedDebug') is True asset_root=media['assetRoot'];basic_root=media['bootstrapRoot'];pin=media['indexSha256'] with zipfile.ZipFile(args.apk) as archive: raw=archive.read('assets/'+asset_root+'manifest.json');assert hashlib.sha256(raw).hexdigest()==pin index=json.loads(raw);refs=[p['runtimeManifest'] for p in index['conversationPackages']]+[e['mouthRuntimeManifest'] for e in index['edges'] if 'mouthRuntimeManifest' in e] patch_count=sum(len(json.loads(archive.read('assets/'+asset_root+r['path']))['patches'])*5 for r in refs) fallback_row=next(p for p in index['conversationPackages'] if p['id']==index['fallbackPackageId']) fallback_frames=json.loads(archive.read('assets/'+asset_root+fallback_row['runtimeManifest']['path']))['body']['frameCount'] build=build.replace('const val EMOTION_MANIFEST_SHA="987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887"','const val EMOTION_MANIFEST_SHA="'+pin+'"') build=build.replace('const val AVATAR_STARTUP_FIX=false','const val AVATAR_STARTUP_FIX=true') build=build.replace('object BuildConfig {','object BuildConfig { const val AVATAR_USER_ASSET_CANDIDATE=true;const val EMOTION_ASSET_ROOT="'+asset_root+'";const val STARTUP_ASSET_ROOT="'+basic_root+'";const val STARTUP_MANIFEST_SHA="'+media['bootstrapSha256']+'";') else: patch_count=3185 build=build.replace('object BuildConfig {','object BuildConfig { const val AVATAR_USER_ASSET_CANDIDATE=false;const val EMOTION_ASSET_ROOT="avatar/a01-expression-action-v1/";const val STARTUP_ASSET_ROOT="avatar/startup-white-01/";const val STARTUP_MANIFEST_SHA="461f5cfc10036de5f10ca3ce765fb8d9998697d3fd035aa9b1862d2ccfc3eaa2";') main=r''' import com.gorios.lanvoice.avatar.* import com.gorios.lanvoice.dialogue.* import android.os.TestScheduler import android.media.CodecFixture import android.media.MediaPlayer import android.graphics.SurfaceTexture import android.view.TextureView fun main(args: Array) { android.content.Archive.zip=java.util.zip.ZipFile(args.single()) val context=android.content.Context();val pack=checkNotNull(AvatarPack.load(context)) println("LOADER|status=${pack.motionStatus}|full=${pack.emotionAction!=null}|actions=${pack.emotionAction?.actionPack?.assets?.size}") val index=checkNotNull(pack.emotionAction) fun rig(): Triple>> { TestScheduler.reset();CodecFixture.reset();CodecFixture.width=pack.continuous!!.body.width;CodecFixture.height=pack.continuous!!.body.height;MediaPlayer.created.clear();CodecFixture.emitNativeSurface=true index.packages.values.forEach { CodecFixture.timelines[it.root+it.body.path]=it.body.ptsUs } index.edges.mapNotNull { it.mouthRuntime }.forEach { CodecFixture.timelines[it.root+it.body.path]=it.body.ptsUs } index.actionPack?.assets?.mapNotNull { it.media }?.forEach { CodecFixture.timelines[it.root+it.path]=it.ptsUs;CodecFixture.audioPaths.add(it.root+it.path) } val binding=AvatarMediaBinding();binding.beginTurn(7) val trace=mutableListOf>() val view=EmotionActionAvatarView(context,pack,binding,{ trace.add(TestScheduler.now to it) }) view.render(true);TestScheduler.advanceBy(1);return Triple(view,binding,trace) } fun printTrace(case: String,trace: List>) { var old="";for((ms,v) in trace)if(v.actual!=old) { println("FRAME|case=$case|ms=$ms|actual=${v.actual}|cursor=${v.clipId}|reason=${v.reason}");old=v.actual } } run { val(view,binding,trace)=rig();TestScheduler.advanceBy(30_000) printTrace("idle30s",trace);println("IDLE|current=${binding.currentPackageId}|visual=${binding.visualStatus}") check(trace.none { it.second.actual=="media_failed" });check(trace.any { it.second.actual.startsWith("body_idle-") }) TestScheduler.until(15_000) { binding.currentPackageId?.startsWith("idle-")==true } val parked=checkNotNull(binding.currentPackageId);val startRows=trace.size binding.beginTurn(8);binding.intent(null,false);TestScheduler.advanceBy(30_000) val changed=trace.drop(startRows).any { it.second.actual=="bridge" || it.second.actual.startsWith("idle_variant_") } println("IDLE_NEWTURN|parked=$parked|after30s=${binding.currentPackageId}|routed=$changed|status=${binding.visualStatus}") check(changed) check(trace.drop(startRows).any { it.second.actual=="body_neutral-01" }) for(wanted in listOf("idle-breathe-01","idle-microshift-01")) { // Begin at a genuine fresh entry, not an arbitrary late frame of an already // visible variant. Legal return may otherwise occur during the next700ms. TestScheduler.until(70_000) { binding.currentPackageId==wanted && trace.lastOrNull()?.second?.clipId=="f0_loop0" } val start=trace.size repeat(5) { i -> binding.beginTurn(10L+i);binding.intent(null,false);TestScheduler.advanceBy(100) } binding.prepare(mediaReply(RoleEmotion.HAPPY,turn=14,seq=1)) binding.intent(mediaReply(RoleEmotion.NEUTRAL,turn=14,seq=2),true) TestScheduler.advanceBy(200);check(binding.currentPackageId==wanted) binding.intent(null,false) TestScheduler.advanceBy(30_000) val returned=trace.drop(start).any { it.second.actual=="body_neutral-01" } check(returned && trace.drop(start).any { it.second.actual=="bridge" }) println("IDLE_NEWTURN|parked=$wanted|turns=5|legal_return=$returned|after30s=${binding.currentPackageId}") } view.dispose();TestScheduler.advanceBy(100) } run { val(view,binding,trace)=rig() binding.prepare(mediaReply(RoleEmotion.HAPPY,seq=1));TestScheduler.advanceBy(500) println("EMOTION|prepare_only|current=${binding.currentPackageId}|visual=${binding.visualStatus}") binding.intent(mediaReply(RoleEmotion.HAPPY,seq=2),true);TestScheduler.advanceBy(1000) binding.intent(null,false) // Same MainActivity path when short reply drained. TestScheduler.advanceBy(6000) println("EMOTION|requested=happy1|current=${binding.currentPackageId}|visual=${binding.visualStatus}") binding.intent(mediaReply(RoleEmotion.SAD,seq=3),true);TestScheduler.advanceBy(1500);binding.intent(null,false);TestScheduler.advanceBy(7000) println("EMOTION|requested=sad1|current=${binding.currentPackageId}|visual=${binding.visualStatus}") printTrace("happy_sad",trace);check(trace.none { it.second.actual=="media_failed" });check(binding.currentPackageId=="sad-01");view.dispose();TestScheduler.advanceBy(100) } for(initial in listOf(RoleEmotion.NEUTRAL,RoleEmotion.HAPPY)) for(assetChoice in 0..1) { val(view,binding,trace)=rig();binding.intent(mediaReply(initial),false);TestScheduler.advanceBy(6000) var stop: ((Boolean)->Unit)?=null;val statuses=mutableListOf() val controller=ActionController(index.actionPack,binding,{TestScheduler.now},{stop=it},statuses::add,choose={assetChoice}) check(controller.offer(ActionPlan("public_fixture_action_id_001",7,index.actionPack!!.manifestSha,120000))) println("DANCE|initial=${initial.wire}|offered=true|before_stop_players=${MediaPlayer.created.size}") stop!!(true);MediaPlayer.created.single().let { it.prepared!!(it) };TestScheduler.until(15000) { MediaPlayer.created.any { it.started } || trace.any { it.second.actual=="media_failed" } } val movie=MediaPlayer.created.single();println("DANCE|started=${movie.started}|current=${binding.currentPackageId}|status=${statuses.last().status}") val field=view.javaClass.getDeclaredField("textures").apply { isAccessible=true };val textures=field.get(view) as List val listener=textures[3].surfaceTextureListener!!;val surface=textures[3].surfaceTexture!! index.actionPack.assets[assetChoice].media!!.ptsUs.forEachIndexed { i,pts -> if(i>0) TestScheduler.advanceBy(42);surface.timestamp=pts*1000;listener.onSurfaceTextureUpdated(surface) if(i==0) { println("DANCE_LAYER|initial=${initial.wire}|first_frame_alpha=${textures[3].alpha}|body_alpha=${textures.take(3).map { it.alpha }}") TestScheduler.advanceBy(21) println("DANCE_LAYER|initial=${initial.wire}|after_21ms_alpha=${textures[3].alpha}|body_alpha=${textures.take(3).map { it.alpha }}|movie_started=${movie.started}|phase=${binding.visualStatus}") check(movie.started && textures[3].alpha==1f && textures.take(3).all { it.alpha==0f }) } check(textures[3].alpha==1f && textures.take(3).all { it.alpha==0f }) } println("DANCE_OWNER|initial=${initial.wire}|asset=${index.actionPack.assets[assetChoice].id}|frames=${index.actionPack.assets[assetChoice].media!!.ptsUs.size}|music_visible=${index.actionPack.assets[assetChoice].media!!.ptsUs.size}|conversation_visible=0|state=${binding.diagnosticState}") TestScheduler.advanceBy(50);movie.completion!!(movie);TestScheduler.until(15000) { statuses.last().status!="started" } println("DANCE|ended=${statuses.last().status}|released=${movie.released}|return=${binding.currentPackageId}") printTrace("dance_${initial.wire}",trace);check(statuses.last().status=="completed");check(binding.currentPackageId=="neutral-01");view.dispose();TestScheduler.advanceBy(100) } println("HOST_REPLAY|fix_verified=true|dance_layer_retained=true|idle_newturn_legal_return=true|native_device=false|surface_availability_mock=true|record_stop_mock=true|json_adapter=host") } ''' startup_main=r''' import com.gorios.lanvoice.avatar.* import android.os.TestScheduler fun main(args: Array) { android.content.Archive.zip=java.util.zip.ZipFile(args[0]);android.content.Archive.privateDir=java.io.File(args[1]) android.os.Looper.getMainLooper();android.content.Archive.requireWorker=true val context=android.content.Context();var base: ContinuousAvatarPack?=null;var pack: AvatarPack?=null fun waitReady() { val deadline=System.nanoTime()+40_000_000_000L while(pack==null || base==null) { TestScheduler.advanceBy(0);check(System.nanoTime()