hunt Claude Sonnet 5 commited on
Commit
52ecda8
·
1 Parent(s): 7a90831

WO-2 verbose spec — Pipeline 1/2 acoustic ingress + supervisor routing

Browse files
.kiro/specs/wo2-acoustic-ingress-routing/design.md CHANGED
@@ -1,17 +1,377 @@
1
- # WO-2: Design
2
 
3
- ## Architecture
4
 
5
- `miranda-audio` owns mic capture + VAD + the parakeet.cpp FFI wrapper. `miranda-supervisor` owns the Nemotron-Flash routing logic and turn-taking state machine — kept separate because the audio crate should have zero LLM/networking dependencies (keeps it embeddable/testable in isolation).
6
 
7
- ## parakeet.cpp FFI
8
 
9
- This project already has a real, verified-working `parakeet.cpp` deployment (built from source with `-march=native` because this hardware class lacks AVX2 — see `llamacpp-huggingface-expert` skill for the exact lesson). The FFI wrapper (`cxx` crate) should link against that existing build's shared library rather than vendoring a second copy. Bind the C API surface `parakeet.cpp` already exposes (transcribe from PCM buffer → token stream) — do not reinvent a Rust-native ASR path.
 
 
 
 
 
 
 
 
 
 
10
 
11
- ## Node Warden concept (Vanguard Innovation #1)
12
 
13
- `miranda-supervisor` is also where the Work Order 1 "Node Warden" pattern lives operationally: a small local GGUF model (1-4B, via llama.cpp — see `llamacpp-huggingface-expert`) monitoring this node's own throughput. This is a later refinement, not required for WO-2's first pass — get the deterministic ASR/VAD/routing path working and correct before adding self-monitoring.
14
 
15
- ## Cross-reference
16
 
17
- Full Hermes Execution Prompt and Sequence Matrix: `nobility-posh-framework` Kiro skill.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # WO-2: Acoustic Ingress, VAD & Supervisory Routing — Design
2
 
3
+ **Read requirements.md first.** This document expands the *how*, building on the *what* in requirements.md. If you skipped the pre-flight in requirements.md, go back now.
4
 
5
+ ---
6
 
7
+ ## Where WO-2 sits in Miranda's crate graph
8
 
9
+ ```
10
+ miranda-engine (workspace root)
11
+ ├── miranda-ipc ← WO-1 ✓ COMPLETE — the ring bus everything writes into
12
+ ├── miranda-audio ← WO-2 PIPELINE 2 target: mic capture + VAD + parakeet.cpp FFI
13
+ │ └── deps: miranda-ipc (bus writes), cpal (mic), ort (Silero VAD), cxx (FFI)
14
+ ├── miranda-supervisor ← WO-2 PIPELINE 2 target: Nemotron-Flash turn-taking state machine
15
+ │ └── deps: miranda-ipc (bus reads), tokio, reqwest
16
+ ├── miranda-core ← not WO-2 — shared types and config, read-only from WO-2
17
+ ├── miranda-nodes ← future WO-3/4 — expression + rendering nodes
18
+ └── miranda-transport ← future WO-4 — WebRTC transport
19
+ ```
20
 
21
+ **Pipeline 1 does not add Rust crates for audio/ASR.** It uses the browser (`getUserMedia()` + AWS SDK in TypeScript) and makes HTTP/WebSocket calls to AWS-managed services. The `miranda-audio` crate is Pipeline 2 only. The `miranda-supervisor` crate handles routing for both pipelines (Bedrock Converse API in Pipeline 1, Nemotron-Flash in Pipeline 2) because the routing logic is shared — only the model endpoint URL changes.
22
 
23
+ **Crate dependency direction is locked.** `miranda-audio` → `miranda-ipc` (audio writes to bus). `miranda-supervisor` → `miranda-ipc` (supervisor reads from bus). Neither audio nor supervisor imports from each other — they communicate only through the ring bus. Do not invert these dependencies.
24
 
25
+ ---
26
 
