hunt Claude Sonnet 5 commited on
Commit
df0137a
Β·
1 Parent(s): e8def61

WO-1 spec: verbose, spoon-feed-ready rewrite for Kiro

Browse files

requirements.md: pre-flight checklist, all 4 skill references, EVE/THE VANITY
context, repo structure map, 7 EARS requirements with inline rationale, 6-point
acceptance criteria.

design.md: full crate dependency graph, 3-buffer layout table, exact struct
definitions with field sizes, atomic ordering rationale, unsafe invariant
guidance, cross-reference section mapping each design choice to its skill.

tasks.md: 7 tasks with exact commands, paste-ready handoff blocks for model
switches, escalation wording, and downstream unblocking note.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

.kiro/specs/wo1-workspace-ipc-backbone/design.md CHANGED
@@ -1,15 +1,163 @@
1
  # WO-1: Design
2
 
3
- ## Architecture
4
 
5
- `miranda-core` holds shared constants (52 blendshapes, 9 SH coefficients) and error types β€” every other crate depends on it. `miranda-ipc` owns the ring buffer itself and depends only on `miranda-core`. This dependency direction is already scaffolded in the workspace's `Cargo.toml` files β€” do not invert it (nothing should depend on `miranda-ipc` transitively pulling in unrelated node logic).
6
 
7
- ## The ring buffer
8
 
9
- - Backing store: `memmap2::MmapMut` over a file at `/dev/shm/miranda_bus`, sized to hold N fixed-size slots (choose N as a power of 2 for cheap modulo via bitmask).
10
- - Head/tail: `AtomicUsize` (or `AtomicU64` if wraparound at `usize::MAX` slots is a real concern β€” it isn't at this scale), `Ordering::AcqRel` on the write side, `Ordering::Acquire` on the read side.
11
- - Slot layout: a tagged union isn't C-ABI-safe across languages the same way a fixed struct-per-type is β€” prefer three separate fixed-size ring buffers (audio / blendshape / spherical-harmonic) over one polymorphic ring, since the FFI boundary (WO-2's parakeet.cpp binding) needs a stable, simple layout.
12
 
13
- ## Cross-reference
 
 
 
 
14
 
15
- See the `nobility-posh-framework` Kiro skill for the full Hermes Execution Prompt and the Sequence Matrix performance targets.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # WO-1: Design
2
 
3
+ This document is the technical blueprint for Work Order 1. Read `requirements.md` in this directory first β€” it contains the pre-flight checklist, the skill references, and the context about EVE, THE VANITY, and what this IPC backbone is actually for. This doc assumes you have read that.
4
 
5
+ ---
6
 
7
+ ## Where this fits in the full system
8
 
9
+ Miranda-Engine is a **workflow-agnostic testing harness**. The IPC backbone you're building in WO-1 is the central nervous system β€” the shared-memory bus that all other Work Orders write into and read from:
 
 
10
 
11
+ ```
12
+ [WO-2: Audio/VAD/ASR] ──writes AudioChunk──────────────┐
13
+ [WO-3: Kinematics] ──writes BlendshapeFrame──────────┼──▢ /dev/shm/miranda_bus ──▢ [WO-5: Renderer]
14
+ [WO-3: Lighting] ──writes SphericalHarmonicsβ”€β”€β”€β”€β”€β”€β”€β”˜ ──▢ [WO-4: WebRTC transport]
15
+ ```
16
 
