Integrate reviewed full action pack admission and bounded idle scheduling

This commit is contained in:
zenord
2026-10-13 07:19:34 +08:00
parent 97f87e2409
commit f0620ddd65
21 changed files with 285 additions and 75 deletions
+4 -1
View File
@@ -18,6 +18,7 @@ def avatarNatural = providers.gradleProperty('avatarNatural').orNull == 'true'
def avatarUiCandidate = providers.gradleProperty('avatarUiCandidate').orNull == 'true' def avatarUiCandidate = providers.gradleProperty('avatarUiCandidate').orNull == 'true'
def avatarMouthCandidate = providers.gradleProperty('avatarMouthCandidate').orNull == 'true' def avatarMouthCandidate = providers.gradleProperty('avatarMouthCandidate').orNull == 'true'
def avatarActionCandidate = providers.gradleProperty('avatarActionCandidate').orNull == 'true' def avatarActionCandidate = providers.gradleProperty('avatarActionCandidate').orNull == 'true'
def avatarFullActionCandidate = providers.gradleProperty('avatarFullActionCandidate').orNull == 'true'
def actionVersionCode = (providers.gradleProperty('actionVersionCode').orNull ?: '16').toInteger() def actionVersionCode = (providers.gradleProperty('actionVersionCode').orNull ?: '16').toInteger()
if (avatarActionCandidate && (!avatarMouthCandidate || actionVersionCode < 16)) { if (avatarActionCandidate && (!avatarMouthCandidate || actionVersionCode < 16)) {
throw new GradleException('Action stage requires the existing mouth runtime and a fresh code >=16') throw new GradleException('Action stage requires the existing mouth runtime and a fresh code >=16')
@@ -32,6 +33,7 @@ def naturalManifestSha = providers.gradleProperty('naturalManifestSha').orNull ?
def emotionManifestSha = providers.gradleProperty('emotionManifestSha').orNull ?: '' def emotionManifestSha = providers.gradleProperty('emotionManifestSha').orNull ?: ''
if (emotionManifestSha && !(emotionManifestSha ==~ /[0-9a-f]{64}/)) throw new GradleException('Emotion graph requires exact external manifest SHA') if (emotionManifestSha && !(emotionManifestSha ==~ /[0-9a-f]{64}/)) throw new GradleException('Emotion graph requires exact external manifest SHA')
if (emotionManifestSha && (!avatarActionCandidate || !avatarMouthCandidate || !avatarNatural || actionVersionCode < 17)) throw new GradleException('Emotion candidate requires own-mouth runtime and a fresh code >=17') if (emotionManifestSha && (!avatarActionCandidate || !avatarMouthCandidate || !avatarNatural || actionVersionCode < 17)) throw new GradleException('Emotion candidate requires own-mouth runtime and a fresh code >=17')
if (avatarFullActionCandidate && (!emotionManifestSha || !avatarActionCandidate || actionVersionCode < 18)) throw new GradleException('Full candidate requires pinned emotion/action graph and fresh code >=18')
if (avatarNatural && !(naturalManifestSha ==~ /[0-9a-f]{64}/)) { if (avatarNatural && !(naturalManifestSha ==~ /[0-9a-f]{64}/)) {
throw new GradleException('Natural debug candidate requires exact runtime manifest SHA') throw new GradleException('Natural debug candidate requires exact runtime manifest SHA')
} }
@@ -88,7 +90,8 @@ android {
buildFeatures { compose true; buildConfig true } buildFeatures { compose true; buildConfig true }
buildTypes { buildTypes {
debug { debug {
if (emotionManifestSha) versionNameSuffix '-emotion-dev' if (avatarFullActionCandidate) { /* Full reviewed debug integration candidate: 0.7.0 */ }
else if (emotionManifestSha) versionNameSuffix '-emotion-dev'
else if (avatarActionCandidate) versionNameSuffix '-stage-dev' else if (avatarActionCandidate) versionNameSuffix '-stage-dev'
else if (avatarMouthCandidate) versionNameSuffix '-mouth-dev' else if (avatarMouthCandidate) versionNameSuffix '-mouth-dev'
else if (avatarUiCandidate) versionNameSuffix '-ui-dev' else if (avatarUiCandidate) versionNameSuffix '-ui-dev'
@@ -46,7 +46,10 @@ class ActionController(
val valid = capability val valid = capability
if (active || valid == null || next.packSha != valid.manifestSha || next.id.length !in 16..64 || if (active || valid == null || next.packSha != valid.manifestSha || next.id.length !in 16..64 ||
next.turn !in 0..0xffff_ffffL || next.ttlMs !in 1..120_000) return false next.turn !in 0..0xffff_ffffL || next.ttlMs !in 1..120_000) return false
val candidates = valid.assets.filter { it.id != previous } // Prefer a different variant 3:1, while two assets still remain random rather
// than a forced alternating playlist. The model chooses dance, never a variant.
val different=valid.assets.filter { it.id != previous }
val candidates = if(previous==null) valid.assets else different+different+different+valid.assets.filter { it.id==previous }
val asset = candidates[choose(candidates.size)] val asset = candidates[choose(candidates.size)]
val fence = ++generation val fence = ++generation
plan = next; deadline = clock()+next.ttlMs; changed(true) plan = next; deadline = clock()+next.ttlMs; changed(true)
@@ -131,6 +131,7 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
val visualEmotion=pack?.emotionAction?.visuals?.firstOrNull { it.id==visualId }?.emotion val visualEmotion=pack?.emotionAction?.visuals?.firstOrNull { it.id==visualId }?.emotion
Text("当前画面:${visualEmotion?.label ?: if(pack?.emotionAction!=null) "过渡或未呈现" else "中立"} · ${video.actual}",fontSize=12.sp) Text("当前画面:${visualEmotion?.label ?: if(pack?.emotionAction!=null) "过渡或未呈现" else "中立"} · ${video.actual}",fontSize=12.sp)
Text("视觉选择:${mediaBinding?.selection?.let { "${it.visualEmotion.wire}/${it.visualIntensity}" } ?: "未选择"} · ${mediaBinding?.visualStatus ?: "旧中立素材"}",fontSize=12.sp) Text("视觉选择:${mediaBinding?.selection?.let { "${it.visualEmotion.wire}/${it.visualIntensity}" } ?: "未选择"} · ${mediaBinding?.visualStatus ?: "旧中立素材"}",fontSize=12.sp)
if(pack?.emotionAction!=null) Text("整合候选 · 动态自然度、音乐听审及真机未测;表达可能等待 2–4 秒出口和约 1 秒过渡",fontSize=12.sp)
AvatarDiagnostics(pack,video) AvatarDiagnostics(pack,video)
Text("AEC:${state.aec.name} · 效果待真机验证",fontSize=12.sp) Text("AEC:${state.aec.name} · 效果待真机验证",fontSize=12.sp)
Row { Row {
@@ -214,6 +215,7 @@ fun EngineeringPreviewScreen(pack: AvatarPack?,micGranted: Boolean,cameraGranted
Text("可手动申请权限;授权后仍不启动采集",fontSize=12.sp) Text("可手动申请权限;授权后仍不启动采集",fontSize=12.sp)
PermissionSettings(micGranted,cameraGranted,micSettings,cameraSettings,permissionPending,onAuthorizeMic,onAuthorizeCamera) PermissionSettings(micGranted,cameraGranted,micSettings,cameraSettings,permissionPending,onAuthorizeMic,onAuthorizeCamera)
Text("合成意图:${override?.name ?: if(pack?.emotionAction!=null) emotionLabel else trace.label}",fontSize=12.sp) Text("合成意图:${override?.name ?: if(pack?.emotionAction!=null) emotionLabel else trace.label}",fontSize=12.sp)
if(pack?.emotionAction!=null) Text("整合候选 · 动态自然度、音乐听审及真机未测;表达可能等待 2–4 秒出口和约 1 秒过渡",fontSize=12.sp)
AvatarDiagnostics(pack,video) AvatarDiagnostics(pack,video)
Row(horizontalArrangement=Arrangement.spacedBy(8.dp)) { Row(horizontalArrangement=Arrangement.spacedBy(8.dp)) {
TextButton(onClick={override=AvatarMode.IDLE}) { Text("Idle") } TextButton(onClick={override=AvatarMode.IDLE}) { Text("Idle") }
@@ -26,7 +26,8 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
private val create: (Int)->CompositeMediaPort,private val music: MusicMediaPort, private val create: (Int)->CompositeMediaPort,private val music: MusicMediaPort,
private val reveal: (Int?)->Unit,private val report: (String,BodyFrameKey?)->Unit = { _,_-> }, private val reveal: (Int?)->Unit,private val report: (String,BodyFrameKey?)->Unit = { _,_-> },
private val allowSilentEdges: Boolean=false, private val allowSilentEdges: Boolean=false,
private val chooseIdle: (Int)->Int = { kotlin.random.Random.nextInt(it) }) : ActionPlayer { private val chooseIdle: (Int)->Int = { kotlin.random.Random.nextInt(it) },
private val chooseIdleCycles: ()->Int = { kotlin.random.Random.nextInt(2,4) }) : ActionPlayer {
private data class Slot(val number: Int,val port: CompositeMediaPort,val pack: ContinuousAvatarPack, private data class Slot(val number: Int,val port: CompositeMediaPort,val pack: ContinuousAvatarPack,
val entry: Int,val packageId: String?,var key: BodyFrameKey?=null,var live: Boolean=true,var closedMouth: Boolean=false) val entry: Int,val packageId: String?,var key: BodyFrameKey?=null,var live: Boolean=true,var closedMouth: Boolean=false)
private val slots=mutableListOf<Slot>() private val slots=mutableListOf<Slot>()
@@ -38,6 +39,9 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
private var selectedId=index.fallbackId private var selectedId=index.fallbackId
private var idleTarget: String?=null private var idleTarget: String?=null
private var lastIdle: String?=null private var lastIdle: String?=null
private var idleCycles=0
private var idleCycleGoal=chooseIdleCycles().also { check(it in 2..3) }
private fun resetIdleCycles() { idleCycles=0;idleCycleGoal=chooseIdleCycles().also { check(it in 2..3) } }
var selection: RoleVisualSelection?=null;private set var selection: RoleVisualSelection?=null;private set
val currentPackageId: String? get() = if(inBridge || actionStarted) null else visible?.packageId val currentPackageId: String? get() = if(inBridge || actionStarted) null else visible?.packageId
val visualStatus: String get() = when { val visualStatus: String get() = when {
@@ -67,14 +71,14 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
private val releaseWaiters=mutableListOf<()->Unit>() private val releaseWaiters=mutableListOf<()->Unit>()
fun beginTurn(id: Long?) { fun beginTurn(id: Long?) {
if(id==turn) return if(id==turn) return
turn=id;seq=-1;generation++;revision=0;talk=false;selection=null;idleTarget=null turn=id;seq=-1;generation++;revision=0;talk=false;selection=null;idleTarget=null;resetIdleCycles()
selectedId=visible?.packageId ?: index.fallbackId selectedId=visible?.packageId ?: index.fallbackId
if(!inBridge && revealing==null) discardRoute() if(!inBridge && revealing==null) discardRoute()
applyMouth() applyMouth()
} }
fun start() { fun start() {
if(active || closing!=0) return if(active || closing!=0) return
active=true;generation++;revision=0 active=true;generation++;revision=0;resetIdleCycles()
val slot=prepare(index.fallbackId,0);visible=slot val slot=prepare(index.fallbackId,0);visible=slot
// Ports must deliver callbacks asynchronously, like both Android ports. // Ports must deliver callbacks asynchronously, like both Android ports.
} }
@@ -94,10 +98,10 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
seq=reply.sequence seq=reply.sequence
selection=RoleVisualSelector.select(reply.emotion,reply.intensity,index.visuals,index.fallbackId) selection=RoleVisualSelector.select(reply.emotion,reply.intensity,index.visuals,index.fallbackId)
selectedId=checkNotNull(selection).packageId selectedId=checkNotNull(selection).packageId
idleTarget=null idleTarget=null;resetIdleCycles()
} }
talk=talking && reply?.turnId==turn talk=talking && reply?.turnId==turn
if(talk) idleTarget=null if(talk) { idleTarget=null;idleCycles=0 }
applyMouth() applyMouth()
if(active && !inBridge && !actionStarted) plan() if(active && !inBridge && !actionStarted) plan()
} }
@@ -143,6 +147,9 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
key==previous || key.index!=slot.pack.body.frameCount-1 || key==previous || key.index!=slot.pack.body.frameCount-1 ||
selection?.visualEmotion?.let { it!=com.gorios.lanvoice.dialogue.RoleEmotion.NEUTRAL }==true || selection?.visualEmotion?.let { it!=com.gorios.lanvoice.dialogue.RoleEmotion.NEUTRAL }==true ||
index.visuals.none { it.id==slot.packageId && it.emotion==com.gorios.lanvoice.dialogue.RoleEmotion.NEUTRAL }) return index.visuals.none { it.id==slot.packageId && it.emotion==com.gorios.lanvoice.dialogue.RoleEmotion.NEUTRAL }) return
idleCycles++
if(idleCycles<idleCycleGoal) return
resetIdleCycles()
if(idleTarget!=null && slot.packageId==idleTarget && slot.packageId!=index.fallbackId) { if(idleTarget!=null && slot.packageId==idleTarget && slot.packageId!=index.fallbackId) {
idleTarget=index.fallbackId;report("idle_variant_return_queued",key);return idleTarget=index.fallbackId;report("idle_variant_return_queued",key);return
} }
@@ -231,7 +238,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
override fun play(asset: ActionAsset,finished: (ActionEnd)->Unit,failed: ()->Unit) { override fun play(asset: ActionAsset,finished: (ActionEnd)->Unit,failed: ()->Unit) {
val media=asset.media val media=asset.media
if(!active || action!=null || media==null || index.actionPack?.assets?.contains(asset)!=true) { failed();return } if(!active || action!=null || media==null || index.actionPack?.assets?.contains(asset)!=true) { failed();return }
action=asset;actionFinished=finished;actionFailed=failed;musicReady=false;talk=false;idleTarget=null;applyMouth() action=asset;actionFinished=finished;actionFailed=failed;musicReady=false;talk=false;idleTarget=null;resetIdleCycles();applyMouth()
val epoch=++musicEpoch val epoch=++musicEpoch
music.prepare(media,{ if(active && epoch==musicEpoch && action==asset) { musicReady=true;plan() } }, music.prepare(media,{ if(active && epoch==musicEpoch && action==asset) { musicReady=true;plan() } },
{ if(active && epoch==musicEpoch && actionStarted) reveal(3) },{ { if(active && epoch==musicEpoch && actionStarted) reveal(3) },{
@@ -0,0 +1,60 @@
# Full action/emotion debug candidate — 2026-10-13
Pi explicitly admitted exact index `987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887`
from `.runtime/avatar-imports/a01-expression-action-v1/code-recovery-full-index-04`.
Approval covers independently hashed files and inspected face/fullbody/junction frames,
not comprehensive realtime naturalness, music listening, rights, device/GPU or <=1s SLA.
The immutable exact index is archived as `docs/avatar-manifests/a01-code-recovery-full-index-04.json`.
The owner's production summary remains data-only outside Git.
Implemented: five continuous own-mouth bodies N97/97/49/97/97, eight25-frame own-mouth
one-shot bridges, thirteen legal edges, two241-frame H264/AAC dance assets. Each own
runtime binds actual body SHA/PTS/N and5 mouth levels at1.1 sourcepx; mouth state curves
have independent6/12-frame clocks. TALK keeps phase through bridge/target; ACTION disables
mouth. Late/stale callbacks are fenced; bounded three playback slots and32MB total
RGBA admission remain enforced. Actual combined patch RGBA is10,911,120 bytes.
Idle variants are actually scheduled after2–3 completed neutral cycles, using legal
bridges and avoiding consecutive variants; voice/model expression/action has priority.
Dance choices prefer a different variant3:1 without forced exact alternation.
Seven model labels are preserved; happy/sad intensity2 uses slightly visual intensity1,
unsupported angry falls back as a whole package. Camera cues are independent, sharing off.
Main screen remains full avatar+gear; permissions remain first-foreground/manual.
Full production admission/import passed:5065 indexed hash/bytes checks,3222 runtime
referenced files imported,1844 review/backups excluded from APK. Original03 source and
code17 import are preserved. Reproduce the deterministic recovery using
`scripts/repair-idle-state-clock.py` against source SHA
`3a6d43cc9bf810077c55652b1fb7876cb0b3b2767ae5cbcc93fe5e9e19825781` into a new independent
output. Only two idle state frameCount/PTS were repaired; root refs/inventory rehashed.
No image/audio/video pixels were changed. Never reuse another candidate's stale SHA.
Gateway0.8 retains Qwen3.8-27b/thinking=false/json_schema/Asia-Shanghai per-request
single-system clock. Public `gateway/reviewed_action_packs.json` admits only the exact
full pin with asset_01/02 minimum video bounds10042ms. Old code17/unknown pins negotiate
no dance; HELLO cannot add packs. Canonical hash/busy/private-env/unit fences and backup
passed; only `lan-voice-gateway.service` restarted. Model/ASR/TTS/VAD services and private
provider/TTS settings were preserved. The archive model-free suite passed97 tests with
one existing Silero-model skip (98 total), nine JVM/UI suites passed,28 packaging tests,
200 actual asset software-EGL golden cases,56 actual-view callback cases,289 bridge TALK
assertions,27 idle driver assertions and17 five-body/full-action graph assertions passed.
Application/instrumentation build and HTTP packaging evidence will be appended below.
Action path requires pre-reply single-TTS drain → server ticket → actual capture stop
confirmation → legal source A → music/video with mouth off → native music end, final video
PTS, release and restored return A → completed → independent after turn/single-TTS drain.
Completion min-duration guards do not prove real playback. Repeated/late/owner/TTL/newturn/
background/settings-cancel/disconnect are fenced; no extra LLM or fixed after sentence.
During ACTION no captured PCM backlog/ASR or voice barge-in is allowed. After expression
is exposed only in its own after turn. Public probe media/record/drain confirmations are
explicitly simulated; actual ASR/Qwen/TTS service calls are distinguished from fixtures.
Known boundary: neutral/happy exit wait up to4.042s, sad up to2.042s plus1.042s bridge.
Early prepare is speculative preload; final valid expression is authoritative. Audio does
not wait for body/bridge; bridge-own mouth continues TALK. No <=1s expression claim.
Dance effective audioEnd10s, decoded AAC padding tail10.005333s, video10.041667s;
actual player completion/release controls recovery, never a10s metadata timer.
True device/GPU/mic-stop/music-tail/listening/perception certification is not_run;
no device install is authorized or performed. Music ASR auxiliary nonempty length4 for
both task audios cannot attribute background words to the actor. Commercial rights unknown.
Asset owner reports21 submitted calls/known video $4.16; image and two rate-attempt fees
unknown. This repair/code/build/probe stage made0 paid AI/media-generation calls.
+18 -1
View File
@@ -157,7 +157,7 @@ P4b/P5 integration preflight (2026-10-13; no new asset schema):
- Idle variants are additional neutral/visualIntensity0 conversationPackages rows, - Idle variants are additional neutral/visualIntensity0 conversationPackages rows,
each with own runtimeManifest, loopEdge and real fallback↔variant edges. Live each with own runtimeManifest, loopEdge and real fallback↔variant edges. Live
variant entry/return bridges need their own mouthRuntimeManifest too. Idle variant entry/return bridges need their own mouthRuntimeManifest too. Idle
selection occurs after a completed neutral cycle, returns through fallback and selection occurs after2–3 completed neutral cycles, returns through fallback and
avoids consecutive repeats where two variants exist. Active TALK, queued model avoids consecutive repeats where two variants exist. Active TALK, queued model
expression and action have priority; happy/sad expression is retained when speech expression and action have priority; happy/sad expression is retained when speech
ends. No random phase cuts, fixed TTS delay or new model tag is introduced. ends. No random phase cuts, fixed TTS delay or new model tag is introduced.
@@ -191,3 +191,20 @@ then configure capabilities/import through the separately approved release proce
- All source/target frames bind the silent delivered body SHA/PTS, not an immutable - All source/target frames bind the silent delivered body SHA/PTS, not an immutable
master with audio/cover. Count241 and approximate10s are not substitutes for master with audio/cover. Count241 and approximate10s are not substitutes for
independently measured video duration, final video PTS and presented audio end. independently measured video duration, final video PTS and presented audio end.
Full candidate admission (Pi exact pin, 2026-10-13):
`987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887`
is the independent code-recovery-full-index-04 index. Candidate frame/hash/own-layer
review permits debug integration, not comprehensive dynamic naturalness, music
listening, rights, device/GPU or perception SLA certification. All eight nonnative
bridges have their own TALK runtime; their one-shot body clock is independent of
6/12-frame mouth state clocks. Five conversation bodies and two music actions are
admitted only after production parser/media/inventory/cache checks. Runtime import
includes3222 referenced files, excluding1844 review/backup inventory files.
The public gateway registry pins both dance variants to10042ms measured video
bounds. Clients with unknown/old partial pack pins remain action-unavailable;
client HELLO cannot add to this registry. Completion still requires actual player
end/stop/release and restored A, not metadata elapsed time. Idle variant selection
waits2–3 completed neutral cycles; speech/model expression/action has priority.
Dance selection prefers a different variant3:1, allowing random repeats rather than
forcing an alternating playlist. The model chooses only kind dance.
+44 -31
View File
@@ -12,7 +12,7 @@
"bytes": 12421 "bytes": 12421
}, },
"app.py": { "app.py": {
"source": "app.py", "source": "workspace:gateway/app.py",
"sha256": "d6520894dfbe035f64b1984aae15976db4df0e7e720195c81d3bf483b240056f", "sha256": "d6520894dfbe035f64b1984aae15976db4df0e7e720195c81d3bf483b240056f",
"bytes": 5105 "bytes": 5105
}, },
@@ -34,12 +34,12 @@
}, },
"gateway.py": { "gateway.py": {
"source": "workspace:gateway/gateway.py", "source": "workspace:gateway/gateway.py",
"sha256": "fc4f53494ff253e5016c4e951ece462ae63b0b8567f0633654bce0eb74042b07", "sha256": "de94825b2005c5e4eedd1beb10360b477dc40d7e1bd6dc5c7d95b50bbc46cbef",
"bytes": 45740, "bytes": 45724,
"upstream_sha256": "d088bedcf5c0accd4712e06202f6ced8ab155aad57a5b05683724efa346326ce" "upstream_sha256": "d088bedcf5c0accd4712e06202f6ced8ab155aad57a5b05683724efa346326ce"
}, },
"guest_sessions.py": { "guest_sessions.py": {
"source": "guest_sessions.py", "source": "workspace:gateway/guest_sessions.py",
"sha256": "cc082fdb6c2ff7f5a41361ffe9ea2a53ebb944ee37354f65119405ad7a521c82", "sha256": "cc082fdb6c2ff7f5a41361ffe9ea2a53ebb944ee37354f65119405ad7a521c82",
"bytes": 1429 "bytes": 1429
}, },
@@ -50,7 +50,7 @@
"upstream_sha256": "2cf8b006bf486a03e038a69daa860ebb71a86989161cf6a7ea610114177a249f" "upstream_sha256": "2cf8b006bf486a03e038a69daa860ebb71a86989161cf6a7ea610114177a249f"
}, },
"persona_resolver.py": { "persona_resolver.py": {
"source": "persona_resolver.py", "source": "workspace:gateway/persona_resolver.py",
"sha256": "deb33b4f4c17792fa5a6837362d5b29173e60a57bb993b61363bd4882d66d5de", "sha256": "deb33b4f4c17792fa5a6837362d5b29173e60a57bb993b61363bd4882d66d5de",
"bytes": 1180 "bytes": 1180
}, },
@@ -77,7 +77,7 @@
"upstream_sha256": "d3b0201dff992b1bd0258d4aa06f8e7688322c9904c0b885aa6cf7be7046717d" "upstream_sha256": "d3b0201dff992b1bd0258d4aa06f8e7688322c9904c0b885aa6cf7be7046717d"
}, },
"protocol.py": { "protocol.py": {
"source": "protocol.py", "source": "workspace:gateway/protocol.py",
"sha256": "d9f522d958935200002e56024949a12b71eb89b3f3241635c5c307b798ee71c5", "sha256": "d9f522d958935200002e56024949a12b71eb89b3f3241635c5c307b798ee71c5",
"bytes": 2419 "bytes": 2419
}, },
@@ -117,7 +117,7 @@
"bytes": 6223 "bytes": 6223
}, },
"segmentation.py": { "segmentation.py": {
"source": "segmentation.py", "source": "workspace:gateway/segmentation.py",
"sha256": "562ffc6e06f5b9f9072860b588feae3a5d7cd6eaa8577ac928d770071b06978d", "sha256": "562ffc6e06f5b9f9072860b588feae3a5d7cd6eaa8577ac928d770071b06978d",
"bytes": 2206 "bytes": 2206
}, },
@@ -134,17 +134,17 @@
"upstream_sha256": "26f9e374354b714ab1a03b56af90bcbf32135711dc4f26e2c53eaa90c7f02ddd" "upstream_sha256": "26f9e374354b714ab1a03b56af90bcbf32135711dc4f26e2c53eaa90c7f02ddd"
}, },
"tests/test_gateway.py": { "tests/test_gateway.py": {
"source": "tests/test_gateway.py", "source": "workspace:gateway/tests/test_gateway.py",
"sha256": "f22aa98f3d6f62a2949a9047ec97e6dd686cac807d989a314a95deca718a3104", "sha256": "f22aa98f3d6f62a2949a9047ec97e6dd686cac807d989a314a95deca718a3104",
"bytes": 5814 "bytes": 5814
}, },
"tests/test_guests.py": { "tests/test_guests.py": {
"source": "tests/test_guests.py", "source": "workspace:gateway/tests/test_guests.py",
"sha256": "6bc531f1bff85b8ea550bc88c634726531a1ef241ba5c861dbb8c963adf31c35", "sha256": "6bc531f1bff85b8ea550bc88c634726531a1ef241ba5c861dbb8c963adf31c35",
"bytes": 1848 "bytes": 1848
}, },
"tests/test_history.py": { "tests/test_history.py": {
"source": "tests/test_history.py", "source": "workspace:gateway/tests/test_history.py",
"sha256": "fc13a69811cfc4f4acf265ea9e0cdd67d566358ebe9b9b53cae76197db8bce78", "sha256": "fc13a69811cfc4f4acf265ea9e0cdd67d566358ebe9b9b53cae76197db8bce78",
"bytes": 8570 "bytes": 8570
}, },
@@ -155,32 +155,32 @@
"upstream_sha256": "2576f2be903c69270cb1dec1e12448154554798bd7fca866d78e66e31594cbcb" "upstream_sha256": "2576f2be903c69270cb1dec1e12448154554798bd7fca866d78e66e31594cbcb"
}, },
"tests/test_segmentation.py": { "tests/test_segmentation.py": {
"source": "tests/test_segmentation.py", "source": "workspace:gateway/tests/test_segmentation.py",
"sha256": "cf80a74958a715a81180a7932efb84f1d0974b434cf4fc3354b68c604ccbf463", "sha256": "cf80a74958a715a81180a7932efb84f1d0974b434cf4fc3354b68c604ccbf463",
"bytes": 2240 "bytes": 2240
}, },
"tests/test_v08.py": { "tests/test_v08.py": {
"source": "tests/test_v08.py", "source": "workspace:gateway/tests/test_v08.py",
"sha256": "f993d4162576494e814786f26376ba80ab8a77af98ba70de4379055bb9525082", "sha256": "f993d4162576494e814786f26376ba80ab8a77af98ba70de4379055bb9525082",
"bytes": 2635 "bytes": 2635
}, },
"tests/test_vad.py": { "tests/test_vad.py": {
"source": "tests/test_vad.py", "source": "workspace:gateway/tests/test_vad.py",
"sha256": "bff64c0aafa05c085af7c1c9418244609129d405320fe1080b4ba05a8e304228", "sha256": "bff64c0aafa05c085af7c1c9418244609129d405320fe1080b4ba05a8e304228",
"bytes": 4899 "bytes": 4899
}, },
"tests_fake.py": { "tests_fake.py": {
"source": "tests_fake.py", "source": "workspace:gateway/tests_fake.py",
"sha256": "9a40f1948352f69f1dd20f8514baef58ae3d11eec240e1d2324d8990bad915d8", "sha256": "9a40f1948352f69f1dd20f8514baef58ae3d11eec240e1d2324d8990bad915d8",
"bytes": 133 "bytes": 133
}, },
"tts_debug.py": { "tts_debug.py": {
"source": "tts_debug.py", "source": "workspace:gateway/tts_debug.py",
"sha256": "d7b31b98a7f8ab688981873ef81decdf0b2f0167113c9103df039b7b24c9ccf2", "sha256": "d7b31b98a7f8ab688981873ef81decdf0b2f0167113c9103df039b7b24c9ccf2",
"bytes": 5103 "bytes": 5103
}, },
"vad.py": { "vad.py": {
"source": "vad.py", "source": "workspace:gateway/vad.py",
"sha256": "3718ff9b296b2bba447100af520a631f221dcbfa322dd564cdc5809fb3675f23", "sha256": "3718ff9b296b2bba447100af520a631f221dcbfa322dd564cdc5809fb3675f23",
"bytes": 6997 "bytes": 6997
}, },
@@ -326,8 +326,8 @@
}, },
"action_protocol.py": { "action_protocol.py": {
"source": "workspace:gateway/action_protocol.py", "source": "workspace:gateway/action_protocol.py",
"sha256": "6e312aaa3736b99c24215512187a16689d4a5af8635b29bbc13c7cc1e002bace", "sha256": "ca98055f9ddba361d36607791522cee15ce254b3d40395cd45c508e96c42a2f8",
"bytes": 3394 "bytes": 4166
}, },
"action_reply.py": { "action_reply.py": {
"source": "workspace:gateway/action_reply.py", "source": "workspace:gateway/action_reply.py",
@@ -341,8 +341,8 @@
}, },
"tests/test_action_protocol.py": { "tests/test_action_protocol.py": {
"source": "workspace:gateway/tests/test_action_protocol.py", "source": "workspace:gateway/tests/test_action_protocol.py",
"sha256": "fdc6c6206a6a0478166bc49b062c2981158cf1a6a8cdcf3e0d0df57a86fa4020", "sha256": "f1340c6c68674fc5d077003ca6be51746b31462ccc26acc0c092fbad01f629dc",
"bytes": 15127, "bytes": 15881,
"upstream_sha256": "ae564b6a6e51620a33250e160df2ae0ba6619c5ea6d1063e96bfcd8baa144a79" "upstream_sha256": "ae564b6a6e51620a33250e160df2ae0ba6619c5ea6d1063e96bfcd8baa144a79"
}, },
"tests/test_action_reply.py": { "tests/test_action_reply.py": {
@@ -354,6 +354,11 @@
"source": "workspace:gateway/tests/test_server_clock.py", "source": "workspace:gateway/tests/test_server_clock.py",
"sha256": "b7e91ff717fbdcb76984829bd7b184b4633f80dc01637cff33cc0d90363a9518", "sha256": "b7e91ff717fbdcb76984829bd7b184b4633f80dc01637cff33cc0d90363a9518",
"bytes": 2681 "bytes": 2681
},
"reviewed_action_packs.json": {
"source": "workspace:gateway/reviewed_action_packs.json",
"sha256": "830334cacf04bc488e7f07809a6defdcec481410b6bedb7b78cfa78f8ecf334e",
"bytes": 125
} }
}, },
"archive_baseline_commit": "19a7adccd9322986eb0646b165b9ce1cf2650cf2", "archive_baseline_commit": "19a7adccd9322986eb0646b165b9ce1cf2650cf2",
@@ -387,13 +392,13 @@
}, },
"release_baseline_commit": "d43c7d4e809a5a6b18ca9f28c8163a2f9ad34c7f", "release_baseline_commit": "d43c7d4e809a5a6b18ca9f28c8163a2f9ad34c7f",
"deployment_baseline": { "deployment_baseline": {
"release": "gateway-0.8.0 / Android-0.7.0-stage-dev-code16", "release": "gateway-0.8.0 / reviewed full action/emotion candidate",
"files": { "files": {
"action_protocol.py": "6e312aaa3736b99c24215512187a16689d4a5af8635b29bbc13c7cc1e002bace", "action_protocol.py": "ca98055f9ddba361d36607791522cee15ce254b3d40395cd45c508e96c42a2f8",
"action_reply.py": "4d66164a6668a571dc861282a5c80e408b51dfcfd67f45141e8c6701f6b81364", "action_reply.py": "4d66164a6668a571dc861282a5c80e408b51dfcfd67f45141e8c6701f6b81364",
"app.py": "d6520894dfbe035f64b1984aae15976db4df0e7e720195c81d3bf483b240056f", "app.py": "d6520894dfbe035f64b1984aae15976db4df0e7e720195c81d3bf483b240056f",
"face_context.py": "d032ff8033a49219595d6edff2950856937e024782143621d37d02b56b024315", "face_context.py": "d032ff8033a49219595d6edff2950856937e024782143621d37d02b56b024315",
"gateway.py": "fc4f53494ff253e5016c4e951ece462ae63b0b8567f0633654bce0eb74042b07", "gateway.py": "de94825b2005c5e4eedd1beb10360b477dc40d7e1bd6dc5c7d95b50bbc46cbef",
"guest_sessions.py": "cc082fdb6c2ff7f5a41361ffe9ea2a53ebb944ee37354f65119405ad7a521c82", "guest_sessions.py": "cc082fdb6c2ff7f5a41361ffe9ea2a53ebb944ee37354f65119405ad7a521c82",
"history.py": "0015b3143268f3e22a8a8a53b65ef4e3522f1f881dfca213c93142899c02631e", "history.py": "0015b3143268f3e22a8a8a53b65ef4e3522f1f881dfca213c93142899c02631e",
"llm_provider.py": "b3cf6ab5e4c953ef13dc00802f4594055164c89b10b875dda44f071ad1ede082", "llm_provider.py": "b3cf6ab5e4c953ef13dc00802f4594055164c89b10b875dda44f071ad1ede082",
@@ -402,9 +407,10 @@
"personas/yangmi.lorebook.json": "73badae3fd8582555caa338e50fb6193e64e6a43025dd469672aa903c1c4b71b", "personas/yangmi.lorebook.json": "73badae3fd8582555caa338e50fb6193e64e6a43025dd469672aa903c1c4b71b",
"protocol.py": "d9f522d958935200002e56024949a12b71eb89b3f3241635c5c307b798ee71c5", "protocol.py": "d9f522d958935200002e56024949a12b71eb89b3f3241635c5c307b798ee71c5",
"reply_emotion.py": "080f04e368c5a7d26254f2b870803238941aa481d457227ba15a870fd4a4e3c0", "reply_emotion.py": "080f04e368c5a7d26254f2b870803238941aa481d457227ba15a870fd4a4e3c0",
"reviewed_action_packs.json": "830334cacf04bc488e7f07809a6defdcec481410b6bedb7b78cfa78f8ecf334e",
"segmentation.py": "562ffc6e06f5b9f9072860b588feae3a5d7cd6eaa8577ac928d770071b06978d", "segmentation.py": "562ffc6e06f5b9f9072860b588feae3a5d7cd6eaa8577ac928d770071b06978d",
"server_clock.py": "dc46d79fd43c8b94f52acfdea0564058c47f3a3b8b43aa53fe6868a1821f3a0e", "server_clock.py": "dc46d79fd43c8b94f52acfdea0564058c47f3a3b8b43aa53fe6868a1821f3a0e",
"tests/test_action_protocol.py": "2e19bb1471a2bab67bfb7adca1630151d466e50d9ebc103e54c2f92566f63b63", "tests/test_action_protocol.py": "f1340c6c68674fc5d077003ca6be51746b31462ccc26acc0c092fbad01f629dc",
"tests/test_action_reply.py": "0c40a937be4c6545e04ed2268df1714c34dce982058f6b19daabf06b0fa30932", "tests/test_action_reply.py": "0c40a937be4c6545e04ed2268df1714c34dce982058f6b19daabf06b0fa30932",
"tests/test_continuity.py": "d8390238f390463a98f12b9909bb5846be65f5b6dc1b21b94338b4cd75aaafae", "tests/test_continuity.py": "d8390238f390463a98f12b9909bb5846be65f5b6dc1b21b94338b4cd75aaafae",
"tests/test_debug.py": "7d1d7876c4106f3df0b84cf8f7e479afb4a30ca51264fb94fa288fdd8155883e", "tests/test_debug.py": "7d1d7876c4106f3df0b84cf8f7e479afb4a30ca51264fb94fa288fdd8155883e",
@@ -443,35 +449,42 @@
"time_zone": "Asia/Shanghai", "time_zone": "Asia/Shanghai",
"action_protocol": 1, "action_protocol": 1,
"ordered_expression": "strict schema prefix preload only; final authoritative", "ordered_expression": "strict schema prefix preload only; final authoritative",
"action_default": "unavailable until exact independently reviewed pack negotiation" "action_default": "unavailable until exact independently reviewed pack negotiation",
"reviewed_action_pack": "987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887"
}, },
"previous_deployment_baseline": { "previous_deployment_baseline": {
"release": "gateway-0.7.3 / Android-0.5.2", "release": "gateway-0.8.0 / Android-0.7.0-stage-dev-code16",
"files": { "files": {
"action_protocol.py": "6e312aaa3736b99c24215512187a16689d4a5af8635b29bbc13c7cc1e002bace",
"action_reply.py": "4d66164a6668a571dc861282a5c80e408b51dfcfd67f45141e8c6701f6b81364",
"app.py": "d6520894dfbe035f64b1984aae15976db4df0e7e720195c81d3bf483b240056f", "app.py": "d6520894dfbe035f64b1984aae15976db4df0e7e720195c81d3bf483b240056f",
"face_context.py": "d032ff8033a49219595d6edff2950856937e024782143621d37d02b56b024315", "face_context.py": "d032ff8033a49219595d6edff2950856937e024782143621d37d02b56b024315",
"gateway.py": "ea268a5abf36f79483427a78991d9ab2bab814ea3042ffcc08025de8c4af6b6d", "gateway.py": "fc4f53494ff253e5016c4e951ece462ae63b0b8567f0633654bce0eb74042b07",
"guest_sessions.py": "cc082fdb6c2ff7f5a41361ffe9ea2a53ebb944ee37354f65119405ad7a521c82", "guest_sessions.py": "cc082fdb6c2ff7f5a41361ffe9ea2a53ebb944ee37354f65119405ad7a521c82",
"history.py": "2cf8b006bf486a03e038a69daa860ebb71a86989161cf6a7ea610114177a249f", "history.py": "0015b3143268f3e22a8a8a53b65ef4e3522f1f881dfca213c93142899c02631e",
"llm_provider.py": "21aa2885c24f3240e891fd5325b09446ae1d8a95497d07a53082410d9fac2b10", "llm_provider.py": "b3cf6ab5e4c953ef13dc00802f4594055164c89b10b875dda44f071ad1ede082",
"persona_resolver.py": "deb33b4f4c17792fa5a6837362d5b29173e60a57bb993b61363bd4882d66d5de", "persona_resolver.py": "deb33b4f4c17792fa5a6837362d5b29173e60a57bb993b61363bd4882d66d5de",
"personas/lvbu.lorebook.json": "1f144b431bdd5d9cda0ce593438fa88e717c0671d496105883a3d4db7bd635ea", "personas/lvbu.lorebook.json": "1f144b431bdd5d9cda0ce593438fa88e717c0671d496105883a3d4db7bd635ea",
"personas/yangmi.lorebook.json": "73badae3fd8582555caa338e50fb6193e64e6a43025dd469672aa903c1c4b71b", "personas/yangmi.lorebook.json": "73badae3fd8582555caa338e50fb6193e64e6a43025dd469672aa903c1c4b71b",
"protocol.py": "d9f522d958935200002e56024949a12b71eb89b3f3241635c5c307b798ee71c5", "protocol.py": "d9f522d958935200002e56024949a12b71eb89b3f3241635c5c307b798ee71c5",
"reply_emotion.py": "080f04e368c5a7d26254f2b870803238941aa481d457227ba15a870fd4a4e3c0", "reply_emotion.py": "080f04e368c5a7d26254f2b870803238941aa481d457227ba15a870fd4a4e3c0",
"segmentation.py": "562ffc6e06f5b9f9072860b588feae3a5d7cd6eaa8577ac928d770071b06978d", "segmentation.py": "562ffc6e06f5b9f9072860b588feae3a5d7cd6eaa8577ac928d770071b06978d",
"server_clock.py": "dc46d79fd43c8b94f52acfdea0564058c47f3a3b8b43aa53fe6868a1821f3a0e",
"tests/test_action_protocol.py": "2e19bb1471a2bab67bfb7adca1630151d466e50d9ebc103e54c2f92566f63b63",
"tests/test_action_reply.py": "0c40a937be4c6545e04ed2268df1714c34dce982058f6b19daabf06b0fa30932",
"tests/test_continuity.py": "d8390238f390463a98f12b9909bb5846be65f5b6dc1b21b94338b4cd75aaafae", "tests/test_continuity.py": "d8390238f390463a98f12b9909bb5846be65f5b6dc1b21b94338b4cd75aaafae",
"tests/test_debug.py": "7d1d7876c4106f3df0b84cf8f7e479afb4a30ca51264fb94fa288fdd8155883e", "tests/test_debug.py": "7d1d7876c4106f3df0b84cf8f7e479afb4a30ca51264fb94fa288fdd8155883e",
"tests/test_face_context.py": "c297866117fa7406b5fda95250b67ca7ebd7476486ddd5455935c140d31c9f6f", "tests/test_face_context.py": "c297866117fa7406b5fda95250b67ca7ebd7476486ddd5455935c140d31c9f6f",
"tests/test_gateway.py": "f22aa98f3d6f62a2949a9047ec97e6dd686cac807d989a314a95deca718a3104", "tests/test_gateway.py": "f22aa98f3d6f62a2949a9047ec97e6dd686cac807d989a314a95deca718a3104",
"tests/test_gateway_emotion.py": "234310a9f44e3ece56482f4e2080e4f0882d1ea8b7dcd85795c816a8c1ebed78", "tests/test_gateway_emotion.py": "b4123066d3b50220825bf83aa3e96950a02d091d522f08085fb293d29f9706cf",
"tests/test_gateway_reply_face.py": "393c95b7e97981b46445cd699890bb7b732d1c479310daf09bdf2c8349e47f4c", "tests/test_gateway_reply_face.py": "393c95b7e97981b46445cd699890bb7b732d1c479310daf09bdf2c8349e47f4c",
"tests/test_guests.py": "6bc531f1bff85b8ea550bc88c634726531a1ef241ba5c861dbb8c963adf31c35", "tests/test_guests.py": "6bc531f1bff85b8ea550bc88c634726531a1ef241ba5c861dbb8c963adf31c35",
"tests/test_history.py": "fc13a69811cfc4f4acf265ea9e0cdd67d566358ebe9b9b53cae76197db8bce78", "tests/test_history.py": "fc13a69811cfc4f4acf265ea9e0cdd67d566358ebe9b9b53cae76197db8bce78",
"tests/test_llm_provider.py": "43669d1fd7e61452b96f314a7f161fbcec843e463c74208d0f892fb58b839785", "tests/test_llm_provider.py": "9395b0f1da36a09aebcc9c2d7c151328526449c1bcedbb5f97a190d0fc5573df",
"tests/test_personas.py": "013b18e7b7f0e582d8d7e04f5b1fb78009e993f96357be67a5367e70444b43e1", "tests/test_personas.py": "013b18e7b7f0e582d8d7e04f5b1fb78009e993f96357be67a5367e70444b43e1",
"tests/test_reply_emotion.py": "4ff2774187df8220ddbc8ef5b79910ae5047af3bacdb9476b0d2a8f55929d3be", "tests/test_reply_emotion.py": "4ff2774187df8220ddbc8ef5b79910ae5047af3bacdb9476b0d2a8f55929d3be",
"tests/test_segmentation.py": "cf80a74958a715a81180a7932efb84f1d0974b434cf4fc3354b68c604ccbf463", "tests/test_segmentation.py": "cf80a74958a715a81180a7932efb84f1d0974b434cf4fc3354b68c604ccbf463",
"tests/test_server_clock.py": "b7e91ff717fbdcb76984829bd7b184b4633f80dc01637cff33cc0d90363a9518",
"tests/test_v08.py": "f993d4162576494e814786f26376ba80ab8a77af98ba70de4379055bb9525082", "tests/test_v08.py": "f993d4162576494e814786f26376ba80ab8a77af98ba70de4379055bb9525082",
"tests/test_vad.py": "bff64c0aafa05c085af7c1c9418244609129d405320fe1080b4ba05a8e304228", "tests/test_vad.py": "bff64c0aafa05c085af7c1c9418244609129d405320fe1080b4ba05a8e304228",
"tests_fake.py": "9a40f1948352f69f1dd20f8514baef58ae3d11eec240e1d2324d8990bad915d8", "tests_fake.py": "9a40f1948352f69f1dd20f8514baef58ae3d11eec240e1d2324d8990bad915d8",
+18
View File
@@ -1,10 +1,28 @@
"""Ephemeral one-owner, one-connection action tickets. No persistence or replay.""" """Ephemeral one-owner, one-connection action tickets. No persistence or replay."""
from dataclasses import dataclass from dataclasses import dataclass
import json
import os
from pathlib import Path
import re import re
import secrets import secrets
import time import time
def configured_packs():
"""Public coordinator-reviewed registry plus explicit private operator overrides.
Invalid registry/config fails closed; no client can add a pack through HELLO.
"""
path=Path(__file__).with_name('reviewed_action_packs.json')
try:
if path.exists() and path.stat().st_size>8192: return {}
public=json.loads(path.read_text()) if path.exists() else {}
private=json.loads(os.environ.get('LAN_ACTION_PACKS','{}'))
if not isinstance(public,dict) or not isinstance(private,dict): return {}
# The immutable public pin's measured bounds cannot be shortened by env config.
return {**private,**public}
except (ValueError,OSError):return {}
def negotiate(hello, configured): def negotiate(hello, configured):
"""Server configuration pins independently reviewed manifests, never client claims.""" """Server configuration pins independently reviewed manifests, never client claims."""
if hello.get('action_protocol') != 1 or hello.get('action_kinds') != ['dance']: if hello.get('action_protocol') != 1 or hello.get('action_kinds') != ['dance']:
+2 -2
View File
@@ -21,7 +21,7 @@ from history import History
from face_context import FaceContext from face_context import FaceContext
from reply_emotion import SYSTEM_FRAGMENT, parse_reply from reply_emotion import SYSTEM_FRAGMENT, parse_reply
from action_reply import ACTION_FRAGMENT, ExpressionPrefix, parse_action_reply from action_reply import ACTION_FRAGMENT, ExpressionPrefix, parse_action_reply
from action_protocol import ActionPlans, negotiate from action_protocol import ActionPlans, negotiate, configured_packs
from guest_sessions import GuestSessions, COOKIE from guest_sessions import GuestSessions, COOKIE
from tts_debug import DebugStore from tts_debug import DebugStore
from persona_resolver import resolve_persona from persona_resolver import resolve_persona
@@ -754,7 +754,7 @@ async def dialogue(ws: WebSocket):
session.synthesis_mode = synthesis_mode session.synthesis_mode = synthesis_mode
session.owner = owner or 'admin' session.owner = owner or 'admin'
session.action_plans = ActionPlans(session.owner, session.connection_generation) session.action_plans = ActionPlans(session.owner, session.connection_generation)
session.action_capability = negotiate(hello, json.loads(os.environ.get('LAN_ACTION_PACKS', '{}'))) session.action_capability = negotiate(hello, configured_packs())
if owner: session.auth_check = lambda: bool(app.state.guests.get(owner)) if owner: session.auth_check = lambda: bool(app.state.guests.get(owner))
voice_mode = hello.get('voice_mode', 'continuous_voice') voice_mode = hello.get('voice_mode', 'continuous_voice')
if voice_mode not in ('continuous_voice', 'fragment'): raise ValueError('voice mode') if voice_mode not in ('continuous_voice', 'fragment'): raise ValueError('voice mode')
+6
View File
@@ -0,0 +1,6 @@
{
"987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887": {
"asset_01": 10042,
"asset_02": 10042
}
}
+2
View File
@@ -16,6 +16,8 @@ args=parser.parse_args()
with tempfile.TemporaryDirectory(prefix='lan-voice-archive-check-') as folder: with tempfile.TemporaryDirectory(prefix='lan-voice-archive-check-') as folder:
stage = Path(folder) stage = Path(folder)
for source in root.glob('*.py'): shutil.copy2(source, stage/source.name) for source in root.glob('*.py'): shutil.copy2(source, stage/source.name)
registry=root/'reviewed_action_packs.json'
if registry.exists():shutil.copy2(registry,stage/registry.name)
for name in ('tests','personas','web'): for name in ('tests','personas','web'):
shutil.copytree(root/name, stage/name, ignore=shutil.ignore_patterns('__pycache__')) shutil.copytree(root/name, stage/name, ignore=shutil.ignore_patterns('__pycache__'))
if args.vad_model: if args.vad_model:
+10 -1
View File
@@ -6,7 +6,8 @@ import unittest
from pathlib import Path from pathlib import Path
import httpx import httpx
from action_protocol import ActionPlans, negotiate from action_protocol import ActionPlans, negotiate, configured_packs
from unittest.mock import patch
from action_reply import parse_action_reply from action_reply import parse_action_reply
from gateway import Dialogue from gateway import Dialogue
from history import History from history import History
@@ -30,6 +31,14 @@ RAW=json.dumps(dict(emotion='happy',intensity=1,reply='好呀。',action='dance'
class ActionProtocolTests(unittest.TestCase): class ActionProtocolTests(unittest.TestCase):
def test_unknown_capability_and_independent_review_allowlist(self): def test_unknown_capability_and_independent_review_allowlist(self):
full='987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887'
with patch.dict('os.environ',{'LAN_ACTION_PACKS':'{}'}):
reviewed=configured_packs()
self.assertEqual(reviewed[full],{'asset_01':10042,'asset_02':10042})
self.assertIsNone(negotiate({'action_protocol':1,'action_kinds':['dance'],'action_pack_sha256':
'e73f336123bf5e2dec2d82b97eb22cc632a4ee75bcf7f4bd0052b1ff42d95cd7'},reviewed))
self.assertEqual(negotiate({'action_protocol':1,'action_kinds':['dance'],'action_pack_sha256':full},reviewed)[0],full)
with patch.dict('os.environ',{'LAN_ACTION_PACKS':'[]'}):self.assertEqual(configured_packs(),{})
configured={SHA:PACK[1]} configured={SHA:PACK[1]}
for hello in ({},{'action_protocol':1},{'action_protocol':2,'action_kinds':['dance'],'action_pack_sha256':SHA}, for hello in ({},{'action_protocol':1},{'action_protocol':2,'action_kinds':['dance'],'action_pack_sha256':SHA},
{'action_protocol':1,'action_kinds':['dance'],'action_pack_sha256':'b'*64}): {'action_protocol':1,'action_kinds':['dance'],'action_pack_sha256':'b'*64}):
+11 -4
View File
@@ -57,7 +57,14 @@ async def main(stage):
'http://127.0.0.1:8888/v1','qwen3.8-27b','json_schema','Asia/Shanghai') 'http://127.0.0.1:8888/v1','qwen3.8-27b','json_schema','Asia/Shanghai')
report.update(provider=provider.model,zone=provider.clock.zone.key,mode=provider.structured_output) report.update(provider=provider.model,zone=provider.clock.zone.key,mode=provider.structured_output)
fixture_sha=hashlib.sha256(b'isolated-public-action-calling-path-fixture-not-an-asset').hexdigest() fixture_sha=hashlib.sha256(b'isolated-public-action-calling-path-fixture-not-an-asset').hexdigest()
os.environ['LAN_ACTION_PACKS']=json.dumps({fixture_sha:{'asset_01':1000,'asset_02':1000}}) if approved:
from action_protocol import configured_packs
assert configured_packs().get(approved['sha256'])==approved['durations']
fixture_sha=approved['sha256'];playback_ms=max(approved['durations'].values())
report['approved_pack_metadata']=approved
else:
playback_ms=1000
os.environ['LAN_ACTION_PACKS']=json.dumps({fixture_sha:{'asset_01':1000,'asset_02':1000}})
token=secrets.token_urlsafe(32) # Ephemeral fixture token, never output. token=secrets.token_urlsafe(32) # Ephemeral fixture token, never output.
history=History(stage/'fixture-history.sqlite3');await history.initialize() history=History(stage/'fixture-history.sqlite3');await history.initialize()
clocks=[] clocks=[]
@@ -115,7 +122,7 @@ async def main(stage):
event=json.loads(await ws.recv());assert event['type']=='hello' event=json.loads(await ws.recv());assert event['type']=='hello'
return event return event
availability=[] availability=[]
for cap in ({},{'action_protocol':1,'action_kinds':['dance'],'action_pack_sha256':'b'*64}): for cap in ({},{'action_protocol':1,'action_kinds':['dance'],'action_pack_sha256':'b'*64},{'action_protocol':1,'action_kinds':['dance'],'action_pack_sha256':'e73f336123bf5e2dec2d82b97eb22cc632a4ee75bcf7f4bd0052b1ff42d95cd7'}):
async with websockets.connect(f'ws://127.0.0.1:{port}/ws/dialogue',**kwargs) as ws: async with websockets.connect(f'ws://127.0.0.1:{port}/ws/dialogue',**kwargs) as ws:
event=await hello(ws,cap);availability.append(event['action_available']);assert not event['action_available'] event=await hello(ws,cap);availability.append(event['action_available']);assert not event['action_available']
async with asyncio.timeout(5): async with asyncio.timeout(5):
@@ -189,7 +196,7 @@ async def main(stage):
await ws.send(json.dumps({'type':'ping'})) await ws.send(json.dumps({'type':'ping'}))
if kind=='pong' and plan is not None and after_turn is None: if kind=='pong' and plan is not None and after_turn is None:
assert report['tts_requests']==2 and len(emotions)==1 assert report['tts_requests']==2 and len(emotions)==1
await asyncio.sleep(max(0,1.05-(time.monotonic()-started_at))) await asyncio.sleep(max(0,(playback_ms/1000+.05)-(time.monotonic()-started_at)))
await ws.send(json.dumps(complete));await ws.send(json.dumps(complete)) await ws.send(json.dumps(complete));await ws.send(json.dumps(complete))
trace({'type':'fixture.audio_video_end_returnA_completed_twice','turn_id':pre_turn}) trace({'type':'fixture.audio_video_end_returnA_completed_twice','turn_id':pre_turn})
if kind=='speech.start': if kind=='speech.start':
@@ -218,7 +225,7 @@ async def main(stage):
'premature_completion_no_after':True,'action_pcm_no_second_asr':True, 'premature_completion_no_after':True,'action_pcm_no_second_asr':True,
'prepare_ms':metrics[pre_turn].get('expression_prepare_ms'), 'prepare_ms':metrics[pre_turn].get('expression_prepare_ms'),
'full_reply_ms':metrics[pre_turn]['llm_first_body_ms'],'finish_reason':metrics[pre_turn]['llm_finish_reason'], 'full_reply_ms':metrics[pre_turn]['llm_first_body_ms'],'finish_reason':metrics[pre_turn]['llm_finish_reason'],
'simulated_media_duration_ms':1000,'mic_audio_record':'not_run','music_video_playback':'not_run'} 'simulated_media_duration_ms':playback_ms,'mic_audio_record':'not_run','music_video_playback':'not_run'}
finally: finally:
server.should_exit=True server.should_exit=True
with suppress(Exception): await asyncio.wait_for(task,5) with suppress(Exception): await asyncio.wait_for(task,5)
+4 -4
View File
@@ -35,7 +35,7 @@ with tempfile.TemporaryDirectory(prefix='voice-gateway-stage-') as folder:
for name,content in bundle.items(): for name,content in bundle.items():
path=stage/name;path.parent.mkdir(parents=True,exist_ok=True);path.write_bytes(base64.b64decode(content)) path=stage/name;path.parent.mkdir(parents=True,exist_ok=True);path.write_bytes(base64.b64decode(content))
test_start=time.perf_counter() 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'}) result=subprocess.run([sys.executable,str(stage/'scripts/check-archive.py')],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, 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,
'candidate_source_hashes':{name:hashlib.sha256((stage/name).read_bytes()).hexdigest() for name in deploy_files}} 'candidate_source_hashes':{name:hashlib.sha256((stage/name).read_bytes()).hexdigest() for name in deploy_files}}
if result.returncode: print(json.dumps(summary));raise SystemExit(1) if result.returncode: print(json.dumps(summary));raise SystemExit(1)
@@ -45,7 +45,7 @@ with tempfile.TemporaryDirectory(prefix='voice-gateway-stage-') as folder:
if health().get('busy'):raise RuntimeError('gateway_busy_after_tests_no_restart') if health().get('busy'):raise RuntimeError('gateway_busy_after_tests_no_restart')
backup=root/'.runtime/backups'/time.strftime('voice-gateway-%Y%m%d-%H%M%S');backup.mkdir(parents=True,mode=0o700) backup=root/'.runtime/backups'/time.strftime('voice-gateway-%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. # 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'))+list((root/'personas').glob('*.json')): for path in list(root.glob('*.py'))+list((root/'tests').glob('*.py'))+list((root/'personas').glob('*.json'))+list(root.glob('reviewed_action_packs.json')):
dst=backup/path.relative_to(root);dst.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(path,dst) 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): 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) dst=backup/'private'/str(i);dst.parent.mkdir(parents=True,exist_ok=True,mode=0o700);shutil.copy2(path,dst)
@@ -86,9 +86,9 @@ def main():
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--apply',action='store_true');args=parser.parse_args() 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()) source=root/'gateway';manifest=json.loads((source/'SOURCE_MANIFEST.json').read_text())
baseline=manifest.get('deployment_baseline',manifest['provider_baseline'])['files'] baseline=manifest.get('deployment_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')}) 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')}|{'reviewed_action_packs.json'})
public_personas={'personas/lvbu.lorebook.json','personas/yangmi.lorebook.json'} public_personas={'personas/lvbu.lorebook.json','personas/yangmi.lorebook.json'}
assert all((n.endswith('.py') or n in public_personas) and not Path(n).is_absolute() and '..' not in Path(n).parts for n in files) assert all((n.endswith('.py') or n in public_personas or n=='reviewed_action_packs.json') 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} expected={name:baseline.get(name) for name in files}
record=root/'logs/voice-investigation/gateway-emotion-deploy.json' record=root/'logs/voice-investigation/gateway-emotion-deploy.json'
# SOURCE_MANIFEST is the reviewed expected live baseline. Old ignored records # SOURCE_MANIFEST is the reviewed expected live baseline. Old ignored records
+29 -10
View File
@@ -252,10 +252,25 @@ def next_version(paths):
return max([16,*codes])+1 return max([16,*codes])+1
def tested_source(): def reviewed_actions(index,pin,registry):
"""External pin is necessary but never replaces production media validation."""
require(registry is not None,'dance import/publication requires separately reviewed gateway capability admission; read-only gate supported')
table=read_json(registry)
expected={row['id']:(row['clip']['durationUs']+999)//1000 for row in index['actions']}
require(set(expected)=={'asset_01','asset_02'} and all(row['kind']=='dance' and row['mouthAllowed'] is False for row in index['actions']),'reviewed dance shape')
require(table.get(pin)==expected,'reviewed action pin/duration mismatch')
return expected
def tested_source(full=False):
client=json.loads((ROOT/'logs/avatar-safe-061/client-tests.json').read_text()) client=json.loads((ROOT/'logs/avatar-safe-061/client-tests.json').read_text())
require(client['status']=='passed' and client['jvm_entry_points']==9,'client regression evidence') require(client['status']=='passed' and client['jvm_entry_points']==9,'client regression evidence')
for name,digest in client['hashes'].items(): require(file_sha(ROOT/name)==digest,'untested source: '+name) for name,digest in client['hashes'].items(): require(file_sha(ROOT/name)==digest,'untested source: '+name)
if full:
evidence=read_json(ROOT/'logs/action-emotion/full-release/checks.json')
require(evidence['gateway_passed']==97 and evidence['gateway_skipped']==1 and evidence['offline_gles_goldens']==200 and evidence['packaging_passed']>=27,'full release regression evidence')
for name,digest in evidence['hashes'].items(): require(file_sha(ROOT/name)==digest,'full release evidence drift: '+name)
return
evidence=json.loads((ROOT/'logs/action-emotion/bridge-talk/delivery.json').read_text()) evidence=json.loads((ROOT/'logs/action-emotion/bridge-talk/delivery.json').read_text())
require(evidence['gateway_passed']==97 and evidence['gateway_skipped']==1 and evidence['offline_gles_goldens']==40,'gateway/GLES evidence') require(evidence['gateway_passed']==97 and evidence['gateway_skipped']==1 and evidence['offline_gles_goldens']==40,'gateway/GLES evidence')
for name,digest in evidence['source_hashes'].items(): for name,digest in evidence['source_hashes'].items():
@@ -268,18 +283,20 @@ def packaging_tests_current():
for name,digest in evidence['hashes'].items(): require(file_sha(ROOT/name)==digest,'untested packaging source: '+name) for name,digest in evidence['hashes'].items(): require(file_sha(ROOT/name)==digest,'untested packaging source: '+name)
def publish(report,output,requested): def publish(report,output,requested,full=False):
require(all(edge.get('nativeLoop') is True or 'mouthRuntimeManifest' in edge for edge in read_json(ROOT/'app/src/main/assets'/ASSET_ROOT/'manifest.json')['edges']), require(all(edge.get('nativeLoop') is True or 'mouthRuntimeManifest' in edge for edge in read_json(ROOT/'app/src/main/assets'/ASSET_ROOT/'manifest.json')['edges']),
'live emotion release needs bridge-own TALK runtimes') 'live emotion release needs bridge-own TALK runtimes')
tested_source();packaging_tests_current();require(file_sha(ROLLBACK)==ROLLBACK_SHA,'rollback drift') tested_source(full);packaging_tests_current();require(file_sha(ROLLBACK)==ROLLBACK_SHA,'rollback drift')
version=next_version((ROOT/'artifacts').glob('*.apk')) version=next_version((ROOT/'artifacts').glob('*.apk'))
if requested is not None: if requested is not None:
require(requested>=version,'version code occupied');version=requested require(requested>=version,'version code occupied');version=requested
require(not full or version>=18,'full candidate needs code >=18')
subprocess.run([str(ROOT/'scripts/build.sh'),'assembleDebug','compileDebugAndroidTestKotlin','-PavatarActionCandidate=true', subprocess.run([str(ROOT/'scripts/build.sh'),'assembleDebug','compileDebugAndroidTestKotlin','-PavatarActionCandidate=true',
'-PavatarNatural=true','-PavatarMouthCandidate=true','-PnaturalManifestSha='+LEGACY_PIN, '-PavatarNatural=true','-PavatarMouthCandidate=true','-PnaturalManifestSha='+LEGACY_PIN,
'-PemotionManifestSha='+report['manifest_sha256'],'-PactionVersionCode='+str(version)],check=True,cwd=ROOT) '-PemotionManifestSha='+report['manifest_sha256'],'-PactionVersionCode='+str(version),'-PavatarFullActionCandidate='+str(full).lower()],check=True,cwd=ROOT)
built=ROOT/'app/build/outputs/apk/debug/app-debug.apk';badge=badging(built) built=ROOT/'app/build/outputs/apk/debug/app-debug.apk';badge=badging(built)
for text in ("name='com.gorios.lanvoice'",f"versionCode='{version}'","versionName='0.7.0-emotion-dev'","sdkVersion:'26'","targetSdkVersion:'34'"): version_name='0.7.0' if full else '0.7.0-emotion-dev'
for text in ("name='com.gorios.lanvoice'",f"versionCode='{version}'",f"versionName='{version_name}'","sdkVersion:'26'","targetSdkVersion:'34'"):
require(text in badge,'APK metadata: '+text) require(text in badge,'APK metadata: '+text)
require(re.search(r'^native-code: (.+)$',badge,re.M)[1].strip()=="'arm64-v8a'",'APK ABI') 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(built)],text=True) cert=subprocess.check_output([str(TOOLS/'apksigner'),'verify','--verbose','--print-certs',str(built)],text=True)
@@ -295,7 +312,8 @@ def publish(report,output,requested):
config=ROOT/'app/build/generated/source/buildConfig/debug/com/gorios/lanvoice/BuildConfig.java' config=ROOT/'app/build/generated/source/buildConfig/debug/com/gorios/lanvoice/BuildConfig.java'
require('EMOTION_MANIFEST_SHA = "'+report['manifest_sha256']+'"' in config.read_text(),'compiled index pin mismatch') require('EMOTION_MANIFEST_SHA = "'+report['manifest_sha256']+'"' in config.read_text(),'compiled index pin mismatch')
require(version>=next_version((ROOT/'artifacts').glob('*.apk')),'version became occupied during build') require(version>=next_version((ROOT/'artifacts').glob('*.apk')),'version became occupied during build')
artifact=ROOT/f'artifacts/lan-voice-v070-emotion-candidate-code{version}-arm64-debug.apk' stem='action-emotion' if full else 'emotion-candidate'
artifact=ROOT/f'artifacts/lan-voice-v070-{stem}-code{version}-arm64-debug.apk'
with artifact.open('xb') as f,built.open('rb') as source: shutil.copyfileobj(source,f) with artifact.open('xb') as f,built.open('rb') as source: shutil.copyfileobj(source,f)
digest=file_sha(artifact);checksum=f'{digest} {artifact.name}\n'.encode() digest=file_sha(artifact);checksum=f'{digest} {artifact.name}\n'.encode()
with artifact.with_suffix('.apk.sha256').open('xb') as f: f.write(checksum) with artifact.with_suffix('.apk.sha256').open('xb') as f: f.write(checksum)
@@ -304,8 +322,8 @@ def publish(report,output,requested):
with opener.open(url,timeout=30) as response: require(response.status==200 and sha(response.read())==digest,'HTTP APK bytes mismatch') with opener.open(url,timeout=30) as response: require(response.status==200 and sha(response.read())==digest,'HTTP APK bytes mismatch')
with opener.open(url+'.sha256',timeout=15) as response: require(response.status==200 and response.read()==checksum,'HTTP checksum mismatch') with opener.open(url+'.sha256',timeout=15) as response: require(response.status==200 and response.read()==checksum,'HTTP checksum mismatch')
require(file_sha(ROLLBACK)==ROLLBACK_SHA,'rollback modified') require(file_sha(ROLLBACK)==ROLLBACK_SHA,'rollback modified')
delivery={'status':'partial_emotion_candidate','version_name':'0.7.0-emotion-dev','version_code':version,'url':url,'sha256':digest, delivery={'status':'full_action_emotion_candidate' if full else 'partial_emotion_candidate','version_name':version_name,'version_code':version,'url':url,'sha256':digest,
'certificate_sha256':CERT,'manifest_sha256':report['manifest_sha256'],'dance_available':False,'action_count':0, 'certificate_sha256':CERT,'manifest_sha256':report['manifest_sha256'],'dance_available':full,'action_count':report['action_count'],
'http_bytes_verified':True,'device':'not_run','naturalness':'not_certified','paid_calls':0,'gateway_deployed':False} 'http_bytes_verified':True,'device':'not_run','naturalness':'not_certified','paid_calls':0,'gateway_deployed':False}
(output/'delivery.json').write_text(json.dumps(delivery,indent=2)+'\n') (output/'delivery.json').write_text(json.dumps(delivery,indent=2)+'\n')
return delivery return delivery
@@ -320,12 +338,13 @@ def main():
parser.add_argument('--previous-import-report',type=Path,help='Verified previous bundle-gate.json; requires --previous-pin and fresh backup') parser.add_argument('--previous-import-report',type=Path,help='Verified previous bundle-gate.json; requires --previous-pin and fresh backup')
parser.add_argument('--previous-pin') parser.add_argument('--previous-pin')
parser.add_argument('--backup',type=Path) parser.add_argument('--backup',type=Path)
parser.add_argument('--action-registry',type=Path,help='Reviewed public gateway registry required for full dance release')
parser.add_argument('--version-code',type=int,help='Default max existing APK code+1, minimum17') parser.add_argument('--version-code',type=int,help='Default max existing APK code+1, minimum17')
args=parser.parse_args();manifest=args.manifest.resolve(strict=True);output=args.output.resolve() args=parser.parse_args();manifest=args.manifest.resolve(strict=True);output=args.output.resolve()
require(not output.exists() and not output.is_relative_to(manifest.parent),'new evidence outside owner root required') require(not output.exists() and not output.is_relative_to(manifest.parent),'new evidence outside owner root required')
if args.import_only or args.publish: require(args.pi_pin==args.sha256 and re.fullmatch('[0-9a-f]{64}',args.pi_pin or ''),'external Pi pin required') if args.import_only or args.publish: require(args.pi_pin==args.sha256 and re.fullmatch('[0-9a-f]{64}',args.pi_pin or ''),'external Pi pin required')
if args.import_only or args.publish: if args.import_only or args.publish:
require(read_json(manifest)['actions']==[],'dance import/publication requires separately reviewed gateway capability admission; read-only gate supported') if read_json(manifest)['actions']: reviewed_actions(read_json(manifest),args.pi_pin,args.action_registry)
output.mkdir(parents=True) output.mkdir(parents=True)
report=check_bundle(manifest,args.sha256,output) report=check_bundle(manifest,args.sha256,output)
if args.import_only or args.publish: if args.import_only or args.publish:
@@ -337,7 +356,7 @@ def main():
require(not args.previous_pin and not args.backup,'previous import report required') require(not args.previous_pin and not args.backup,'previous import report required')
import_files(manifest.parent,report['files'],target) import_files(manifest.parent,report['files'],target)
(output/'import.json').write_text(json.dumps({'externally_pinned_sha256':args.pi_pin,'files':len(report['files']),'naturalness':'not_certified'})+'\n') (output/'import.json').write_text(json.dumps({'externally_pinned_sha256':args.pi_pin,'files':len(report['files']),'naturalness':'not_certified'})+'\n')
result=publish(report,output,args.version_code) if args.publish else {k:v for k,v in report.items() if k!='files'} result=publish(report,output,args.version_code,bool(report['action_count'])) if args.publish else {k:v for k,v in report.items() if k!='files'}
print(json.dumps(result,indent=2)) print(json.dumps(result,indent=2))
+13 -1
View File
@@ -13,13 +13,25 @@ ROOT=Path(__file__).resolve().parents[1]
def main(): def main():
parser=argparse.ArgumentParser(description=__doc__) parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output',type=Path,required=True,help='New ignored numeric evidence file') parser.add_argument('--output',type=Path,required=True,help='New ignored numeric evidence file')
parser.add_argument('--approved-pack-sha',help='Exact public registry pin; no fixture admission')
parser.add_argument('--pack-gate',type=Path,help='Matching production gate for actual action metadata')
args=parser.parse_args() args=parser.parse_args()
output=args.output.resolve() output=args.output.resolve()
if output.exists() or not output.is_relative_to(ROOT/'logs'): raise ValueError('new logs evidence required') if output.exists() or not output.is_relative_to(ROOT/'logs'): raise ValueError('new logs evidence required')
source={p.name:base64.b64encode(p.read_bytes()).decode() for p in (ROOT/'gateway').glob('*.py')} source={p.name:base64.b64encode(p.read_bytes()).decode() for p in (ROOT/'gateway').glob('*.py')}
approved=None
if args.approved_pack_sha:
registry=ROOT/'gateway/reviewed_action_packs.json'
table=json.loads(registry.read_text())
gate=json.loads(args.pack_gate.read_text())
assert gate['status']=='passed' and gate['manifest_sha256']==args.approved_pack_sha and gate['action_count']==2
durations={row['id']:(row['durationUs']+999)//1000 for row in gate['action_measurements']}
assert table[args.approved_pack_sha]==durations
approved={'sha256':args.approved_pack_sha,'durations':durations,'body_packages':5,'edges':13,'own_bridges':8}
source[registry.name]=base64.b64encode(registry.read_bytes()).decode()
baseline=json.loads((ROOT/'gateway/SOURCE_MANIFEST.json').read_text())['deployment_baseline']['files'] baseline=json.loads((ROOT/'gateway/SOURCE_MANIFEST.json').read_text())['deployment_baseline']['files']
expected={name:digest for name,digest in baseline.items() if name in source and name!='tests_fake.py'} expected={name:digest for name,digest in baseline.items() if name in source and name!='tests_fake.py'}
payload='sources='+repr(source)+'\nexpected='+repr(expected)+'\n'+(ROOT/'scripts/action-calling-path-remote.py').read_text() payload='sources='+repr(source)+'\nexpected='+repr(expected)+'\napproved='+repr(approved)+'\n'+(ROOT/'scripts/action-calling-path-remote.py').read_text()
run=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5', run=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 -'], '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=210) input=payload.encode(),capture_output=True,timeout=210)
+10
View File
@@ -43,6 +43,16 @@ fun actionCheck() {
now+=10001;controller.tick();release!!();check(statuses.last().status=="failed") now+=10001;controller.tick();release!!();check(statuses.last().status=="failed")
check(controller.offer(plan(3)));confirm!!(false);release!!() check(controller.offer(plan(3)));confirm!!(false);release!!()
check(statuses.last().status=="failed" && controller.active && picked.size==4) check(statuses.last().status=="failed" && controller.active && picked.size==4)
val repeated=mutableListOf<String>()
var done: ((ActionEnd)->Unit)?=null
val randomPlayer=object: ActionPlayer {
override fun play(asset: ActionAsset,finished: (ActionEnd)->Unit,failed: ()->Unit) { repeated.add(asset.id);done=finished }
override fun stop(released: ()->Unit) { released() }
}
val random=ActionController(pack,randomPlayer,{now},{it(true)},{},choose={it-1})
check(random.offer(plan(20)));now+=1200;done!!(ActionEnd(true,true,true))
check(random.offer(plan(21)));now+=1200;done!!(ActionEnd(true,true,true))
check(repeated==listOf("asset_02","asset_02")) // Repeat is possible, not forced exact alternation.
val missing=ActionController(null,player,{now},{confirm=it},{statuses.add(it)}) val missing=ActionController(null,player,{now},{confirm=it},{statuses.add(it)})
check(missing.capability==null && !missing.offer(plan(5))) check(missing.capability==null && !missing.offer(plan(5)))
+5 -5
View File
@@ -14,7 +14,7 @@ fun fullActionGraphCheck() {
val rows=bodies.map { (id,body)->mapOf<String,Any?>("id" to id, val rows=bodies.map { (id,body)->mapOf<String,Any?>("id" to id,
"emotion" to if(id.startsWith("idle")) "neutral" else id,"visualIntensity" to if(id in setOf("happy","sad")) 1 else 0, "emotion" to if(id.startsWith("idle")) "neutral" else id,"visualIntensity" to if(id in setOf("happy","sad")) 1 else 0,
"mouthBodySha256" to body.body.sha256,"runtimeManifest" to mapOf("path" to "$id/manifest.json","sha256" to body.manifestSha), "mouthBodySha256" to body.body.sha256,"runtimeManifest" to mapOf("path" to "$id/manifest.json","sha256" to body.manifestSha),
"entryAnchor" to "A","exitAnchor" to "A","legalExitFrames" to listOf(body.body.frameCount-1),"loopEdge" to "$id-loop") } "entryAnchor" to "A","exitAnchor" to "A","legalExitFrames" to if(id=="neutral") listOf(0,96) else listOf(body.body.frameCount-1),"loopEdge" to "$id-loop") }
val mouths=linkedMapOf<String,ContinuousAvatarPack>() val mouths=linkedMapOf<String,ContinuousAvatarPack>()
val loops=bodies.map { (id,body)->mapOf<String,Any?>("id" to "$id-loop","from" to id,"to" to id, val loops=bodies.map { (id,body)->mapOf<String,Any?>("id" to "$id-loop","from" to id,"to" to id,
"fromFrame" to body.body.frameCount-1,"fromPtsUs" to body.body.ptsUs.last(),"toFrame" to 0,"toPtsUs" to 0L, "fromFrame" to body.body.frameCount-1,"fromPtsUs" to body.body.ptsUs.last(),"toFrame" to 0,"toPtsUs" to 0L,
@@ -30,8 +30,8 @@ fun fullActionGraphCheck() {
val dance=dynamicPack(241,24,"f".repeat(64)) val dance=dynamicPack(241,24,"f".repeat(64))
val actions=listOf("asset_01","asset_02").map { id->mapOf<String,Any?>("id" to id,"kind" to "dance", val actions=listOf("asset_01","asset_02").map { id->mapOf<String,Any?>("id" to id,"kind" to "dance",
"mouthAllowed" to false,"disallowTALK" to true,"entryAnchor" to "A","returnAnchor" to "A", "mouthAllowed" to false,"disallowTALK" to true,"entryAnchor" to "A","returnAnchor" to "A",
"sourcePackageId" to "neutral","sourceFrame" to 96,"sourcePtsUs" to 4_000_000L, "sourcePackageId" to "neutral","sourceFrame" to 0,"sourcePtsUs" to 0L,
"returnPackageId" to "neutral","returnFrame" to 0,"returnPtsUs" to 0L, "returnPackageId" to "neutral","returnFrame" to 96,"returnPtsUs" to 4_000_000L,
"clip" to clip(dance,"$id.mp4",true),"audioEndUs" to 10_000_000L) } "clip" to clip(dance,"$id.mp4",true),"audioEndUs" to 10_000_000L) }
val root=mapOf<String,Any?>("schemaVersion" to 2,"identityId" to "a01","packId" to "a01-expression-action-v1", val root=mapOf<String,Any?>("schemaVersion" to 2,"identityId" to "a01","packId" to "a01-expression-action-v1",
"fallbackPackageId" to "neutral","conversationPackages" to rows,"edges" to loops+bridges,"actions" to actions) "fallbackPackageId" to "neutral","conversationPackages" to rows,"edges" to loops+bridges,"actions" to actions)
@@ -44,7 +44,7 @@ fun fullActionGraphCheck() {
check(index.actionPack?.assets?.size==2 && index.actionPack.assets.all { it.media?.ptsUs?.size==241 });assertions++ check(index.actionPack?.assets?.size==2 && index.actionPack.assets.all { it.media?.ptsUs?.size==241 });assertions++
val bytes=index.packages.values.sumOf { it.rgbaBytes }+index.edges.mapNotNull { it.mouthRuntime }.sumOf { it.rgbaBytes } val bytes=index.packages.values.sumOf { it.rgbaBytes }+index.edges.mapNotNull { it.mouthRuntime }.sumOf { it.rgbaBytes }
check(bytes==bodies.values.sumOf { it.rgbaBytes }+mouths.values.sumOf { it.rgbaBytes } && bytes<=BodyTimeline.MAX_PACK_CACHE_BYTES);assertions++ check(bytes==bodies.values.sumOf { it.rgbaBytes }+mouths.values.sumOf { it.rgbaBytes } && bytes<=BodyTimeline.MAX_PACK_CACHE_BYTES);assertions++
for(change in listOf(mapOf("sourceFrame" to 0),mapOf("sourcePtsUs" to 0L),mapOf("returnPtsUs" to 1L), for(change in listOf(mapOf("sourceFrame" to 95),mapOf("sourcePtsUs" to 1L),mapOf("returnPtsUs" to 1L),
mapOf("sourcePackageId" to "idle-breathe"),mapOf("returnPackageId" to "idle-shift"))) { mapOf("sourcePackageId" to "idle-breathe"),mapOf("returnPackageId" to "idle-shift"))) {
check(read(root+("actions" to listOf(actions[0]+change,actions[1])))==null);assertions++ check(read(root+("actions" to listOf(actions[0]+change,actions[1])))==null);assertions++
} }
@@ -54,5 +54,5 @@ fun fullActionGraphCheck() {
} }
val inflated=bodies.mapValues { (_,body)->body.copy(patches=body.patches.map { it.copy(width=80,height=44) }) } val inflated=bodies.mapValues { (_,body)->body.copy(patches=body.patches.map { it.copy(width=80,height=44) }) }
check(inflated.values.all { it.rgbaBytes<=BodyTimeline.MAX_RGBA_BYTES } && read(bodyData=inflated)==null);assertions++ check(inflated.values.all { it.rgbaBytes<=BodyTimeline.MAX_RGBA_BYTES } && read(bodyData=inflated)==null);assertions++
println("PASS: $assertions full5-body/13-edge/8-own-bridge/two241-frame-action parser assertions; RGBA=$bytes bytes, source96/4s/return binding and total-cache rejection; fixtures only") println("PASS: $assertions full5-body/13-edge/8-own-bridge/two241-frame-action parser assertions; RGBA=$bytes bytes, source0/return96/4s binding and total-cache rejection; fixtures only")
} }
+16 -4
View File
@@ -28,11 +28,13 @@ fun idleVariantCheck() {
override fun close(released: ()->Unit) { released() } override fun close(released: ()->Unit) { released() }
} }
val ports=mutableListOf<Port>();val trace=mutableListOf<String>() val ports=mutableListOf<Port>();val trace=mutableListOf<String>()
val driver=ConversationMediaDriver(index,{ Port().also(ports::add) },music,{}, { phase,_->trace.add(phase) },chooseIdle={0}) val driver=ConversationMediaDriver(index,{ Port().also(ports::add) },music,{}, { phase,_->trace.add(phase) },chooseIdle={0},chooseIdleCycles={2})
driver.beginTurn(7);driver.start();val fallback=ports.single() driver.beginTurn(7);driver.start();val fallback=ports.single()
(0..95).forEach { fallback.emit(it) } (0..95).forEach { fallback.emit(it) }
check(ports.size==1);checks++ // No arbitrary phase departure. check(ports.size==1);checks++ // No arbitrary phase departure.
fallback.emit(96);check(ports.size==3 && trace.contains("idle_variant_queued"));checks++ fallback.emit(96);check(ports.size==1);checks++
(0..95).forEach { fallback.emit(it,1) };check(ports.size==1);checks++
fallback.emit(96,1);check(ports.size==3 && trace.contains("idle_variant_queued"));checks++
fun bridgeTo(target: Port,bridge: Port) { fun bridgeTo(target: Port,bridge: Port) {
target.emit(0);bridge.emit(0) target.emit(0);bridge.emit(0)
check(trace.last()=="bridge" && !bridge.loop);checks++ check(trace.last()=="bridge" && !bridge.loop);checks++
@@ -42,9 +44,13 @@ fun idleVariantCheck() {
val idle1=ports[1];bridgeTo(idle1,ports[2]) val idle1=ports[1];bridgeTo(idle1,ports[2])
check(driver.currentPackageId=="happy" && driver.visualStatus=="neutral_idle_variant");checks++ check(driver.currentPackageId=="happy" && driver.visualStatus=="neutral_idle_variant");checks++
(1 until idle1.pack.body.frameCount).forEach { idle1.emit(it) } (1 until idle1.pack.body.frameCount).forEach { idle1.emit(it) }
check(ports.size==3);checks++
(0 until idle1.pack.body.frameCount).forEach { idle1.emit(it,1) }
check(trace.contains("idle_variant_return_queued") && ports.size==5);checks++ check(trace.contains("idle_variant_return_queued") && ports.size==5);checks++
val returned=ports[3];bridgeTo(returned,ports[4]) val returned=ports[3];bridgeTo(returned,ports[4])
(1..96).forEach { returned.emit(it) } (1..96).forEach { returned.emit(it) }
check(ports.size==5);checks++
(0..96).forEach { returned.emit(it,1) }
val idle2=ports[5];bridgeTo(idle2,ports[6]) val idle2=ports[5];bridgeTo(idle2,ports[6])
check(driver.currentPackageId=="sad");checks++ // Pick0 still excludes previous idle1. check(driver.currentPackageId=="sad");checks++ // Pick0 still excludes previous idle1.
driver.intent(mediaReply(RoleEmotion.NEUTRAL),true) driver.intent(mediaReply(RoleEmotion.NEUTRAL),true)
@@ -57,15 +63,21 @@ fun idleVariantCheck() {
driver.stop {};val count=trace.size driver.stop {};val count=trace.size
idle2.emit(0);ports[8].ended();check(trace.size==count && ports.all { it.closed });checks++ idle2.emit(0);ports[8].ended();check(trace.size==count && ports.all { it.closed });checks++
val three=mutableListOf<Port>()
val slow=ConversationMediaDriver(index,{ Port().also(three::add) },music,{},chooseIdle={0},chooseIdleCycles={3})
slow.beginTurn(7);slow.start()
repeat(2) { cycle -> (0..96).forEach { three[0].emit(it,cycle.toLong()) };check(three.size==1);checks++ }
(0..95).forEach { three[0].emit(it,2) };check(three.size==1);checks++
three[0].emit(96,2);check(three.size==3);checks++;slow.stop {}
// Missing bridge mouth prevents idle activation even with valid own body layers. // Missing bridge mouth prevents idle activation even with valid own body layers.
val noMouth=index.copy(edges=index.edges.map { if(it.nativeLoop) it else it.copy(mouthRuntime=null) }) val noMouth=index.copy(edges=index.edges.map { if(it.nativeLoop) it else it.copy(mouthRuntime=null) })
val guarded=mutableListOf<Port>() val guarded=mutableListOf<Port>()
val other=ConversationMediaDriver(noMouth,{ Port().also(guarded::add) },music,{},chooseIdle={0}) val other=ConversationMediaDriver(noMouth,{ Port().also(guarded::add) },music,{},chooseIdle={0},chooseIdleCycles={2})
other.beginTurn(7);other.start();(0..96).forEach { guarded[0].emit(it) } other.beginTurn(7);other.start();(0..96).forEach { guarded[0].emit(it) }
check(guarded.size==1);checks++;other.stop {} check(guarded.size==1);checks++;other.stop {}
// A retained happy/sad expression must not turn neutral when speech ends. // A retained happy/sad expression must not turn neutral when speech ends.
val expressive=mutableListOf<Port>() val expressive=mutableListOf<Port>()
val retained=ConversationMediaDriver(base,{ Port().also(expressive::add) },music,{},chooseIdle={0}) val retained=ConversationMediaDriver(base,{ Port().also(expressive::add) },music,{},chooseIdle={0},chooseIdleCycles={2})
retained.beginTurn(7);retained.start();retained.intent(mediaReply(RoleEmotion.HAPPY),false) retained.beginTurn(7);retained.start();retained.intent(mediaReply(RoleEmotion.HAPPY),false)
(0..96).forEach { expressive[0].emit(it) };expressive[1].emit(0);expressive[2].emit(0) (0..96).forEach { expressive[0].emit(it) };expressive[1].emit(0);expressive[2].emit(0)
expressive[2].emit(1);expressive[2].emit(2);expressive[2].ended() expressive[2].emit(1);expressive[2].emit(2);expressive[2].ended()
+4 -4
View File
@@ -144,14 +144,14 @@ fun actualMediaViewCheck() {
val (idleView,idleBinding,idleTrace)=rig(idleIndex) val (idleView,idleBinding,idleTrace)=rig(idleIndex)
TestScheduler.advanceBy(3000) TestScheduler.advanceBy(3000)
check(idleTrace.all { it.actual=="body_neutral" });cases++ check(idleTrace.all { it.actual=="body_neutral" });cases++
TestScheduler.until { idleBinding.currentPackageId in setOf("happy","sad") } TestScheduler.until(15_000) { idleBinding.currentPackageId in setOf("happy","sad") }
val firstIdle=idleBinding.currentPackageId val firstIdle=idleBinding.currentPackageId
check(idleTrace.any { it.actual=="bridge" } && idleBinding.visualStatus=="neutral_idle_variant");cases++ check(idleTrace.any { it.actual=="bridge" } && idleBinding.visualStatus=="neutral_idle_variant");cases++
TestScheduler.until { idleBinding.currentPackageId=="neutral" } TestScheduler.until(15_000) { idleBinding.currentPackageId=="neutral" }
TestScheduler.until { idleBinding.currentPackageId in setOf("happy","sad") } TestScheduler.until(15_000) { idleBinding.currentPackageId in setOf("happy","sad") }
check(idleBinding.currentPackageId!=firstIdle && idleTrace.none { it.actual=="media_failed" });cases++ check(idleBinding.currentPackageId!=firstIdle && idleTrace.none { it.actual=="media_failed" });cases++
idleBinding.intent(mediaReply(RoleEmotion.NEUTRAL),true) idleBinding.intent(mediaReply(RoleEmotion.NEUTRAL),true)
TestScheduler.until { idleBinding.currentPackageId=="neutral" } TestScheduler.until(15_000) { idleBinding.currentPackageId=="neutral" }
val speechStart=idleTrace.size;TestScheduler.advanceBy(9000) val speechStart=idleTrace.size;TestScheduler.advanceBy(9000)
check(idleTrace.drop(speechStart).all { it.actual=="body_neutral" });cases++ check(idleTrace.drop(speechStart).all { it.actual=="body_neutral" });cases++
val beforeDispose=idleTrace.size;idleView.dispose();TestScheduler.advanceBy(1000) val beforeDispose=idleTrace.size;idleView.dispose();TestScheduler.advanceBy(1000)
+10
View File
@@ -120,6 +120,16 @@ class PackageTests(unittest.TestCase):
self.assertNotEqual(result.returncode,0);self.assertIn('read-only gate supported',result.stderr) self.assertNotEqual(result.returncode,0);self.assertIn('read-only gate supported',result.stderr)
self.assertFalse(out.exists()) self.assertFalse(out.exists())
def test_reviewed_full_admission_exact_duration_pin(self):
index=self.dance_index();pin='a'*64;registry=self.base/'approved.json'
registry.write_text(json.dumps({pin:{'asset_01':1000,'asset_02':1000}}))
self.assertEqual(pack.reviewed_actions(index,pin,registry),{'asset_01':1000,'asset_02':1000})
with self.assertRaisesRegex(ValueError,'pin/duration'): pack.reviewed_actions(index,'b'*64,registry)
registry.write_text(json.dumps({pin:{'asset_01':999,'asset_02':1000}}))
with self.assertRaisesRegex(ValueError,'pin/duration'): pack.reviewed_actions(index,pin,registry)
index['actions'][0]['mouthAllowed']=True
with self.assertRaisesRegex(ValueError,'dance shape'): pack.reviewed_actions(index,pin,registry)
def test_paths(self): def test_paths(self):
for name in ('../x','x/../y','x//y','/x','x/./y','https://host/x','x\\y'): for name in ('../x','x/../y','x//y','/x','x/./y','https://host/x','x\\y'):
with self.subTest(name=name),self.assertRaises(ValueError): pack.relative(name) with self.subTest(name=name),self.assertRaises(ValueError): pack.relative(name)