27
+ ## Data flow diagrams
28
+
29
+ ### Pipeline 1 (AWS-native — build first)
30
+
31
+ ```
32
+ Browser (client-apps/web/)
33
+ │
34
+ ├─── getUserMedia() ──→ PCM audio stream (16 kHz, mono, f32)
35
+ │
36
+ ├─── VAD (energy threshold or WebRTC VAD wasm) ──→ SpeechStart/SpeechEnd events
37
+ │ │
38
+ │ └─── on SpeechStart → begin sending PCM chunks via WebSocket
39
+ │
40
+ ├─── WebSocket to miranda-supervisor (Axum) ──→ sends AudioChunk structs
41
+ │
42
+ [miranda-supervisor receives AudioChunk, forwards to Transcribe]
43
+ │
44
+ ├─── Amazon Transcribe Streaming (WebSocket) ──→ partial + final transcripts
45
+ │ │
46
+ │ ├─── partial result → VadEvent::PartialTranscript → EVE "processing" expression
47
+ │ │
48
+ │ └─── final result → VadEvent::FinalTranscript → Bedrock Converse API call
49
+ │
50
+ ├─── Amazon Bedrock Converse API (amazon.nova-pro-v1:0 default)
51
+ │ │
52
+ │ └─── response → TurnComplete signal → downstream (WO-3 TTS, WO-5 render)
53
+ │
54
+ [IPC bus writes — Pipeline 1 uses in-process ring rather than /dev/shm for browser context]
55
+ │
56
+ └─── audio_bus: AudioChunk written for logging/debug telemetry (WO-4 will consume)
57
+ ```
58
+
59
+ ### Pipeline 2 (parakeet.cpp + Nemotron-Flash)
60
+
61
+ ```
62
+ cpal (miranda-audio) ──→ PCM audio stream (16 kHz, mono, f32)
63
+ │
64
+ ├─── Silero VAD (ort ONNX runtime) ──→ SpeechStart/SpeechEnd events
65
+ │ │
66
+ │ ├─── rising edge: write VadEvent::SpeechStart to audio_bus
67
+ │ └─── falling edge: write VadEvent::SpeechEnd to audio_bus
68
+ │
69
+ ├─── on SpeechStart: write AudioChunk stream to audio_bus (WO-1 ring)
70
+ │
71
+ ├─── parakeet.cpp FFI (cxx binding in miranda-audio)
72
+ │ │
73
+ │ ├─── reads AudioChunk from audio_bus ring
74
+ │ ├─── calls transcribe_pcm(buf, len) → token string
75
+ │ └─── writes TranscriptChunk to miranda-ipc channel
76
+ │
77
+ └─── miranda-supervisor
78
+ │
79
+ ├─── reads TranscriptChunk from bus
80
+ ├─── Nemotron-Flash turn-taking: partial → continue, final → dispatch
81
+ └─── on TurnComplete → downstream TTS node (WO-3)
82
+ ```
83
+
84
+ ---
85
+
86
+ ## Pipeline 1: technical implementation details
87
+
88
+ ### Browser mic capture (`client-apps/web/`)
89
+
90
+ The existing Vite/React/TS code in `client-apps/web/` is from the `eve-ecc` carry-forward. Extend it, do not rewrite it. The mic capture goes in a new file `client-apps/web/src/audio/MicCapture.ts`:
91
+
92
+ ```typescript
93
+ // MediaDevices.getUserMedia with 16 kHz mono PCM — exact params for Transcribe
94
+ const stream = await navigator.mediaDevices.getUserMedia({
95
+ audio: { sampleRate: 16000, channelCount: 1, echoCancellation: true }
96
+ });
97
+ const ctx = new AudioContext({ sampleRate: 16000 });
98
+ const source = ctx.createMediaStreamSource(stream);
99
+ const processor = ctx.createScriptProcessor(1024, 1, 1);
100
+ source.connect(processor);
101
+ processor.connect(ctx.destination);
102
+ processor.onaudioprocess = (e) => {
103
+ const pcm = e.inputBuffer.getChannelData(0); // Float32Array, 1024 samples
104
+ onAudioChunk(pcm); // write to Transcribe WebSocket
105
+ };
106
+ ```
107
+
108
+ **Why 1024 samples / 16 kHz = 64 ms per chunk.** Transcribe Streaming recommends 100–250 ms audio chunks. 2× 1024 = 2048 samples = 128 ms — send two processor buffers per Transcribe write, or configure `bufferSize: 2048` directly. Do not send single 64 ms chunks — Transcribe's internal buffer alignment penalizes very small inputs.
109
+
110
+ ### Amazon Transcribe Streaming setup
111
+
112
+ SDK: `@aws-sdk/client-transcribe-streaming` — this should already be in the workspace from the Pipeline 1 steering doc. If not, add it to `client-apps/web/package.json`.
113
+
114
+ ```typescript
115
+ import { TranscribeStreamingClient, StartStreamTranscriptionCommand } from '@aws-sdk/client-transcribe-streaming';
116
+
117
+ const client = new TranscribeStreamingClient({ region: 'us-east-1' });
118
+ const command = new StartStreamTranscriptionCommand({
119
+ LanguageCode: 'en-US',
120
+ MediaSampleRateHertz: 16000,
121
+ MediaEncoding: 'pcm',
122
+ AudioStream: audioGenerator(), // async generator yielding { AudioEvent: { AudioChunk: pcmBuffer } }
123
+ EnablePartialResultsStabilization: true,
124
+ PartialResultsStability: 'medium',
125
+ });
126
+ const response = await client.send(command);
127
+ for await (const event of response.TranscriptResultStream) {
128
+ if (event.TranscriptEvent?.Transcript?.Results) {
129
+ for (const result of event.TranscriptEvent.Transcript.Results) {
130
+ const text = result.Alternatives?.[0]?.Transcript ?? '';
131
+ if (result.IsPartial) onPartialTranscript(text);
132
+ else onFinalTranscript(text);
133
+ }
134
+ }
135
+ }
136
+ ```
137
+
138
+ **Credentials**: access AMANDA vault MCP with `get_key("aws")` — never hardcode keys, never put them in environment files that get committed. Credentials flow in at runtime through the MCP vault call. See `.kiro/steering/pipeline-1-aws-native.md` for the exact vault call pattern.
139
+
140
+ **Two-stage partial/final distinction is mandatory** (REQ-4). When `result.IsPartial === true`, emit a `PartialTranscript` event that triggers EVE's "thinking" micro-expression. When `result.IsPartial === false`, that's the stable final result — dispatch to Bedrock.
141
+
142
+ ### Amazon Bedrock Converse API (`miranda-supervisor`)
143
+
144
+ Model: `amazon.nova-pro-v1:0` (CAT-3 workhorse, Bedrock-native, full tool-calling). Only escalate to `anthropic.claude-sonnet-5` if Nova Pro fails on a specific turn-taking edge case after two attempts.
145
+
146
+ ```typescript
147
+ import { BedrockRuntimeClient, ConverseCommand } from '@aws-sdk/client-bedrock-runtime';
148
+
149
+ const bedrock = new BedrockRuntimeClient({ region: 'us-east-1' });
150
+ const response = await bedrock.send(new ConverseCommand({
151
+ modelId: 'amazon.nova-pro-v1:0',
152
+ messages: [{ role: 'user', content: [{ text: finalTranscript }] }],
153
+ system: [{ text: SUPERVISOR_SYSTEM_PROMPT }],
154
+ }));
155
+ const reply = response.output?.message?.content?.[0]?.text ?? '';
156
+ emitTurnComplete(reply);
157
+ ```
158
+
159
+ `SUPERVISOR_SYSTEM_PROMPT` is the turn-taking persona prompt. Keep it in a separate constant — it will change over time as Pipeline 2 swaps Nemotron-Flash in. The function signature (`emitTurnComplete(text: string)`) must not change between Pipeline 1 and Pipeline 2.
160
+
161
+ ---
162
+
163
+ ## Pipeline 2: technical implementation details
164
+
165
+ ### `miranda-audio` crate — mic capture with `cpal`
166
+
167
+ `cpal` is the cross-platform audio I/O library for Rust. It provides a stream callback on a dedicated audio thread. **The audio callback must never block** — the only work allowed inside it is writing to the IPC ring buffer (which is a lock-free atomic write, same as WO-1's `audio_bus` producer side).
168
+
169
+ ```toml
170
+ # miranda-audio/Cargo.toml
171
+ [dependencies]
172
+ miranda-ipc = { path = "../miranda-ipc" }
173
+ cpal = "0.15"
174
+ ort = { version = "2", features = ["load-dynamic"] } # Silero VAD ONNX runtime
175
+ cxx = "1" # parakeet.cpp FFI
176
+ ```
177
+
178
+ ```rust
179
+ // miranda-audio/src/capture.rs — the cpal callback skeleton
180
+ use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
181
+ use miranda_ipc::{AudioBus, AudioChunk};
182
+
183
+ pub fn start_capture(bus: &'static AudioBus) -> cpal::Stream {
184
+ let host = cpal::default_host();
185
+ let device = host.default_input_device().expect("no mic");
186
+ let config = cpal::StreamConfig {
187
+ channels: 1,
188
+ sample_rate: cpal::SampleRate(16000),
189
+ buffer_size: cpal::BufferSize::Fixed(160), // 10 ms @ 16 kHz
190
+ };
191
+ device.build_input_stream(
192
+ &config,
193
+ move |data: &[f32], _| {
194
+ let chunk = AudioChunk::from_pcm(data);
195
+ bus.push(chunk); // lock-free ring write — see WO-1 design
196
+ },
197
+ |err| eprintln!("audio stream error: {err}"),
198
+ None,
199
+ ).expect("failed to build input stream")
200
+ }
201
+ ```
202
+
203
+ **Why 160-sample chunks (10 ms)?** This matches Silero VAD's internal frame size. VAD is computed per-chunk — sending larger chunks delays the VAD rising edge. See REQ-2: 10 ms detection target.
204
+
205
+ ### Silero VAD (ONNX runtime via `ort`)
206
+
207
+ Silero VAD is a small (2 MB) ONNX model that takes 512 samples (32 ms @ 16 kHz) and returns a speech probability. Run it every 4 chunks (4 × 10 ms = 40 ms frame):
208
+
209
+ ```rust
210
+ // miranda-audio/src/vad.rs
211
+ use ort::{Environment, Session};
212
+
213
+ pub struct SileroVad {
214
+ session: Session,
215
+ buffer: Vec<f32>, // accumulates 512 samples before inference
216
+ h: Vec<f32>, // hidden state — must persist across frames
217
+ c: Vec<f32>,
218
+ }
219
+
220
+ impl SileroVad {
221
+ pub fn feed(&mut self, chunk: &[f32]) -> Option<VadEvent> {
222
+ self.buffer.extend_from_slice(chunk);
223
+ if self.buffer.len() < 512 { return None; }
224
+ let prob = self.run_inference(&self.buffer[..512]); // → f32 0..1
225
+ self.buffer.drain(..512);
226
+ if prob > 0.5 { Some(VadEvent::SpeechStart) }
227
+ else { Some(VadEvent::SpeechEnd) }
228
+ }
229
+ }
230
+ ```
231
+
232
+ The ONNX model file path: check `llamacpp-huggingface-expert` skill for where it's already placed in this repo. Do not download it again. If it is not yet in the repo, download it once from HuggingFace (`snakers4/silero-vad`) and place it in `assets/models/silero_vad.onnx`. Add that path to `.gitignore` if the file exceeds 5 MB.
233
+
234
+ ### parakeet.cpp FFI binding (`cxx`)
235
+
236
+ **Read the `llamacpp-huggingface-expert` Kiro skill before touching this.** It contains the exact build flags, the ISA mismatch note for Celeron N4500 (no AVX2 — use `-march=native` only, not `-mavx2`), and the existing parakeet.cpp binary path.
237
+
238
+ The FFI binding wraps a minimal C API. parakeet.cpp already exposes this function — the `cxx` binding should bind the existing API, not add new C++ symbols:
239
+
240
+ ```cpp
241
+ // Declared in parakeet.cpp's header (do not add new symbols)
242
+ extern "C" const char* transcribe_pcm(const float* buf, size_t len);
243
+ ```
244
+
245
+ ```rust
246
+ // miranda-audio/src/asr/parakeet_ffi.rs
247
+ #[cxx::bridge]
248
+ mod ffi {
249
+ unsafe extern "C++" {
250
+ include!("parakeet.h");
251
+ fn transcribe_pcm(buf: *const f32, len: usize) -> *const c_char;
252
+ }
253
+ }
254
+
255
+ pub fn transcribe(samples: &[f32]) -> String {
256
+ let raw = unsafe { ffi::transcribe_pcm(samples.as_ptr(), samples.len()) };
257
+ // SAFETY: parakeet.cpp returns a valid null-terminated UTF-8 string
258
+ // or null on empty audio. The pointer is valid until the next transcribe_pcm call.
259
+ if raw.is_null() { return String::new(); }
260
+ unsafe { std::ffi::CStr::from_ptr(raw).to_string_lossy().into_owned() }
261
+ }
262
+ ```
263
+
264
+ **MIRI note:** The FFI call is `unsafe` and MIRI cannot cross the FFI boundary. Wrap the integration test in `#[cfg(not(miri))]` — the same pattern used in WO-1's `test_round_trip_latency`. The unit test for the Silero VAD logic (which is pure Rust) CAN run under MIRI and should.
265
+
266
+ ### `miranda-supervisor` turn-taking state machine (Pipeline 2)
267
+
268
+ Nemotron-Flash is accessed via AMANDA's vault MCP (`get_key("nemotron")`). It is NOT a Bedrock model — it runs on NVIDIA's NIM API. The URL pattern is `https://integrate.api.nvidia.com/v1` with the Nemotron-Flash model name. See `live-avatar-expert` skill for the exact endpoint pattern.
269
+
270
+ The state machine has four states:
271
+
272
+ ```
273
+ IDLE ──SpeechStart──→ LISTENING
274
+ LISTENING ──PartialTranscript──→ PROCESSING_PARTIAL (Nemotron not called yet)
275
+ PROCESSING_PARTIAL ──FinalTranscript──→ PROCESSING_FINAL (Nemotron called here)
276
+ PROCESSING_FINAL ──NemotronResponse──→ IDLE (TurnComplete emitted, EVE begins response)
277
+
278
+ LISTENING ──SpeechStart──→ LISTENING (re-entry while listening: extend the utterance window)
279
+ PROCESSING_FINAL ──SpeechStart──→ LISTENING (interruption: cancel in-flight Nemotron call, restart)
280
+ ```
281
+
282
+ The interruption case (fourth transition) is required by acceptance criterion 8. A new `SpeechStart` while Nemotron is mid-call cancels the `tokio` task (via `tokio::select!` on a cancellation signal), resets to LISTENING, and begins accumulating the new utterance. Do not let the stale Nemotron response from the previous turn arrive after the interruption — the user's new input has overridden it.
283
+
284
+ ### Rolling lookahead buffer
285
+
286
+ The lookahead buffer is a circular slice of the `audio_bus` ring — not a second buffer. Since WO-1's ring holds 64 audio slots and the producer (mic capture) runs ahead of the consumer (parakeet.cpp / Transcribe), the consumer can read `current + 1` and `current + 2` slots ahead by inspecting the ring's write pointer without moving the read pointer. This is safe and lock-free because:
287
+
288
+ 1. The write pointer is an `AtomicUsize` (WO-1 design)
289
+ 2. Reading ahead of the read pointer but behind the write pointer cannot access uninitialized slots — write always precedes read by the ring's natural invariant
290
+
291
+ Document this in code as:
292
+
293
+ ```rust
294
+ // SAFETY: lookahead reads at ring.write_ptr - 2 through ring.write_ptr - 1.
295
+ // These slots were written before we advanced our read_ptr, so they are
296
+ // fully initialized and will not be overwritten until the ring wraps (64 slots
297
+ // ahead of where we are now). At 16 kHz / 10ms chunks, that is 640 ms of
298
+ // lookahead safety margin — far more than the 20 ms we actually use.
299
+ ```
300
+
301
+ ---
302
+
303
+ ## Struct definitions from WO-1 (read-only — do not modify)
304
+
305
+ WO-2 **reads from** these structs. They are defined in `miranda-ipc/src/lib.rs`. Do not add fields or change sizes — doing so breaks alignment proofs and invalidates the mmap layout WO-1 built.
306
+
307
+ ```rust
308
+ // miranda-ipc/src/lib.rs — these are WO-1 definitions, read them but do not edit
309
+ #[repr(C, align(64))]
310
+ pub struct AudioChunk {
311
+ pub timestamp_us: u64, // 8 bytes
312
+ pub sample_count: u32, // 4 bytes
313
+ pub sample_rate: u32, // 4 bytes
314
+ pub samples: [f32; 160], // 640 bytes
315
+ _pad: [u8; 0], // align(64) compiler handles padding
316
+ }
317
+ // Total: 656 bytes per slot, 64 slots in audio_bus → 41,984 bytes
318
+
319
+ #[repr(C, align(64))]
320
+ pub struct BlendshapeFrame {
321
+ pub timestamp_us: u64,
322
+ pub weights: [f32; 52], // ARKit-52 blend shape coefficients
323
+ _pad: [u8; 4],
324
+ }
325
+ // Total: 216 bytes per slot, 128 slots in blendshape_bus → 27,648 bytes
326
+ ```
327
+
328
+ WO-2 only writes `AudioChunk` to `audio_bus`. `BlendshapeFrame` is written by WO-3 (expression kinematics). WO-2 must not touch `blendshape_bus`.
329
+
330
+ ---
331
+
332
+ ## What Kiro skill to check for each implementation question
333
+
334
+ | Question | Answer is in this skill |
335
+ |---|---|
336
+ | Why is the latency target 30 ms? What does the full glass-to-glass budget look like? | `nobility-posh-framework` — Sequence Matrix, ASR slot in the pipeline |
337
+ | What's the exact Transcribe Streaming API call pattern? | `aws-pipeline-architect` — Pipeline 1 section, Transcribe Streaming |
338
+ | What's the Bedrock Converse API format? Which model ID? | `aws-pipeline-architect` — Bedrock Converse API section |
339
+ | What build flags does parakeet.cpp need? Where is the binary? | `llamacpp-huggingface-expert` — ISA mismatch + build flags section |
340
+ | What's the Nemotron-Flash NIM API endpoint format? | `live-avatar-expert` — Nemotron section |
341
+ | How does the Node Warden monitor per-node latency in the future? | `llamacpp-huggingface-expert` — Node Warden micro-LLM section |
342
+ | What does the "Instant Presence Standard" say about VAD rising-edge response? | `nobility-posh-framework` — IPS, Vanguard Innovation #21 |
343
+ | Can WO-2 be containerized? | `aws-pipeline-architect` — Podman hybrid placement rule (yes — audio nodes can run in Podman; WO-1 IPC bus cannot) |
344
+
345
+ ---
346
+
347
+ ## Verification command sequence (run in this order)
348
+
349
+ After all Pipeline 1 tasks are done:
350
+ ```bash
351
+ # 1. WO-1 still passes (must never regress)
352
+ cargo test -p miranda-ipc
353
+
354
+ # 2. Pipeline 1: open THE VANITY in browser, speak a test sentence, confirm transcript appears
355
+ # (manual — no automated test for mic→Transcribe→Bedrock round-trip)
356
+ ```
357
+
358
+ After all Pipeline 2 tasks are done:
359
+ ```bash
360
+ # 1. WO-1 still passes
361
+ cargo test -p miranda-ipc
362
+
363
+ # 2. miranda-audio compiles with cxx FFI
364
+ cargo build -p miranda-audio
365
+
366
+ # 3. All unit tests pass (pure-Rust tests run under MIRI, FFI tests are cfg(not(miri)) skipped)
367
+ cargo test -p miranda-audio -- --nocapture
368
+
369
+ # 4. MIRI on Silero VAD pure-Rust logic (FFI test excluded by #[cfg(not(miri))])
370
+ cargo +nightly miri test -p miranda-audio
371
+
372
+ # 5. miranda-supervisor compiles and state machine tests pass
373
+ cargo test -p miranda-supervisor -- --nocapture
374
+
375
+ # 6. Latency benchmark: real mic → parakeet.cpp transcript, print elapsed_us
376
+ cargo test -p miranda-audio --test bench_asr -- --nocapture
377
+ ```
.kiro/specs/wo2-acoustic-ingress-routing/requirements.md CHANGED
@@ -1,18 +1,113 @@
1
  # WO-2: Acoustic Ingress, VAD & Supervisory Routing — Requirements
2
 
3
- **Role**: Real-Time Audio Systems Specialist. **Depends on**: WO-1 (ring buffer must exist). **Target**: <30ms transcription.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  ## Requirements (EARS notation)
6
 
7
- 1. WHEN the microphone produces PCM audio THE SYSTEM SHALL capture it via a non-blocking stream (`cpal`) and write chunks into the WO-1 ring buffer without blocking the audio callback thread.
8
- 2. WHEN speech begins or ends in the incoming audio THE SYSTEM SHALL detect the transition using Silero VAD within 10ms of the actual transition.
9
- 3. WHEN a PCM frame is ready for transcription THE SYSTEM SHALL pass it directly from the lock-free ring to the parakeet.cpp engine via the `cxx` FFI boundary — no intermediate copy through a non-realtime path (e.g. no round-trip through a Python process).
10
- 4. WHEN parakeet.cpp returns a transcript token stream THE SYSTEM SHALL forward it to the Nemotron-Flash supervisory agent in `miranda-supervisor` for intent parsing and turn-taking evaluation.
11
- 5. WHEN the supervisory agent determines the user has finished their turn THE SYSTEM SHALL dispatch a signal to the downstream TTS and motion nodes.
12
- 6. WHEN audio is actively streaming THE SYSTEM SHALL maintain a rolling lookahead buffer so mouth coarticulation shaping has upcoming audio context, not just the current frame.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
- ## Acceptance criteria
 
 
 
 
15
 
16
- - Reuse the existing native `parakeet.cpp` build already deployed in this project (see `llamacpp-huggingface-expert` Kiro skill for the exact binary/build flags — `-march=native`, CPU-only) rather than rebuilding it from scratch.
17
- - Measure and report real end-to-end transcription latency, not a vendor-claimed number.
18
- - VAD transition latency is measured against real audio, not synthetic silence-to-tone test signals only.
 
 
 
 
1
  # WO-2: Acoustic Ingress, VAD & Supervisory Routing — Requirements
2
 
3
+ **Role**: Real-Time Audio Systems Specialist.
4
+ **Depends on**: WO-1 complete — the IPC ring buffer at `/dev/shm/miranda_bus` must exist and pass its round-trip test before any WO-2 code runs. Verify with `cargo test -p miranda-ipc` before starting.
5
+ **Target**: ≤30 ms from mic input to transcript token — measured on real audio, not claimed.
6
+ **Pipeline scope**: WO-2 is built in two passes. **Pipeline 1 (do first)** uses Amazon Transcribe Streaming — batteries-included, no GPU, no FFI. **Pipeline 2 (do second)** replaces Transcribe with parakeet.cpp via a Rust FFI binding for lower latency and local operation. The IPC bus, VAD logic, and supervisor routing structure are shared between both.
7
+
8
+ ---
9
+
10
+ ## Read these first — mandatory pre-flight
11
+
12
+ You are entering a fully pre-loaded Kiro workspace. These documents contain decisions already made. Do not re-derive them from scratch; read them and build on them.
13
+
14
+ ### 1. WO-1 is a prerequisite — verify before starting
15
+
16
+ Run from the repo root:
17
+ ```
18
+ cargo test -p miranda-ipc
19
+ ```
20
+ If any test fails, do not proceed. WO-2 writes into the ring buffers WO-1 built. A broken bus means every WO-2 integration test is measuring noise, not the audio pipeline.
21
+
22
+ ### 2. Project overview
23
+
24
+ Read `PROJECT_OVERVIEW.md` at the repo root. It establishes:
25
+ - Miranda-Engine as the harness (not a fixed pipeline)
26
+ - Pipeline 1 (AWS-native, batteries-included) as the first workflow to test
27
+ - EVE as the permanent 2D control reference in THE VANITY's right pane
28
+ - The CAT-5 model routing table with all five current models
29
+
30
+ ### 3. Pipeline 1 node mapping for WO-2
31
+
32
+ Read `.kiro/steering/pipeline-1-aws-native.md` before writing a single line of WO-2 code. For Pipeline 1, the WO-2 acoustic ingress node maps as follows:
33
+
34
+ | WO-2 component | Pipeline 1 implementation | Pipeline 2 implementation |
35
+ |---|---|---|
36
+ | Microphone capture | Browser `MediaDevices.getUserMedia()` API in `client-apps/web/` | `cpal` crate in `miranda-audio` |
37
+ | VAD (voice activity detection) | Browser WebRTC VAD or simple energy threshold | Silero VAD (ONNX runtime in Rust) |
38
+ | ASR (speech → text) | **Amazon Transcribe Streaming** (WebSocket, managed) | **parakeet.cpp** via `cxx` FFI binding |
39
+ | Transcript routing | **Amazon Bedrock Converse API** (Nova Pro or Claude Haiku) | Nemotron-Flash in `miranda-supervisor` |
40
+ | IPC bus writes | `AudioChunk` to `audio_bus` | `AudioChunk` to `audio_bus` (identical) |
41
+
42
+ The IPC bus contract (`AudioChunk` struct, `audio_bus` ring) is **identical in both pipelines**. Build Pipeline 1 first to prove the bus integration. Pipeline 2 swaps the implementations without touching the bus or the downstream consumers.
43
+
44
+ ### 4. The four global Kiro skills
45
+
46
+ All four are globally available at `~/.kiro/skills/`. They answer specific questions that will arise during WO-2:
47
+
48
+ - **`nobility-posh-framework`** — the full Sequence Matrix performance targets (ASR ≤120 ms in the full pipeline), the Node Warden concept (small local GGUF model monitoring each node's own throughput), the 25 Vanguard Innovations, the Instant Presence Standard. Read this to understand *why* the 30 ms latency target exists in the context of the full glass-to-glass budget.
49
+ - **`aws-pipeline-architect`** — the Pipeline 1 AWS service details: Transcribe Streaming API, Bedrock Converse API, Polly viseme output. Includes SDK names, cost model, and the Podman hybrid placement rule (WO-2 can be containerized; WO-1's IPC bus cannot).
50
+ - **`llamacpp-huggingface-expert`** — critical for Pipeline 2: the exact parakeet.cpp build flags (`-march=native` is mandatory on Celeron N4500 which lacks AVX2 — see the ISA mismatch section), the GGUF quantization table, and the `llama-server` OpenAI-compatible endpoint format. Also contains the Node Warden micro-LLM guidance for future self-monitoring.
51
+ - **`live-avatar-expert`** — the 5-stage universal live avatar pattern; WO-2 implements stage 1 (ingress/acoustic) and stage 2 (understanding/routing). Read the ingress section to understand what the downstream stages (WO-3 expression, WO-5 rendering) expect to receive from this Work Order.
52
+
53
+ ### 5. What EVE needs from WO-2
54
+
55
+ EVE is the permanent 2D control reference in THE VANITY's right pane. She is scored against the Instant Presence Standard (see `eve-ecc-docs/INSTANT-PRESENCE-STANDARD.md`). WO-2's job in that context is:
56
+
57
+ - Detect when the human starts speaking (VAD rising edge) → trigger EVE's listening micro-expression (Vanguard Innovation #21)
58
+ - Detect when the human finishes speaking (VAD falling edge + turn-taking signal) → trigger EVE's processing state, then dispatch to TTS/motion
59
+ - Feed transcript tokens to the cognitive core (Bedrock in Pipeline 1, Nemotron in Pipeline 2) fast enough that EVE's response starts visibly within 150 ms of the human's last word
60
+
61
+ The rolling lookahead buffer (requirement 6 below) exists specifically because EVE's mouth coarticulation on the *next* phoneme must be pre-computed — without lookahead, the lip sync lags behind the audio by one chunk.
62
+
63
+ ---
64
 
65
  ## Requirements (EARS notation)
66
 
67
+ **REQ-1** — WHEN the microphone produces PCM audio
68
+ THE SYSTEM SHALL capture it and write `AudioChunk` structs into the WO-1 `audio_bus` ring buffer without blocking the audio capture thread.
69
+
70
+ > *Pipeline 1 note: in Pipeline 1, mic capture happens in the browser via `getUserMedia()` — the AudioChunk is constructed in JavaScript/TypeScript in `client-apps/web/` and the ring bus is simulated in-process (or via a WebSocket to the Rust process). Pipeline 2 uses `cpal` in `miranda-audio` for native mic capture. The `AudioChunk` struct and the bus write contract are identical; only the capture side changes.*
71
+
72
+ **REQ-2** — WHEN speech begins or ends in the incoming audio stream
73
+ THE SYSTEM SHALL detect the transition (voice activity) within 10 ms of the actual transition and emit a typed event (`VadEvent::SpeechStart` or `VadEvent::SpeechEnd`) that downstream consumers can subscribe to.
74
+
75
+ > *10 ms is not arbitrary — it maps to one `AudioChunk` frame (160 samples at 16 kHz). A VAD that takes 30+ ms to detect speech start has already missed a phoneme, and the lookahead buffer cannot compensate for detection latency.*
76
+
77
+ **REQ-3** — WHEN a VAD `SpeechStart` event fires
78
+ THE SYSTEM SHALL begin forwarding `AudioChunk`s from the ring buffer to the active ASR engine (Transcribe Streaming in Pipeline 1, parakeet.cpp in Pipeline 2) and continue until `SpeechEnd`.
79
+
80
+ **REQ-4** — WHEN the ASR engine returns a transcript token or segment
81
+ THE SYSTEM SHALL forward it to the supervisory routing layer (`miranda-supervisor`) for intent parsing and turn-taking evaluation — with no intermediate copy through a non-realtime path (no file, no Python subprocess, no HTTP round-trip between ASR and supervisor in the hot path).
82
+
83
+ > *Pipeline 1 note: Transcribe Streaming returns partial and final results over the WebSocket connection. Partial results trigger EVE's "processing" micro-expression. Final results trigger the full cognitive core call. This two-stage distinction is architectural — do not collapse it to "wait for final result" only.*
84
+
85
+ **REQ-5** — WHEN the supervisory routing layer determines the user has finished their turn
86
+ THE SYSTEM SHALL dispatch a `TurnComplete` signal with the full transcript to the downstream TTS node (Amazon Polly in Pipeline 1, Hive TTS stub in Pipeline 2) and simultaneously signal the motion nodes to begin EVE's response posture.
87
+
88
+ **REQ-6** — WHEN audio is actively streaming to the ASR engine
89
+ THE SYSTEM SHALL maintain a rolling lookahead buffer of at least 2 future `AudioChunk` frames so the expression/rendering layer has upcoming audio context for mouth coarticulation pre-computation.
90
+
91
+ > *This requirement exists because EVE's lip sync (WO-3, WO-5) must animate the *next* phoneme's blend shape weight before the audio for that phoneme actually plays. Without a lookahead, lip sync always lags by one chunk.*
92
+
93
+ **REQ-7** — WHEN Pipeline 2 is being built
94
+ THE SYSTEM SHALL reuse the existing native `parakeet.cpp` build already deployed in this project (exact path and build flags documented in the `llamacpp-huggingface-expert` Kiro skill) rather than rebuilding from scratch. The `cxx` FFI binding must bind the C API surface that parakeet.cpp already exposes (`transcribe_pcm(buf: *const f32, len: usize) -> *const char`), not invent a new one.
95
+
96
+ ---
97
+
98
+ ## Acceptance criteria — what "WO-2 done" looks like
99
+
100
+ WO-2 has two completion levels:
101
 
102
+ **Pipeline 1 complete (minimum for WO-3 to start):**
103
+ 1. Real audio from the browser microphone flows through `getUserMedia()` → VAD → Transcribe Streaming → Bedrock Converse → `TurnComplete` signal, with the transcript visible in THE VANITY's node graph.
104
+ 2. End-to-end latency from speech-end to `TurnComplete` signal is measured and recorded (not the target — the actual number from a real test sentence).
105
+ 3. The `audio_bus` ring in `/dev/shm/miranda_bus` shows non-zero write activity during speech (`cargo test -p miranda-ipc` still passes after WO-2 code is added).
106
+ 4. VAD rising/falling edges are logged with timestamps during a real speech test.
107
 
108
+ **Pipeline 2 complete (full WO-2):**
109
+ 5. All Pipeline 1 criteria above still pass.
110
+ 6. `cargo build -p miranda-audio` exits 0 with the `cxx` FFI binding compiled.
111
+ 7. `cargo test -p miranda-audio` includes a round-trip test: write a 10 ms PCM sine-wave chunk, pass through the FFI to parakeet.cpp, confirm a non-empty token is returned.
112
+ 8. The Nemotron-Flash turn-taking state machine in `miranda-supervisor` handles at least: mid-sentence partial result, turn-complete final result, and interruption (new `SpeechStart` while Nemotron is still processing the previous turn).
113
+ 9. Real end-to-end latency (mic → transcript via parakeet.cpp) is measured and compared against Pipeline 1's Transcribe Streaming baseline.
.kiro/specs/wo2-acoustic-ingress-routing/tasks.md CHANGED
@@ -1,11 +1,498 @@
1
- # WO-2: Tasks
2
 
3
- Per `model-routing-protocol.md`: no CAT 5 in this Work Order — the hardest single task (parakeet.cpp FFI) is CAT 4, Sonnet 5 primary with evidence-triggered Opus escalation.
4
 
5
- - [ ] [CAT 3] Add `cpal` to `miranda-audio/Cargo.toml`; implement non-blocking mic capture writing into the WO-1 audio ring.
6
- - [ ] [CAT 2] Integrate Silero VAD (find a Rust binding or ONNX-runtime path — verify latency claim, don't assume it).
7
- - [ ] [CAT 4] Locate this project's existing built `parakeet.cpp` binary/library (see `llamacpp-huggingface-expert` skill for its exact path/build flags) and write the `cxx` FFI binding against it. Escalate to Opus 5 if two attempts fail — cross-language ABI/memory-ownership bugs are exactly the CAT 4 profile.
8
- - [ ] [CAT 3] Wire PCM frames from the ring buffer directly into the FFI call — no intermediate file/socket hop.
9
- - [ ] [CAT 3] Implement the Nemotron-Flash routing interface in `miranda-supervisor`: intent parsing, turn-taking state, dispatch signal to TTS/motion.
10
- - [ ] [CAT 2] Add a rolling lookahead audio buffer for coarticulation shaping.
11
- - [ ] [CAT 1] Measure real end-to-end latency (mic → transcript) and record the actual number, not the target.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # WO-2 Tasks — Acoustic Ingress, VAD & Supervisory Routing
2
 
3
+ ## Pre-flight before touching a single task
4
 
5
+ **You are Kiro, the agent building this.** Read the full pre-flight in `requirements.md` before starting any task in this file. Every task below assumes you have already done these three things:
6
+
7
+ 1. `cargo test -p miranda-ipc` — passes clean on this machine. If it fails, stop and fix WO-1 before proceeding. WO-2 writes into WO-1's ring buffers. A broken bus poisons every WO-2 integration test.
8
+ 2. Read `.kiro/steering/pipeline-1-aws-native.md` — you need to know exactly which AWS service fills the ASR role in Pipeline 1 (Amazon Transcribe Streaming) versus Pipeline 2 (parakeet.cpp).
9
+ 3. Run `node scripts/cat-router-check.mjs` — confirms which CAT tiers have pending tasks and whether you'll need Claude Sonnet 5 or Opus 5 this session.
10
+
11
+ ---
12
+
13
+ ## Clarifications embedded — Kiro does not need to ask about these
14
+
15
+ **Q: Is Hermes running? Should I route these tasks through Hermes?**
16
+ A: No. Hermes is not integrated, not running. These Work Orders were written in a Hermes-style prompt format, but Kiro is the agent executing them. Do not wait for or reference Hermes.
17
+
18
+ **Q: Pipeline 1 uses parakeet.cpp?**
19
+ A: No. Pipeline 1 uses Amazon Transcribe Streaming for ASR. parakeet.cpp is Pipeline 2. The node label in THE VANITY says "Riva ASR" — that is a role label. Transcribe Streaming fills that role slot in Pipeline 1. parakeet.cpp fills it in Pipeline 2. Do not install or use parakeet.cpp for Pipeline 1 tasks.
20
+
21
+ **Q: Which Amazon Bedrock model ID should I use for Pipeline 1 routing?**
22
+ A: `amazon.nova-pro-v1:0` — CAT 3, Bedrock-native, full tool-calling. Only escalate to `anthropic.claude-sonnet-5` if Nova Pro fails after two real verified attempts on a specific turn-taking edge case.
23
+
24
+ **Q: Single session or multi-session for this Work Order?**
25
+ A: Multi-session. Pipeline 1 tasks (T1–T4) are one session. Pipeline 2 tasks (T5–T9) are a second session that starts after Pipeline 1 is verified complete. Before closing each session, emit the CAT handoff block for the next tier change. Re-read the tasks.md pre-flight at the start of the second session.
26
+
27
+ **Q: What do I do when I hit the CAT 4 parakeet.cpp FFI task?**
28
+ A: Stop on the CAT 3 model, emit the handoff block at the bottom of this file, switch to Claude Sonnet 5, then re-issue T7 alone on the Sonnet 5 session. Do not attempt T7 on Nova Pro.
29
+
30
+ ---
31
+
32
+ ## CAT routing summary for WO-2
33
+
34
+ | Task | CAT | Model | Why |
35
+ |---|---|---|---|
36
+ | T1 | CAT 1 | Qwen3 Coder Next | Add npm deps and scaffold TypeScript files — pure mechanical boilerplate |
37
+ | T2 | CAT 2 | Amazon Nova Lite | Simple energy-threshold VAD math, known pattern, no risk |
38
+ | T3 | CAT 3 | Amazon Nova Pro | Transcribe Streaming WebSocket integration — third-party SDK, behavioral tests |
39
+ | T4 | CAT 3 | Amazon Nova Pro | Bedrock Converse routing — SDK call, state dispatch, same tier as T3 |
40
+ | T5 | CAT 2 | Amazon Nova Lite | cpal mic capture scaffold — known Rust audio pattern |
41
+ | T6 | CAT 2 | Amazon Nova Lite | Silero VAD ONNX inference — standard ort pipeline |
42
+ | T7 | CAT 4 | Claude Sonnet 5 | parakeet.cpp cxx FFI — unsafe Rust ABI, cross-language memory contract, real failure risk |
43
+ | T8 | CAT 3 | Amazon Nova Pro | Nemotron-Flash state machine — complex but bounded logic, NIM API |
44
+ | T9 | CAT 1 | Qwen3 Coder Next | Latency measurement — print elapsed_us, no logic |
45
+
46
+ ---
47
+
48
+ ## SESSION 1 — Pipeline 1 (AWS-native, do first)
49
+
50
+ ### T1 — [CAT 1] Add AWS SDK deps and scaffold TypeScript audio files
51
+
52
+ **Model: Qwen3 Coder Next**
53
+
54
+ 1. In `client-apps/web/package.json`, add:
55
+ ```json
56
+ "@aws-sdk/client-transcribe-streaming": "^3",
57
+ "@aws-sdk/client-bedrock-runtime": "^3"
58
+ ```
59
+ 2. Run `npm install` from `client-apps/web/` and confirm it exits 0.
60
+ 3. Create these empty files (scaffold only — T2/T3/T4 will fill them):
61
+ - `client-apps/web/src/audio/MicCapture.ts`
62
+ - `client-apps/web/src/audio/VadDetector.ts`
63
+ - `client-apps/web/src/audio/TranscribeClient.ts`
64
+ - `client-apps/web/src/audio/BedrockRouter.ts`
65
+ 4. Run `npx tsc --noEmit` from `client-apps/web/` — must exit 0 (empty files are valid TS).
66
+
67
+ **Evidence required**: `npm install` output (0 errors), `tsc --noEmit` exit 0.
68
+
69
+ ---
70
+
71
+ ### T2 — [CAT 2] Implement browser VAD (energy threshold)
72
+
73
+ **Model: Amazon Nova Lite**
74
+
75
+ Implement `client-apps/web/src/audio/VadDetector.ts`. This is a simple RMS energy threshold — no ML model needed for Pipeline 1.
76
+
77
+ ```typescript
78
+ // Energy-threshold VAD for Pipeline 1 browser context
79
+ export type VadEvent = 'speech-start' | 'speech-end';
80
+
81
+ export class VadDetector {
82
+ private isSpeaking = false;
83
+ private silenceFrames = 0;
84
+ private readonly THRESHOLD = 0.01; // RMS energy floor
85
+ private readonly SILENCE_FRAMES = 15; // 15 × 64ms ≈ 1 second of silence → SpeechEnd
86
+
87
+ feed(pcm: Float32Array): VadEvent | null {
88
+ const rms = Math.sqrt(pcm.reduce((s, x) => s + x * x, 0) / pcm.length);
89
+ if (rms > this.THRESHOLD) {
90
+ this.silenceFrames = 0;
91
+ if (!this.isSpeaking) {
92
+ this.isSpeaking = true;
93
+ return 'speech-start';
94
+ }
95
+ } else {
96
+ this.silenceFrames++;
97
+ if (this.isSpeaking && this.silenceFrames >= this.SILENCE_FRAMES) {
98
+ this.isSpeaking = false;
99
+ this.silenceFrames = 0;
100
+ return 'speech-end';
101
+ }
102
+ }
103
+ return null;
104
+ }
105
+ }
106
+ ```
107
+
108
+ Write one unit test in `client-apps/web/src/audio/VadDetector.test.ts` using Vitest:
109
+ - Feed 20 frames of silence (all zeros) → no event
110
+ - Feed 5 frames of loud audio (RMS > threshold) → `'speech-start'` on the first frame
111
+ - Feed 15 more frames of silence → `'speech-end'`
112
+
113
+ Run `npx vitest run --reporter=verbose` from `client-apps/web/` — test must pass.
114
+
115
+ **Evidence required**: Vitest output showing the VadDetector test passing.
116
+
117
+ ---
118
+
119
+ ### T3 — [CAT 3] Implement Transcribe Streaming client
120
+
121
+ **Model: Amazon Nova Pro**
122
+
123
+ Implement `client-apps/web/src/audio/TranscribeClient.ts`. This is the Amazon Transcribe Streaming WebSocket integration. Read `.kiro/steering/pipeline-1-aws-native.md` and the `aws-pipeline-architect` Kiro skill before writing this.
124
+
125
+ Key requirements:
126
+ - Credentials: call AMANDA vault MCP `get_key("aws")` — never hardcode keys
127
+ - Stream PCM chunks as 2048-sample batches (2 × 1024 from ScriptProcessor = 128 ms per send)
128
+ - Handle both `IsPartial: true` (emit `onPartialTranscript`) and `IsPartial: false` (emit `onFinalTranscript`)
129
+ - Re-entrancy: if a new `SpeechStart` arrives while a Transcribe stream is active, close the current stream gracefully and open a new one
130
+
131
+ ```typescript
132
+ import { TranscribeStreamingClient, StartStreamTranscriptionCommand } from '@aws-sdk/client-transcribe-streaming';
133
+
134
+ export class TranscribeClient {
135
+ private client: TranscribeStreamingClient;
136
+
137
+ constructor(
138
+ private onPartialTranscript: (text: string) => void,
139
+ private onFinalTranscript: (text: string) => void
140
+ ) {
141
+ this.client = new TranscribeStreamingClient({ region: 'us-east-1' });
142
+ }
143
+
144
+ async startStream(audioGenerator: AsyncGenerator<Uint8Array>): Promise<void> {
145
+ const command = new StartStreamTranscriptionCommand({
146
+ LanguageCode: 'en-US',
147
+ MediaSampleRateHertz: 16000,
148
+ MediaEncoding: 'pcm',
149
+ AudioStream: (async function* () {
150
+ for await (const chunk of audioGenerator) {
151
+ yield { AudioEvent: { AudioChunk: chunk } };
152
+ }
153
+ })(),
154
+ EnablePartialResultsStabilization: true,
155
+ PartialResultsStability: 'medium',
156
+ });
157
+ const response = await this.client.send(command);
158
+ for await (const event of response.TranscriptResultStream!) {
159
+ const results = event.TranscriptEvent?.Transcript?.Results ?? [];
160
+ for (const result of results) {
161
+ const text = result.Alternatives?.[0]?.Transcript ?? '';
162
+ if (result.IsPartial) this.onPartialTranscript(text);
163
+ else this.onFinalTranscript(text);
164
+ }
165
+ }
166
+ }
167
+ }
168
+ ```
169
+
170
+ Write an integration test in `TranscribeClient.test.ts` that:
171
+ - Mocks the `TranscribeStreamingClient` to return one partial result and one final result
172
+ - Confirms `onPartialTranscript` is called once and `onFinalTranscript` is called once
173
+
174
+ **Evidence required**: `npx vitest run` passing with the mock integration test.
175
+
176
+ ---
177
+
178
+ ### T4 — [CAT 3] Implement Bedrock Converse routing
179
+
180
+ **Model: Amazon Nova Pro**
181
+
182
+ Implement `client-apps/web/src/audio/BedrockRouter.ts`. This takes the final transcript from T3 and calls Amazon Bedrock Converse API to generate EVE's response.
183
+
184
+ Read `aws-pipeline-architect` skill section "Amazon Bedrock Converse API" before writing.
185
+
186
+ Model ID: `amazon.nova-pro-v1:0`
187
+ Credentials: `get_key("aws")` via AMANDA vault MCP — same pattern as T3.
188
+
189
+ ```typescript
190
+ import { BedrockRuntimeClient, ConverseCommand } from '@aws-sdk/client-bedrock-runtime';
191
+
192
+ const SYSTEM_PROMPT = `You are EVE, a real-time digital human companion.
193
+ Respond in 1-2 sentences. Be warm, present, and conversational.
194
+ Never describe your own actions. Never say "As an AI."`;
195
+
196
+ export class BedrockRouter {
197
+ private client = new BedrockRuntimeClient({ region: 'us-east-1' });
198
+
199
+ async route(transcript: string): Promise<string> {
200
+ const response = await this.client.send(new ConverseCommand({
201
+ modelId: 'amazon.nova-pro-v1:0',
202
+ messages: [{ role: 'user', content: [{ text: transcript }] }],
203
+ system: [{ text: SYSTEM_PROMPT }],
204
+ }));
205
+ return response.output?.message?.content?.[0]?.text ?? '';
206
+ }
207
+ }
208
+ ```
209
+
210
+ Wire T2 + T3 + T4 together in `client-apps/web/src/audio/AcousticPipeline.ts`:
211
+
212
+ ```typescript
213
+ // Orchestrator: MicCapture → VadDetector → TranscribeClient → BedrockRouter → TurnComplete
214
+ export class AcousticPipeline {
215
+ constructor(
216
+ private onTurnComplete: (transcript: string, response: string) => void
217
+ ) {}
218
+
219
+ async start(): Promise<void> {
220
+ const vad = new VadDetector();
221
+ const router = new BedrockRouter();
222
+ const transcribe = new TranscribeClient(
223
+ (partial) => console.log('[partial]', partial), // TODO WO-3: trigger EVE processing expression
224
+ async (final) => {
225
+ const response = await router.route(final);
226
+ this.onTurnComplete(final, response);
227
+ }
228
+ );
229
+ // MicCapture feeds VadDetector; on speech-start, open Transcribe stream
230
+ // ... (mic capture glue goes here — use getUserMedia from design.md)
231
+ }
232
+ }
233
+ ```
234
+
235
+ **Manual verification required** (no automated test for mic → real AWS → response):
236
+ - Open THE VANITY in browser (`npm run dev` from `client-apps/web/`)
237
+ - Speak: "Hello EVE, how are you?"
238
+ - Confirm: partial transcript appears in console within 1 second of speech start
239
+ - Confirm: final transcript appears and BedrockRouter returns a response
240
+ - Log timestamps at SpeechStart, FinalTranscript, and TurnComplete — record elapsed times
241
+
242
+ **Evidence required**: Console log output showing the three timestamps and the response text from Bedrock. Paste the output verbatim (do not summarize).
243
+
244
+ ---
245
+
246
+ ## SESSION 2 — Pipeline 2 (parakeet.cpp + Nemotron-Flash)
247
+
248
+ Start a new Kiro session. Re-read this tasks.md pre-flight. Run `cargo test -p miranda-ipc` again to confirm WO-1 is still clean after Session 1 changes.
249
+
250
+ ---
251
+
252
+ ### T5 — [CAT 2] cpal mic capture in `miranda-audio`
253
+
254
+ **Model: Amazon Nova Lite**
255
+
256
+ Create `miranda-audio/src/capture.rs` with the `cpal`-based mic capture skeleton from design.md. The cpal callback must:
257
+ - Capture 16 kHz mono PCM as `f32`
258
+ - Use `BufferSize::Fixed(160)` — 10 ms at 16 kHz
259
+ - Write one `AudioChunk` per callback to `audio_bus` via the WO-1 ring API
260
+ - Never allocate in the audio callback — no `Vec::push`, no `Box::new`
261
+
262
+ Add `cpal` to `miranda-audio/Cargo.toml`. Run:
263
+
264
+ ```bash
265
+ cargo build -p miranda-audio
266
+ ```
267
+
268
+ Must exit 0.
269
+
270
+ Write a unit test `test_chunk_size` that creates an `AudioChunk::from_pcm` with 160 samples and confirms `chunk.sample_count == 160` and `chunk.sample_rate == 16000`. Run:
271
+
272
+ ```bash
273
+ cargo test -p miranda-audio -- test_chunk_size --nocapture
274
+ ```
275
+
276
+ Must pass.
277
+
278
+ **Evidence required**: `cargo build` output (0 errors, 0 warnings), `cargo test` output showing `test_chunk_size ok`.
279
+
280
+ ---
281
+
282
+ ### T6 — [CAT 2] Silero VAD ONNX inference
283
+
284
+ **Model: Amazon Nova Lite**
285
+
286
+ Implement `miranda-audio/src/vad.rs` using the Silero VAD ONNX model via the `ort` crate. Before writing any code:
287
+ - Check `assets/models/silero_vad.onnx` — if it exists, use it. Do not download again.
288
+ - If it does not exist: download from `https://github.com/snakers4/silero-vad/raw/master/files/silero_vad.onnx`, place at `assets/models/silero_vad.onnx`, add to `.gitignore`.
289
+
290
+ Add `ort = { version = "2", features = ["load-dynamic"] }` to `miranda-audio/Cargo.toml`.
291
+
292
+ Implement `SileroVad::feed(&mut self, chunk: &[f32]) -> Option<VadEvent>` per the design.md spec. Key correctness requirement: the LSTM hidden state (`h`, `c`) must persist across `feed()` calls — if you reset hidden state per call, VAD accuracy collapses to near zero.
293
+
294
+ Write unit test `test_vad_silence_no_event`:
295
+ - Feed 100 chunks of zero-value PCM (silence)
296
+ - Confirm no `VadEvent::SpeechStart` is ever returned
297
+
298
+ Write unit test `test_vad_tone_detected`:
299
+ - Feed 50 chunks of 1.0 amplitude sine wave (clear speech signal)
300
+ - Confirm `VadEvent::SpeechStart` is returned at some point in the first 20 chunks
301
+
302
+ These tests are pure Rust (no FFI) and must pass under MIRI:
303
+ ```bash
304
+ cargo +nightly miri test -p miranda-audio -- test_vad_silence_no_event test_vad_tone_detected
305
+ ```
306
+
307
+ **Evidence required**: `cargo test` passing both vad tests, then `cargo +nightly miri test` output showing both pass under MIRI.
308
+
309
+ ---
310
+
311
+ ### T7 — [CAT 4] parakeet.cpp cxx FFI binding
312
+
313
+ **Model: Claude Sonnet 5 — STOP before this task and switch models**
314
+
315
+ Before starting T7, on the Amazon Nova Pro session, emit:
316
+
317
+ ```
318
+ === CAT 4 HANDOFF — switching to Claude Sonnet 5 ===
319
+ Task: T7 — parakeet.cpp cxx FFI binding
320
+ Status: T5 and T6 complete and verified
321
+ State: miranda-audio crate builds clean with cpal mic capture and Silero VAD.
322
+ Both VAD tests pass including under MIRI. audio_bus ring writes confirmed.
323
+ parakeet.cpp binary is at [INSERT PATH FROM llamacpp-huggingface-expert SKILL].
324
+ The C API exposed is: extern "C" const char* transcribe_pcm(const float* buf, size_t len);
325
+ Incoming needs to know:
326
+ - Use cxx = "1" in Cargo.toml, not bindgen
327
+ - DO NOT add new symbols to parakeet.cpp — bind the existing C API only
328
+ - The FFI integration test must be wrapped in #[cfg(not(miri))] — MIRI cannot cross the FFI boundary
329
+ - Build flags: -march=native mandatory (no -mavx2 on Celeron N4500)
330
+ - Read llamacpp-huggingface-expert Kiro skill before any FFI code — ISA mismatch section is critical
331
+ === END HANDOFF ===
332
+ ```
333
+
334
+ **Then switch to Claude Sonnet 5 and re-issue T7 on that session.**
335
+
336
+ ---
337
+
338
+ **[Claude Sonnet 5 picks up here]**
339
+
340
+ Read the `llamacpp-huggingface-expert` Kiro skill fully before writing any code. Specifically:
341
+ - ISA mismatch section (Celeron N4500 lacks AVX2 — build parakeet.cpp with `-march=native` only)
342
+ - The existing binary path for parakeet.cpp in this repo
343
+ - The C API surface (`transcribe_pcm`)
344
+
345
+ Implement `miranda-audio/src/asr/parakeet_ffi.rs` per the design.md spec:
346
+
347
+ ```rust
348
+ #[cxx::bridge]
349
+ mod ffi {
350
+ unsafe extern "C++" {
351
+ include!("parakeet.h");
352
+ unsafe fn transcribe_pcm(buf: *const f32, len: usize) -> *const c_char;
353
+ }
354
+ }
355
+
356
+ pub fn transcribe(samples: &[f32]) -> String {
357
+ let raw = unsafe { ffi::transcribe_pcm(samples.as_ptr(), samples.len()) };
358
+ if raw.is_null() { return String::new(); }
359
+ // SAFETY: parakeet.cpp returns a valid null-terminated UTF-8 string
360
+ // valid until the next transcribe_pcm call. We own the data after to_string_lossy.
361
+ unsafe { std::ffi::CStr::from_ptr(raw).to_string_lossy().into_owned() }
362
+ }
363
+ ```
364
+
365
+ Add `build.rs` in `miranda-audio/` to configure the cxx build linking to parakeet.cpp. Run:
366
+
367
+ ```bash
368
+ cargo build -p miranda-audio
369
+ ```
370
+
371
+ Must exit 0 — this is the primary verification. A cxx FFI build failure is a real verification failure and counts toward CAT 4 escalation.
372
+
373
+ Write integration test `test_transcribe_sine_wave` wrapped in `#[cfg(not(miri))]`:
374
+ - Generate 16000 f32 samples of a 440 Hz sine wave (1 second of audio)
375
+ - Call `transcribe(samples)`
376
+ - Confirm the return value is a non-null, non-empty `String` (the specific text doesn't matter — just that the FFI round-trip works without a segfault)
377
+
378
+ ```bash
379
+ cargo test -p miranda-audio -- test_transcribe_sine_wave --nocapture
380
+ ```
381
+
382
+ **If this test fails twice** (real `cargo build` error or segfault — not uncertainty), emit:
383
+
384
+ ```
385
+ CAT 5 ESCALATION — T7 parakeet.cpp FFI has failed real verification twice on Claude Sonnet 5.
386
+ Switch to Claude Opus 5 before the third attempt.
387
+ ```
388
+
389
+ **Evidence required**: `cargo build -p miranda-audio` exit 0, `cargo test` output showing `test_transcribe_sine_wave ok`.
390
+
391
+ ---
392
+
393
+ ### T8 — [CAT 3] Nemotron-Flash turn-taking state machine
394
+
395
+ **Model: Amazon Nova Pro**
396
+
397
+ Before starting T8, switch back from Claude Sonnet 5 to Amazon Nova Pro. Emit a brief handoff:
398
+
399
+ ```
400
+ === CAT 3 HANDOFF — switching back to Amazon Nova Pro ===
401
+ Task: T8 — Nemotron-Flash state machine in miranda-supervisor
402
+ Status: T7 complete — parakeet.cpp FFI builds clean, sine-wave round-trip test passes
403
+ State: miranda-audio builds with cpal + Silero VAD + cxx FFI. Next: miranda-supervisor routing.
404
+ Incoming needs to know:
405
+ - Nemotron-Flash is NOT a Bedrock model — it uses NVIDIA NIM API (AMANDA vault key "nemotron")
406
+ - Read live-avatar-expert Kiro skill for the NIM endpoint URL format
407
+ - State machine must handle: partial transcript, final transcript, and INTERRUPTION case
408
+ === END HANDOFF ===
409
+ ```
410
+
411
+ Implement `miranda-supervisor/src/turn_machine.rs` with the four-state machine from design.md:
412
+
413
+ States: `IDLE → LISTENING → PROCESSING_PARTIAL → PROCESSING_FINAL → IDLE`
414
+
415
+ Interruption path: `PROCESSING_FINAL --SpeechStart--> LISTENING` (cancel in-flight Nemotron call).
416
+
417
+ Use `tokio::select!` for cancellation:
418
+
419
+ ```rust
420
+ tokio::select! {
421
+ result = nemotron_call => {
422
+ // normal completion
423
+ emit_turn_complete(result);
424
+ self.state = State::Idle;
425
+ }
426
+ _ = cancellation_rx.recv() => {
427
+ // interrupted — discard nemotron result, return to listening
428
+ self.state = State::Listening;
429
+ }
430
+ }
431
+ ```
432
+
433
+ Read the `live-avatar-expert` skill for the Nemotron-Flash NIM API endpoint and request format. Credentials via `get_key("nemotron")` from AMANDA vault MCP.
434
+
435
+ Write unit tests for the three behavioral cases (mock the Nemotron call):
436
+ - `test_normal_turn`: partial → final → TurnComplete emitted
437
+ - `test_interruption`: start turn → SpeechStart interrupts mid-Nemotron → second TurnComplete (not first) emitted
438
+ - `test_silence_no_dispatch`: silence frames → no TurnComplete
439
+
440
+ ```bash
441
+ cargo test -p miranda-supervisor -- --nocapture
442
+ ```
443
+
444
+ All three tests must pass.
445
+
446
+ **Evidence required**: `cargo test -p miranda-supervisor` output showing all three tests passing.
447
+
448
+ ---
449
+
450
+ ### T9 — [CAT 1] Latency measurement
451
+
452
+ **Model: Qwen3 Coder Next**
453
+
454
+ Add a benchmark integration test `miranda-audio/tests/bench_asr.rs` that measures wall-clock latency from PCM audio write to transcript return via parakeet.cpp FFI:
455
+
456
+ ```rust
457
+ #[cfg(not(miri))]
458
+ #[test]
459
+ fn bench_asr_latency() {
460
+ // Generate 3 seconds of test audio (sine wave at 440 Hz)
461
+ let samples: Vec<f32> = (0..48000)
462
+ .map(|i| (2.0 * std::f64::consts::PI * 440.0 * i as f64 / 16000.0).sin() as f32)
463
+ .collect();
464
+
465
+ let start = std::time::Instant::now();
466
+ let transcript = miranda_audio::asr::parakeet_ffi::transcribe(&samples);
467
+ let elapsed_us = start.elapsed().as_micros();
468
+
469
+ println!("parakeet.cpp latency: {elapsed_us} μs");
470
+ println!("transcript: {transcript:?}");
471
+ // No assert on latency — just measure and print. The Pipeline 1 baseline from T4 is the comparison point.
472
+ assert!(!transcript.is_empty(), "parakeet.cpp returned empty transcript for sine wave input");
473
+ }
474
+ ```
475
+
476
+ Run:
477
+
478
+ ```bash
479
+ cargo test -p miranda-audio --test bench_asr -- --nocapture
480
+ ```
481
+
482
+ Record the printed `latency` value. This is the Pipeline 2 ASR baseline. Compare to the Pipeline 1 Transcribe Streaming latency recorded in T4. Document both numbers in a comment at the top of `bench_asr.rs`.
483
+
484
+ **Evidence required**: `cargo test` output with the two latency numbers visible in console output.
485
+
486
+ ---
487
+
488
+ ## WO-2 done — what this unlocks
489
+
490
+ When all 9 tasks have real command-output evidence:
491
+ - Pipeline 1 path: browser mic → Transcribe → Bedrock → TurnComplete ✓
492
+ - Pipeline 2 path: cpal → Silero VAD → parakeet.cpp → Nemotron-Flash → TurnComplete ✓
493
+ - `audio_bus` ring in `/dev/shm/miranda_bus` receiving live AudioChunks ✓
494
+ - Latency baseline measured for both paths ✓
495
+
496
+ WO-3 (ARKit-52 SIMD kinematics — BlendshapeFrame generation) can now start. The `audio_bus` WO-3 reads from is live, and the `TurnComplete` signal WO-3 waits for is being emitted.
497
+
498
+ Run `node scripts/cat-router-check.mjs` — WO-2 tasks should show all `[x]` complete. If any remain open, do not mark WO-2 done.