17
+ THE VANITY's left pane (the node graph in `client-apps/web/`) visualizes this topology. The node names (Riva ASR β†’ Nemotron β†’ Hive TTS β†’ Audio2Face-3D β†’ Omniverse) are **role labels** β€” they show what class of processing happens at each position. When Miranda-Engine is running, real Rust nodes write their outputs to this bus; the renderer reads from it to update EVE's live expression. WO-1 is the bus. Nothing else can start until it exists.
18
+
19
+ ---
20
+
21
+ ## Crate dependency graph
22
+
23
+ The dependency direction is already scaffolded in the workspace `Cargo.toml` files. **Do not change this graph** β€” inverting a dependency (e.g., making `miranda-core` depend on `miranda-ipc`) would create circular dependencies that `cargo` will refuse to build.
24
+
25
+ ```
26
+ miranda-core ← no dependencies on other workspace crates (foundation)
27
+ ↑
28
+ miranda-ipc ← depends only on miranda-core
29
+ ↑
30
+ miranda-audio ← depends on miranda-ipc (writes AudioChunks to bus) [WO-2]
31
+ miranda-nodes ← depends on miranda-ipc (node trait reads/writes bus) [WO-3]
32
+ miranda-supervisor ← depends on miranda-ipc (manages bus lifecycle)
33
+ miranda-transport ← depends on miranda-ipc (reads bus for WebRTC frames) [WO-4]
34
+ ```
35
+
36
+ **What lives in `miranda-core`**: shared constants (BLENDSHAPE_COUNT = 52, SH_COEFF_COUNT = 9), the three fixed-size payload structs (`AudioChunk`, `BlendshapeFrame`, `SphericalHarmonics`), and the error types. Everything that multiple crates need to agree on.
37
+
38
+ **What lives in `miranda-ipc`**: the ring buffer implementation β€” the mmap, the atomic head/tail, and the push/pop methods. Nothing else.
39
+
40
+ ---
41
+
42
+ ## The three ring buffers
43
+
44
+ Do not use a single polymorphic ring buffer. Use three separate, fixed-size ring buffers β€” one per payload type:
45
+
46
+ | Buffer | Payload type | Fixed slot size | Write rate |
47
+ |---|---|---|---|
48
+ | `audio_bus` | `AudioChunk` | see below | ~100 Hz (10 ms chunks) |
49
+ | `blendshape_bus` | `BlendshapeFrame` | 52 Γ— 4 bytes + 8 bytes timestamp = 216 bytes | 60 Hz (60 FPS) |
50
+ | `sh_bus` | `SphericalHarmonics` | 9 Γ— 4 bytes + 8 bytes timestamp = 44 bytes | 30–60 Hz |
51
+
52
+ **Why three separate buffers instead of one tagged union?**
53
+ A tagged union over these three types would have a C-ABI footprint as large as the largest member. It would also require every reader to branch on the tag, which adds complexity on the hot path. More critically: WO-2's parakeet.cpp FFI binding needs to write `AudioChunk`s directly into the bus from C++ β€” a single polymorphic buffer makes that harder to get right. Three simple buffers with known, fixed layouts are safer at the FFI boundary.
54
+
55
+ ---
56
+
57
+ ## `AudioChunk` struct design
58
+
59
+ A raw audio chunk from the microphone or from a VAD pre-buffer. The sample rate, channel count, and format come from the pipeline configuration (mono 16 kHz f32 is the target for Parakeet/ASR; do not hardcode these as magic numbers in the struct β€” use constants from `miranda-core`).
60
+
61
+ ```rust
62
+ // In miranda-core/src/lib.rs
63
+ pub const AUDIO_SAMPLE_RATE_HZ: u32 = 16_000;
64
+ pub const AUDIO_CHUNK_FRAMES: usize = 160; // 10 ms at 16 kHz
65
+
66
+ #[repr(C)]
67
+ #[derive(Debug, Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
68
+ pub struct AudioChunk {
69
+ pub timestamp_us: u64, // microseconds since harness start
70
+ pub sample_rate: u32, // always AUDIO_SAMPLE_RATE_HZ in v1
71
+ pub frame_count: u32, // number of valid samples in `samples`
72
+ pub samples: [f32; AUDIO_CHUNK_FRAMES], // 160 Γ— 4 = 640 bytes
73
+ }
74
+ ```
75
+
76
+ Total size: 8 + 4 + 4 + 640 = **656 bytes per slot**.
77
+
78
+ **`bytemuck::Pod` and `bytemuck::Zeroable`**: these derive macros from the `bytemuck` crate verify at compile time that the struct has no padding, no uninit bytes, and no invalid bit patterns β€” which is required for safe casting to/from `&[u8]` when writing to and reading from the mmap. Do not skip these derives; they are the compile-time proof of the safety invariant.
79
+
80
+ ---
81
+
82
+ ## `BlendshapeFrame` struct design
83
+
84
+ The 52 ARKit blend shapes that drive facial animation on EVE. These are normalized weights in [0.0, 1.0]. WO-3 (ARKit-52 SIMD kinematics) will be the primary writer; the renderer (WO-5) will be the primary reader.
85
+
86
+ ```rust
87
+ // In miranda-core/src/lib.rs
88
+ pub const BLENDSHAPE_COUNT: usize = 52;
89
+
90
+ #[repr(C)]
91
+ #[derive(Debug, Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
92
+ pub struct BlendshapeFrame {
93
+ pub timestamp_us: u64,
94
+ pub weights: [f32; BLENDSHAPE_COUNT], // 52 Γ— 4 = 208 bytes
95
+ }
96
+ ```
97
+
98
+ Total size: 8 + 208 = **216 bytes per slot**.
99
+
100
+ ---
101
+
102
+ ## `SphericalHarmonics` struct design
103
+
104
+ L2 spherical harmonic lighting coefficients β€” 9 floats that encode the low-frequency ambient lighting environment. These are used by the Gaussian-splat renderer (WO-5) to relights EVE's render dynamically.
105
+
106
+ ```rust
107
+ // In miranda-core/src/lib.rs
108
+ pub const SH_COEFF_COUNT: usize = 9;
109
+
110
+ #[repr(C)]
111
+ #[derive(Debug, Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
112
+ pub struct SphericalHarmonics {
113
+ pub timestamp_us: u64,
114
+ pub coefficients: [f32; SH_COEFF_COUNT], // 9 Γ— 4 = 36 bytes
115
+ }
116
+ ```
117
+
118
+ Total size: 8 + 36 = **44 bytes per slot**.
119
+
120
+ ---
121
+
122
+ ## Ring buffer implementation β€” structure
123
+
124
+ The ring buffer is implemented in `miranda-ipc/src/lib.rs`. The design uses a **power-of-2 capacity** for each buffer so that the head/tail modulo operation can be replaced with a bitmask (`index & (capacity - 1)`), avoiding an integer division on the hot path.
125
+
126
+ ```rust
127
+ // Recommended capacity (power of 2, tunable later):
128
+ const AUDIO_RING_SLOTS: usize = 64; // ~640 ms of audio at 100 Hz writes
129
+ const BLENDSHAPE_RING_SLOTS: usize = 128; // ~2 s at 60 Hz writes
130
+ const SH_RING_SLOTS: usize = 128;
131
+
132
+ // The bus layout in /dev/shm/miranda_bus:
133
+ // [AtomicUsize head_audio][AtomicUsize tail_audio][AudioChunk Γ— 64]
134
+ // [AtomicUsize head_blend][AtomicUsize tail_blend][BlendshapeFrame Γ— 128]
135
+ // [AtomicUsize head_sh] [AtomicUsize tail_sh] [SphericalHarmonics Γ— 128]
136
+ // (all at fixed offsets within the mmap β€” do not use pointer arithmetic to
137
+ // find them; use explicit byte offsets computed from the sizes above)
138
+ ```
139
+
140
+ **Atomic ordering β€” the critical part:**
141
+
142
+ - Writer: `head` is read with `Ordering::Relaxed`, `tail` is written with `Ordering::Release` after the slot is written. This ensures that any reader doing an `Acquire` load of `tail` sees the fully-written slot.
143
+ - Reader: `tail` is loaded with `Ordering::Acquire`, `head` is written with `Ordering::Release` after consuming the slot.
144
+ - Do not use `Ordering::SeqCst` β€” it adds an unnecessary full memory fence on x86 and is a performance regression on ARM. `AcqRel`/`Acquire`/`Release` is the correct pattern for a SPSC ring buffer.
145
+
146
+ **The `AtomicUsize` in shared memory β€” the unsafe invariant:**
147
+
148
+ `AtomicUsize` cannot be trivially placed in an mmap region because the mmap returns a `*mut u8` and `AtomicUsize` requires proper alignment and initialization. The correct approach:
149
+ 1. Cast the mmap pointer to a `*mut AtomicUsize` at the known offset.
150
+ 2. Use `AtomicUsize::from_mut` or raw pointer operations with `// SAFETY:` comments explaining that: (a) the alignment is correct (usize-aligned offset), (b) the memory is valid for the lifetime of the mmap, and (c) the initial value was written as `0u8.repeat(size_of::<usize>())` before the cast.
151
+
152
+ This is the CAT 5 task. Do not implement it on anything other than Opus 5.
153
+
154
+ ---
155
+
156
+ ## Cross-references β€” where to find the science behind the design decisions
157
+
158
+ - **ARKit 52 blend shapes**: `~/.kiro/skills/nobility-posh-framework/SKILL.md` β†’ section on WO-3, the Hermes Execution Prompt for the kinematics work order, and the blend shape channel list.
159
+ - **L2 spherical harmonics**: `~/.kiro/skills/live-avatar-expert/SKILL.md` β†’ rendering science section (GaussianAvatars + FLAME + TetGS) and the reference papers on real-time relighting.
160
+ - **Performance targets (≀50 ΞΌs)**: the Sequence Matrix in `~/.kiro/skills/nobility-posh-framework/SKILL.md` β€” the 50 ΞΌs target is for the IPC round-trip alone, as one segment in the full glass-to-glass latency budget.
161
+ - **Podman placement rule (WO-1 is bare-metal)**: `~/.kiro/skills/aws-pipeline-architect/SKILL.md` β†’ Podman hybrid placement section. WO-1's SHM bus cannot be inside a container.
162
+ - **`bytemuck` and `#[repr(C)]` correctness**: `~/.kiro/skills/llamacpp-huggingface-expert/SKILL.md` β†’ the FFI boundary section. The same C-ABI layout principles that make parakeet.cpp safe to call from Rust apply here.
163
+ - **The Instant Presence Standard**: `eve-ecc-docs/INSTANT-PRESENCE-STANDARD.md` in this repo β€” this is what every downstream Work Order is ultimately serving. WO-1's latency target (≀50 ΞΌs) is derived from the requirement that EVE must respond to audio input within 150 ms glass-to-glass, of which the IPC bus is one segment.
.kiro/specs/wo1-workspace-ipc-backbone/requirements.md CHANGED
@@ -1,18 +1,128 @@
1
  # WO-1: Cargo Workspace & Lock-Free IPC Backbone β€” Requirements
