fix: fence voice turns and playback; add opt-in face context

This commit is contained in:
zenord
2026-10-11 20:50:11 +08:00
parent 885bb3f2db
commit 9b428fb76f
46 changed files with 2306 additions and 32 deletions
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env python3
"""Two bounded 1-token synthetic requests isolate chat-template role compatibility. No voice/chat logs."""
from pathlib import Path
import json, subprocess
REMOTE=r'''
import json,httpx
rows=[]
base={'model':'qwen3.8-27b','max_tokens':1,'temperature':0,'stream':False,'chat_template_kwargs':{'enable_thinking':False}}
with httpx.Client(timeout=15,trust_env=False) as client:
for mode,messages in [
('two_system',[{'role':'system','content':'简短回答。'},{'role':'system','content':'本轮可选摄像头观察可能误判,以用户台词为主。'},{'role':'user','content':'你好'}]),
('merged_system',[{'role':'system','content':'简短回答。本轮可选摄像头观察可能误判,以用户台词为主。'},{'role':'user','content':'你好'}])]:
response=client.post('http://127.0.0.1:8888/v1/chat/completions',json={**base,'messages':messages})
text=response.text.lower()
row={'mode':mode,'http_status':response.status_code,'body_chars':len(text),
'role_or_template_error':any(x in text for x in ('system role','system message','roles must','chat template','conversation roles','only supports','alternat'))}
# Fixed synthetic inputs only; errors are classified, never save response text.
try:
data=response.json()
row['error_type']=str(data.get('error',{}).get('type',''))[:80]
row['completion_tokens']=data.get('usage',{}).get('completion_tokens')
except Exception: pass
rows.append(row)
print(json.dumps({'results':rows}))
'''
root=Path(__file__).resolve().parents[1]
command=('cd /home/gorios-spark-2/lan-voice && if [ -x .venv/bin/python ]; then exec .venv/bin/python -; elif [ -x venv/bin/python ]; then exec venv/bin/python -; else exec python3 -; fi')
r=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5','gorios-spark-2@192.168.31.61',command],input=REMOTE.encode(),capture_output=True,timeout=45)
if r.stdout:
data=json.loads(r.stdout)
(root/'logs/voice-investigation/backend-template.json').write_text(json.dumps(data,indent=2)+'\n')
print(json.dumps(data))
if r.stderr: print('Remote stderr present; no content printed.')
raise SystemExit(r.returncode)
+4 -1
View File
@@ -27,6 +27,9 @@ with tempfile.TemporaryDirectory(prefix='lan-voice-expression-check-') as output
subprocess.run([java, '-cp', compiler, 'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler',
'-no-stdlib', '-no-reflect', '-jvm-target', '17', '-classpath', stdlib, '-d', output,
'app/src/main/java/com/gorios/lanvoice/expression/ExpressionRules.kt',
'tests/expression/ExpressionRulesCheck.kt'], check=True)
'app/src/main/java/com/gorios/lanvoice/expression/FaceCueRules.kt',
'tests/expression/ExpressionRulesCheck.kt',
'tests/expression/FaceCueRulesCheck.kt'], check=True)
subprocess.run([java, '-cp', output + ':' + stdlib, 'ExpressionRulesCheckKt'], check=True)
subprocess.run([java, '-cp', output + ':' + stdlib, 'FaceCueRulesCheckKt'], check=True)
PY
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env python3
"""Real production coordinator/playback with deterministic device/transport doubles. No sockets."""
from pathlib import Path
import subprocess
import tempfile
ROOT = Path(__file__).resolve().parents[1]
CACHE = Path('/home/ubuntu/android-build/gradle-home/caches/modules-2/files-2.1')
FALLBACK = Path('/tmp/lanvoice-gradle-home/caches/modules-2/files-2.1')
JAVA = '/home/ubuntu/android-build/jdk/temurin-17.0.20.1/bin/java'
def jar(group, artifact, version):
for base in (CACHE, FALLBACK):
result = list((base/group/artifact/version).glob('*/*.jar'))
if result: return str(result[0])
raise RuntimeError(f'Missing cached {group}:{artifact}:{version}')
stdlib = jar('org.jetbrains.kotlin','kotlin-stdlib','2.0.20')
compiler = ':'.join([jar('org.jetbrains.kotlin','kotlin-compiler-embeddable','2.0.20'), stdlib,
jar('org.jetbrains.kotlin','kotlin-reflect','1.6.10'), jar('org.jetbrains.kotlin','kotlin-script-runtime','2.0.20'),
jar('org.jetbrains.intellij.deps','trove4j','1.0.20200330'), jar('org.jetbrains','annotations','23.0.0'),
str(next((CACHE/'org.jetbrains.kotlinx/kotlinx-coroutines-core-jvm').glob('*/*/*.jar')))])
cp = ':'.join([stdlib, jar('com.squareup.okhttp3','okhttp','4.12.0'), jar('com.squareup.okio','okio-jvm','3.6.0')])
source = ROOT/'app/src/main/java/com/gorios/lanvoice'
suites = [
('session','ConnectionCheckKt', [source/'audio/VoiceSession.kt', source/'net/DialogueClient.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt']),
('playback','PlaybackCheckKt', [source/'audio/AudioPlayback.kt']),
('capture','CaptureCheckKt', [source/'audio/AudioCapture.kt']),
('protocol','ProtocolCheckKt', [source/'net/DialogueProtocol.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt']),
]
for name, main, real in suites:
with tempfile.TemporaryDirectory(prefix=f'lan-voice-{name}-') as out:
files = list((ROOT/'tests'/name).glob('*.kt')) + real
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)
+209
View File
@@ -0,0 +1,209 @@
#!/usr/bin/env python3
"""Run in this workspace's ordinary shell. Read-only remote inspection, no credentials/log bodies saved."""
import io
import json
import os
import re
import ssl
import subprocess
import sys
import tarfile
import urllib.error
import urllib.request
from pathlib import Path
REMOTE_ROOT = Path('/home/gorios-spark-2/lan-voice')
HOST = 'gorios-spark-2@192.168.31.61'
SERVICE = re.compile(r'lan.?voice|gateway|stt|tts|qwen|vllm|asr|cosy', re.I)
def command(args, cwd=None):
try:
result = subprocess.run(args, cwd=cwd, capture_output=True, timeout=20)
return result.returncode, result.stdout.decode(errors='replace'), result.stderr.decode(errors='replace')
except (OSError, subprocess.TimeoutExpired) as error:
return -1, '', type(error).__name__
def log_metadata(entry):
if not isinstance(entry, dict):
entry = {'message': str(entry)}
msg = str(entry.get('msg', entry.get('message', entry.get('MESSAGE', ''))))
# Do not print arbitrary messages, recognitions, prompts, completions or exception bodies.
prefixes = ('onEvent', 'acceptTurn', 'ABORT', 'LISTEN', 'AudioRecord', 'startCapture',
'capture start', 'connection', 'finish', 'ws', 'auth', 'hello', 'health',
'state=', 'downlink', 'voice button', 'microphone', 'activity', 'session',
'foreground', 'app_launch', 'send_report')
event = next((p for p in prefixes if msg.startswith(p)), 'redacted')
for phase in ('capture.end', 'llm.finished', 'tts.start', 'tts.stop', 'playback.drained',
'ws open', 'hello received', 'hello sent', 'auth ok', 'ws closed', 'ws failure',
'initialization ok', 'startRecording ok'):
if phase in msg:
event = phase
break
result = {'event': event}
for key in ('ts', 'timestamp_ms', '__REALTIME_TIMESTAMP'):
if str(entry.get(key, '')).isdigit():
result[key] = int(entry[key])
tag = entry.get('tag')
if tag in ('connect', 'ws', 'auth', 'audio', 'error'):
result['tag'] = tag
numeric = r'turn_id|turn|oldTurn|currentTurn|nextTurn|blockedTurn|nextBlocked|id|seq|epoch|retired|retiredNow|frames|bytes|samples|duration_ms|elapsed_ms|latency_ms|rtf|status|code'
for match in re.finditer(r'\b(' + numeric + r')=(-?\d+(?:\.\d+)?|null)\b', msg):
result[match[1]] = match[2]
for key in ('kind', 'state', 'phase', 'reason', 'active', 'capturing', 'hasTurn',
'accepted', 'listenReset', 'released', 'permission', 'changingConfig'):
match = re.search(r'\b' + key + r'=([A-Za-z_][A-Za-z_0-9:.-]{0,70}|true|false|null)\b', msg)
if match:
# Only structural identifiers; no arbitrary quoted/free-text values.
result[key] = match[1]
statuses = re.findall(r'\b(?:CONNECTED|DISCONNECTED|CONNECTING|BUSY)\b', msg)
if statuses:
result['connection_states'] = statuses
code = re.search(r'\b(?:closed:|HTTP)\s*(\d{3,4})\b', msg)
if code:
result['http_or_close_code'] = int(code[1])
result['exception_types'] = sorted(set(re.findall(r'\b[A-Z][A-Za-z]*(?:Exception|Error)\b', msg)))
return result
def items(value, keys):
if isinstance(value, list):
return value
if isinstance(value, dict):
for key in keys:
if isinstance(value.get(key), list):
return value[key]
return [value] if isinstance(value, dict) else []
def remote_evidence():
ctx = ssl.create_default_context(cafile=str(REMOTE_ROOT / '.runtime/gateway-cert.pem'))
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), urllib.request.HTTPSHandler(context=ctx))
result = {}
for endpoint in ('health', 'debug/report', 'debug/log'):
try:
with opener.open('https://192.168.31.61:5011/' + endpoint, timeout=5) as response:
data = response.read(2_000_001)
if len(data) > 2_000_000:
raise ValueError('response exceeds bounded inspection size')
data = json.loads(data)
if endpoint == 'debug/report':
reports = []
for wrapped in items(data, ('reports', 'items', 'entries')):
if not isinstance(wrapped, dict):
continue
report = wrapped.get('report', wrapped)
if isinstance(report, dict) and report.get('logs'):
reports.append(report)
report = max(reports, key=lambda r: float(r.get('timestamp', 0)), default=None)
if report:
summary = {key: report.get(key) for key in ('timestamp', 'app_version', 'device',
'android_api', 'connection', 'voice_active', 'phase', 'aec')}
summary['logs'] = [log_metadata(e) for e in report['logs'][-500:]]
result[endpoint] = summary
else:
result[endpoint] = {'nonempty_report_found': False, 'response_keys': list(data)[:20] if isinstance(data, dict) else []}
elif endpoint == 'debug/log':
result[endpoint] = [log_metadata(e) for e in items(data, ('logs', 'items', 'entries'))[-100:]]
else:
result[endpoint] = {key: data.get(key) for key in ('status', 'version', 'ok')}
except Exception as error:
result[endpoint] = {'error_type': type(error).__name__, 'http_status': getattr(error, 'code', None)}
code, status, _ = command(['docker', 'ps', '--format', '{{.Names}}\t{{.Status}}'])
result['containers_status'] = [line for line in status.splitlines() if SERVICE.search(line)]
result['docker_exit'] = code
result['container_logs'] = {}
for line in result['containers_status']:
name = line.split('\t')[0]
_, out, err = command(['docker', 'logs', '--since', '20m', '--tail', '150', name])
result['container_logs'][name] = [log_metadata(s) for s in (out + err).splitlines()]
result['systemd'] = []
result['journal'] = {}
for user in (False, True):
prefix = ['systemctl'] + (['--user'] if user else [])
_, out, _ = command(prefix + ['list-units', '--all', '--type=service', '--no-pager', '--no-legend', '--plain'])
for line in out.splitlines():
if not SERVICE.search(line):
continue
result['systemd'].append({'user': user, 'status': line.strip()})
unit = line.strip().split()[0]
_, journal, _ = command(['journalctl'] + (['--user'] if user else []) +
['-u', unit, '--since', '-20min', '-n', '400', '--no-pager', '-o', 'json'])
result['journal'][unit] = []
for record in journal.splitlines():
try:
result['journal'][unit].append(log_metadata(json.loads(record)))
except ValueError:
pass
print(json.dumps(result, ensure_ascii=False, indent=2))
def remote_sources():
# Deployment directories may have no tracked files. Inspect live source files,
# with explicit exclusions, instead of assuming this is a populated Git checkout.
paths = []
excluded = {'models', 'data', 'assets', 'voices', 'lorebooks', 'node_modules',
'venv', '__pycache__', 'logs', 'artifacts', 'build', 'dist'}
for base, directories, files in os.walk(REMOTE_ROOT, followlinks=False):
directories[:] = [d for d in directories if not d.startswith('.') and d not in excluded
and not (Path(base) / d).is_symlink()]
for name in files:
if Path(name).suffix in ('.py', '.toml') or name == 'AGENTS.md':
paths.append((Path(base) / name).relative_to(REMOTE_ROOT))
if not paths:
raise RuntimeError('no live gateway Python sources found')
total = 0
with tarfile.open(fileobj=sys.stdout.buffer, mode='w|gz') as archive:
for relative in sorted(paths):
path = Path(relative)
if path.is_absolute() or '..' in path.parts or path.suffix not in ('.py', '.toml') and path.name != 'AGENTS.md':
continue
if any(part.startswith('.') or part in ('models', 'data', 'assets', 'voices', 'lorebooks') for part in path.parts):
continue
source = REMOTE_ROOT / path
if source.is_symlink() or not source.is_file() or source.stat().st_size > 1_000_000:
continue
total += source.stat().st_size
if total > 12_000_000:
raise RuntimeError('gateway source snapshot exceeds 12MB')
archive.add(source, arcname=relative, recursive=False)
def local():
root = Path(__file__).resolve().parents[1]
output = root / 'logs/voice-investigation'
output.mkdir(parents=True, exist_ok=True)
source = Path(__file__).read_bytes()
ssh = ['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=5', HOST, 'python3', '-']
for mode in ('--remote-evidence', '--remote-sources'):
result = subprocess.run(ssh + [mode], input=source, capture_output=True, timeout=180)
if result.returncode:
# SSH diagnostics contain no report, chat or credential bodies.
print(result.stderr.decode(errors='replace')[-1000:], file=sys.stderr)
raise SystemExit(result.returncode)
if mode == '--remote-evidence':
summary = json.loads(result.stdout)
(output / 'evidence.json').write_text(json.dumps(summary, ensure_ascii=False, indent=2) + '\n')
else:
destination = output / 'backend-source'
destination.mkdir(exist_ok=True)
with tarfile.open(fileobj=io.BytesIO(result.stdout), mode='r:gz') as archive:
for member in archive:
path = Path(member.name)
if not member.isfile() or path.is_absolute() or '..' in path.parts:
raise RuntimeError('unsafe source archive entry')
target = destination / path
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(archive.extractfile(member).read())
print('Saved redacted evidence and gateway sources to logs/voice-investigation/ (git ignored).')
if __name__ == '__main__':
if '--remote-evidence' in sys.argv:
remote_evidence()
elif '--remote-sources' in sys.argv:
remote_sources()
else:
local()
+130
View File
@@ -0,0 +1,130 @@
#!/usr/bin/env python3
"""Controlled gateway-only deployment from this workspace; ordinary shell required for SSH.
Default stages/tests only. --apply backs up and restarts ONLY lan-voice-gateway.service.
"""
import argparse
import base64
import hashlib
import json
from pathlib import Path
import subprocess
REMOTE = r'''
import base64, hashlib, io, json, os, shutil, ssl, subprocess, sys, tempfile, time, unittest, urllib.request
from pathlib import Path
ROOT = Path('/home/gorios-spark-2/lan-voice')
UNIT = 'lan-voice-gateway.service'
def health():
ctx = ssl.create_default_context(cafile=str(ROOT/'.runtime/gateway-cert.pem'))
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx))
with opener.open('https://192.168.31.61:5011/health',timeout=3) as r: return json.load(r)
def decode(name): return base64.b64decode(bundle[name])
def atomic(path, content):
tmp=path.with_name(path.name+'.v040.tmp')
tmp.write_bytes(content); tmp.chmod(0o600); tmp.replace(path)
original=(ROOT/'gateway.py').read_bytes()
base_source = original
if hashlib.sha256(original).hexdigest()!=base_hash:
# A follow-up fix may replace only the exact version deployed by this script.
if not previous or hashlib.sha256(original).hexdigest()!=previous.get('gateway_sha256'):
raise RuntimeError('live_gateway_changed_refusing_patch')
backup_source = Path(previous['backup']).resolve()
if not backup_source.is_relative_to((ROOT/'.runtime/backups').resolve()):
raise RuntimeError('invalid_backup_path')
base_source = (backup_source/'gateway.py').read_bytes()
if hashlib.sha256(base_source).hexdigest()!=base_hash:
# A second follow-up backup contains a patched version. The immutable initial
# base snapshot is saved separately by the workspace deployment record.
initial = Path(previous.get('initial_backup', previous['backup'])).resolve()
if not initial.is_relative_to((ROOT/'.runtime/backups').resolve()): raise RuntimeError('invalid_backup_path')
base_source = (initial/'gateway.py').read_bytes()
if hashlib.sha256(base_source).hexdigest()!=base_hash: raise RuntimeError('base_backup_mismatch')
if apply and health().get('busy'): raise RuntimeError('gateway_busy_no_restart')
with tempfile.TemporaryDirectory(prefix='voice-v040-stage-') as folder:
stage=Path(folder)
for path in ROOT.glob('*.py'): shutil.copy2(path,stage/path.name)
shutil.copytree(ROOT/'tests',stage/'tests',ignore=shutil.ignore_patterns('__pycache__'))
for name in ('web','personas'):
if (ROOT/name).exists(): (stage/name).symlink_to(ROOT/name,target_is_directory=True)
(stage/'.runtime').mkdir()
if (ROOT/'.runtime/personas').exists(): (stage/'.runtime/personas').symlink_to(ROOT/'.runtime/personas',target_is_directory=True)
# Only gateway.py is patched. The other production file is enum/TTL validation.
(stage/'gateway.py').write_bytes(base_source)
(stage/'gateway.patch').write_bytes(decode('gateway.patch'))
subprocess.run(['patch','--batch','--fuzz=0','-p0','-i','gateway.patch'],cwd=stage,check=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
(stage/'face_context.py').write_bytes(decode('face_context.py'))
for name in ('test_face_context.py','test_gateway_reply_face.py'): (stage/'tests'/name).write_bytes(decode(name))
runner = """
import sys,unittest
sys.path[:0]=['.','tests']
modules=['test_gateway','test_continuity','test_history','test_v08','test_debug','test_segmentation','test_guests','test_personas','test_face_context','test_gateway_reply_face']
suite=unittest.TestSuite(unittest.defaultTestLoader.loadTestsFromName(name) for name in modules)
result=unittest.TextTestRunner(verbosity=2).run(suite)
raise SystemExit(not result.wasSuccessful())
"""
result=subprocess.run([sys.executable,'-c',runner],cwd=stage,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=90)
# Synthetic tests only. Never attach runtime reports, tokens, prompts or microphone audio.
if result.returncode:
print(json.dumps({'status':'tests_failed','test_output':result.stdout.decode(errors='replace')}))
raise SystemExit(1)
summary={'status':'tests_passed','test_output':result.stdout.decode(errors='replace'),'applied':False}
patched=(stage/'gateway.py').read_bytes()
if apply:
# Recheck after staged tests: no overwriting concurrent edits or interrupting an active user.
if (ROOT/'gateway.py').read_bytes()!=original: raise RuntimeError('gateway_changed_during_tests')
if health().get('busy'): raise RuntimeError('gateway_busy_after_tests_no_restart')
backup=ROOT/'.runtime/backups'/time.strftime('voice-v040-%Y%m%d-%H%M%S')
backup.mkdir(parents=True,mode=0o700)
existed={name:(ROOT/name).exists() for name in ('gateway.py','face_context.py')}
for name,present in existed.items():
if present: shutil.copy2(ROOT/name,backup/name)
(backup/'manifest.json').write_text(json.dumps(existed)); (backup/'manifest.json').chmod(0o600)
try:
atomic(ROOT/'face_context.py',decode('face_context.py'))
atomic(ROOT/'gateway.py',patched)
subprocess.run(['systemctl','--user','restart',UNIT],check=True,timeout=30,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
healthy=False
for attempt in range(15):
try:
if health().get('status')=='ok': healthy=True;break
except Exception: pass
time.sleep(1)
if not healthy: raise RuntimeError('gateway_health_failed')
except BaseException:
for name,present in existed.items():
if present: atomic(ROOT/name,(backup/name).read_bytes())
elif (ROOT/name).exists(): (ROOT/name).unlink()
subprocess.run(['systemctl','--user','restart',UNIT],timeout=30,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
raise
summary.update(status='deployed',applied=True,initial_backup=previous.get('initial_backup', previous['backup']) if previous else str(backup),backup=str(backup),gateway_sha256=hashlib.sha256(patched).hexdigest(),face_context_sha256=hashlib.sha256(decode('face_context.py')).hexdigest(),health='ok')
print(json.dumps(summary))
'''
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--apply',action='store_true')
args=parser.parse_args()
root=Path(__file__).resolve().parents[1]
bundle={name:base64.b64encode((root/'backend'/name).read_bytes()).decode() for name in
('gateway.patch','face_context.py','test_face_context.py','test_gateway_reply_face.py')}
record=root/'logs/voice-investigation/gateway-deploy.json'
previous=json.loads(record.read_text()) if record.exists() else None
payload='previous='+repr(previous)+'\n'+'bundle='+repr(bundle)+'\nbase_hash='+repr((root/'backend/gateway-base.sha256').read_text().strip())+'\napply='+repr(args.apply)+'\n'+REMOTE
remote=('cd /home/gorios-spark-2/lan-voice && '
'if [ -x .venv/bin/python ]; then exec .venv/bin/python -; '
'elif [ -x venv/bin/python ]; then exec venv/bin/python -; else exec python3 -; fi')
result=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5','gorios-spark-2@192.168.31.61',remote],input=payload.encode(),capture_output=True,timeout=180)
directory=root/'logs/voice-investigation';directory.mkdir(parents=True,exist_ok=True)
if result.stdout:
data=json.loads(result.stdout)
if args.apply and data.get('applied') and record.exists():
(directory/'gateway-deploy-previous.json').write_bytes(record.read_bytes())
name = ('gateway-deploy.json' if data.get('applied') else 'gateway-apply-failed.json') if args.apply else 'gateway-staged-tests.json'
(directory/name).write_text(json.dumps(data,ensure_ascii=False,indent=2)+'\n')
print(f'Gateway {data["status"]}; details saved under logs/voice-investigation/')
if result.stderr: print('Remote execution stderr present; no raw payload printed.')
raise SystemExit(result.returncode)
if __name__=='__main__': main()
+67
View File
@@ -0,0 +1,67 @@
#!/bin/bash
# Approved author/remote; run in ordinary workspace shell because agent .git is read-only.
set -euo pipefail
cd "$(dirname "$0")/.."
python3 - <<'PY'
from pathlib import Path
import hashlib,json
root=Path.cwd(); logs=root/'logs/voice-investigation'
release=json.loads((logs/'release.json').read_text())
assert release['version_name']=='0.4.0' and release['version_code']==7
assert hashlib.sha256((root/release['apk']).read_bytes()).hexdigest()==release['sha256']
probe=json.loads((logs/'probe-after.json').read_text())
assert probe['status']=='passed' and probe['llm_chars']>0 and probe['downlink_bytes']>0 and probe['drained_ack']
assert probe['backend_metrics']['face_cue_used'] and probe['invalid_face_control_survived']
deploy=json.loads((logs/'gateway-deploy.json').read_text())
assert deploy['status']=='deployed' and 'Ran 43 tests' in deploy['test_output'] and '\nOK\n' in deploy['test_output']
checks=(root/'logs/reply-regressions.log').read_text()
assert 'PASS: typed enum-only face serialization' in checks and 'Traceback' not in checks and 'Exception in thread' not in checks
PY
if [ "$(git remote get-url origin)" != 'git@git.oops.school:heihei/baji-vc.git' ]; then
echo 'Unexpected origin: refusing commit/push' >&2
exit 1
fi
git diff --check
git add -- .gitignore app/build.gradle \
app/src/main/java/com/gorios/lanvoice/MainActivity.kt \
app/src/main/java/com/gorios/lanvoice/audio/AudioCapture.kt \
app/src/main/java/com/gorios/lanvoice/audio/AudioPlayback.kt \
app/src/main/java/com/gorios/lanvoice/audio/AudioOutputGate.kt \
app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt \
app/src/main/java/com/gorios/lanvoice/net/DialogueClient.kt \
app/src/main/java/com/gorios/lanvoice/net/DialogueProtocol.kt \
app/src/main/java/com/gorios/lanvoice/expression/ExpressionController.kt \
app/src/main/java/com/gorios/lanvoice/expression/ExpressionUi.kt \
app/src/main/java/com/gorios/lanvoice/expression/FaceCueRules.kt \
docs/PLAN.md docs/EXPRESSION.md docs/VOICE_REPAIR_040.md \
backend/face_context.py backend/gateway.patch backend/gateway-base.sha256 \
backend/test_face_context.py backend/test_gateway_reply_face.py \
scripts/collect-voice-evidence.py scripts/probe-reply.py scripts/check-backend-template.py \
scripts/deploy-gateway.py scripts/rollback-gateway.py scripts/package-release.sh \
scripts/check-expression-rules.sh scripts/check-reply-regressions.py scripts/finalize-release.sh \
tests/capture tests/playback tests/session tests/protocol tests/expression/FaceCueRulesCheck.kt
python3 - <<'PY'
import subprocess
paths=subprocess.check_output(['git','diff','--cached','--name-only'],text=True).splitlines()
assert paths, 'Nothing staged'
for path in paths:
assert not path.startswith(('logs/','artifacts/','.runtime/','.aws/','.codex/')),path
assert not path.endswith(('.pem','.key','.keystore','.apk','.pyc')),path
content=subprocess.check_output(['git','diff','--cached','--no-ext-diff','--unified=0'],text=True)
assert not any(('-----BEGIN ' + kind + '-----') in content for kind in ('PRIVATE KEY','OPENSSH PRIVATE KEY','RSA PRIVATE KEY'))
print(f'Reviewed {len(paths)} staged source/test/doc files; no reports/APKs/keys staged')
PY
git diff --cached --check
git -c user.name=zenord -c user.email=zenord@email.com commit -m 'fix: fence voice turns and playback; add opt-in face context'
git push origin HEAD
python3 - <<'PY'
import json,subprocess
from pathlib import Path
commit=subprocess.check_output(['git','rev-parse','HEAD'],text=True).strip()
branch=subprocess.check_output(['git','symbolic-ref','--short','HEAD'],text=True).strip()
remote=subprocess.check_output(['git','ls-remote','origin','refs/heads/'+branch],text=True).split()[0]
assert remote==commit, 'remote HEAD verification failed'
result={'commit':commit,'branch':branch,'remote':'git@git.oops.school:heihei/baji-vc.git','push':'verified'}
Path('logs/voice-investigation/git-release.json').write_text(json.dumps(result,indent=2)+'\n')
print(json.dumps(result,indent=2))
PY
+46
View File
@@ -0,0 +1,46 @@
#!/bin/bash
# Ordinary workspace shell: normal build entry, true package/signature checks, archive + HTTP check.
set -euo pipefail
cd "$(dirname "$0")/.."
./scripts/build.sh
source /home/ubuntu/android-build/env.sh
TOOLS=/home/ubuntu/android-build/sdk/build-tools/34.0.0
APK=app/build/outputs/apk/debug/app-debug.apk
mkdir -p logs/voice-investigation artifacts
"$TOOLS/aapt" dump badging "$APK" > logs/voice-investigation/release-badging.txt
"$TOOLS/apksigner" verify --verbose --print-certs "$APK" > logs/voice-investigation/release-signature.txt
python3 - <<'PY'
import hashlib,json,re,shutil,urllib.request,subprocess
from pathlib import Path
root=Path.cwd()
badging=(root/'logs/voice-investigation/release-badging.txt').read_text()
assert "name='com.gorios.lanvoice'" in badging
assert "versionCode='7'" in badging and "versionName='0.4.0'" in badging
native=re.search(r'^native-code: (.+)$',badging,re.M)
assert native and native[1].strip()=="'arm64-v8a'", 'unexpected ABI'
source=root/'app/build/outputs/apk/debug/app-debug.apk'
previous=root/'artifacts/lan-voice-v033-arm64-debug.apk'
if previous.exists():
old=subprocess.check_output(['/home/ubuntu/android-build/sdk/build-tools/34.0.0/apksigner','verify','--print-certs',str(previous)],text=True)
new=(root/'logs/voice-investigation/release-signature.txt').read_text()
pattern=r'Signer #1 certificate SHA-256 digest: (\w+)'
assert re.search(pattern,old)[1]==re.search(pattern,new)[1], 'signing certificate changed: update install would fail'
artifact=root/'artifacts/lan-voice-v040-arm64-debug.apk'
shutil.copy2(source,artifact)
digest=hashlib.sha256(artifact.read_bytes()).hexdigest()
artifact.with_suffix('.apk.sha256').write_text(f'{digest} {artifact.name}\n')
# Existing HTTP server root can be the workspace or artifacts; check the actual bytes.
base='http://192.168.31.124:8080/'
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}))
url=None
for path in ('artifacts/'+artifact.name, artifact.name):
try:
with opener.open(base+path,timeout=15) as response:
downloaded=hashlib.sha256(response.read()).hexdigest()
if downloaded==digest: url=base+path;break
except Exception: pass
assert url is not None, 'APK built, but existing HTTP server did not serve matching bytes'
result=dict(version_name='0.4.0',version_code=7,apk=str(artifact.relative_to(root)),bytes=artifact.stat().st_size,sha256=digest,url=url,signature='apksigner_verified',real_phone_playback='not_tested')
(root/'logs/voice-investigation/release.json').write_text(json.dumps(result,indent=2)+'\n')
print(json.dumps(result,indent=2))
PY
+176
View File
@@ -0,0 +1,176 @@
#!/usr/bin/env python3
"""One bounded public-sample round against live gateway. Run only in the workspace ordinary shell."""
import json
import subprocess
from pathlib import Path
PROBE = r'''
import asyncio, contextlib, io, json, math, re, ssl, struct, sys, time, urllib.request, wave
from pathlib import Path
ROOT = Path('/home/gorios-spark-2/lan-voice')
sys.path.insert(0, str(ROOT))
summary = {'test': 'one_public_sample_round', 'real_phone_playback': 'not_tested'}
sanitize = helper['log_metadata']
summary['tts_metadata'] = []
for path in sorted((ROOT/'.runtime/tts-debug').glob('*/metadata.json'), key=lambda p:p.stat().st_mtime, reverse=True)[:20]:
try:
if path.stat().st_size > 1_000_000: continue
data = json.loads(path.read_text())
row = {key:data.get(key) for key in ('turn_id','created','status','samples','seconds','peak','rms','truncated','writer_error')}
row['tts_requests'] = len(data.get('tts_requests',[]))
row['tts_input_chars'] = [len(r.get('input','')) for r in data.get('tts_requests',[])]
metrics = data.get('metrics',{})
row['metrics'] = {key:metrics.get(key) for key in ('stt_ms','llm_first_body_ms','llm_finished_ms','tts_first_pcm_ms','capture_to_first_pcm_ms','total_ms','tts_request_count','face_cue_used')}
row['segments'] = [{k:s.get(k) for k in ('audio_seconds','total_ms','rtf','pcm_chunks','first_pcm_ms','first_voiced_ms','max_chunk_interarrival_ms')} for s in metrics.get('tts_segments',[])]
summary['tts_metadata'].append(row)
except Exception as error:
summary['tts_metadata'].append({'error_type':type(error).__name__})
summary['runtime_logs'] = {}
logpaths = list((ROOT/'.runtime').glob('*.log')) + list((ROOT/'logs').glob('*.log'))
unit = Path.home()/'.config/systemd/user/lan-voice-gateway.service'
if unit.exists():
for line in unit.read_text().splitlines():
if line.startswith(('StandardOutput=append:','StandardError=append:','StandardOutput=file:','StandardError=file:')):
logpaths.append(Path(line.split(':',1)[1]))
for path in dict.fromkeys(logpaths):
if not path.is_file(): continue
with path.open('rb') as stream:
stream.seek(max(0,path.stat().st_size-131072))
lines=stream.read().decode(errors='replace').splitlines()[-500:]
rows=[]
for line in lines:
row=sanitize(line)
trace=re.search(r'File "([^"\n]+)", line (\d+), in ([A-Za-z_0-9<>]+)',line)
if trace: row['trace']={'file':trace[1], 'line':int(trace[2]), 'function':trace[3]}
http=re.search(r'\b(POST|GET) (/v1/(?:chat/completions|audio/speech|audio/transcriptions))[^\n]*?\b([1-5]\d\d)\b',line)
if http: row['backend_http']={'method':http[1],'path':http[2],'status':int(http[3])}
if row.get('trace') or row.get('exception_types') or row.get('backend_http') or row['event']!='redacted': rows.append(row)
summary['runtime_logs'][str(path)] = rows
async def probe():
import websockets
from protocol import pack, unpack
ctx=ssl.create_default_context(cafile=str(ROOT/'.runtime/gateway-cert.pem'))
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx))
with opener.open('https://192.168.31.61:5011/health',timeout=5) as response: health=json.load(response)
if health.get('busy'): raise RuntimeError('gateway_busy_probe_not_started')
sample=ROOT/'tmp/public_tts_16k.wav'
with wave.open(str(sample),'rb') as audio:
assert (audio.getframerate(),audio.getnchannels(),audio.getsampwidth())==(16000,1,2)
assert audio.getnframes() <= 16000*15, 'public sample exceeds 15s bound'
pcm=audio.readframes(audio.getnframes())
summary['input_samples']=len(pcm)//2
started=time.perf_counter()
summary.update(events={},llm_chars=0,llm_deltas=0,downlink_frames=0,downlink_bytes=0,pcm_peak=0,pcm_square=0,drained_ack=False)
def stamp(name): summary.setdefault(name,round((time.perf_counter()-started)*1000,2))
kwargs=dict(ssl=ctx,origin='https://192.168.31.61:5011',open_timeout=5,close_timeout=2)
# The deployed websockets version accepts proxy=None; avoid any system proxy.
if 'proxy' in __import__('inspect').signature(websockets.connect).parameters: kwargs['proxy']=None
async with websockets.connect('wss://192.168.31.61:5011/ws/dialogue',**kwargs) as ws:
auth=json.loads(await asyncio.wait_for(ws.recv(),5)); assert auth['type']=='auth' and auth.get('state')=='ok'
await ws.send(json.dumps({'type':'hello','codec':'pcm16','sample_rate':16000,'frame_duration':20,'persona':'default','voice_mode':'continuous_voice','tts_debug':False}))
while True:
event=json.loads(await asyncio.wait_for(ws.recv(),5))
if event['type']=='hello': break
summary['face_context_supported']=event.get('context_face_cue_version')
if after: assert summary['face_context_supported']==1, 'face protocol not advertised'
await ws.send(json.dumps({'type':'listen','mode':'manual','state':'start','barge_in':False}))
while True:
event=json.loads(await asyncio.wait_for(ws.recv(),5))
if event['type']=='listen' and event.get('state')=='start': turn=event['turn_id']; break
for offset in range(0,len(pcm),640):
chunk=pcm[offset:offset+640]
if len(chunk)<640: chunk += bytes(640-len(chunk))
await ws.send(pack(1,turn,offset//640+1,chunk))
await asyncio.sleep(.02)
if after:
cue={'type':'context.face_cue','version':1,'turn_id':turn,'valid':True,'cue':'smiling','intensity':.8,'duration_ms':900,'age_ms':0}
# Explicit synthetic observation: never represents the user's face.
await ws.send(json.dumps(cue))
summary['synthetic_face_context_sent']=True
await ws.send(json.dumps({'type':'listen','mode':'manual','state':'stop'}))
stamp('input_end_ms')
last_seq=0; stopped=False
async with asyncio.timeout(60):
while True:
raw=await ws.recv()
if isinstance(raw,bytes):
actual,seq,audio=unpack(raw,2)
assert actual==turn and seq==last_seq+1 and 0<len(audio)<=1920
last_seq=seq; summary['downlink_frames']+=1;summary['downlink_bytes']+=len(audio)
samples=struct.unpack('<'+'h'*(len(audio)//2),audio)
summary['pcm_peak']=max(summary['pcm_peak'],max(map(abs,samples),default=0))
summary['pcm_square']+=sum(x*x for x in samples)
stamp('first_pcm_ms')
continue
event=json.loads(raw);kind=event.get('type','unknown')
summary['events'][kind]=summary['events'].get(kind,0)+1
if kind=='abort': turn=event['turn_id'];last_seq=0
if kind=='capture.end': stamp('capture_end_ms');summary['turn']=turn
if kind=='stt': summary['stt_chars']=len(event.get('text',''));stamp('stt_ms')
if kind=='llm':
summary['llm_chars']+=len(event.get('text',''));summary['llm_deltas']+=1;stamp('first_llm_ms')
if kind=='llm.finished': stamp('llm_finished_ms')
if kind=='voice.metrics': summary['tts_requests']=event.get('tts_request_count')
if kind=='metrics':
values=event.get('values',{})
summary['backend_metrics']={key:values.get(key) for key in ('stt_ms','llm_finished_ms','tts_first_pcm_ms','total_ms','tts_request_count','face_cue_used')}
summary['segments']=[{key:s.get(key) for key in ('audio_seconds','total_ms','rtf','max_chunk_interarrival_ms')} for s in values.get('tts_segments',[])]
if kind=='error': raise RuntimeError('gateway_backend_error')
if kind=='tts' and event.get('state')=='stop':
stopped=True; stamp('tts_stop_ms')
assert summary.get('stt_chars',0)>0 and summary['llm_chars']>0 and summary['downlink_frames']>0
# Model native drain is tested separately; this probe only confirms protocol ack.
await ws.send(json.dumps({'type':'playback.drained','turn_id':turn}))
if stopped and kind=='listen' and event.get('state')=='resumed':
summary['drained_ack']=True;stamp('drained_ack_ms');break
if after:
assert summary['backend_metrics'].get('face_cue_used') is True, 'ASR-time face snapshot missing'
await ws.send(json.dumps({'type':'context.face_cue','version':1,'turn_id':turn,'valid':False,'cue':'unknown','intensity':0,'duration_ms':0,'age_ms':0}))
await ws.send(json.dumps({'type':'context.face_cue','version':1,'turn_id':turn,'valid':True,'cue':'gaze_left','intensity':.8,'duration_ms':900,'age_ms':0}))
# A whitelisted control with invalid fields clears context; it must not close 1008.
await ws.send(json.dumps({'type':'ping'}))
while json.loads(await asyncio.wait_for(ws.recv(),5)).get('type')!='pong': pass
summary['invalid_face_control_survived']=True
assert summary['pcm_peak']>327, 'no voiced PCM amplitude'
summary['pcm_rms']=round(math.sqrt(summary.pop('pcm_square')/(summary['downlink_bytes']//2)),2)
summary['status']='passed'
try:
asyncio.run(probe())
except Exception as error:
summary['status']='failed'; summary['error_type']=type(error).__name__
summary['close_code']=getattr(error,'code',None)
summary.pop('pcm_square',None)
print(json.dumps(summary,ensure_ascii=False,indent=2))
raise SystemExit(0 if summary['status']=='passed' else 1)
'''
def main():
root = Path(__file__).resolve().parents[1]
collector = (root / 'scripts/collect-voice-evidence.py').read_text()
payload = "after=" + repr('--after' in __import__('sys').argv) + "\nhelper={'__name__':'collector_library'}\nexec(" + repr(collector) + ",helper)\n" + PROBE
# Use the existing gateway venv if present; never install packages or load a new model.
remote = ('cd /home/gorios-spark-2/lan-voice && '
'if [ -x .venv/bin/python ]; then exec .venv/bin/python -; '
'elif [ -x venv/bin/python ]; then exec venv/bin/python -; else exec python3 -; fi')
result = subprocess.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=5',
'gorios-spark-2@192.168.31.61', remote],
input=payload.encode(), capture_output=True, timeout=100)
output = root / 'logs/voice-investigation'
output.mkdir(parents=True, exist_ok=True)
if result.stdout:
data = json.loads(result.stdout)
target = output / ('probe-after.json' if '--after' in __import__('sys').argv else 'probe-before.json')
if target.exists() and '--after' in __import__('sys').argv:
(output/'probe-after-previous.json').write_bytes(target.read_bytes())
target.write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n')
print(f'Saved redacted numeric probe results: {target.relative_to(root)}; status={data.get("status")}')
if result.stderr:
# Remote script emits no payloads. Avoid printing unexpected tracebacks/raw server errors.
print('Remote stderr present; inspect script/environment (no content printed).')
raise SystemExit(result.returncode)
if __name__ == '__main__':
main()
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env python3
"""Restore exact gateway files from the last controlled backup; ordinary shell required."""
import json, subprocess, sys
from pathlib import Path
REMOTE=r'''
import hashlib,json,ssl,subprocess,time,urllib.request
from pathlib import Path
root=Path('/home/gorios-spark-2/lan-voice')
backup=Path(record['backup']).resolve()
assert backup.is_relative_to((root/'.runtime/backups').resolve())
assert hashlib.sha256((root/'gateway.py').read_bytes()).hexdigest()==record['gateway_sha256'], 'concurrent change: refusing rollback'
ctx=ssl.create_default_context(cafile=str(root/'.runtime/gateway-cert.pem'))
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx))
def health():
with opener.open('https://192.168.31.61:5011/health',timeout=3) as response: return json.load(response)
assert not health().get('busy'), 'busy: no rollback/restart'
manifest=json.loads((backup/'manifest.json').read_text())
for name,existed in manifest.items():
assert name in ('gateway.py','face_context.py')
path=root/name
if existed:
tmp=path.with_name(path.name+'.rollback.tmp')
tmp.write_bytes((backup/name).read_bytes());tmp.chmod(0o600);tmp.replace(path)
elif path.exists(): path.unlink()
subprocess.run(['systemctl','--user','restart','lan-voice-gateway.service'],check=True,timeout=30,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
for attempt in range(15):
try:
if health().get('status')=='ok': print(json.dumps({'status':'rolled_back','backup':str(backup),'health':'ok'}));break
except Exception: pass
time.sleep(1)
else: raise RuntimeError('rollback health failed')
'''
root=Path(__file__).resolve().parents[1]
record=json.loads((root/'logs/voice-investigation/gateway-deploy.json').read_text())
if '--initial' in sys.argv: record['backup']=record.get('initial_backup',record['backup'])
payload='record='+repr({k:record[k] for k in ('backup','gateway_sha256')})+'\n'+REMOTE
r=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5','gorios-spark-2@192.168.31.61','python3 -'],input=payload.encode(),capture_output=True,timeout=90)
if r.stdout:
result=json.loads(r.stdout);print(json.dumps(result))
(root/'logs/voice-investigation/gateway-rollback.json').write_text(json.dumps(result,indent=2)+'\n')
if r.stderr: print('Remote rollback error; no raw content printed.')
raise SystemExit(r.returncode)