feat(android): add isolated lvbu persona build and pinned asset selection

This commit is contained in:
zenord
2026-10-14 16:41:36 +08:00
parent 3371997252
commit 5a7be557d0
23 changed files with 1507 additions and 31 deletions
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env python3
"""Production Android AUTH/HELLO -> isolated existing ASGI gateway, no live services.
Run with the existing gori-speech interpreter. Compiles Kotlin against deterministic
Android main/transport/JSON adapters. All server identities and history are synthetic.
"""
import ast
import asyncio
import json
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
ROOT=Path(__file__).resolve().parents[1]
tree=ast.parse((ROOT/'scripts/check-reply-regressions.py').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(ROOT/'scripts/check-reply-regressions.py')}
exec(compile(ast.Module(body=nodes,type_ignores=[]),'test-toolchain','exec'),ns)
with tempfile.TemporaryDirectory(prefix='character-handshake-') as folder:
stage=Path(folder)
source=ROOT/'app/src/main/java/com/gorios/lanvoice'
files=list((ROOT/'tests/character').glob('*.kt'))
files+=[ROOT/'tests/session'/n for n in ('AndroidMain.kt','AndroidLog.kt','DebugUploadDouble.kt')]
files+=[ROOT/'tests/protocol/JSONArrayDouble.kt']
files+=[source/n for n in ('net/DialogueClient.kt','net/DialogueProtocol.kt','diag/DiagnosticLog.kt',
'diag/StartupTrace.kt','avatar/ActionController.kt','dialogue/ReplyEmotion.kt',
'expression/FaceCueRules.kt','expression/ExpressionRules.kt','expression/PresenceRules.kt')]
subprocess.run([ns['JAVA'],'-cp',ns['compiler'],'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler',
'-no-stdlib','-no-reflect','-jvm-target','17','-nowarn','-classpath',ns['cp'],
'-d',str(stage/'classes'),*map(str,files)],check=True)
hello_file=stage/'hello.jsonl'
subprocess.run([ns['JAVA'],'-Dcharacter.helloFile='+str(hello_file),'-cp',
str(stage/'classes')+':'+ns['cp'],'HandshakeCheckKt'],check=True,timeout=30)
hellos=[json.loads(row) for row in hello_file.read_text().splitlines()]
for path in (ROOT/'gateway').glob('*.py'):shutil.copyfile(path,stage/path.name)
shutil.copyfile(ROOT/'gateway/reviewed_action_packs.json',stage/'reviewed_action_packs.json')
shutil.copytree(ROOT/'gateway/personas',stage/'personas')
(stage/'web').mkdir()
(stage/'.runtime/personas').mkdir(parents=True)
for persona in ('lvbu','yangmi_fiction'):
(stage/'.runtime/personas'/ (persona+'.json')).write_text(json.dumps({'voice_id':'synthetic-'+persona}))
# New interpreter: imports never reach a live gateway or its private configuration.
runner=r'''
import asyncio,json
from pathlib import Path
from unittest.mock import patch
from fastapi.testclient import TestClient
import gateway
from history import History
from guest_sessions import GuestSessions
state=gateway.app.state
state.busy=False;state.token='synthetic-character-token-'+('x'*24)
class NoInferenceModel:
def new_state(self): return None
def infer(self,*args): raise AssertionError('no ASR/VAD/model calls authorized by this fixture')
state.model=NoInferenceModel();state.client=None;state.guests=GuestSessions()
state.guest_enabled=False;state.lan_open=False;state.debug=None
state.voices=[dict(id=v) for v in (gateway.DEFAULT_VOICE_ID,'synthetic-lvbu','synthetic-yangmi_fiction')]
history=History(Path('synthetic.sqlite3'));asyncio.run(history.initialize());state.history=history
client=TestClient(gateway.app) # no lifespan/model loading
hellos=[json.loads(row) for row in Path('hello.jsonl').read_text().splitlines()]
ids=[]
for hello in hellos:
with patch('gateway.load_active_profile',return_value={'persona':'yangmi_fiction','voice_id':'synthetic-yangmi_fiction'}) as profile:
with client.websocket_connect('/ws/dialogue',headers={'Origin':'https://192.168.31.61:5011'}) as ws:
ws.send_json(dict(type='auth',token=state.token));assert ws.receive_json()['type']=='auth'
ws.send_json(hello)
ack=ws.receive_json();assert ack['type']=='hello'
assert ack['voice_id']==('synthetic-lvbu' if hello['persona']=='lvbu' else 'synthetic-yangmi_fiction')
assert profile.call_count==(0 if hello['persona']=='lvbu' else 1)
assert ack['action_available']==('action_pack_sha256' in hello)
assert ack['action_pending']==('action_pending_pack_sha256' in hello)
assert ack['conversation_id'] not in ids;ids.append(ack['conversation_id'])
assert ws.receive_json()['type']=='history'
assert state.busy is False, 'disconnect did not release existing gateway busy owner'
# A non-default persona stays server-locked even if a caller offers another voice/CID.
hello=next(x for x in hellos if x['persona']=='lvbu' and 'action_pack_sha256' in x)
with patch('gateway.load_active_profile',side_effect=AssertionError('lvbu must ignore global profile')):
with client.websocket_connect('/ws/dialogue',headers={'Origin':'https://192.168.31.61:5011'}) as ws:
ws.send_json(dict(type='auth',token=state.token));ws.receive_json()
ws.send_json(dict(hello,voice_id=gateway.DEFAULT_VOICE_ID,conversation_id=ids[0]))
ack=ws.receive_json()
assert ack['voice_id']=='synthetic-lvbu' and ack['conversation_id'] not in ids
ws.receive_json()
assert state.busy is False
print('PASS: five existing ASGI WS handshakes from actual Android HELLO; lvbu ignores active_profile, server-locks voice, fresh CID, ready/pending exact pin and disconnect busy cleanup; 0 ASR/LLM/TTS calls, synthetic-only')
'''
subprocess.run([sys.executable,'-c',runner],cwd=stage,check=True,timeout=30)
+164
View File
@@ -0,0 +1,164 @@
#!/usr/bin/env python3
"""Build/verify one trusted Lvbu debug profile over unchanged code33 media.
No gateway mutations, voice selection, model calls or device installation.
Default profile can be built and verified separately without publishing a main APK.
"""
import argparse
import hashlib
import importlib.util
import json
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import urllib.request
import zipfile
ROOT = Path(__file__).resolve().parents[1]
TOOLS = Path('/home/ubuntu/android-build/sdk/build-tools/34.0.0')
CERT = 'b9608336bc1ed1de3269bb4594f9fe718daaa5439511c5187aa385d2b799dcf1'
BASELINE = ROOT/'artifacts/lan-voice-v0714-black-tulle-correct03-code33-arm64-debug.apk'
BASELINE_SHA = 'ba00023507e8f396f95e165f1aa744aba3a51d5072cbb8d5c2504a6159c75157'
spec = importlib.util.spec_from_file_location('character_assets', ROOT/'scripts/select-character-assets.py')
select = importlib.util.module_from_spec(spec)
spec.loader.exec_module(select)
require = select.require
def file_sha(p):
with Path(p).open('rb') as f:
return hashlib.file_digest(f, 'sha256').hexdigest()
def flags(profile, version):
pin = select.catalog()['mediaBundles']['black-correct03']['indexSha256']
return ['-PcharacterProfile='+profile, '-PactionVersionCode='+str(version),
'-PnaturalManifestSha=0a3c4918ba746019cf1df885bec66e5858a8950997dac4f64e7d37094be64dad',
'-PemotionManifestSha='+pin] + ['-P'+name+'=true' for name in (
'avatarUserNetworkActions', 'avatarUserAssetCandidate', 'avatarActionCandidate',
'avatarNatural', 'avatarMouthCandidate', 'avatarFullActionCandidate', 'avatarPlaybackClockFix',
'avatarStartupFix', 'presenceCandidate', 'faceDiagnosticsFix', 'cameraCompatibilityFix',
'cameraDirectYuv', 'cameraPreviewStream', 'cameraProbeDiagnostic')]
def build_dir(profile):
return ROOT/('app/build' if profile == 'main' else 'app/build/characters/'+profile)
def verify(apk, profile, version):
catalog = select.catalog()
role = catalog['profiles'][profile]
media = catalog['mediaBundles']['black-correct03']
selected = select.selection(ROOT/'app/src/main/assets', profile, emotion_sha=media['indexSha256'],
user_assets=True, mouth=True, startup=True)
require(file_sha(BASELINE) == BASELINE_SHA, 'code33 rollback drift')
with zipfile.ZipFile(BASELINE) as old, zipfile.ZipFile(apk) as new:
names = lambda z: {n for n in z.namelist() if n.startswith('assets/') and not n.endswith('/')}
require(names(new) == names(old) == {'assets/'+n for n in selected['files']}, 'APK selection inventory mismatch')
for name in names(new):
raw = new.read(name)
row = selected['files'][name[7:]]
require(raw == old.read(name) and len(raw) == row['bytes'] and select.digest(raw) == row['sha256'],
'APK media drift: '+name)
if name.endswith('.mp4'):
require(new.getinfo(name).compress_type == zipfile.ZIP_STORED, 'video compression drift')
for name in ('startup_poster', 'startup_black_tulle_poster'):
n = 'res/drawable-nodpi-v4/'+name+'.png'
require(new.read(n) == old.read(n), 'poster resource drift')
# Read real DEX static values rather than trusting a generated Java file.
with tempfile.TemporaryDirectory() as folder:
dex_text = ''
for name in new.namelist():
if re.fullmatch(r'classes\d*\.dex', name):
dex = Path(folder)/name
dex.write_bytes(new.read(name))
result = subprocess.check_output([str(TOOLS/'dexdump'), str(dex)]).decode('utf-8', errors='replace')
match = re.search(r"Class descriptor\s*:\s*'Lcom/gorios/lanvoice/BuildConfig;'([\s\S]*?)(?=\nClass #|\Z)", result)
if match:
dex_text = match[1]
break
require(dex_text, 'BuildConfig absent from actual DEX')
dex_values = dict(re.findall(r"name\s*:\s*'([^']+)'[^\n]*\n\s*type[^\n]*\n\s*access[^\n]*\n\s*value\s*:\s*([^\n]+)", dex_text))
expected = {'APPLICATION_ID': role['applicationId'], 'DIALOGUE_PERSONA': role['persona'],
'CHARACTER_PROFILE': profile, 'EMOTION_MANIFEST_SHA': media['indexSha256'],
'EMOTION_ASSET_ROOT': media['assetRoot'], 'STARTUP_ASSET_ROOT': media['bootstrapRoot'],
'STARTUP_MANIFEST_SHA': media['bootstrapSha256']}
for field, value in expected.items():
require(dex_values.get(field) == '"'+value+'"', 'APK DEX mismatch: '+field)
for field, value in {'AVATAR_NETWORK_ACTIONS_ALLOWED': True, 'AVATAR_USER_ASSET_CANDIDATE': True,
'PERMISSION_CONNECTION_RETENTION': role['permissionConnectionRetention']}.items():
require(dex_values.get(field) == str(value).lower(), 'APK DEX boolean mismatch: '+field)
require(dex_values.get('VERSION_CODE') == str(version) and
dex_values.get('VERSION_NAME') == '"0.7.14'+role['versionSuffix']+'"', 'APK DEX version mismatch')
badge = subprocess.check_output([str(TOOLS/'aapt'), 'dump', 'badging', str(apk)], text=True)
version_name = '0.7.14'+role['versionSuffix']
for value in ("name='"+role['applicationId']+"'", f"versionCode='{version}'",
"versionName='"+version_name+"'", "sdkVersion:'26'", "targetSdkVersion:'34'",
"application-label:'"+role['appName']+"'"):
require(value in badge, 'APK badging: '+value)
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(apk)], text=True)
require(re.search(r'Signer #1 certificate SHA-256 digest: (\w+)', cert)[1] == CERT, 'debug certificate mismatch')
xml = subprocess.check_output([str(TOOLS/'aapt'), 'dump', 'xmltree', str(apk), 'AndroidManifest.xml'], text=True)
require('com.gorios.lanvoice.MainActivity' in xml and 'com.gorios.lanvoice.CameraDiagnosticsActivity' in xml,
'actual manifest class resolution')
require('sharedUserId' not in xml, 'shared UID would break private storage isolation')
authorities = re.findall(r'android:authorities[^=]*="([^"]+)"', xml)
require(authorities and all(a.startswith(role['applicationId']+'.') for a in authorities), 'provider authority isolation')
require('android:allowBackup' in xml and ('0xffffffff' if role['allowBackup'] else '0x0') in
re.search(r'android:allowBackup[^\n]*', xml)[0], 'backup mismatch')
return {'profile': profile, 'application_id': role['applicationId'], 'persona': role['persona'],
'version_name': version_name, 'version_code': version, 'certificate_sha256': CERT,
'index_sha256': media['indexSha256'], 'assets_unchanged': len(selected['files']),
'poster_resources_unchanged': 2, 'provider_authorities': authorities,
'actual_dex_verified': True, 'device': 'not_run', 'gateway_changed': False}
def publish(apk, report):
name = f"lan-voice-v0714-lvbu-test-code{report['version_code']}-arm64-debug.apk"
artifact = ROOT/'artifacts'/name
with artifact.open('xb') as out, apk.open('rb') as src:
shutil.copyfileobj(src, out)
sha = file_sha(artifact)
checksum = (sha+' '+name+'\n').encode()
with artifact.with_suffix('.apk.sha256').open('xb') as out:
out.write(checksum)
url = 'http://192.168.31.124:8080/'+name
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
with opener.open(url, timeout=30) as r:
require(r.status == 200 and select.digest(r.read()) == sha, 'HTTP APK bytes mismatch')
with opener.open(url+'.sha256', timeout=15) as r:
require(r.status == 200 and r.read() == checksum, 'HTTP checksum mismatch')
return {**report, 'url': url, 'sha256': sha, 'bytes': artifact.stat().st_size, 'http_bytes_verified': True}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--profile', choices=['main', 'lvbu-test'], default='lvbu-test')
parser.add_argument('--version-code', type=int, default=34)
parser.add_argument('--build', action='store_true')
parser.add_argument('--publish', action='store_true')
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
require(args.version_code >= 34, 'fresh character version required')
require(not args.publish or args.profile == 'lvbu-test', 'main publication outside this task')
if args.publish:
require(not (ROOT/'artifacts'/f'lan-voice-v0714-lvbu-test-code{args.version_code}-arm64-debug.apk').exists(),
'published character version is immutable; choose a new code')
if args.build:
subprocess.run([str(ROOT/'scripts/build.sh'), ':app:assembleDebug', ':app:compileDebugAndroidTestKotlin',
*flags(args.profile, args.version_code)], check=True, cwd=ROOT)
apk = build_dir(args.profile)/'outputs/apk/debug/app-debug.apk'
report = verify(apk, args.profile, args.version_code)
if args.publish:
report = publish(apk, report)
args.output.parent.mkdir(parents=True, exist_ok=True)
with args.output.open('x') as out:
out.write(json.dumps(report, indent=2, ensure_ascii=False)+'\n')
print(json.dumps(report, indent=2, ensure_ascii=False))
if __name__ == '__main__':
main()
+4 -3
View File
@@ -6,9 +6,10 @@ import argparse, hashlib, io, json, subprocess
from pathlib import Path
from PIL import Image
ROOT=Path(__file__).resolve().parents[1]
PIN='208f703ed92bf795bfeb78a1cef89b67bed2e45da80038a56157fd1ecd4cfa93'
ASSET_ROOT='avatar/a01-black-tulle-roomy720-correct03/'
BASIC_ROOT='avatar/startup-black-tulle-correct03/'
MEDIA=json.loads((ROOT/'manifests/character-build-profiles.json').read_bytes())['mediaBundles']['black-correct03']
PIN=MEDIA['indexSha256']
ASSET_ROOT=MEDIA['assetRoot']
BASIC_ROOT=MEDIA['bootstrapRoot']
sha=lambda data:hashlib.sha256(data).hexdigest()
def derive(source):
+162
View File
@@ -0,0 +1,162 @@
#!/usr/bin/env python3
"""Select immutable runtime references, common assets and explicit legacy retention.
No generation, decoding, source modification or gateway operation. Full media admission
remains the existing production gate. Unlisted source directories never enter the APK.
"""
import argparse
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import shutil
import tempfile
ROOT = Path(__file__).resolve().parents[1]
CATALOG = ROOT / 'manifests/character-build-profiles.json'
def require(ok, reason):
if not ok:
raise ValueError(reason)
def relative(value):
require(isinstance(value, str) and value and '\\' not in value, 'invalid asset path')
path = PurePosixPath(value)
require(not path.is_absolute() and str(path) == value and all(p not in ('..', '.') for p in path.parts), 'asset path escape')
return value
def digest(data):
return hashlib.sha256(data).hexdigest()
def catalog():
data = json.loads(CATALOG.read_bytes())
require(data['schemaVersion'] == 1 and set(data['profiles']) == {'main', 'lvbu-test'}, 'unsupported profile catalog')
return data
def selection(assets, profile='main', *, emotion_sha='', user_assets=False, mouth=False, startup=False):
data = catalog()
require(profile in data['profiles'], 'unknown character profile')
role = data['profiles'][profile]
bundle_id = ('black-correct03' if user_assets else 'white-full04') if emotion_sha else None
require(role['mediaSelection'] == 'existing-build-flags' or
role['mediaSelection'] == bundle_id and mouth and startup, 'profile/media flags mismatch')
bundle = data['mediaBundles'][bundle_id] if bundle_id else None
if bundle:
require(emotion_sha == bundle['indexSha256'], 'selected exact index mismatch')
assets = Path(assets).resolve(strict=True)
files = {}
def source(name):
name = relative(name)
p = assets / name
require(all(not (assets / Path(*PurePosixPath(name).parts[:i])).is_symlink()
for i in range(1, len(PurePosixPath(name).parts) + 1)), 'asset symlink rejected')
require(p.is_file() and p.resolve().is_relative_to(assets), 'missing/escaped asset: ' + name)
return p
def add(name, sha, size=None):
p = source(name)
raw = p.read_bytes()
require(len(raw) <= 128_000_000 and digest(raw) == sha and (size is None or len(raw) == size), 'asset hash/bytes mismatch: ' + name)
row = {'sha256': sha, 'bytes': len(raw)}
require(name not in files or files[name] == row, 'conflicting asset reference')
files[name] = row
return raw
for name, row in data['commonAssets'].items():
add(name, row['sha256'], row['bytes'])
legacy = json.loads((ROOT / data['retainedInventory']).read_bytes())
require(legacy['schemaVersion'] == 1 and len(legacy['files']) == 594, 'legacy retention inventory mismatch')
for name, row in legacy['files'].items():
if not mouth and name.startswith('avatar/a01-neutral-graph-v1/runtime-04/'):
continue
add(name, row['sha256'], row['bytes'])
if bundle:
base = bundle['assetRoot']
index = json.loads(add(base + 'manifest.json', emotion_sha))
require(index['identityId'] == bundle['identityId'] and index['packId'] == bundle['packId'], 'media identity mismatch')
declared = {relative(r['path']): r for r in index['files']}
def payload(name, sha):
row = declared.get(relative(name))
require(row is not None and row['sha256'] == sha, 'index inventory reference mismatch')
return add(base + name, sha, row['bytes'])
def runtime(ref):
raw = payload(ref['path'], ref['sha256'])
body = json.loads(raw)
require(body['identityId'] == bundle['identityId'], 'runtime media identity mismatch')
parent = str(PurePosixPath(ref['path']).parent) + '/'
payload(parent + body['body']['path'], body['body']['sha256'])
for patch in body['patches']:
for level in patch['levels']:
payload(parent + level['path'], level['sha256'])
for row in index['conversationPackages']:
runtime(row['runtimeManifest'])
for edge in index['edges']:
payload(edge['clip']['path'], edge['clip']['sha256'])
if edge.get('mouthRuntimeManifest'):
runtime(edge['mouthRuntimeManifest'])
for action in index['actions']:
payload(action['clip']['path'], action['clip']['sha256'])
if startup:
boot_root = bundle['bootstrapRoot']
boot = json.loads(add(boot_root + 'manifest.json', bundle['bootstrapSha256']))
require(boot['sourceIndexSha256'] == emotion_sha and boot['body']['path'] in files and
files[boot['body']['path']]['sha256'] == boot['body']['sha256'], 'bootstrap/index/body mismatch')
poster = add(boot_root + 'poster.png', boot['posterSha256'])
resource = ROOT / 'app/src/main/res/drawable-nodpi' / (bundle['posterResource'] + '.png')
require(resource.read_bytes() == poster, 'drawable/bootstrap poster mismatch')
return {'schemaVersion': 1, 'profile': profile, 'application_id': role['applicationId'],
'persona': role['persona'], 'media_bundle': bundle_id, 'media_identity': bundle['identityId'] if bundle else 'a01',
'index_sha256': emotion_sha, 'files': files, 'file_count': len(files)}
def stage(assets, output, report):
output = Path(output)
expected = ROOT / ('app/build' if report['profile'] == 'main' else 'app/build/characters/' + report['profile']) / 'generated/packagedAssets'
require(not output.is_symlink() and output.resolve() == expected, 'staging must use isolated app build output')
output.parent.mkdir(parents=True, exist_ok=True)
temporary = Path(tempfile.mkdtemp(prefix='.character-assets-', dir=output.parent))
try:
for name, row in report['files'].items():
dest = temporary / name
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(Path(assets) / name, dest)
require(dest.stat().st_size == row['bytes'] and digest(dest.read_bytes()) == row['sha256'], 'source changed during staging')
if output.exists():
shutil.rmtree(output)
os.rename(temporary, output)
finally:
if temporary.exists():
shutil.rmtree(temporary)
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--profile', choices=['main', 'lvbu-test'], required=True)
p.add_argument('--assets', type=Path, default=ROOT / 'app/src/main/assets')
p.add_argument('--emotion-sha', default='')
for flag in ('user-assets', 'mouth', 'startup'):
p.add_argument('--' + flag, choices=['true', 'false'], default='false')
p.add_argument('--output', type=Path)
p.add_argument('--report', type=Path)
a = p.parse_args()
result = selection(a.assets, a.profile, emotion_sha=a.emotion_sha, user_assets=a.user_assets == 'true',
mouth=a.mouth == 'true', startup=a.startup == 'true')
if a.output:
stage(a.assets, a.output, result)
if a.report:
a.report.parent.mkdir(parents=True, exist_ok=True)
a.report.write_text(json.dumps(result, indent=2, ensure_ascii=False) + '\n')
print(json.dumps({k: v for k, v in result.items() if k != 'files'}, ensure_ascii=False))
if __name__ == '__main__':
main()