2
 
3
- **Role**: Principal Systems Engineer. **Depends on**: nothing (foundation). **Target**: <50ΞΌs tensor transfer.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  ## Requirements (EARS notation)
6
 
7
- 1. WHEN the workspace is built with `cargo build` THE SYSTEM SHALL compile all six crates (`miranda-core`, `miranda-ipc`, `miranda-audio`, `miranda-nodes`, `miranda-supervisor`, `miranda-transport`) with zero errors.
8
- 2. WHEN `miranda-ipc` initializes THE SYSTEM SHALL map a POSIX shared-memory region at `/dev/shm/miranda_bus` using `memmap2`.
9
- 3. WHEN two threads/processes write and read concurrently on the ring buffer THE SYSTEM SHALL use lock-free atomic head/tail pointers (no mutex) to coordinate access.
10
- 4. WHEN a raw audio chunk, a 52-channel ARKit blendshape frame, or a 9-coefficient spherical-harmonic vector is written to the bus THE SYSTEM SHALL use a fixed-size, `#[repr(C)]`-aligned struct matching C-ABI layout rules.
11
- 5. WHEN a payload is written and then read back from the ring buffer THE SYSTEM SHALL return byte-for-byte identical data (round-trip integrity).
12
- 6. IF the ring buffer is full WHEN a writer attempts to write THE SYSTEM SHALL either block with a bounded wait or return a clear backpressure signal β€” never silently drop or corrupt data.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
- ## Acceptance criteria
15
 
16
- - `cargo build` succeeds workspace-wide.
17
- - `cargo test` in `miranda-ipc` includes a real round-trip test: write a payload from one thread, read it from another, assert equality.
18
- - No `unsafe` block lacks a comment explaining the invariant it upholds (this is where memory-alignment bugs hide).
 
 
 
 
1
  # WO-1: Cargo Workspace & Lock-Free IPC Backbone β€” Requirements
2
 
