Show startup shell before background avatar admission and update reviewed capabilities

This commit is contained in:
zenord
2026-10-13 14:57:13 +08:00
parent 345e26e245
commit 40abf3a14e
41 changed files with 1113 additions and 124 deletions
+53 -9
View File
@@ -8,6 +8,7 @@ import argparse
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')
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'
@@ -25,6 +26,8 @@ class JSONObject(private val map: Map<String,Any?>) {
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<String,Any?>)
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<*>)
@@ -34,6 +37,7 @@ 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
@@ -54,12 +58,21 @@ private class Parser(val s: String) {
'''
context=r'''
package android.content
class Context { val assets = Assets() }
class Context {
val assets = Assets();val applicationContext get()=this;val packageName="com.gorios.lanvoice"
val packageManager=PackageManager();val filesDir get()=Archive.privateDir
}
class PackageManager { fun getPackageInfo(name: String,flags: Int)=PackageInfo() }
class PackageInfo { val versionCode=22;val lastUpdateTime=123456L }
class Assets {
fun open(path: String): java.io.InputStream = java.io.ByteArrayInputStream(Archive.zip.getInputStream(checkNotNull(Archive.zip.getEntry("assets/"+path)) { "missing_asset" }).use { it.readBytes() })
fun open(path: String): java.io.InputStream {
if(Archive.requireWorker) check(Thread.currentThread()!==Archive.owner) { "asset_read_on_main" }
synchronized(Archive.reads) {Archive.reads.add(path)}
return java.io.ByteArrayInputStream(Archive.zip.getInputStream(checkNotNull(Archive.zip.getEntry("assets/"+path)) { "missing_asset" }).use { it.readBytes() })
}
fun openFd(path: String) = Descriptor(path)
}
object Archive { lateinit var zip: java.util.zip.ZipFile }
object Archive { lateinit var zip: java.util.zip.ZipFile;lateinit var privateDir: java.io.File;var requireWorker=false;val owner=Thread.currentThread();val reads=mutableListOf<String>() }
object AssetFixture { val paths=mutableMapOf<java.io.FileDescriptor,String>() }
class Descriptor(path: String="") : java.io.Closeable {
val fileDescriptor=java.io.FileDescriptor();val startOffset=0L;val length=20L
@@ -76,7 +89,7 @@ graphics=(ROOT/'tests/avatar/Graphics.kt').read_text();graphics=graphics.replace
}
''')
build='''package com.gorios.lanvoice
object BuildConfig { const val DEBUG=true;const val AVATAR_NATURAL=true;const val AVATAR_ENGINEERING=true;const val AVATAR_MOUTH_CANDIDATE=true
object BuildConfig { 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"
}'''
@@ -100,7 +113,7 @@ fun main(args: Array<String>) {
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<Pair<Long,VideoPresentation>>()
val view=EmotionActionAvatarView(context,pack,binding) { trace.add(TestScheduler.now to it) }
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<Pair<Long,VideoPresentation>>) {
@@ -174,12 +187,43 @@ fun main(args: Array<String>) {
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<String>) {
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()<deadline);Thread.sleep(1) }
}
StartupAvatarRepository.request(context,{base=it},{pack=it.getOrThrow()});waitReady()
check(base!!.body.frameCount==97 && base!!.patches.isEmpty() && base!!.curves.isEmpty())
check(pack!!.emotionAdmission=="accepted" && pack!!.emotionAction!!.packages.size==5)
val patchReads=android.content.Archive.reads.count { it.contains("/patches/") }
check(patchReads==if(args[2]=="cold") 3185 else 0)
val count=android.content.Archive.reads.size;val original=pack;base=null;pack=null
StartupAvatarRepository.request(context,{base=it},{pack=it.getOrThrow()});waitReady()
check(pack===original && android.content.Archive.reads.size==count)
println("STARTUP_REPOSITORY|mode=${args[2]}|main_asset_reads=0|patch_reads=$patchReads|same_process_reloads=0|packages=5|bridge_mouths=8|sensors=0|device=false")
}
'''
with tempfile.TemporaryDirectory(prefix='baji-runtime-audit-') as td:
tmp=Path(td);files=[]
for path in (ROOT/'tests/avatar').glob('*.kt'):
if path.name not in ('Pack.kt','Context.kt','Graphics.kt'):files.append(path)
for name,txt in [('Json.kt',json_adapter),('Context.kt',context),('Graphics.kt',graphics),('BuildConfig.kt',build),('Audit.kt',main)]:
if path.name not in ('Pack.kt','Context.kt','Graphics.kt') and not(args.startup_loader and path.name=='Clock.kt'):files.append(path)
if args.startup_loader:
clock=(ROOT/'tests/avatar/Clock.kt').read_text().replace('fun getMainLooper() = main','private val owner=Thread.currentThread();fun myLooper(): Looper?=if(Thread.currentThread()===owner) main else null;fun getMainLooper() = main')
clock=clock.replace(' fun add(', ' @Synchronized fun add(').replace(' fun remove(', ' @Synchronized fun remove(').replace(' fun advanceBy(', ' @Synchronized fun advanceBy(')
p=tmp/'Clock.kt';p.write_text(clock);files.append(p)
for name,txt in [('Json.kt',json_adapter),('Context.kt',context),('Graphics.kt',graphics),('BuildConfig.kt',build),('Audit.kt',startup_main if args.startup_loader else main)]:
p=tmp/name;p.write_text(txt);files.append(p)
files+=real+[ROOT/'app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt']
files+=real+[ROOT/'app/src/main/java/com/gorios/lanvoice'/p for p in ('avatar/AvatarPack.kt','avatar/StartupAvatarView.kt','avatar/StartupLoadCache.kt','diag/StartupTrace.kt')]
if args.startup_loader: files.append(ROOT/'app/src/main/java/com/gorios/lanvoice/avatar/StartupAvatarRepository.kt')
subprocess.run([java,'-cp',compiler,'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler','-no-stdlib','-no-reflect','-jvm-target','17','-nowarn','-classpath',cp,'-d',str(tmp),*map(str,files)],check=True)
subprocess.run([java,'-cp',str(tmp)+':'+cp,'AuditKt',str(args.apk.resolve())],check=True,timeout=45)
if args.startup_loader:
receipt=tmp/'private';receipt.mkdir()
for mode in ('cold','receipt'):
subprocess.run([java,'-cp',str(tmp)+':'+cp,'AuditKt',str(args.apk.resolve()),str(receipt),mode],check=True,timeout=45)
else: subprocess.run([java,'-cp',str(tmp)+':'+cp,'AuditKt',str(args.apk.resolve())],check=True,timeout=45)
+10 -1
View File
@@ -73,10 +73,19 @@ assert 'pack?.emotionAction!=null && mediaBinding!=null' in source
assert 'remember(pack,mediaBinding) { EmotionActionAvatarView' in source
assert 'onOfflinePreview' in text(block('},settings=',block('fun CallScreen')))
assert 'danceActive' in text(block('fun EngineeringPreviewScreen'))
assert 'else expressions.diagnosticsSnapshot()' in activity and 'else session.faceDiagnosticsSnapshot()' in activity
assert 'if(::expressions.isInitialized) expressions.diagnosticsSnapshot()' in activity and 'if(::session.isInitialized) session.faceDiagnosticsSnapshot()' in activity
assert 'EMOTION_MANIFEST_SHA' in (ROOT/'app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt').read_text()
permissions=text(block('fun PermissionSettings'))
for label in ('已授权','未授权','申请麦克风权限','申请摄像头权限','系统权限设置'):
assert label in permissions
assert '本版仅修复界面;嘴层沿用 runtime03,变形问题尚未修复' in source
status=text(block('fun StartupStatus'))
assert 'if(stage!="preparing" && !connecting) return' in status
assert 'if(stage=="preparing")' in status and 'if(connecting)' in status
assert 'end=88.dp' in text(home) and 'StartupStatus(' in text(home)
assert 'remember(mediaBinding) { StartupAvatarView' in source
assert 'LaunchedEffect(resumed,restart,override,danceActive,pack)' in source
assert 'if(!BuildConfig.AVATAR_STARTUP_FIX) avatarPack = AvatarPack.load(this)' in activity
assert activity.index('setContent {') < activity.index('private fun initializeNormal')
assert 'OnDrawListener' in activity and 'StartupAvatarRepository.request' in activity
print('PASS: clean home has persistent avatar + one 48dp safe-inset gear; normal/offline text and controls are sheet-only; sheet state never keys renderer/session; offline construction bypasses sensors/network. Source contracts only; real-device probe pending.')
+2
View File
@@ -45,6 +45,8 @@ 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 in ('session','avatar'): files.append(source/'diag/StartupTrace.kt')
if name=='avatar': files += [source/'avatar/StartupAvatarView.kt',source/'avatar/StartupLoadCache.kt']
if name == 'avatar' and (args.runtime_manifest or args.index_manifest):
definitions=[]
def kotlin(value):
+25 -12
View File
@@ -271,7 +271,7 @@ def tested_source(full=False):
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')
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())
@@ -286,18 +286,23 @@ def packaging_tests_current():
for name,digest in evidence['hashes'].items(): require(file_sha(ROOT/name)==digest,'untested packaging source: '+name)
def verify_runtime_fix_assets(built,pin):
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('/')}
require(paths(new)==paths(old),'runtime fix avatar inventory changed')
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):
def publish(report,output,requested,full=False,runtime_fix=False,playback_diagnostic=False,playback_clock_fix=False,startup_fix=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')
@@ -305,14 +310,17 @@ def publish(report,output,requested,full=False,runtime_fix=False,playback_diagno
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 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).lower()],check=True,cwd=ROOT)
'-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()],check=True,cwd=ROOT)
built=ROOT/'app/build/outputs/apk/debug/app-debug.apk';badge=badging(built)
version_name='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')
version_name='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')
@@ -321,6 +329,7 @@ def publish(report,output,requested,full=False,runtime_fix=False,playback_diagno
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')
@@ -328,10 +337,11 @@ def publish(report,output,requested,full=False,runtime_fix=False,playback_diagno
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 runtime_fix or playback_diagnostic or playback_clock_fix: require(verify_runtime_fix_assets(built,report['manifest_sha256'])==len(report['files']),'runtime fix file count')
stem='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='v073' if playback_clock_fix else 'v072' if playback_diagnostic else 'v071' if runtime_fix else 'v070'
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='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='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()
@@ -343,7 +353,9 @@ def publish(report,output,requested,full=False,runtime_fix=False,playback_diagno
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':False,'runtime_fix':runtime_fix,'diagnostic_only':playback_diagnostic,'playback_clock_fix':playback_clock_fix,'runtime_files_unchanged_from_code18':len(report['files']) if runtime_fix or playback_diagnostic or playback_clock_fix else None}
'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,'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
@@ -362,8 +374,9 @@ def main():
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')
args=parser.parse_args();
require(sum((args.runtime_fix,args.playback_diagnostic,args.playback_clock_fix))<=1,'choose one build purpose')
require(sum((args.runtime_fix,args.playback_diagnostic,args.playback_clock_fix,args.startup_fix))<=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')
@@ -380,7 +393,7 @@ def main():
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) if args.publish else {k:v for k,v in report.items() if k!='files'}
result=publish(report,output,args.version_code,bool(report['action_count']),args.runtime_fix,args.playback_diagnostic,args.playback_clock_fix,args.startup_fix) if args.publish else {k:v for k,v in report.items() if k!='files'}
print(json.dumps(result,indent=2))
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env python3
"""Recreate tiny bootstrap from frozen neutral sourceframe0. Free CPU only, no new media.
Portrait outputs are ignored; never commit generated PNG/video. Requires existing ffmpeg/Pillow.
"""
import argparse,hashlib,io,json,subprocess
from pathlib import Path
from PIL import Image
ROOT=Path(__file__).resolve().parents[1]
PIN='987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887'
BASIC_SHA='461f5cfc10036de5f10ca3ce765fb8d9998697d3fd035aa9b1862d2ccfc3eaa2'
sha=lambda b:hashlib.sha256(b).hexdigest()
def prepare(verify_only=False):
archive=ROOT/'manifests/startup-white-01.json';raw=archive.read_bytes();assert sha(raw)==BASIC_SHA
meta=json.loads(raw);assert meta['sourceIndexSha256']==PIN
assets=ROOT/'app/src/main/assets';index=assets/'avatar/a01-expression-action-v1/manifest.json'
assert sha(index.read_bytes())==PIN
body=assets/meta['body']['path'];assert sha(body.read_bytes())==meta['body']['sha256']
outputs={assets/'avatar/startup-white-01/manifest.json':raw}
poster=assets/'avatar/startup-white-01/poster.png';resource=ROOT/'app/src/main/res/drawable-nodpi/startup_poster.png'
if verify_only:
data=poster.read_bytes();assert sha(data)==meta['posterSha256'];assert resource.read_bytes()==data
else:
native=subprocess.check_output(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-i',str(body),'-frames:v','1','-f','image2pipe','-vcodec','png','-'],timeout=30)
image=Image.open(io.BytesIO(native)).convert('RGB').resize((240,424),Image.Resampling.LANCZOS)
out=io.BytesIO();image.save(out,format='PNG',optimize=True);data=out.getvalue()
assert sha(data)==meta['posterSha256'],'Deterministic poster changed; do not invent a new pin'
outputs[poster]=data;outputs[resource]=data
poster_bytes=len(data)
for path,data in outputs.items():
if verify_only: assert path.read_bytes()==data
else:
path.parent.mkdir(parents=True,exist_ok=True)
if path.exists():assert path.read_bytes()==data,'Refuse unknown bootstrap overwrite'
else:path.write_bytes(data)
return {'status':'passed','index_sha256':PIN,'bootstrap_sha256':BASIC_SHA,'new_avatar_files':2,'poster_bytes':poster_bytes,'width':240,'height':424,'paid_calls':0}
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--verify-only',action='store_true')
print(json.dumps(prepare(parser.parse_args().verify_only),indent=2))
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Finite model-free WS route replay of canonical deployed source in isolated localhost.
No live phone/session/history, no inference, no fake pack approvals or live configuration.
"""
import json,subprocess
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
REMOTE=r'''
import asyncio,contextlib,inspect,json,secrets,socket,tempfile,hashlib,sys
from pathlib import Path
root=Path('/home/gorios-spark-2/lan-voice')
for name,digest in expected.items():assert hashlib.sha256((root/name).read_bytes()).hexdigest()==digest
import shutil
stage_dir=tempfile.TemporaryDirectory(prefix='startup-canonical-source-')
stage=Path(stage_dir.name)
for path in root.glob('*.py'):shutil.copy2(path,stage/path.name)
shutil.copy2(root/'reviewed_action_packs.json',stage/'reviewed_action_packs.json')
(stage/'web').mkdir();sys.path.insert(0,str(stage))
import gateway as g
import uvicorn,websockets,httpx
from history import History
from guest_sessions import GuestSessions
from tests_fake import FakeModel
from action_protocol import configured_packs
pin='987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887'
assert configured_packs()[pin]=={'asset_01':10042,'asset_02':10042}
async def main():
with tempfile.TemporaryDirectory(prefix='startup-capabilities-probe-') as directory:
history=History(Path(directory)/'public-empty.sqlite3');await history.initialize()
token=secrets.token_urlsafe(32)
async with httpx.AsyncClient(transport=httpx.MockTransport(lambda req: (_ for _ in ()).throw(AssertionError('no_inference_allowed')))) as client:
state=g.app.state
state.busy=False;state.model=FakeModel();state.client=client;state.history=history
state.token=token;state.guest_enabled=False;state.lan_open=False;state.guests=GuestSessions();state.debug=None
state.voices=[{'id':g.DEFAULT_VOICE_ID,'source':'registered_reference','default':True}]
server=uvicorn.Server(uvicorn.Config(g.app,host='127.0.0.1',port=0,lifespan='off',log_level='critical',access_log=False))
sock=socket.socket();sock.bind(('127.0.0.1',0));sock.listen();sock.setblocking(False);port=sock.getsockname()[1]
task=asyncio.create_task(server.serve(sockets=[sock]));rows=[]
try:
async with asyncio.timeout(5):
while not server.started:await asyncio.sleep(.01)
kwargs={'origin':'https://192.168.31.61:5011','open_timeout':3,'close_timeout':1}
if 'proxy' in inspect.signature(websockets.connect).parameters:kwargs['proxy']=None
for kind,offer in [('pending',{'action_protocol':1,'action_kinds':[],'action_pending_pack_sha256':pin}),('legacy',{}),('unknown',{'action_protocol':1,'action_kinds':[],'action_pending_pack_sha256':'b'*64})]:
async with websockets.connect(f'ws://127.0.0.1:{port}/ws/dialogue',**kwargs) as ws:
await ws.send(json.dumps({'type':'auth','token':token}));assert json.loads(await ws.recv())['type']=='auth'
await ws.send(json.dumps({'type':'hello','codec':'pcm16','sample_rate':16000,'frame_duration':20,'persona':'default','tts_debug':False,**offer}))
hello=json.loads(await ws.recv());assert hello['type']=='hello' and not hello['action_available']
assert hello['action_pending']==(kind=='pending')
async def update(value):
await ws.send(json.dumps({'type':'client.capabilities.ready','action_protocol':1,'action_kinds':['dance'],'action_pack_sha256':value}))
async with asyncio.timeout(3):
while True:
event=json.loads(await ws.recv())
if event['type']=='client.capabilities':return event['action_available'],event['turn_id']
assert event['type']=='history' # Isolated empty history; never saved or printed.
denied=await update('b'*64);accepted=await update(pin);duplicate=await update(pin)
assert not denied[0] and accepted[0]==(kind=='pending') and duplicate==accepted
rows.append({'offer':kind,'hello_available':False,'pending':hello['action_pending'],'ready_available':accepted[0],'duplicate_turn_unchanged':duplicate[1]==hello['turn_id']})
async with asyncio.timeout(3):
while state.busy:await asyncio.sleep(.01)
finally:
server.should_exit=True;await task
return {'status':'passed','scope':'canonical source isolated actual WS routes; no live session','rows':rows,'connections':3,'model_calls':0,'asr_calls':0,'tts_calls':0,'device':'not_run'}
print(json.dumps(asyncio.run(main())))
stage_dir.cleanup()
'''
def main():
expected=json.loads((ROOT/'gateway/SOURCE_MANIFEST.json').read_text())['deployment_baseline']['files']
payload='expected='+repr(expected)+'\n'+REMOTE
result=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5','gorios-spark-2@192.168.31.61','cd /home/gorios-spark-2/lan-voice && exec .venv/bin/python -'],input=payload.encode(),capture_output=True,timeout=25)
if result.returncode:
print('FAIL: isolated capability probe; remote exception suppressed, no live changes');raise SystemExit(1)
report=json.loads(result.stdout);output=ROOT/'logs/action-emotion/startup-074/capability-ws.json'
output.parent.mkdir(parents=True,exist_ok=True);output.write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report,indent=2))
if __name__=='__main__':main()