feat: merge reply emotions while preserving configurable Qwen/Doubao provider

This commit is contained in:
zenord
2026-10-12 10:57:14 +08:00
parent 19a7adccd9
commit d43c7d4e80
36 changed files with 1264 additions and 98 deletions
+2
View File
@@ -64,6 +64,8 @@ def scan(name, data):
for pattern in patterns:
for match in re.finditer(pattern,text):
if match.lastindex and match.group(1).startswith('REPLACE_'): continue
# A fixed reserved-domain negative fixture tests rejecting URL credentials.
if name.endswith('tests/test_llm_provider.py') and match.group(0)=='http://user:password@' and text[match.end():].startswith('example.com/v1'): continue
raise RuntimeError(f'Possible embedded secret in {name}; inspect locally before any Git add')
+18
View File
@@ -0,0 +1,18 @@
#!/bin/bash
# Model-free local JVM/rule/parser regressions; persistent numeric result for release checks.
set -euo pipefail
cd "$(dirname "$0")/.."
mkdir -p logs/voice-investigation
python3 scripts/check-reply-regressions.py > logs/voice-investigation/client-emotion-tests.txt 2>&1
./scripts/check-expression-rules.sh > logs/voice-investigation/expression-emotion-tests.txt 2>&1
(cd gateway && python3 -m unittest discover -s tests -p test_reply_emotion.py -v) > logs/voice-investigation/parser-emotion-tests.txt 2>&1
python3 - <<'PY'
import hashlib,json
from pathlib import Path
root=Path.cwd()
files=list((root/'app/src/main/java').rglob('*.kt')) + list((root/'tests').rglob('*.kt'))
files += [root/'gateway/reply_emotion.py',root/'scripts/check-reply-regressions.py']
result={'status':'passed','scope':'production Kotlin coordinator/playback/capture/protocol with device/transport doubles; pure face rules and structured parser','real_phone_playback':'not_tested','hashes':{str(p.relative_to(root)):hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(files)}}
(root/'logs/voice-investigation/client-emotion-tests.json').write_text(json.dumps(result,indent=2)+'\n')
print('Client/expression/parser emotion regressions passed (no real speaker)')
PY
+2 -2
View File
@@ -23,10 +23,10 @@ compiler = ':'.join([jar('org.jetbrains.kotlin','kotlin-compiler-embeddable','2.
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']),
('session','ConnectionCheckKt', [source/'audio/VoiceSession.kt', source/'dialogue/ReplyEmotion.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']),
('protocol','ProtocolCheckKt', [source/'net/DialogueProtocol.kt', source/'dialogue/ReplyEmotion.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:
+66
View File
@@ -0,0 +1,66 @@
#!/usr/bin/env python3
"""Four bounded public compatibility calls; current Qwen and saved Doubao, no live config changes."""
from pathlib import Path
import base64,json,subprocess
root=Path(__file__).resolve().parents[1]
CORE=r'''
import json,time,httpx
from llm_provider import LLMProvider
from reply_emotion import SYSTEM_FRAGMENT,parse_reply
provider=LLMProvider();rows=[]
with httpx.Client(timeout=30,trust_env=False) as client:
for name,prompt in [('ordinary','一加一等于几?'),('happy','请用明显高兴的语气祝贺我完成公开练习。')]:
start=time.perf_counter();first=None;raw='';finish=None
messages=[{'role':'system','content':'以下角色设定只约束reply口述内容,旧有不输出JSON约定不约束外层结构。用简短中文直接回答。\n'+SYSTEM_FRAGMENT},{'role':'user','content':prompt}]
url,headers,body=provider.request(messages,max_tokens=160)
row={'case':name}
try:
with client.stream('POST',url,headers=headers,json=body) as r:
row['http_status']=r.status_code;r.raise_for_status()
for line in r.iter_lines():
if not line.startswith('data:'):continue
data=line[5:].strip()
if data=='[DONE]':break
for choice in json.loads(data).get('choices',[]):
delta=choice.get('delta',{}).get('content') or ''
if delta and first is None:first=round((time.perf_counter()-start)*1000,2)
raw+=delta;finish=choice.get('finish_reason') or finish
if len(raw)>8192:raise ValueError('reply bound')
parsed=parse_reply(raw)
row.update(source=parsed.source,emotion=parsed.emotion,intensity=parsed.intensity,reply_chars=len(parsed.reply),finish_reason=finish,first_token_ms=first)
except Exception as error:row['error_type']=type(error).__name__
row['elapsed_ms']=round((time.perf_counter()-start)*1000,2)
if first is not None:row['structured_wait_ms']=round(row['elapsed_ms']-first,2)
rows.append(row)
passed=all(x.get('source')=='model' and x.get('finish_reason')=='stop' for x in rows)
print(json.dumps({'status':'passed' if passed else 'failed','base_url':provider.base_url,'model_alias':provider.model,'chat_template_kwargs':provider.template_kwargs,'key_present':bool(provider.api_key),'strategy':'prompt_only_json_single_system_single_request','results':rows}))
raise SystemExit(0 if passed else 1)
'''
REMOTE=r'''
import tempfile,pathlib,sys,base64,os,subprocess,json
root=pathlib.Path('/home/gorios-spark-2/lan-voice')
pid=subprocess.check_output(['systemctl','--user','show','lan-voice-gateway.service','-p','MainPID','--value'],text=True).strip()
running=dict(x.split('=',1) for x in pathlib.Path('/proc/'+pid+'/environ').read_bytes().decode().split('\0') if '=' in x)
with tempfile.TemporaryDirectory(prefix='reply-structure-') as d:
for name,content in bundle.items():pathlib.Path(d,name).write_bytes(base64.b64decode(content))
code='import sys\nsys.path.insert(0,'+repr(d)+')\n'+core
qwen=subprocess.run([sys.executable,'-'],input=code,text=True,capture_output=True,timeout=70,env={**os.environ,**running})
# Existing private provider file is loaded only into a subprocess; never copied or logged.
doubao=subprocess.run(['bash','-c','set -a; source .runtime/gori-baji-llm.env; source .runtime/gori-baji-provider.env; exec .venv/bin/python -'],cwd=root,input=code,text=True,capture_output=True,timeout=70)
rows={}
for name,result in [('qwen_current',qwen),('doubao_saved',doubao)]:
try:rows[name]=json.loads(result.stdout)
except ValueError:rows[name]={'status':'failed','returncode':result.returncode,'stderr_present':bool(result.stderr)}
passed=all(r.get('status')=='passed' for r in rows.values())
print(json.dumps({'status':'passed' if passed else 'failed','results':rows,'live_configuration_changed':False,'real_weights_verified':False}))
raise SystemExit(0 if passed else 1)
'''
bundle={name:base64.b64encode((root/'gateway'/name).read_bytes()).decode() for name in ('llm_provider.py','reply_emotion.py')}
payload='bundle='+repr(bundle)+'\ncore='+repr(CORE)+'\n'+REMOTE
r=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=150)
if r.stdout:
data=json.loads(r.stdout);out=root/'logs/voice-investigation/reply-structure.json';out.parent.mkdir(parents=True,exist_ok=True)
if out.exists():out.with_name('reply-structure-previous.json').write_bytes(out.read_bytes())
out.write_text(json.dumps(data,indent=2)+'\n');print(json.dumps(data))
if r.stderr:print('Remote stderr present (content suppressed).')
raise SystemExit(r.returncode)
+109
View File
@@ -0,0 +1,109 @@
#!/usr/bin/env python3
"""Canonical gateway/ deployment fenced to observed provider source. Default: isolated tests only."""
import argparse, base64, hashlib, json, subprocess
from pathlib import Path
REMOTE=r'''
import base64,hashlib,json,os,shutil,ssl,stat,subprocess,sys,tempfile,time,urllib.request,re
from pathlib import Path
root=Path('/home/gorios-spark-2/lan-voice');unit='lan-voice-gateway.service'
def digest(path): return hashlib.sha256(path.read_bytes()).hexdigest() if path.exists() else None
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 atomic(path,content,mode):
path.parent.mkdir(parents=True,exist_ok=True)
tmp=path.with_name(path.name+'.v050.tmp');tmp.write_bytes(content);tmp.chmod(mode);tmp.replace(path)
def live_hashes():return {name:digest(root/name) for name in deploy_files}
original=live_hashes()
if original!=expected:
print(json.dumps({'status':'source_changed','mismatches':{name:{'expected':expected[name],'actual':original[name]} for name in expected if expected[name]!=original[name]},'applied':False}));raise SystemExit(1)
# Preserve complete unit and private environment loading relationships on server only.
unit_text=subprocess.check_output(['systemctl','--user','cat',unit])
fragment=subprocess.check_output(['systemctl','--user','show',unit,'-p','FragmentPath','--value'],text=True).strip()
dropins=subprocess.check_output(['systemctl','--user','show',unit,'-p','DropInPaths','--value'],text=True).split()
private_files=[Path(fragment)]+[Path(p) for p in dropins]+list((root/'.runtime').glob('*.env'))
for name in re.findall(r'^EnvironmentFile=-?(.+)$',unit_text.decode(),re.M):
p=Path(name.strip().strip('"'));assert p.is_absolute();private_files.append(p)
private_files=sorted(set(p for p in private_files if p.is_file()))
private_hashes={str(p):digest(p) for p in private_files}
def relation_unchanged():
return subprocess.check_output(['systemctl','--user','cat',unit])==unit_text and all(digest(Path(p))==h for p,h in private_hashes.items())
if apply and health().get('busy'): raise RuntimeError('gateway_busy_no_restart')
with tempfile.TemporaryDirectory(prefix='voice-v050-stage-') as folder:
stage=Path(folder)
for name,content in bundle.items():
path=stage/name;path.parent.mkdir(parents=True,exist_ok=True);path.write_bytes(base64.b64decode(content))
test_start=time.perf_counter()
result=subprocess.run([sys.executable,str(stage/'scripts/check-archive.py'),'--vad-model',str(root/'models/silero_vad.onnx')],cwd=stage,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=120,env={**os.environ,'PYTHONDONTWRITEBYTECODE':'1'})
summary={'status':'tests_passed' if result.returncode==0 else 'tests_failed','test_output':result.stdout.decode(errors='replace'),'test_elapsed_ms':round((time.perf_counter()-test_start)*1000,2),'applied':False,'expected_hashes':original}
if result.returncode: print(json.dumps(summary));raise SystemExit(1)
if apply:
if live_hashes()!=original:raise RuntimeError('source_changed_during_tests')
if not relation_unchanged():raise RuntimeError('environment_or_unit_changed_during_tests')
if health().get('busy'):raise RuntimeError('gateway_busy_after_tests_no_restart')
backup=root/'.runtime/backups'/time.strftime('voice-v050-%Y%m%d-%H%M%S');backup.mkdir(parents=True,mode=0o700)
# Save all actual runtime Python sources/tests, modes, plus unit/env privately. No logs/history/audio copied.
for path in list(root.glob('*.py'))+list((root/'tests').glob('*.py')):
dst=backup/path.relative_to(root);dst.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(path,dst)
for i,path in enumerate(private_files):
dst=backup/'private'/str(i);dst.parent.mkdir(parents=True,exist_ok=True,mode=0o700);shutil.copy2(path,dst)
(backup/'unit.txt').write_bytes(unit_text);(backup/'unit.txt').chmod(0o600)
existed={name:(root/name).exists() for name in deploy_files}
modes={name:stat.S_IMODE((root/name).stat().st_mode) if existed[name] else 0o644 for name in deploy_files}
(backup/'manifest.json').write_text(json.dumps(existed));(backup/'manifest.json').chmod(0o600)
(backup/'metadata.json').write_text(json.dumps({'modes':modes,'private_files':{str(p):{'backup':'private/'+str(i),'sha256':private_hashes[str(p)],'mode':stat.S_IMODE(p.stat().st_mode)} for i,p in enumerate(private_files)},'unit_sha256':hashlib.sha256(unit_text).hexdigest()}));(backup/'metadata.json').chmod(0o600)
if live_hashes()!=original or not relation_unchanged():raise RuntimeError('source_or_environment_changed_before_apply')
if health().get('busy'):raise RuntimeError('gateway_busy_before_apply_no_restart')
try:
for name in deploy_files:atomic(root/name,(stage/name).read_bytes(),modes[name])
subprocess.run(['systemctl','--user','restart',unit],check=True,timeout=30,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
for attempt in range(15):
try:
if health().get('status')=='ok':break
except Exception:pass
time.sleep(1)
else:raise RuntimeError('gateway_health_failed')
assert relation_unchanged(),'environment_loading_changed'
deployed=live_hashes()
assert deployed=={name:hashlib.sha256((stage/name).read_bytes()).hexdigest() for name in deploy_files}
except BaseException:
# Never overwrite an edit made by another operator, even while rolling back a failed restart.
staged_hashes={name:hashlib.sha256((stage/name).read_bytes()).hexdigest() for name in deploy_files}
if any(value not in (original[name],staged_hashes[name]) for name,value in live_hashes().items()):
raise RuntimeError('concurrent_source_change_refusing_automatic_rollback')
for name,present in existed.items():
if present:atomic(root/name,(backup/name).read_bytes(),modes[name])
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,backup=str(backup),hashes=deployed,modes=modes,environment_unchanged=True,unit_sha256=hashlib.sha256(unit_text).hexdigest(),health='ok',restart_unit=unit)
print(json.dumps(summary))
'''
def main():
root=Path(__file__).resolve().parents[1]
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--apply',action='store_true');args=parser.parse_args()
source=root/'gateway';manifest=json.loads((source/'SOURCE_MANIFEST.json').read_text())
baseline=manifest['provider_baseline']['files']
files=sorted(set(baseline)|{p.relative_to(source).as_posix() for p in source.glob('*.py')}|{p.relative_to(source).as_posix() for p in (source/'tests').glob('*.py')})
assert all(n.endswith('.py') and not Path(n).is_absolute() and '..' not in Path(n).parts for n in files)
expected={name:baseline.get(name) for name in files}
record=root/'logs/voice-investigation/gateway-emotion-deploy.json'
if record.exists():
previous=json.loads(record.read_text())
if previous.get('applied'):expected=previous['hashes'];assert set(expected)==set(files)
bundle={}
for path in source.rglob('*'):
name=path.relative_to(source).as_posix()
if not path.is_file() or any(x.startswith('.') or x in ('__pycache__','models','logs') for x in path.relative_to(source).parts):continue
if path.suffix in ('.py','.json','.js','.html','.css'):bundle[name]=base64.b64encode(path.read_bytes()).decode()
payload='import json\nbundle='+repr(bundle)+'\ndeploy_files='+repr(files)+'\nexpected='+repr(expected)+'\napply='+repr(args.apply)+'\ntry:\n exec('+repr(REMOTE)+')\nexcept Exception as error:\n print(json.dumps({"status":"blocked","error_type":type(error).__name__,"reason":str(error) if isinstance(error,RuntimeError) else "remote_execution_error","applied":False}))\n raise SystemExit(1)\n'
command='cd /home/gorios-spark-2/lan-voice && exec .venv/bin/python -'
r=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5','gorios-spark-2@192.168.31.61',command],input=payload.encode(),capture_output=True,timeout=210)
if r.stdout:
data=json.loads(r.stdout);out=record if data.get('applied') else record.with_name('gateway-emotion-staged.json');out.parent.mkdir(parents=True,exist_ok=True)
if out.exists() and data.get('applied'):out.with_name('gateway-emotion-deploy-previous.json').write_bytes(out.read_bytes())
out.write_text(json.dumps(data,indent=2)+'\n');print('Gateway '+data['status'])
if r.stderr:print('Remote stderr present (content suppressed); no concurrent hash check bypassed.')
raise SystemExit(r.returncode)
if __name__=='__main__':main()
+2 -1
View File
@@ -127,4 +127,5 @@ def main():
raise SystemExit(result.returncode)
if __name__=='__main__': main()
if __name__=='__main__':
raise SystemExit('Historical v040 patch deployment disabled; use scripts/deploy-gateway-source.py for canonical provider + emotion source.')
+71
View File
@@ -0,0 +1,71 @@
#!/bin/bash
# Explicit source-only release commit/push; no runtime, diagnostics or binary staging.
set -euo pipefail
cd "$(dirname "$0")/.."
[ "$(git branch --show-current)" = main ]
[ "$(git remote get-url origin)" = 'git@git.oops.school:heihei/baji-vc.git' ]
git merge-base --is-ancestor 19a7adccd9322986eb0646b165b9ce1cf2650cf2 HEAD
if [ -n "$(git diff --cached --name-only)" ]; then
echo 'Existing staged changes preserved; refusing mixed release commit.' >&2
exit 1
fi
python3 - <<'PY'
from pathlib import Path
import hashlib,json,runpy
root=Path.cwd();directory=root/'logs/voice-investigation'
load=lambda name:json.loads((directory/name).read_text())
release=load('release-emotion.json');probe=load('probe-emotion.json');deploy=load('gateway-emotion-deploy.json');client=load('client-emotion-tests.json')
assert release['version_name']=='0.5.0' and release['version_code']==8 and release['signature']=='apksigner_verified'
assert release['download_http_status']==200 and release['download_bytes']==release['bytes']
assert hashlib.sha256((root/release['apk']).read_bytes()).hexdigest()==release['sha256']
assert hashlib.sha256((root/'artifacts/lan-voice-v040-arm64-debug.apk').read_bytes()).hexdigest()=='5a6f88cb2f825dbcd5c7b8c1f212b369534bc53c49533e196fb5e9287902e934'
assert probe['status']=='passed' and probe['downlink_bytes']>0 and probe['llm_chars']>0 and probe['drained_ack']
assert probe['emotion_count']==1 and probe['emotion_before_pcm'] and probe['tts_input_matches_body'] and probe['tts_requests']==1
assert deploy['status']=='deployed' and deploy['applied'] and deploy['health']=='ok' and client['status']=='passed'
assert deploy['environment_unchanged'] and load('reply-structure.json')['status']=='passed'
verification=load('provider-release-verified.json')
assert verification['status']=='passed' and verification['live_source_hashes_match'] and verification['private_environment_and_unit_unchanged']
for name,digest in deploy['hashes'].items():assert hashlib.sha256((root/'gateway'/name).read_bytes()).hexdigest()==digest,name
for name,digest in client['hashes'].items():assert hashlib.sha256((root/name).read_bytes()).hexdigest()==digest,name
manifest=load('gateway-baseline-git.json');assert manifest['commit']=='19a7adccd9322986eb0646b165b9ce1cf2650cf2'
source=json.loads((root/'gateway/SOURCE_MANIFEST.json').read_text())
for name,row in source['files'].items():assert hashlib.sha256((root/'gateway'/name).read_bytes()).hexdigest()==row['sha256'],name
scan=runpy.run_path('scripts/archive-gateway.py',run_name='archive_library')['scan']
for p in (root/'gateway').rglob('*'):
if p.is_file() and '__pycache__' not in p.parts:scan(str(p.relative_to(root/'gateway')),p.read_bytes())
print('Verified APK, bounded live pipeline, full gateway/client tests, canonical deployed source hashes; real phone remains untested')
PY
git diff --check
git add -- app/build.gradle app/src/main/java/com/gorios/lanvoice/MainActivity.kt \
app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt \
app/src/main/java/com/gorios/lanvoice/dialogue/ReplyEmotion.kt \
app/src/main/java/com/gorios/lanvoice/expression/ExpressionController.kt \
app/src/main/java/com/gorios/lanvoice/expression/ExpressionState.kt \
app/src/main/java/com/gorios/lanvoice/expression/ExpressionUi.kt \
app/src/main/java/com/gorios/lanvoice/net/DialogueProtocol.kt \
gateway/gateway.py gateway/llm_provider.py gateway/reply_emotion.py gateway/SOURCE_MANIFEST.json gateway/README.md gateway/env.example gateway/scripts/check-archive.py \
gateway/tests/test_continuity.py gateway/tests/test_reply_emotion.py gateway/tests/test_gateway_emotion.py gateway/tests/test_llm_provider.py \
tests/session/AudioDoubles.kt tests/session/ProtocolEvents.kt tests/session/ConnectionCheck.kt tests/protocol/ProtocolCheck.kt \
scripts/check-reply-regressions.py scripts/check-reply-structure.py scripts/check-emotion-regressions.sh \
scripts/deploy-gateway-source.py scripts/rollback-gateway-source.py scripts/update-gateway-manifest.py scripts/deploy-gateway.py scripts/archive-gateway.py \
scripts/probe-reply-emotion.py scripts/package-emotion-release.sh scripts/finalize-emotion-release.sh \
docs/REPLY_EMOTION_050.md docs/PLAN.md
git diff --cached --check
python3 - <<'PY'
import subprocess
names=subprocess.check_output(['git','diff','--cached','--name-only'],text=True).splitlines()
assert names and all(n.startswith(('app/','gateway/','tests/','scripts/','docs/')) for n in names)
assert not any(any(x in n.split('/') for x in ('logs','artifacts','.runtime','__pycache__','models')) or n.endswith(('.pem','.key','.apk','.wav','.pcm','.pyc')) for n in names)
PY
git -c user.name=zenord -c user.email=zenord@email.com commit -m 'feat: merge reply emotions while preserving configurable Qwen/Doubao provider'
git push origin main
python3 - <<'PY'
import json,subprocess
from pathlib import Path
commit=subprocess.check_output(['git','rev-parse','HEAD'],text=True).strip()
remote=subprocess.check_output(['git','ls-remote','origin','refs/heads/main'],text=True).split()[0]
assert commit==remote
result={'commit':commit,'branch':'main','push':'verified','archive':'gateway/','version':'0.5.0','archive_baseline':'19a7adccd9322986eb0646b165b9ce1cf2650cf2'}
Path('logs/voice-investigation/git-emotion-release.json').write_text(json.dumps(result,indent=2)+'\n')
print(json.dumps(result,indent=2))
PY
+65
View File
@@ -0,0 +1,65 @@
#!/bin/bash
# Ordinary workspace shell: normal build entry, true package/signature checks, archive + HTTP check.
set -euo pipefail
cd "$(dirname "$0")/.."
python3 - <<'PY'
from pathlib import Path
import hashlib,json
root=Path.cwd();directory=root/'logs/voice-investigation'
load=lambda name:json.loads((directory/name).read_text())
deploy=load('gateway-emotion-deploy.json');probe=load('probe-emotion.json');client=load('client-emotion-tests.json');compat=load('reply-structure.json')
assert deploy['applied'] and deploy['health']=='ok' and deploy['environment_unchanged']
assert probe['status']=='passed' and probe['downlink_bytes']>0 and probe['emotion_before_pcm'] and probe['drained_ack'] and probe['tts_requests']==1
assert compat['status']=='passed' and client['status']=='passed'
for name,digest in deploy['hashes'].items():assert hashlib.sha256((root/'gateway'/name).read_bytes()).hexdigest()==digest,name
for name,digest in client['hashes'].items():assert hashlib.sha256((root/name).read_bytes()).hexdigest()==digest,name
assert not (root/'artifacts/lan-voice-v050-arm64-debug.apk').exists(), 'release artifact exists: refusing overwrite'
print('Verified tested client/provider source and successful deployed pipeline before APK build')
PY
./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-emotion-badging.txt
"$TOOLS/apksigner" verify --verbose --print-certs "$APK" > logs/voice-investigation/release-emotion-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-emotion-badging.txt').read_text()
assert "name='com.gorios.lanvoice'" in badging
assert "versionCode='8'" in badging and "versionName='0.5.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-v040-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-emotion-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-v050-arm64-debug.apk'
assert not artifact.exists(), 'release artifact exists: refusing overwrite'
assert hashlib.sha256((root/'artifacts/lan-voice-v040-arm64-debug.apk').read_bytes()).hexdigest()=='5a6f88cb2f825dbcd5c7b8c1f212b369534bc53c49533e196fb5e9287902e934'
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:
assert response.status==200
content=response.read()
assert len(content)==artifact.stat().st_size
downloaded=hashlib.sha256(content).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.5.0',version_code=8,apk=str(artifact.relative_to(root)),bytes=artifact.stat().st_size,sha256=digest,url=url,download_http_status=200,download_bytes=len(content),signature='apksigner_verified',real_phone_playback='not_tested')
(root/'logs/voice-investigation/release-emotion.json').write_text(json.dumps(result,indent=2)+'\n')
print(json.dumps(result,indent=2))
PY
+156
View File
@@ -0,0 +1,156 @@
#!/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'}
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(emotion_count=0,emotion_before_pcm=False,json_free_body=True,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')
summary['reply_emotion_supported']=event.get('reply_emotion_version')
assert summary['reply_emotion_supported']==1
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;reply_body='';emotion=None
async with asyncio.timeout(60):
while True:
raw=await ws.recv()
if isinstance(raw,bytes):
actual,seq,audio=unpack(raw,2)
assert emotion is not None and emotion['turn_id']==actual, 'PCM before parsed emotion'
summary['emotion_before_pcm']=True
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':
text=event.get('text','');assert text.strip() and not text.lstrip().startswith(('{','[','```'))
assert not re.search(r'"(?:reply|emotion|intensity)"\s*:',text), 'JSON leaked as dialogue body'
reply_body+=text
summary['llm_chars']+=len(event.get('text',''));summary['llm_deltas']+=1;stamp('first_llm_ms')
if kind=='reply.emotion':
assert event['turn_id']==turn and isinstance(event.get('seq'),int) and event['seq']>0
assert (event.get('emotion'),event.get('intensity')) in [('neutral',0)]+[(e,i) for e in ('happy','angry','sad') for i in (1,2)]
assert event.get('source')=='model', 'real structured output fell back'
assert summary['downlink_frames']==0 and emotion is None and reply_body, 'emotion event order/duplicate'
emotion=event;summary['emotion_count']+=1
summary['reply_emotion']={key:event[key] for key in ('turn_id','seq','emotion','intensity','source')}
if kind=='tts' and event.get('state')=='sentence_start':
assert event.get('text')==reply_body, 'TTS text differs from parsed body'
summary['tts_input_matches_body']=True
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_first_token_ms','llm_first_body_ms','structured_wait_ms','reply_parse_ms','llm_finished_ms','tts_first_pcm_ms','capture_to_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['emotion_count']==1 and summary.get('tts_input_matches_body') and summary.get('tts_requests')==1
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]
payload = 'after=True\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-emotion.json'
if target.exists():
(output/'probe-emotion-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()
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env python3
"""Restore only exact v050-deployed files, from its own backup; no model/container actions."""
import json,subprocess
from pathlib import Path
REMOTE=r'''
import hashlib,json,ssl,subprocess,time,urllib.request,shutil
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())
for name,expected in record['hashes'].items():
assert name.endswith('.py') and not Path(name).is_absolute() and '..' not in Path(name).parts
assert hashlib.sha256((root/name).read_bytes()).hexdigest()==expected, 'concurrent source 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 r:return json.load(r)
assert not health().get('busy'), 'busy: refusing restart'
manifest=json.loads((backup/'manifest.json').read_text());assert set(manifest)==set(record['hashes'])
metadata=json.loads((backup/'metadata.json').read_text())
assert hashlib.sha256(subprocess.check_output(['systemctl','--user','cat','lan-voice-gateway.service'])).hexdigest()==metadata['unit_sha256'], 'unit changed: refusing rollback'
for name,row in metadata['private_files'].items():
assert hashlib.sha256(Path(name).read_bytes()).hexdigest()==row['sha256'], 'private environment changed: refusing rollback'
for name,present in manifest.items():
path=root/name
if present:
tmp=path.with_name(path.name+'.rollback.tmp');shutil.copy2(backup/name,tmp);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-emotion-deploy.json').read_text())
r=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5','gorios-spark-2@192.168.31.61','python3 -'],input=('record='+repr(record)+'\n'+REMOTE).encode(),capture_output=True,timeout=90)
if r.stdout:
data=json.loads(r.stdout);(root/'logs/voice-investigation/gateway-emotion-rollback.json').write_text(json.dumps(data,indent=2)+'\n');print(json.dumps(data))
if r.stderr:print('Remote rollback stderr present (suppressed).')
raise SystemExit(r.returncode)
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/env python3
"""Refresh recoverable source hashes while preserving observed upstream provenance."""
from pathlib import Path
import hashlib,json
root=Path(__file__).resolve().parents[1]/'gateway'
manifest=json.loads((root/'SOURCE_MANIFEST.json').read_text())
manifest['archive_baseline_commit']='19a7adccd9322986eb0646b165b9ce1cf2650cf2'
manifest['workspace_release']='0.5.0'
manifest['code_version']='0.7.1 (legacy health version; reply.emotion version 1 capability)'
for path in sorted(root.rglob('*')):
if not path.is_file():continue
name=path.relative_to(root).as_posix()
if name=='SOURCE_MANIFEST.json' or any(x in path.relative_to(root).parts for x in ('__pycache__','.runtime','models','logs')):continue
raw=path.read_bytes();digest=hashlib.sha256(raw).hexdigest();old=manifest['files'].get(name)
row={'source':old['source'] if old else 'workspace:gateway/'+name,'sha256':digest,'bytes':len(raw)}
if old and old['sha256']!=digest:
row['upstream_sha256']=old.get('upstream_sha256',old['sha256']);row['source']='workspace:gateway/'+name
elif old and 'upstream_sha256' in old:row['upstream_sha256']=old['upstream_sha256']
manifest['files'][name]=row
(root/'SOURCE_MANIFEST.json').write_text(json.dumps(manifest,indent=2,ensure_ascii=False)+'\n')
print('Updated canonical gateway source manifest')