3
+ **Role**: Principal Systems Engineer β€” you are building the foundation every other Work Order depends on.
4
+ **Depends on**: nothing β€” this is the root. Nothing can be built until WO-1 ships.
5
+ **Target**: ≀50 ΞΌs for a full tensor writeβ†’read round-trip on the shared-memory bus, measured on the local build machine (Celeron N4500 or equivalent x86-64).
6
+ **CAT-5 routing**: Run `node scripts/cat-router-check.mjs` from the repo root before touching any task. This Work Order contains **one CAT 5 task** (the ring buffer implementation) β€” you will need Claude Opus 5 for that one task. See `.kiro/steering/model-routing-protocol.md` for the full switching protocol.
7
+
8
+ ---
9
+
10
+ ## Read these first β€” mandatory pre-flight before any code
11
+
12
+ You are working inside a Kiro workspace that has been fully pre-loaded with architecture, science, and operating rules. **Do not skip this section.** Reading these now costs two minutes; skipping them costs a day of wrong assumptions.
13
+
14
+ ### 1. The project overview
15
+
16
+ Read `PROJECT_OVERVIEW.md` at the repo root right now. It explains:
17
+ - What Miranda-Engine *is* (a harness, not a pipeline β€” this distinction is load-bearing)
18
+ - The quad-test design (N parallel pipelines, N independent EVE renders, scored head-to-head)
19
+ - The full CAT-5 model routing table with all five providers
20
+ - What has already been built in this workspace (the 6-crate Rust skeleton, the prior client scaffold, the 5 Work Order specs)
21
+
22
+ ### 2. The master steering rules
23
+
24
+ Read `.kiro/steering/build-standards.md`. These are non-negotiable operating rules that apply to every task in this Work Order:
25
+ - No claimed progress without real command-output evidence
26
+ - Nothing marked done without a real `cargo build` / `cargo test` pass β€” no "should work," no described output
27
+ - No simulated inference β€” if something isn't wired up yet, say so plainly
28
+ - Reuse before rebuild β€” check what's already in the crate stubs before writing new code
29
+
30
+ ### 3. The CAT-5 model routing protocol
31
+
32
+ Read `.kiro/steering/model-routing-protocol.md` in full. The rules in it govern *which model handles which task* in this Work Order. You cannot skip the protocol on a CAT 5 task because the implementation "looks straightforward" β€” lock-free ring buffers are exactly the category where wrong-but-compiling code causes silent data corruption in production at 60 FPS.
33
+
34
+ ### 4. The global Kiro skills loaded into this workspace
35
+
36
+ These four skills are globally available (at `~/.kiro/skills/`). They contain the pre-built architecture knowledge you need. Reference them by name in your session:
37
+
38
+ - **`nobility-posh-framework`** β€” master reference for the NOBILITY POSH FRAMEWORK: EVE, THE VANITY dual-pane design, the Instant Presence Standard, the 25 Vanguard Innovations, the 5 Work Orders as Hermes Execution Prompts, the Sequence Matrix performance targets. **Read this to understand what you're building toward.**
39
+ - **`live-avatar-expert`** β€” the 5-stage universal live-avatar pattern (ingress / understanding / expression / rendering / transport), research papers, rendering science chain (GaussianAvatars + FLAME + TetGS). The IPC backbone you're building in WO-1 is the substrate that the ingress and expression stages (WO-2 and WO-3) will write into.
40
+ - **`aws-pipeline-architect`** β€” AWS deployment, Podman container strategy, CPU/GPU instance tiering, CloudWatch kill-switch discipline. WO-1's IPC bus is **bare-metal only** β€” it uses POSIX shared memory at `/dev/shm/miranda_bus` and cannot run inside a container because the SHM region must be visible to multiple processes on the same host. This rule is documented in the skill.
41
+ - **`llamacpp-huggingface-expert`** β€” GGUF quantization, llama-server endpoint details, ISA mismatch diagnosis (exit 132 = missing AVX2 on Celeron N4500 = build from source with `-march=native`). This matters most in WO-2, but file it now so you know it exists.
42
+
43
+ ### 5. What EVE is and what THE VANITY is
44
+
45
+ **EVE** is the 2D control reference: a single uncropped image at native resolution, permanent on the right pane of THE VANITY (Miranda's dual-pane GUI). She is the ground truth that every pipeline variant gets scored against. She does not move, does not loop, and is never replaced with a video or an AI render during development β€” she is the target.
46
+
47
+ **THE VANITY** is the name of Miranda's dual-pane interface:
48
+ - **Left pane**: the live node graph / harness β€” the React Flow topology from the `eve-ecc` repo scaffold (the "Cerebral Project" UI you can see with L0/L1/L2 tabs, node latency readouts, warm-path status, circuit breaker indicators).
49
+ - **Right pane**: EVE's image, static, uncropped, native resolution, always visible.
50
+
51
+ The model names you see in the node graph topology (Riva ASR, Nemotron Agent, Hive TTS, Audio2Face-3D, Omniverse) are **architectural role labels** β€” they describe the *class of work* that happens at each position in the pipeline. They are not literal product deployments. Miranda is the lab where we engineer our own science to fill those roles. WO-1's IPC bus is the plumbing that connects all of those roles to each other.
52
+
53
+ ### 6. The existing repo structure β€” what has already been built
54
+
55
+ The Rust workspace skeleton already exists and builds clean. Before writing any new code, verify this yourself with `cargo build` from the repo root. The crates that exist:
56
+
57
+ ```
58
+ miranda-engine/
59
+ β”œβ”€β”€ Cargo.toml ← workspace root, resolver="2", 6 members
60
+ β”œβ”€β”€ miranda-core/src/lib.rs ← shared constants + error types (stub)
61
+ β”œβ”€β”€ miranda-ipc/src/lib.rs ← ring buffer home (stub β€” your main target)
62
+ β”œβ”€β”€ miranda-audio/src/lib.rs ← audio capture + VAD plumbing (stub, WO-2)
63
+ β”œβ”€β”€ miranda-nodes/src/lib.rs ← node trait + executor (stub, WO-3)
64
+ β”œβ”€β”€ miranda-supervisor/src/lib.rs ← session lifecycle + quad-test runner (stub)
65
+ β”œβ”€β”€ miranda-transport/src/lib.rs ← WebRTC + telemetry (stub, WO-4)
66
+ β”œβ”€β”€ scripts/cat-router-check.mjs ← CAT-5 backlog scanner β€” run this first
67
+ β”œβ”€β”€ PROJECT_OVERVIEW.md ← start here every session
68
+ β”œβ”€β”€ MASTER_PROMPT.md ← paste into Kiro chat to start a new session
69
+ └── .kiro/
70
+ β”œβ”€β”€ steering/build-standards.md
71
+ β”œβ”€β”€ steering/model-routing-protocol.md
72
+ └── specs/wo1-workspace-ipc-backbone/ ← you are here
73
+ β”œβ”€β”€ requirements.md (this file)
74
+ β”œβ”€β”€ design.md
75
+ └── tasks.md
76
+ ```
77
+
78
+ The prior-attempt client scaffold is also in the repo under `client-apps/web/` β€” React Flow + Vite + TypeScript, already showing a working topology UI. **Do not rebuild it; do not delete it.** WO-5 will wire it to the Rust harness once WO-1 through WO-4 are done.
79
+
80
+ ---
81
 
82
  ## Requirements (EARS notation)
83
 
84
+ EARS = Easy Approach to Requirements Syntax. Every requirement below is either WHEN/SHALL (event-driven) or IF/WHEN/SHALL (conditional). Acceptance criteria at the bottom define what "done" looks like.
85
+
86
+ **REQ-1** β€” WHEN the workspace is built with `cargo build` from the repo root
87
+ THE SYSTEM SHALL compile all six crates (`miranda-core`, `miranda-ipc`, `miranda-audio`, `miranda-nodes`, `miranda-supervisor`, `miranda-transport`) with zero errors and zero warnings treated as errors.
88
+
89
+ > *Baseline: this already passes on the initial commit. Re-verify before starting any other task β€” if it doesn't pass, stop and diagnose before writing new code.*
90
+
91
+ **REQ-2** β€” WHEN `miranda-ipc` initializes
92
+ THE SYSTEM SHALL create or open a POSIX shared-memory region at `/dev/shm/miranda_bus` using the `memmap2` crate, mapping it into the process address space as a mutable byte slice.
93
+
94
+ > *Why /dev/shm: it's a tmpfs mount (RAM-backed), which is what makes the ≀50 ΞΌs target achievable. A regular file on disk cannot meet this target. The path `/dev/shm/miranda_bus` is fixed β€” do not make it configurable at this stage.*
95
+
96
+ **REQ-3** β€” WHEN two threads or processes write and read concurrently on the same ring buffer
97
+ THE SYSTEM SHALL coordinate access using lock-free atomic head and tail pointers β€” specifically `AtomicUsize` with `Ordering::AcqRel` on writes and `Ordering::Acquire` on reads β€” with no mutex, no `RwLock`, and no spinloop that busy-waits indefinitely.
98
+
99
+ > *Why lock-free: the ring buffer is on the critical path of the 60 FPS render loop. A mutex held by a stalled audio thread would cause the renderer to miss its frame deadline. This is not a preference β€” it is a latency constraint.*
100
+
101
+ **REQ-4** β€” WHEN a raw audio chunk, a 52-channel ARKit blendshape frame, or a 9-coefficient spherical-harmonic lighting vector is written to the bus
102
+ THE SYSTEM SHALL use a fixed-size `#[repr(C)]` struct with explicit field alignment matching the C ABI, so the memory layout is identical whether read from Rust, from the future C FFI bindings in WO-2 (parakeet.cpp), or from any other language that may sit on this bus.
103
+
104
+ > *The 52 blendshape channels are the ARKit 52 standard face blend shapes. The 9 SH coefficients are the L2 spherical harmonic lighting representation. These numbers are fixed by the pipeline science β€” do not parameterize them as generic constants that can be changed at runtime.*
105
+
106
+ **REQ-5** β€” WHEN a payload is written to the ring buffer and then read back
107
+ THE SYSTEM SHALL return byte-for-byte identical data (round-trip integrity), verified by a real concurrent test that exercises actual memory-ordering β€” not a single-threaded sequential test that cannot catch race conditions.
108
+
109
+ **REQ-6** β€” IF the ring buffer is full WHEN a writer attempts to push a new payload
110
+ THE SYSTEM SHALL either block with a bounded wait (≀1 ms timeout) or return a typed `BackpressureError` β€” never silently drop the payload and never corrupt the existing contents of the buffer.
111
+
112
+ **REQ-7** β€” WHEN any `unsafe` block appears in `miranda-ipc` or `miranda-core`
113
+ THE SYSTEM SHALL have a `// SAFETY:` comment directly above or inside it explaining in one or two sentences exactly why the unsafe operation is sound β€” specifically: what invariant the caller upholds, and what would happen if the invariant were violated.
114
+
115
+ > *This is not a style preference. The lock-free ring buffer is the single most failure-prone component in the entire project. The safety comment is how a future reader (including you at 2am during a regression) understands why a pointer cast or atomic fence is correct.*
116
+
117
+ ---
118
+
119
+ ## Acceptance criteria β€” what "WO-1 done" looks like
120
 
121
+ WO-1 is complete when **all six** of the following are true, each verified with real command output:
122
 
123
+ 1. `cargo build` from repo root exits 0 with zero warnings on all six crates.
124
+ 2. `cargo test -p miranda-ipc` exits 0 and the output shows a real concurrency test passing β€” with thread names or timestamps in the output proving both threads actually ran, not a degenerate single-threaded execution path.
125
+ 3. The test includes a write from one thread and a read from another, with the read value asserted equal to the written value using `assert_eq!` β€” not just "no panic."
126
+ 4. Every `unsafe` block in `miranda-ipc` and `miranda-core` has a `// SAFETY:` comment.
127
+ 5. The test runs under `cargo test` without `--test-threads=1` β€” it must be safe to run in the default parallel test harness.
128
+ 6. The commit message includes the real output of `cargo test -p miranda-ipc` pasted verbatim β€” not a description of the output.
.kiro/specs/wo1-workspace-ipc-backbone/tasks.md CHANGED
@@ -1,11 +1,277 @@
1
  # WO-1: Tasks
2
 
3
- Per the `model-routing-protocol.md` steering rule: check the `[CAT n]` tag before starting each task. CAT 5 requires Opus 5 β€” stop and request a model switch rather than attempting it on a lower tier.
4
-
5
- - [ ] [CAT 1] Confirm workspace skeleton builds clean (`cargo build` from repo root) β€” already true as of the initial commit; re-verify before starting.
6
- - [ ] [CAT 1] Add `memmap2`, `crossbeam` (or plain `std::sync::atomic`), and `bytemuck` (for safe `#[repr(C)]` casting) to `miranda-ipc/Cargo.toml`.
7
- - [ ] [CAT 3] Define `AudioChunk`, `BlendshapeFrame` (52 f32 weights + timestamp), `SphericalHarmonics` (9 f32 coefficients + timestamp) as `#[repr(C)]` structs in `miranda-core`.
8
- - [ ] [CAT 5] Implement the ring buffer struct in `miranda-ipc` (open-or-create the `/dev/shm/miranda_bus` mapping, atomic head/tail, push/pop methods per data type). **Opus 5 only** β€” lock-free concurrency correctness, silent-corruption risk if wrong.
9
- - [ ] [CAT 4] Write a `#[cfg(test)]` round-trip test: spawn a writer thread and a reader thread, assert every written payload is read back byte-identical, in order. Escalate to Opus 5 if two attempts fail to actually exercise the race condition (a test that only ever passes isn't proof of anything).
10
- - [ ] [CAT 2] Document the safety invariant on every `unsafe` block (why the cast/pointer arithmetic is sound).
11
- - [ ] [CAT 1] Run `cargo test` and paste the real output into the PR/commit β€” no "should work."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # WO-1: Tasks
2
 
3
+ ## Before you start β€” mandatory
4
+
5
+ 1. **Read `requirements.md` and `design.md` in this directory first.** They contain the full context, the pre-flight skill references, and the struct designs you will implement. Do not skip them.
6
+
7
+ 2. **Run the CAT-5 scanner now:**
8
+ ```
9
+ node scripts/cat-router-check.mjs
10
+ ```
11
+ from the repo root. Confirm this Work Order's tasks appear in the output. Paste the output as a reply before beginning.
12
+
13
+ 3. **Check your current model against the first task's CAT tag.** This Work Order starts on CAT 1 (Qwen3 Coder Next). If you are running on a different model, switch before proceeding. See `.kiro/steering/model-routing-protocol.md` for the exact switch notice wording.
14
+
15
+ 4. **Every task below requires real command output as evidence.** A description of what the output "should" say is not evidence. Paste the actual terminal output.
16
+
17
+ ---
18
+
19
+ ## The CAT-5 routing summary for this Work Order
20
+
21
+ | Tasks | CAT tier | Model |
22
+ |---|---|---|
23
+ | T1, T2, T7 | CAT 1 | Qwen3 Coder Next |
24
+ | T6 | CAT 2 | GLM-5 |
25
+ | T3 | CAT 3 | DeepSeek 3.2 |
26
+ | T5 | CAT 4 | Claude Sonnet 5 (escalate to Opus 5 after 2 real failed verifications) |
27
+ | T4 | **CAT 5** | **Claude Opus 5 β€” mandatory, no exceptions** |
28
+
29
+ ---
30
+
31
+ ## Tasks
32
+
33
+ - [ ] [CAT 1] **T1 β€” Verify the workspace builds clean**
34
+
35
+ From the repo root, run:
36
+ ```
37
+ cargo build
38
+ ```
39
+ This must exit 0 with zero errors. If it does not, stop and diagnose before doing anything else β€” the scaffold was clean on the initial commit; something in your environment is different.
40
+
41
+ Paste the real output. Mark this task done with the build output pasted verbatim.
42
+
43
+ *If you get a "linker not found" or "error[E0]: can't find crate" error: check that the Rust toolchain is installed (`rustup show`) and that all six crate directories exist under the repo root (`ls -d miranda-*/`).*
44
+
45
+ ---
46
+
47
+ - [ ] [CAT 1] **T2 β€” Add dependencies to `miranda-ipc/Cargo.toml`**
48
+
49
+ Open `miranda-ipc/Cargo.toml`. Add the following to the `[dependencies]` table:
50
+ ```toml
51
+ miranda-core = { path = "../miranda-core" }
52
+ memmap2 = "0.9"
53
+ bytemuck = { version = "1", features = ["derive"] }
54
+ ```
55
+
56
+ Notes:
57
+ - `memmap2` is the maintained fork of the original `memmap` crate. It provides `MmapMut` for the shared-memory region. Do not use the original `memmap` crate β€” it is unmaintained.
58
+ - `bytemuck` with the `derive` feature enables `#[derive(Pod, Zeroable)]` on the payload structs. These derives are compile-time proofs that a struct has no padding, no uninit bytes, and can be safely cast to/from `&[u8]`.
59
+ - You do not need `crossbeam` or any external atomic crate β€” `std::sync::atomic::AtomicUsize` with explicit orderings is sufficient for this ring buffer.
60
+
61
+ After editing the file, run `cargo build` again to confirm the new deps resolve and compile:
62
+ ```
63
+ cargo build
64
+ ```
65
+ Paste the output. If `memmap2` or `bytemuck` fail to download (offline or registry issue), diagnose β€” do not skip.
66
+
67
+ ---
68
+
69
+ - [ ] [CAT 3] **T3 β€” Define the three payload structs in `miranda-core`**
70
+
71
+ Open `miranda-core/src/lib.rs`. Add the following, exactly as specified in `design.md`. Do not invent different field names or sizes β€” these are fixed by the pipeline science.
72
+
73
+ **Constants (add at the top of the file):**
74
+ ```rust
75
+ pub const AUDIO_SAMPLE_RATE_HZ: u32 = 16_000;
76
+ pub const AUDIO_CHUNK_FRAMES: usize = 160; // 10 ms at 16 kHz
77
+ pub const BLENDSHAPE_COUNT: usize = 52; // ARKit 52 standard blend shapes
78
+ pub const SH_COEFF_COUNT: usize = 9; // L2 spherical harmonic coefficients
79
+ ```
80
+
81
+ **Why these specific numbers:**
82
+ - `AUDIO_CHUNK_FRAMES = 160`: 10 ms of audio at 16 kHz. This is the standard VAD/ASR chunk size for streaming speech recognition (Parakeet, Whisper, all use 10 ms frames).
83
+ - `BLENDSHAPE_COUNT = 52`: the ARKit face blendshape standard (Eyes, brows, mouth, jaw, cheek β€” full facial animation rig). WO-3 will implement the SIMD kinematic solver that produces these 52 values.
84
+ - `SH_COEFF_COUNT = 9`: L2 spherical harmonics β€” 9 coefficients per color channel encoding low-frequency ambient light. Used by the WebGPU Gaussian-splat renderer (WO-5) to relight EVE dynamically.
85
+
86
+ **Structs (add after the constants):**
87
+ ```rust
88
+ #[repr(C)]
89
+ #[derive(Debug, Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
90
+ pub struct AudioChunk {
91
+ pub timestamp_us: u64,
92
+ pub sample_rate: u32,
93
+ pub frame_count: u32,
94
+ pub samples: [f32; AUDIO_CHUNK_FRAMES],
95
+ }
96
+
97
+ #[repr(C)]
98
+ #[derive(Debug, Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
99
+ pub struct BlendshapeFrame {
100
+ pub timestamp_us: u64,
101
+ pub weights: [f32; BLENDSHAPE_COUNT],
102
+ }
103
+
104
+ #[repr(C)]
105
+ #[derive(Debug, Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
106
+ pub struct SphericalHarmonics {
107
+ pub timestamp_us: u64,
108
+ pub coefficients: [f32; SH_COEFF_COUNT],
109
+ }
110
+ ```
111
+
112
+ After adding, run:
113
+ ```
114
+ cargo build -p miranda-core
115
+ ```
116
+ The `bytemuck::Pod` and `bytemuck::Zeroable` derives will fail to compile if the struct has any padding, non-Copy fields, or uninit bytes β€” that is the compile-time safety proof working as intended. If you get a compile error from the derives, it means the struct layout is not C-ABI safe and you must fix it before proceeding.
117
+
118
+ Paste the real build output.
119
+
120
+ *Size check (informational β€” cargo does not assert this automatically):*
121
+ - `AudioChunk`: 8 + 4 + 4 + (160 Γ— 4) = 656 bytes
122
+ - `BlendshapeFrame`: 8 + (52 Γ— 4) = 216 bytes
123
+ - `SphericalHarmonics`: 8 + (9 Γ— 4) = 44 bytes
124
+
125
+ You can verify with `std::mem::size_of::<AudioChunk>()` in a test if you want compile-time confirmation.
126
+
127
+ ---
128
+
129
+ - [ ] [CAT 5] **T4 β€” Implement the ring buffer in `miranda-ipc` β€” Claude Opus 5 ONLY**
130
+
131
+ ⚠️ **MANDATORY MODEL SWITCH BEFORE THIS TASK**
132
+
133
+ If you are not currently running as Claude Opus 5, STOP. Do not attempt this task on any other model. Emit the following and wait for the model to be switched:
134
+
135
+ ```
136
+ CAT 5 MODEL SWITCH REQUIRED β€” T4 (ring buffer implementation) requires Claude Opus 5.
137
+ Switch the chat model dropdown to Claude Opus 5, then re-issue this task alone.
138
+ ```
139
+
140
+ **Handoff block to paste into the Opus 5 session:**
141
+ ```
142
+ === CAT 5 HANDOFF β€” switching to Claude Opus 5 ===
143
+ Task: T4 β€” Implement the lock-free ring buffer in miranda-ipc
144
+ Status: Ready to implement β€” all prerequisites complete (T1 build verified, T2 deps added, T3 structs defined)
145
+ State: miranda-core now exports AudioChunk (656B), BlendshapeFrame (216B), SphericalHarmonics (44B) β€” all #[repr(C)] with bytemuck::Pod. miranda-ipc has memmap2 and bytemuck as deps.
146
+ Incoming needs to know:
147
+ - Three separate ring buffers (not one polymorphic), one per struct type
148
+ - POSIX shared memory at /dev/shm/miranda_bus (tmpfs, RAM-backed β€” required for ≀50 ΞΌs target)
149
+ - AtomicUsize head/tail, AcqRel/Acquire/Release ordering β€” NO mutex, NO SeqCst
150
+ - Power-of-2 slot counts: audio=64, blendshape=128, sh=128
151
+ - AtomicUsize cannot be trivially placed in mmap β€” requires raw pointer cast with SAFETY comment
152
+ - Every unsafe block requires a // SAFETY: comment explaining the invariant
153
+ - bytemuck::bytes_of and bytemuck::from_bytes are the safe cast path for writing/reading slots
154
+ === END HANDOFF ===
155
+ ```
156
+
157
+ **What Opus 5 must implement in `miranda-ipc/src/lib.rs`:**
158
+
159
+ 1. A `MirandaBus` struct that opens or creates `/dev/shm/miranda_bus` using `memmap2::MmapMut`, with the three ring buffers laid out at fixed byte offsets within the mapping.
160
+
161
+ 2. Push methods for each payload type: `push_audio`, `push_blendshape`, `push_sh` β€” each returning `Result<(), BackpressureError>`.
162
+
163
+ 3. Pop methods for each payload type: `pop_audio`, `pop_blendshape`, `pop_sh` β€” each returning `Option<T>` where T is the payload type.
164
+
165
+ 4. The `AtomicUsize` head and tail for each buffer must be placed at the *start* of the mmap at known, alignment-safe byte offsets. The slot data follows.
166
+
167
+ 5. Every `unsafe` block β€” pointer cast, raw memory read/write β€” must have a `// SAFETY:` comment.
168
+
169
+ 6. The implementation must use `bytemuck::bytes_of()` to write a struct as bytes into a slot, and `bytemuck::from_bytes()` to read it back β€” this is the safe, proven path for `#[repr(C)] + Pod` types.
170
+
171
+ **What Opus 5 must NOT do:**
172
+ - Do not use a `Mutex` or `RwLock` anywhere in the hot path
173
+ - Do not use `Ordering::SeqCst`
174
+ - Do not use `unsafe` transmute without a `SAFETY` comment
175
+ - Do not hardcode the struct sizes as magic numbers β€” use `std::mem::size_of::<T>()`
176
+ - Do not make the capacity non-power-of-2
177
+
178
+ After implementation, run:
179
+ ```
180
+ cargo build -p miranda-ipc
181
+ ```
182
+ Paste the real output. If it does not compile cleanly, fix it β€” do not proceed to T5 until T4 builds.
183
+
184
+ ---
185
+
186
+ - [ ] [CAT 4] **T5 β€” Write the concurrent round-trip test β€” Claude Sonnet 5**
187
+
188
+ ⚠️ **Model check:** This task requires Claude Sonnet 5. If you are currently on Opus 5 (from T4), you may switch back to Sonnet 5 for this task, or remain on Opus 5 if you prefer β€” Opus 5 is an acceptable superset for CAT 4 work. If you are on a lower tier, switch to Sonnet 5 first.
189
+
190
+ Write a `#[cfg(test)]` module in `miranda-ipc/src/lib.rs` with a test named `test_blendshape_round_trip_concurrent`. This test must:
191
+
192
+ 1. Open a `MirandaBus` instance (or two, one for write and one for read, if the bus supports multiple openers).
193
+
194
+ 2. Spawn a writer thread that pushes 1,000 `BlendshapeFrame` payloads with distinct, incrementing `timestamp_us` values (0, 1, 2, ... 999) and weights filled with the frame index cast to f32.
195
+
196
+ 3. Spawn a reader thread that pops 1,000 `BlendshapeFrame` payloads and asserts each one is byte-identical to the corresponding payload the writer pushed β€” same `timestamp_us`, same `weights`.
197
+
198
+ 4. Both threads run **concurrently** β€” do not use `thread::sleep` to serialize them, and do not use a channel to artificially sequence them. The test must exercise actual concurrent read-write access.
199
+
200
+ 5. The test must print (using `println!` or `eprintln!`) a message that identifies which thread wrote and which read, with timestamps β€” this is the evidence that proves both threads actually ran concurrently, not sequentially.
201
+
202
+ 6. The test must pass under `cargo test` without `--test-threads=1`.
203
+
204
+ **Escalation rule:** If this test fails real concurrent verification twice (a real race condition, a data corruption assertion, a deadlock), emit:
205
+ ```
206
+ CAT 5 ESCALATION β€” T5 has failed real concurrent verification twice. Switch to Claude Opus 5 before the third attempt.
207
+ ```
208
+
209
+ Run:
210
+ ```
211
+ cargo test -p miranda-ipc -- --nocapture
212
+ ```
213
+ Paste the complete output, including any `println!`/`eprintln!` output from the test threads.
214
+
215
+ ---
216
+
217
+ - [ ] [CAT 2] **T6 β€” Document every `unsafe` block β€” GLM-5**
218
+
219
+ ⚠️ **Model check:** Switch to GLM-5 for this task.
220
+
221
+ Open `miranda-ipc/src/lib.rs` and scan for every `unsafe` block or `unsafe` expression. For each one, add or verify a `// SAFETY:` comment directly above or inside the block explaining:
222
+ - What the unsafe operation is (e.g., "casting *mut u8 at offset N to *mut AtomicUsize")
223
+ - What invariant the caller upholds that makes this sound (e.g., "offset N is 8-byte aligned because it was computed as size_of::<AtomicUsize>() * n from the mmap base, and memmap2 guarantees page alignment")
224
+ - What would happen if the invariant were violated (e.g., "undefined behavior: misaligned atomic operations on x86 can tear")
225
+
226
+ Every `unsafe` block without a `// SAFETY:` comment is a defect in WO-1 β€” the ring buffer is the single most failure-prone component, and these comments are the written record of why it is correct.
227
+
228
+ No build output required for this task (it's a documentation addition), but run:
229
+ ```
230
+ cargo build -p miranda-ipc
231
+ ```
232
+ to confirm no accidental syntax errors were introduced. Paste the output.
233
+
234
+ ---
235
+
236
+ - [ ] [CAT 1] **T7 β€” Final verification pass and commit β€” Qwen3 Coder Next**
237
+
238
+ ⚠️ **Model check:** Switch back to Qwen3 Coder Next for this task.
239
+
240
+ Run the full test suite from the repo root:
241
+ ```
242
+ cargo test
243
+ ```
244
+ and then:
245
+ ```
246
+ cargo test -p miranda-ipc -- --nocapture
247
+ ```
248
+
249
+ The first command verifies that adding WO-1's code has not broken any other crate. The second command shows the full concurrent test output with thread-level detail.
250
+
251
+ Both must exit 0. Paste both outputs verbatim.
252
+
253
+ Then run the CAT-5 scanner to update the pending backlog:
254
+ ```
255
+ node scripts/cat-router-check.mjs
256
+ ```
257
+ All seven WO-1 tasks should now show as done (no unchecked boxes for this Work Order). Paste the scanner output.
258
+
259
+ Commit everything with a message that includes the `cargo test` output:
260
+ ```
261
+ git add -A
262
+ git commit -m "WO-1 complete: lock-free IPC backbone, 3 ring buffers, concurrent round-trip test"
263
+ ```
264
+
265
+ WO-1 is done. The foundation is live. WO-2 (VAD/ASR routing) can begin.
266
+
267
+ ---
268
+
269
+ ## When WO-1 is done β€” what changes
270
+
271
+ Once all seven tasks above are checked off with real evidence:
272
+
273
+ - **WO-2** can begin: `miranda-audio` can now write `AudioChunk`s to the bus for VAD and parakeet.cpp ASR processing.
274
+ - **WO-3** can begin: `miranda-nodes` can now write `BlendshapeFrame`s and `SphericalHarmonics` to the bus from the SIMD kinematics solver.
275
+ - **WO-4** (transport) and **WO-5** (renderer) both depend on WO-2 and WO-3 being further along β€” they can begin design work but not integration work until WO-2 and WO-3 are writing real data to the bus.
276
+
277
+ The MASTER_PROMPT.md at the repo root is the paste-ready prompt for starting WO-2's Kiro session. It includes the updated CAT table with all five models and references both steering docs automatically.