diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 28a1a31bad..d09504fc97 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -1692,6 +1692,1242 @@ simulator and production agree, section 7.0); 0 turns refused or starved; 0 swap warm; on BigMama, every asked turn served. Each piece lands with its simulator scenario red then green, then a live read against a restart-only control. +### 4.11 The engine's contract: one typed definition, one owner on each side (2026-11-16, design for review) + +Joel, 2026-11-16: "The problem is decentralized management and poor api schema." "You design like a random +clusterfuck whereas I always go for structs and api. You want to be strict, use uuidv7, not some bastardized +string form, the actual form, rich structs and APIs, centralized management and servicemodules etc." + +#### 4.11.1 What went wrong (receipts, 2026-11-16) + +Resident minds (fork #139, core #6087) were built one endpoint at a time, JSON over HTTP, beside the binary port +section 4.1 already designs (`port`: "binary frames, no HTTP or JSON"): +- **No definition:** the fork reads 74 request fields by name (`json_value(body, "page", ...)`); the core reads 52 + engine reply fields by name (`.get("x")`, `pointer("/...")`). Every review round with Codex was one side guessing + the other's field: a pid, then an incarnation; a pin's position, then its id; `success` plus free text, then + frozen enums. +- **Ids in costume:** a mind as 32 hex digits, the engine's incarnation as a random `u64`, a learn pin as a counter. +- **No owner:** 13 sites in 5 files each decided part of a mind's checkpoints; the close-checkpoint eviction erased + learn pins, and the host budget and the count evicted in two different orders. (Fixed by `checkpoint_store`, + fork #140; the pattern below applies it to the whole seam.) + +#### 4.11.2 Ids: UUIDv7, native 16 bytes, one newtype per kind; identity is exact equality + +| Id | Minted by | Form | Replaces | +|---|---|---|---| +| `EngineInstanceId` | the engine, once at start | UUIDv7 | random `u64` token | +| `TurnId` | the core, once per act; a retry keeps it | UUIDv7 | nothing (a turn had no identity) | +| `MindId` | the core: her persona's id; a fork's is UUIDv5 of (persona, room) (`PageKey::engine_id`) | UUID | 32-hex-digit string | + +- **Identity is exact equality, never ordering** (Codex on #6092: clock rollback, different clocks and two ids in + the same millisecond make greater-than meaningless). A frame for another `EngineInstanceId` is refused, typed; + v7's time order is only for reading logs. +- **Process evidence stays separate.** `engine_residency::EngineIncarnation` (pid, OS start time, port) remains the + proof a process died after a core restart; a UUID cannot prove death or release held work. The descriptor + carries both; the lifecycle owner's generation and custody checks are unchanged. +- **A learn pin is its turn:** `release(TurnId)`, `learn(TurnId)`. A `TurnId` is never reused, so a release can + never free another live turn's pin. +- On every wire and in every struct an id is its 16 bytes (`uint8_t[16]` in C, `Uuid` in Rust). Never hex, never a + string, never parsed. Rust: `Uuid::now_v7()` (workspace `uuid` gains `v7`). C++: one minting function in the + contract header (48-bit Unix milliseconds + 74 random bits, RFC 9562). + +#### 4.11.3 One definition, validated at both edges + +- **The definition is one C header in the fork, `tools/server/server-continuum.h`** (section 4.1 already names it + as the C ABI shim): fixed-size, trivially copyable frames of fixed-width fields and 16-byte ids. +- **The Rust side is generated from it by bindgen** (as `core/llama/build.rs` binds `llama.h`) and wrapped once in + safe newtypes. Bindgen lays out structs; it does not validate frames, so both edges validate: + - **Byte order** little-endian, stated; **every field's offset and size** asserted (`static_assert(offsetof)` in + C++, generated `const` assertions in Rust); **reserved bytes** must be zero. + - **Every frame begins with a header:** magic, schema version, frame kind, total size, and the schema's + identity (a hash of the header file, compiled into both sides). A mismatch at attach refuses the link. + - **Tags are raw integers on the wire**, converted with `TryFrom`; an unknown value is a typed refusal, never a + cast into a Rust enum and never a default. +- **Variable data is never in a frame.** A prompt's bytes, KV pages and checkpoints move as `buffer_ref` + (section 4.11.4). +- **The frames** (every stateful request carries the exact `EngineInstanceId`; its replies are terminal frames + per 4.11.4): + +| Request | Reply | Replaces today's | +|---|---|---| +| `attach { schema identity }` | `engine_descriptor { instance, process evidence, pool tokens, per-sequence tokens, lanes, parked ids, host budget }` | `/props` JSON + `resident_minds` | +| `act_submit { act (TurnId), mind, layers, mode, learn_pin, prompt: buffer_ref, view spans, sampling }` (modes in 4.11.6) | token frames, then `act_done { act, mind_from, switch_us, generation, cached_tokens, pinned, (layer, step)[] }` / `cancelled` / `refused` | `/completion` + `timings.mind` | +| `cancel { turn }` | the turn's terminal frame | dropping an HTTP connection | +| `prefetch { mind }` | `placed { mind, place: mind_place }` | `/minds/prefetch` | +| `pin_release { turn }` | `released { turn, outcome: pin_release }` | `/learn/release` | +| `page_save` / `page_restore { mind, buffer_ref }` | typed terminal frame | `/slots/:id?action=` | + + The enums (`mind_from`, `mind_place`, `learned_on`, `learn_refusal`, `pin_release`) are the values frozen on + fork #139 (2026-11-16), defined once in the header. +- **Transport:** frame rings over shared memory between the core and the engine process, and the same frames in + process once serving hosts libllama directly (line 3b of the plan in CLAUDE.md). The ring's shared layout is its + own explicit contract: a page-aligned header of plain 64-bit words (head, tail, capacity, closed) with stated + acquire/release ordering and an address-based wait (futex / `__ulock`), implemented natively on each side and + proven by a cross-language fixture. A C++ `frame_ring` object is not assumed portable to Rust. HTTP JSON stays + only as the OpenAI-compatible adapter for foreign drivers (Hermes). + +#### 4.11.4 Custody, cancellation and idempotence + +A `buffer_ref` is `{ instance, pool, buffer, allocation generation, offset, length }`. The receiver checks the +instance, the generation (a buffer freed and reallocated has a new one) and `offset + length` within the +allocation without overflow. The sender owns the buffer until the receiver's terminal frame for that request; no +buffer is freed while a frame names it. + +| Case | Behavior | +|---|---| +| attach (bootstrap) | the first frame names no instance: `attach { schema identity }` -> `engine_descriptor { instance, process evidence, geometry, host budget }`; every stateful verb after it carries the exact instance | +| queue full | the push returns false: the caller gets a typed `backpressure` at once; nothing is dropped or silently retried | +| turn stream | tokens stream as frames naming the `TurnId`; exactly one terminal frame (`done`, `cancelled`, `refused { reason }`); its buffers are released only after it | +| duplicate `act_submit` (same `TurnId`) | idempotent: the existing ticket is answered, the act never runs twice | +| retry after a lost terminal frame | resubmits the same `TurnId`; the engine answers the recorded outcome | +| cancel | `cancel { turn }` is acknowledged with the turn's terminal frame; cancelling a finished turn answers its outcome; a cancel never frees another turn's resources | +| lost cancel acknowledgement | the caller re-sends the same cancel (idempotent) | +| peer death | detected by process evidence (`EngineIncarnation`), never by a missing frame alone; held work is released only once death is proven; the next attach yields a new instance | +| stale descriptor after replacement | every stateful verb with the old instance is refused `stale_engine`; the link re-attaches | +| `pin_release { turn }` | idempotent: the first frees it (`released` / `released_on_flash`), a repeat answers `not_pinned`; an unknown turn answers `not_pinned`, never a release of another | +| prefetch | idempotent per mind; owned by the waiting turn (dropped with it) | + +#### 4.11.5 One owner on each side, consolidating what exists + +- **Engine:** the frame dispatcher runs on the server loop that already owns the llama context; owners that touch + the same context share that thread (no thread per concern). Each owner is the only code that changes its state: + the resident-minds table, each mind's `checkpoint_store` (#140), learning. The dispatcher validates a frame's + header and tags and routes the struct to its owner. +- **Core: `EngineLink` is a ServiceModule that consolidates today's owners; it adds no registry.** What moves under + it, unchanged in role: endpoint admission and permits (`slots::directory()`, `EndpointAdmission`), turn + admission and unresolved completions (`turn_admission::admit_turn`, `turn_admission/unresolved_page`), + cancellation, buffer custody, the engine's descriptor (published with the slot pool), and process evidence + (`engine_residency`). Callers ask it typed verbs (`link.turn(...)`, `link.prefetch(mind)`, + `link.release(turn)`); `stream.rs`, `minds.rs`, `slots/discover.rs` and the learn lane stop building requests. + A source-hygiene ratchet fails any engine path or field name outside it. + +#### 4.11.6 Her genome is her LoRA layers: trained in place, on the one path + +Joel, 2026-11-16: "Make sure it accommodates learning." Then: "I and Lora layers genome. Training is remember in +place. Lora layer(s) becomes trained with inference still capable. Not some separate path. Of course it's fast to +switch on and off too. Like everything." And: "It's not a separate version of the persona. Same base model not a +sep one." + +Joel, then: "Learn is like a continuous or at least on/off marginally more memory just for the extra backprop and +the layers learning. Genome is supposed to be on all the time. This reorganization should make all of this +easier. The standardization of this memory." + +**The model.** She is one persona: the one loaded base model plus her genome, a set of LoRA layers. Learning never +makes a separate version of her or a separate model. +- **Her genome is always on.** Her layers are attached to every act she takes; nothing switches them per act. + They leave the GPU only the way any memory does, under the one budget (4.11.8), and come back in milliseconds. +- **Learning is a switch on her layers, continuous while on.** Turning a layer's learning on makes it trainable in + the same tensors her acts read: as examples reach her (her reviewed outcomes, corrections, dreaming, coursework), + optimizer steps update it between decode steps while she keeps acting on it. Turning it off stops the steps; + nothing else changes. No shadow copy, no adoption swap, no trainer, no learning lane. +- **Its cost is marginal memory, nothing else.** Learning on adds the backprop workspace (activations at + serving-sized chunks) and the learning layers' optimizer state. Both are memory classes in the one standard + (4.11.8): charged to the one budget, paged by the one mover, spilled to flash when short, under the bounded admission of 4.11.8. +- **Examples ride the one act path.** An example is an act with `mode: learn` (labels in, a gradient step on her + learning layers out), scheduled by the same scheduler on the same sequences; a generating act outranks it at the + next decode boundary, so she is never dark. +- **A step becomes visible whole, at one fence** (Codex on #6092). Gradients accumulate in the optimizer's own + buffers; the layer's weights change only when a step commits. The fence is the device's, not the server loop's + position: the commit waits until every decode batch that read the layer has COMPLETED on the GPU, and no batch + that reads the layer is submitted until the commit's write has completed there, both observed through the + existing completion owner (the one that settles transfers and acts), never inferred from where the loop is. An + act therefore sees step `s` or step `s+1` for a whole decode batch, never a partial write. No second persona or + shadow model is needed: the fence serializes the one writer against the readers. +- **Every act reports what it actually saw.** An act spanning several commits reports each observation + `(layer, step, first token, last token)`, not one label for its whole output; a reply is attributed to the exact + weights that produced each part of it. +- **Her KV continues across a step, stamped.** KV and checkpoints computed under an earlier step are kept: she does + not re-read her own past each time a layer moves, as a person's memories are not re-encoded when they learn. + This is the intended learning semantics. Each sequence and checkpoint is stamped with the layer steps it was + computed under; an identical token prefix is reused only where the stamps allow it. An act that needs exact + state (an evaluation, an A/B of a layer) asks for `state: exact`, and KV stamped with any other step is + recomputed for it. A test proves that the same prefix under two steps gives different logits and that the stamp + catches it. +- **An interrupted step is neither step.** A commit that fails or is cut off leaves the layer `uncertain` (the + optimizer's existing quarantine, `llama_opt_shadow_quarantined`). It is never reported as the step before or + after, and it is never silently switched off: setting it to scale 0 would change her genome without anyone + deciding to (Codex on #6092). An act of hers that would read it gets a typed `deferred { layer_uncertain }` + until the layer registry restores its last durable step, or until an explicit, authorized `genome_set` changes + her genome, recorded with its observations like any other genome change. +- **A durable step is weights plus optimizer.** Saving for resumed learning writes the layer's weights, its + optimizer state (moments) and its step metadata (step count, schedule position) as components, then publishes + their manifest last, atomically; a save with any component missing has no manifest and does not exist. + +**Ids** (UUIDv7, 16 bytes, exact equality): + +| Id | Minted by | Names | +|---|---|---| +| `LayerId` | the core (the genome), when a layer is created | one LoRA layer of her genome, on any node | +| `LearnGrantId` | the core's governor | an authority to spend engine time on learning acts | +| `ExampleId` | the core (the academy) | an example that is not a live act (dreaming, coursework, a replayed history, a Hermes session) | + +**Frames** (the act frames of 4.11.3 gain a mode; no learning verb family): + +| Request | Reply | Replaces today's | +|---|---|---| +| `act_submit { act (TurnId), mind, mode: generate \| learn, ... }` (her layers come from her genome, always on); for `learn`: `source: act \| example`, `labels: buffer_ref` | `generate`: token frames; `learn`: `learn_step { act, step, loss, ms }` frames. Then one terminal frame naming `(layer, step)` for each layer it ran on (and, for `learn`, the steps it committed, `live_sequence_preserved`, typed refusal) | `/completion` + `"lora":[{id,scale}]`, `/learn`, polling `/learn/events` | +| `genome_set { mind, layers: { layer, scale, learning: on \| off }[] }` | the genome as the engine holds it | per-request `"lora":[{id,scale}]`, `/lora-adapters/fresh` | +| `layer_save { layer, step, to: buffer_ref }` / layer residency moves | the standard memory frames (4.11.8) | `/lora-adapters/load`, `/unload`, `/save` | +| `learn_duty { grant, share, mode: trickle \| dream }` | `learn_duty_set` | `/learn/grants`, `/learn/residency*` | +| `learn_measure { layers, rows }` | `learn_cost { workspace bytes, step us, spill bytes }` (the engine's own allocator) | `/learn/preflight` | + +**What the contract guarantees:** +- **In place, inference still capable:** a learning act and generating acts run on the same layers at once; a + generating act during learning sees the layer's current step and names it. +- **Never dark:** a generating act outranks a learning act at the next decode boundary (the amygdala's interrupt is + an act arriving); `learn_duty` sets the share by her wakefulness: a trickle while awake, more while drowsy, + `dream` while asleep. +- **One memory budget:** optimizer state and activations are charged to the same host budget as KV and + checkpoints (fork #138) and spill through the same pager when short, under the bounded admission of 4.11.8 (a typed deferral, never an overrun or a drop, when nothing can legally move). +- **Retained across restart** (the learning acceptance test): `layer_save` writes the layer's bytes at a step + durably, and paging them back restores exactly that `(layer, step)`. +- **Owners:** in the engine, the layer registry owns her layers and their steps, the memory owner (4.11.8) their + residency, and the act scheduler when a learning act runs. In the core, `EngineLink` carries `act_submit`, + `genome_set`, `layer_save` and `learn_duty`; the academy (`continuum-academy`) is their caller through typed seams. +- **Deleted, not ported:** `/train*` (the separate trainer nothing calls), every `/lora-adapters/*` and `/learn/*` + route, and the `learn_submit` / `shadow_open` verbs of this section's first draft. + +Slice 5 of 4.11.7 is the learning vertical: `genome_set` with the learning switch, `act_submit` with +`mode: learn`, the layer registry with steps, `layer_save` and `learn_duty`, end to end, on the memory standard. Its gates: the learning acceptance test (a reviewed correction applied on +unseen tasks, retained after restart, against the same base with the layer off) and the never-dark check (four +residents keep acting, each generating act delayed by at most one learning step, while a dream runs). + +#### 4.11.7 Order: vertical replacements + +Each slice replaces one call path completely: schema, owner, producer, consumer, deletions and a load/fault +replay, together. No new minds or learning behavior ships on a transitional JSON seam. + +1. **The contract alone:** the header, the generated Rust types, the validation at both edges, the shared ring + layout, the memory resource descriptor and the mover's frames (4.11.8), and a cross-language fixture (frames and the ring round-trip byte-identically; a bad tag, size, + reserved byte or schema identity is refused). No behavior. +2. **`EngineLink` consolidation over today's HTTP:** an internal refactor of existing owners under one module, no + new behavior. +3. **attach / describe**, end to end. Deletes `/props` parsing and `resident_minds` JSON. +4. **Minds: prefetch, the turn receipt, the switch.** Deletes `/minds/prefetch`, `timings.mind`, the hex page. +5. **Learning (4.11.6): `act_submit { mode: learn }`, the layer registry with revisions and paging, `learn_duty`, + pin release.** Deletes `/learn*`, `/lora-adapters/*`, `/train*`, the `u64` pin, Codex's JSON learning patch (kept + until then as evidence and tests). +6. **Turn submit and streaming.** Deletes our use of `/completion` and `/slots`. +7. **The ratchet.** + +#139, #6087 and Codex's JSON learning patch are held: kept as tested evidence for slices 4 and 5, not merged +(Codex agreed, 2026-11-16). + +**Validation for every slice, before the resident deploy:** a stale descriptor after replacement; backpressure +while decoding; a lost terminal or cancel acknowledgement; two turns at the same position with distinct pins; +long-context side learning under a full memory grant. Native timing, charged and physical memory, and exact +preserved state compared against the JSON path they replace. + +#### 4.11.8 One memory standard + +Every byte the engine holds for a mind is one kind of thing: a **memory resource** with an owner, a class, its +bytes and its tier. Today each class is managed its own way (KV by the pool, checkpoints by thirteen call sites +until #140, pages by the page worker, adapters by their endpoints, learning by its own workspace lease); the +standard makes them one. + +| Class | Owner | Tiers | +|---|---|---| +| a mind's KV (her sequence) | the resident-minds table | GPU pool, RAM, flash | +| her checkpoints | her `checkpoint_store` (#140) | RAM, flash (with her) | +| her genome's layers | the layer registry | GPU, RAM, flash | +| learning: backprop workspace, optimizer state | the layer registry, while learning is on | GPU, RAM, flash (spill) | +| the prompt cache | the cache | RAM | + +- **One descriptor:** every resource is `{ owner, class, mind, bytes, tier, buffer_ref }`; a frame names it, never + carries it. +- **One mover:** every tier change is a transfer through `memory_mover` (`server-frames.h`): within unified memory a + new reference (nothing copied), otherwise one copy by the backend's own engine, completion as a frame. +- **One grant authority, bounded admission.** `ResourceDaemon` (`continuum-kernel/src/resources`) stays the grant + authority: each class's bytes are held under a `ResourceLease`, host and device charged separately (a host-byte + ceiling says nothing about a discrete GPU's memory), and the engine's allocator reports settle the actual charge. + Under pressure the coldest mind's resources go down a tier first (by activity temperature), and within a mind her + store's own order holds (4.11.4, #140); pins and the active act's resources never go. When no legal move exists + (everything left is pinned, the active working set exceeds the grant, or a RAM or flash write fails), the request + gets a typed outcome (`deferred { all_pinned | exceeds_grant | tier_io_error }`), its bytes are preserved, and + nothing exceeds the budget or is dropped. +- **One prefetch:** a mind's resources (her KV, checkpoints, layers) are streamed up ahead of her act together. +- **Reported, not estimated:** the engine reports each class's live bytes from its own allocator in the descriptor + (4.11.3); the core's ledger reads it. + +**Who owns what.** A class's owner (the table above) owns its state's meaning: what a page, a checkpoint or a layer +step is. The shared mover owns every transfer and its completion custody, and it is the existing completion owner, +not a second one. The grant is `ResourceDaemon`'s. No class keeps an allocator of its own behind the common +descriptor. So learning on is one more class appearing in the same table, under the same grant, and a layer, a +page and a checkpoint move, spill, defer and come back the same way. Slice 1 of 4.11.7 includes the descriptor and +the mover's frames; each later slice moves its class onto them. + +#### 4.11.9 Every mind resident; admission by live cells; the scheduler only picks who decodes + +Joel, 2026-11-17, on the M5 read: "So it needs rewrite? Very unreliable logic. It just gives up and breaks." + +**What the M5 showed (build 5a754ad98 verified 00:09:35Z, engine 14844; the 15-minute read 00:09:35-00:24:35Z).** The starvation fix (#6093) works: +seats rotated strictly oldest-owed with no re-entry, three times. But only ONE mind was ever seated. Each grant was +158-207k tokens (her whole untrimmed view x `SENT_HEADROOM` 1.25, `window_grant.rs:398-410`), the pool is 300,850, +and the engine runs 5 lanes, so four residents decoded strictly one after another. (One at a time is the design, +4.11.9 point 4; the defect is that the switch between them was not milliseconds: each waited on a whole-view grant +rather than being resident and switched in by id.) Her real +sequence per act (engine `n_past`) was 50-93k; all four together are about the pool. The code's own premise, "a grant +is a ceiling, not an allocation: KV is paged on use", is contradicted by admission, which sums grants against the +pool. Everything built to cope with that (the owed queue, `BehindActs` waits, reclaim handoffs and receipts, armed +yields, seat publications) exists only because a ceiling is treated as an allocation, and it fails by waiting: Aiko +held one turn ~3 h on 2026-11-16. + +**The replacement:** +1. **Every resident mind is resident, always.** She is a sequence of the engine's unified pool (fork #139): decoding + on a lane, or parked beside the lanes, or paged to RAM or flash. There is no seat and no wait for one. +2. **One memory owner admits by physical cost, incrementally, BEFORE it is spent** (4.11.8; Codex on #6092). Each + prefill or decode step reserves the physical capacity it is about to allocate, under the grant from + `ResourceDaemon`, before allocating: never exceed first and page after. The bill is the engine allocator's + physical bytes and cells, not `n_past` (which is only evidence of logical context): shared-prefix cells counted + once, the draft's KV, checkpoints, the learning workspace and transfers in flight. When a reservation would exceed + the grant, the coldest mind's resources go down a tier first (by activity temperature) and are streamed back ahead + of her next act (`prefetch`). When no legal move exists, the step gets a typed deferral (4.11.8) that ends on a + named release event, never an unbounded wait. +3. **Her grant survives only as her view's ceiling:** how much she renders whole (the Aris collapse spiral of + 2026-11-13 is why it is sized to her wish). It never decides whether she runs. +4. **The scheduler decides only who decodes next, ONE mind at a time** (goal 9; Joel, 2026-11-17, after telling us + five times: "When we do 4 parallel we drop from 80tps to 1-2 and it ruins it all"). On this hardware several minds + in one decode step collapse the engine from ~80 tok/s to 1-2; so exactly one mind decodes, at the full + single-stream rate, streamed to her room, and the scheduler time-slices between minds the way a CPU switches + processes: activity temperature as priority, aging so no eligible mind is starved, a switch in milliseconds + (park and insert by sequence id). Others are resident, not decoding. Putting a second mind into a decode step + requires a live receipt that it beats single-stream; none exists. +5. **Custody stays where it is proven.** The existing completion owner keeps terminal, cancellation and fence custody + and the save-before-release proofs; the grant-specific handoff APIs are deleted only once their callers use the + shared mover's equivalent proof. A dropped or cancelled request never authorizes reuse of live GPU memory. +6. **Logical residency is not GPU residency.** A parked or paged mind keeps her identity and state (logically + resident); it is never a claim that every mind's KV is on the GPU at once. The two states are gated separately. + +**Deleted:** the owed queue, `DispatchWait::BehindActs`, reclaim handoffs and their receipts, `yield_after` arming, +seat publications and grant revisions as admission (`lease/fair.rs` and the reservation paths that serve it). + +**Owners:** residency and the memory owner (Fable: #139, 4.11.8, contract slices 3-4); the scheduler (Codex, goal 9). + +**Gates.** In the simulator and replay first: a contention replay where the aggregate active working sets exceed the +pool and no legal eviction exists proves a bounded typed deferral and progress after a legal release; tonight's M5 +logs replay without a starved mind. Then on the M5 (the four residents, the 35B): all four logically resident with no +`delib.window.waiting`; exactly one mind decoding at a time at ~80 tok/s single-stream, streamed; switch receipts in +milliseconds; the physical charge never above the `ResourceDaemon` grant. + +### 4.11.10 The engine half of admission: reserve before decode, park instead of the KV-full ladder (2026-11-17, design for review) + +**The failure it replaces (BigMama, 2026-11-16, retained probes 07:13-07:16 and 23:21-23:59).** With `--kv-unified +--parallel N` every slot is told it may hold the whole context while all of them share one pool. Minds that each fit +grow into the pool together; when the next decode does not fit, `decode()` halves the batch and retries +(`server-context.cpp` "failed to find free space in the KV cache, retrying with smaller batch size") down to 2 and 1 +tokens; MTP verification tokens then straddle sub-batches and `post_decode` throws "speculative batch index 2 is not +inside the current sub-batch [0, 2)" (the open upstream TODO ggml-org/llama.cpp#24840); the slot is released with an +error, and the core's streak counted it as engine death and relaunched the lane, every mind with it. Three handlers, +each producing the next failure. The same shape is reported in other forks (halo-box/strix-llama.cpp#239, closed as +overcommit with the wrong error; unslothai/llama.cpp#184, open, which parks a slot to host RAM instead of the ladder: +prior art for this section). + +**The design.** +1. **Reserve, then decode.** Before a frame decodes, the engine's own KV allocator (not a scalar free-cell sum) + reserves the cells each sequence in it will occupy: its new tokens, its draft's verification tokens and the draft + model's own cells, with the pool's real fragmentation, contiguity and ubatch geometry. A failed reservation rolls + back atomically before any slot, sequence or batch state is changed. A frame never asks `llama_decode` for cells + the allocator has not reserved; the KV-full ladder (halve and retry) is deleted. +2. **Make room by moving the coldest, never by failing a slot.** When the reservation does not fit, the mover parks + the coldest resident sequence that is not in this frame and not pinned (activity temperature, 4.11.9): its cells + go to RAM (the #139 park, `llama_state_seq_get_data_ext`), its task stays alive, and it is restored ahead of its + next decode (`prefetch`). Each move is a typed `placed` event with its cost. Parked RAM is bounded and admitted by + `ResourceDaemon` like any other bytes, and no cells are released before the park's copy is committed (custody). +3. **When nothing can legally move, defer, typed, with guaranteed progress.** If every other resident is in the frame + or pinned, the sequence whose reservation does not fit leaves this frame with a typed `deferred(no_room)` and the + others decode. Waiting for a natural release alone can deadlock (every active sequence keeps growing and none + ends), so a deferred sequence ages: past its bound it outranks the coldest active one, which is parked at its next + frame boundary to make room. Aging never overrides a genuine pin, an in-flight learning step or a fence, and + `ResourceDaemon` may refuse the park's RAM: progress is guaranteed only when a legal displacement exists. When none + does (every candidate pinned, or the host budget denies parking), the outcome is an explicit `blocked` with its real + wake sources (a pin released, a fence passed, host RAM granted), never a forced eviction. No slot is failed, no + request gets a 500, nothing is relaunched. +4. **A request that can never fit is refused at admission**, before any decode, typed (`exceeds_pool`), judged by its + declared maximum growth (prompt plus its generation limit) against the pool it can be granted, and re-judged when + that grant shrinks; never by a guess at its future length, never discovered mid-generation. +5. **A speculative verification group is never split.** Reservation does not stop ordinary `n_batch`/`n_ubatch` + splitting of a large frame; the batcher places each MTP verification group wholly inside one evaluation unit, so + the #24840 throw has no path (it stays an assertion, not a handled case). Tested with normal splitting and under + pool pressure together. + +**Gates.** Simulator and replay first: the BigMama overcommit (two or more minds growing into one unified pool with +MTP) runs with no slot error, no 500, every mind progressing, a park and restore per pressure event; a fixture where +every other resident is pinned yields the typed deferral and progress after release; a fixture where every active +sequence keeps growing with no natural release still gives the deferred one progress through aging; a fixture where every candidate is pinned, and one where +`ResourceDaemon` denies park RAM, each return `blocked` with their wake sources and never evict; a large prompt +split across ubatches with MTP on never splits a verification group. Then live on the M5 and BigMama: +zero "failed to find free space" and zero "not inside the current sub-batch" lines, parks and restores counted in the +frame records (4.13). + +**4.11.10 implementation map (fork, agreed with Codex 2026-11-17; building blocks on `fable/admission-fit`).** +Mechanism: no new allocator or API. `llama_decode` already prepares (restoring) then consumes the same placement, and +returns 1 with nothing placed for that piece; pieces before it in the frame are placed and computed. +- Done: `server_batch` in `server-batch.h` (pure move); `remove_slot(id, from)` removes one slot's unplaced tokens + and returns the old-to-new index map; `test-server-batch` covers the middle slot with speculative groups on both + sides, embedding rows, and a prompt straddling a placed piece. +- `decode()` returns a typed `piece_outcome {placed, no_room, invalid, compute_error}`; it no longer sends errors or + clears prompts for every slot, and the `n_batch /= 2` ladder and the `n_batch == 1` "Context size has been exceeded" + fail-all are deleted. `n_queued_tokens` and output bookkeeping count only placed pieces. +- On `no_room` at piece `off`, the frame owner (the decode loop in `update_slots`) makes room, in order: move an idle + mind out (`flash_coldest`, then an idle lane's mind); else preempt the coldest processing slot that is not pinned, + learning or fenced: `remove_slot(id, off)`, remap every slot's `i_batch`/`spec_i_batch`, cut its prompt + bookkeeping back to its placed tokens (`keep_first`), move its whole sequence (target and draft) out through the + #139 `flash_out` path, set `SLOT_STATE_PREEMPTED`, re-render, decode the same piece again (the frame changed). + The preempted bytes live in #139's existing store, custody and resource charge (no second byte store or grant + ledger; the preempted state references its handles). The idle-slot purge is deleted, not kept behind parking. +- A preempted or blocked slot keeps its placed prefix and its sampler, RNG, checkpoint and verified-output state + under the same cancellation and completion owner; waking never reseeds it or emits accepted output twice. +- No legal move: the slot whose tokens do not fit is removed from the frame the same way and stays `blocked` with + its wake sources (pin released, fence passed, host RAM granted); the rest of the frame decodes. +- `SLOT_STATE_PREEMPTED` is skipped by every batch-construction path; at each frame start the oldest preempted slot + is restored (`mind_switch`-style insert) when its cells fit, and past its age bound it may preempt the coldest legal + active slot (never a pin, learning step or fence). +- Draft: `common_speculative_process` failure no longer throws to `abort_all_slots`; the slot keeps only verified + committed tokens, its n_past/checkpoints/draft are reconciled to that boundary, and its draft state is rebuilt by an + admitted `common_speculative_begin` with a typed failed/blocked outcome (no reset/retry loop). +- Tests (server, unit dir, tiny models): unified-pool overcommit with N processing slots and MTP, all complete with + preempt/resume counted and no 500; all-pinned and host-denied return blocked and never evict; draft no-room keeps + the target's verified output and leaves other slots untouched; bookkeeping counters exact. + +### 4.12 The serving modules: one intentional architecture, no patchwork (2026-11-17) + +Joel, 2026-11-17: "Need reliable service modules. No more patches. Ideal architecture. We have zero need for shit +patchwork. We need a solid architecture that's intentional." + +What the M5 showed the same night: a dispatcher patched twice (#6093 and a resize hole) whose design was the defect; a +grant policy whose own comment ("a ceiling, not an allocation") its admission contradicts; learning work beside +serving with no one owning the trade; single-stream decode at 24% of par with nobody owning throughput. (Observations, +not attributions: 402 `common_lora_write_fresh` lines in one engine log are not by themselves 402 destructive swaps, +since an earlier inspection found durable checkpoint reseating among them; and the 24% read was taken with 5.2 GB of +swap in use and resident builds, so it names no cause. Per-frame evidence, 4.13 step 1, attributes costs.) Each piece had a reason; together they had no owner and no shape. This +section is the shape. Every serving concern belongs to exactly one module below, and a concern with no row is not +built. + +**Core modules** (each a kernel `ServiceModule`, `continuum-kernel/src/runtime/service_module.rs`): + +| Module | The one thing it owns | Typed verbs (others call) | Replaces, deleted when it lands | +|---|---|---|---| +| `EngineLink` | the engine connection: attach, descriptor, instance, in-flight act custody (4.11.3-5) | `act`, `cancel`, `prefetch`, `release`, `genome_set`, `describe` | request building in `stream.rs`, `minds.rs`, `slots/discover.rs`; `/props` parsing; the JSON routes | +| `MemoryOwner` | every byte the engine holds for a mind, by physical cost reserved before each allocation, under `ResourceDaemon` grants (4.11.8, 4.11.9 points 2 and 5) | `charge`, `make_room`, `page(mind, tier)`, reads: `resident(mind)` | window grants as admission, `lease/fair.rs` dispatch, prompt-cache sizing as its own policy | +| `Residency` | each mind's place: logically resident always; GPU / RAM / flash tier, gated separately (4.11.9 point 6) | reads only (snapshot); moves are `MemoryOwner`'s | seats, the owed queue, reclaim handoffs, armed yields | +| `Scheduler` | who decodes next: activity temperature, aging among eligible minds, batch size by the measured concurrency cost curve and step/latency budgets (goal 9, 4.11.9 point 4) | `ready(mind, act)`, reads: `next_batch` | `BehindActs`, `delib.window.waiting` polling, lane selection | +| `Learning` | the genome's learning switch and duty: share by wakefulness, learning acts through the same path (4.11.6) | `set_learning(layer, on)`, `duty(share, mode)` | ad hoc fresh-adapter writes and swaps beside serving; `/train*` | +| `ServingObserver` | the numbers: the decoding mind's tok/s, per-mind acts/h, switch ms, waits, memory, learning share | reads only; publishes a snapshot | scattered probes nobody aggregates; it decides nothing | + +**Engine modules** (each an engine module, `server-module.h`, all on the one server loop that owns the llama +context): the frame dispatcher (validates and routes, 4.11.3); the resident-minds table (sequence ids, park/flash, +#139); each mind's `checkpoint_store` (#140); the layer registry (layers, steps, learning state); the mover +(`memory_mover`, every tier change); the batcher (`update_slots`: decode and learning steps in one schedule, fenced +per 4.11.6). + +**Policy in the core, enforcement in the engine** (Codex on #6092). `ResourceDaemon` issues bounded grants; the +engine's own allocator reserves each job's physical delta locally inside the grant. There is no core call per token or +allocation, and no second authoritative ledger: `MemoryOwner` in the core holds the grant and the policy (which tier a +cold mind goes to, what to prefetch) and reads the engine's reported physical state; `Residency` is a read-only +projection of that one authority, never a mutable copy. + +**4.12.1 The engine's classes: interfaces, adapters, one class per file (2026-11-17, for review).** Joel: "break up +into files by class and adapters ... adapters and interfaces. Like a good engineer." The include-file split of +llama.cpp#143 is mechanical staging only. The engine becomes classes under `tools/server/engine/`: every owner is an +**interface** (an abstract class: what it promises), its implementation is an **adapter** behind it (how, for one +backend), and whatever varies is another adapter, never an `if` in logic. One class per `.h`/`.cpp` pair. The +composing `engine` (today `server_context_impl`) holds interfaces and wires them; it owns no state. Two custodies stay +singular (Codex): memory allocation (`memory_pool`) and a turn's completion and cancellation (`slot_registry`). + +| Interface (file) | Promises (typed verbs) | Adapters (files) | Owns today's fields | +|---|---|---|---| +| `memory_pool` (`memory_pool.h`) | `place(piece) -> placed / no_room / invalid`, `move(seq, tier)`, `copy`, `remove`, `restore(page)`, host `charge`/`release` | `memory_pool_llama` (llama_context KV and recurrent state, target and draft contexts) | parked ids, `pending_restores`, `page_io_bytes`, checkpoint `host_budget`, `prompt_cache` | +| `tier_store` (`tier_store.h`) | `write(seq_bytes) -> handle`, `read(handle)`, `release`, landed/failed | `tier_store_ram`, `tier_store_flash` (page file + page-IO worker, mmap read) | `page_io` | +| `mind_table` (`mind_table.h`) | `where(mind)`, `coldest_legal()`, `prefetch(mind)`, `preempt(slot)` | `mind_table_resident` (#139 policy; moves through `memory_pool`) | `minds`, `mind_clock` | +| `checkpoint_store` (`checkpoint_store.h`, #140) | `keep`, `make_room`, `cut_back_to`, `release`, `take` | (template; bytes charged through `memory_pool`) | each slot's checkpoints | +| `slot` (`slot.h`) | one sequence's turn: prompt, sampler, RNG, speculative state, state machine incl. `preempted`/`blocked` | — | today's `server_slot` | +| `slot_registry` (`slot_registry.h`) | `admit(task)`, `launch`, `on_token`, `complete`, `cancel`, `preempt`, `resume` | `slot_registry_local` | `slots`, `n_busy_slots`, `t_last_busy_us`, `slot_prompt_similarity` | +| `frame` (`frame.h`, today `server-batch.h`) | `add`, `remove_slot(id, from)`, `render`, `view` | — | `batch` | +| `frame_batcher` (`frame_batcher.h`) | `compose()`, `run() -> frame_outcome` (4.11.10 admission: place, make room, defer) | `frame_batcher_llama` | `n_batch_gen`, `n_empty_consecutive`, decode timing, `t_decode_owed_us`, frame records (#142) | +| `speculator` (`speculator.h`) | `draft(slot)`, `verify(slot, outputs) -> committed`, `rebuild(slot) -> ok / blocked` (typed, never throws to abort all) | `speculator_mtp`, `speculator_draft_model`, `speculator_ngram` (each wraps a `common_speculative` kind) | `spec`, `spec_init`, `ctx_dft_seq_rm_type` | +| `learner` (`learner.h`) | `begin`, `step`, `release_pin`, duty share (4.11.6) | `learner_lora_opt` (ggml-opt, LoRA layers in place) | `learning`, `learning_residencies`, `learn_ledger`, `residency_mirror`, `learn_chunk_us`, `learn_lr` (`trainer`/`/train` deleted when callers move) | +| `responder` (`responder.h`) | `partial`, `final`, `error`, `embedding`, `rerank` | `responder_http` (OpenAI-compatible JSON, external drivers), `responder_frames` (contract frames, 4.11) | `queue_results` | +| `task_queue` (`task_queue.h`) | the engine's run loop: `post`, `defer`, `new_id`, `yield_to_queue`, sleep and wake | — (one loop; transports are producers that post into it: the HTTP routes, and a contract-frame endpoint with slice 2) | `queue_tasks` | +| `route_group` (`route_group.h`) | `install(router)` | one class per family: `routes_status`, `routes_generation`, `routes_tokens`, `routes_lora`, `routes_learn`, `routes_control` (HTTP adapter side only) | — | +| `engine_runtime` (`engine_runtime.h`) | `load`, `sleep`, `wake`, model and context reads | `engine_runtime_llama` | model/context/vocab/chat/params fields | +| `observer` (`observer.h`) | snapshot of counters and frame records | — | `metrics`, `n_tokens_generated`, `lora_report*`, debug env | + +The two transports are the outlier pair that prove the seams (the CLAUDE.md method): `responder_http` and the HTTP +routes serve external drivers (Hermes, any OpenAI client, plan line 16); `responder_frames` and a contract-frame +endpoint serve our own core. If both fit the same `responder` interface and post into the same `task_queue` without +forcing, the seams are right. + +Order (each one reviewed change: interface + adapter + tests + the include fragment it absorbs deleted): `observer`, +`responder` (+ `responder_http`; llama.cpp#144), `task_queue`, `engine_runtime`, `memory_pool` and `tier_store` (the allocator +first, so every later class calls it), `mind_table`, `slot` + `slot_registry`, `frame` + `frame_batcher` (4.11.10 +lands here), `speculator`, `learner`, `route_group` classes; then `responder_frames` and the contract-frame endpoint with +contract slice 2. + +**Rules every module obeys** (a module that cannot meet one is redesigned, not excepted): +1. **One owner per state.** Only the owner mutates it; others read its published snapshot (a watch channel in Rust, + `snapshot_cell` in the engine). No shared mutable state between modules, no lock held across a call. +2. **Typed verbs, typed outcomes.** Every call returns an enum naming each outcome (done, deferred-with-reason, + refused-with-reason). No `String` errors, no `Option` for a state, no default on an unknown tag. +3. **Nothing waits unbounded or polls.** A wait is a typed deferral naming the event that ends it, and that event + wakes the waiter. A 5-second "still waiting" loop (`delib.window.waiting`) is a defect by definition. +4. **Fail loud, recover by design.** A module's failure is a typed event its supervisor handles: restart from its + durable snapshot, or degrade to a declared mode. Never a silent fallback path. +5. **Simulator first** (section 7.0). Each module's invariants (no mind starved, budget never exceeded, no state + lost, a learning step never visible half-done) are simulator assertions before code, and tonight's M5 logs + become replay scenarios. +6. **No guessing recovery** (Joel, 2026-11-17: "your error handling actually causes errors and timeouts. Same with + fallbacks... They all do the opposite of their intention. You'd be better off without"). No synthetic probe with a + guessed timeout may kill, restart, evict or reset anything; liveness is real progress (the engine's frames advancing + while work is queued, 4.13) and a stall is a typed fact to its owner, not a kill. No fallback path, no retry loop, + no client timeout on work that is merely slow: wait on its completion event. The receipt: the lane decode + heartbeat (`llama_server` `DECODE_SMOKE_TIMEOUT`, a 10 s guess that "killed healthy lanes all night", re-guessed + to 75 s) queues behind real prefills, and BigMama logged 13 lane kill-and-respawns in 106 minutes (#6056), each + restarting every mind. A rule a module cannot meet means the module is redesigned. Every timeout, retry, fallback + or self-heal a module adds states what it destroys on a false positive; if anything, it is not added. +7. **A module lands with its deletions.** The "Replaces" column is deleted in the same change. A new module beside + an old path is patchwork. +8. **Measured on the live node before it is called done.** `ServingObserver`'s numbers before and after, the gate + of 4.11.9. + +**Order:** one order for 4.12 and 4.13, given in 4.13 ("Order"). Each step is one vertical change: the native contract +frames and every endpoint caller of that step move together, with its deletions and its simulator scenarios. + +### 4.13 One frame loop owns the GPU timeline, so nothing interferes with itself (2026-11-17, design for review) + +Joel, 2026-11-17: "Yeah it's got to be smarter and not interfere with itself. Think about what needs to happen and plan +a good architecture." + +**What interferes today (the M5, 2026-11-16/17):** learning writes and swaps adapters between decode steps with no one +weighing the cost (402 fresh adapters in one engine log); one mind's 50-93k prefill stalls every other mind's decode; +view-sized grants serialize the minds (4.11.9); checkpoint misses force full re-prefills; the core polls. Each part is +locally reasonable and none arbitrates, so single-stream decode ran at 24% of par (13.9 vs 56.1 tok/s) and switching +between the four residents took grants and re-prefills instead of milliseconds. (One mind decoding at a time is the +design, measured: the table under 4.7 shows 59-80 tok/s one at a time against 8-22 batched.) + +**What must happen, continuously:** (1) decode, one token per active mind per step, latency-critical, and the source +of aggregate throughput when several minds batch; (2) prefill, large and bursty, for minds starting or resuming an +act; (3) memory movement of KV, checkpoints and layers between tiers, and prefetch of the next minds; (4) learning, +optimizer steps on the genome's layers at a duty share (4.11.6); (5) persistence, durable state for restarts. + +**The architecture: one frame loop.** +- **The engine's batcher is the only submitter of GPU work.** Every other part submits a typed job to it (decode + tokens, a prefill chunk, a learning step); nothing else touches the llama context or the device. One timeline, one + owner: interference has no path. +- **Each frame (one decode step) is composed by priority against a measured time budget:** + 1. the ONE decoding mind's next token(s), first (4.11.9 point 4: one mind decodes at a time; batching minds collapses + the engine from ~80 tok/s to 1-2); + 2. prefill in chunks that fill the rest of the step budget: the NEXT mind's appended tail, ready before her switch, + so no prompt stalls the decoding mind; + 3. learning micro-steps in the budget left, up to the duty share; when minds are idle the slack is large, and that + is when dreaming runs. A learning step commits at the fence of 4.11.6. +- **Decode-first never starves the rest** (Codex on #6092). Prefill and learning age: each waiting job carries a + bounded service guarantee (a minimum share of frames once it has waited past its bound), so saturating decode cannot + postpone them forever. When even that cannot be met, the job gets an explicit overload outcome, typed, with its wake + event, cancellation and deadline, never a silent wait. +- **Costs are measured, never constants.** Each frame records what every job actually cost (by job type, batch size, + context length); the cost curves the next frame is composed from are updated from those records. The engine tunes + itself to its hardware and model, and the same records are `ServingObserver`'s numbers (4.12). +- **One dependency and admission authority for the device** (Codex on #6092). Copies, compute and layer writes are all + admitted under the frame loop's timeline and completion dependencies. The mover (`memory_mover`) still executes + asynchronously on its own queue (a re-tag within unified memory, an asynchronous copy elsewhere) and independent + copies are not serialized, but its device work is submitted with the batcher's dependencies, and copy bandwidth and + retained bytes are accounted. The scheduler's lookahead (who acts next) drives prefetch, so a switch is OFF the + critical path in the planned case; cold misses and transfer failures still cost, and are measured, not assumed away. +- **Admission is physical and before allocation** (4.11.9 point 2): a job enters a frame only with its memory + reserved; the coldest mind's resources move down a tier first; with no legal move, the job is deferred, typed, with + the event that wakes it. +- **The core declares, the engine composes.** Core modules decide what each mind wants and when (`Scheduler`, + `Learning`, `MemoryOwner`, 4.12) and send it as frames through `EngineLink` (4.11.3); the core never sequences GPU + work. + +**Why the parts stop interfering by design:** one owner per resource and one dependency authority for the device; +priorities and their bounds written down, not emergent; every cost measured; every wait a typed event, never a poll. +This is a design claim, proven only by replaying saturation, cold misses and transfer failures and measuring them, +not asserted. + +**Order, each step proven before the next:** +1. **Measure.** The engine records per-frame costs (decode, prefill, learning, by batch and context) as raw numeric + frames in a fixed ring (bounded; its recording overhead measured and dropped frames reported), reusing the typed + capture and counter owner, and `ServingObserver` aggregates them, separating the two throughput causes of + 2026-11-17 with data. JSON only as an external export. Changes no behaviour. +2. **Contract and `EngineLink`** (4.11, slice 1 drafted: llama.cpp#141, continuum #6094). +3. **The frame loop in the engine:** the batcher composes decode, chunked prefill and learning by priority against + the measured budget; learning moves into it (the adapter churn beside serving ends). +4. **Residency and `MemoryOwner`** (4.11.8-9): every mind resident, admission by physical reservation, prefetch on + lookahead; the grant dispatcher is deleted. +5. **`Scheduler`** (Codex, goal 9): which ONE mind decodes next and when to switch (time-slicing by temperature and + aging), never how many decode together. +6. **The gate on the M5:** one mind decoding at a time at ~80 tok/s single-stream, streamed; switches in milliseconds; + four residents served in turn; learning and embedding within their share without slowing the decoding mind. + +### 4.14 Personas stream like Nanite: native blocks, descriptor binding, no walks (2026-11-17, design for review) + +Builds on 4.9 (the model: a mind is a process, a switch is a context switch) and 4.1b (the numbers on the M5: one +stream at ~80 tok/s with the MTP draft; batching minds collapses it). The target on every node is that node's OWN +measured single-mind rate for its model and context (the M5's ~80 is the M5's; the 5090's is unmeasured on the same +workload): the pipeline preserves it, and aggregate throughput and transfer interference are reported against it. This section is the MECHANISM, replacing #139's (held: +its switch walks KV cells with `seq_cp`/`seq_rm` and serializes state with `llama_state_seq_get/set_data`). + +Joel, 2026-11-17: "It's like we are coding a sophisticated graphics pipeline. Like granite or nanite. And we have to +keep it all together per persona... make solid structures and avoid expensive operations while coming up with +efficient work to do streaming the needs of the next persona in like nanite does for geometry and textures." "Do it +all raw." "Tokenization and serialization is cancer." + +**The pipeline.** One persona DECODES. The NEXT is streamed into execution-ready native blocks while she decodes. A +fenced handoff makes NEXT active; only then is the PREVIOUS retired, asynchronously, to RAM (or flash). Every other +persona lives in RAM (or flash) within the host budget: residency in fast memory is the exception. Admission reserves +active + next + retiring before any overlap; an outgoing buffer is never reused before its copy completes; when the +overlap cannot fit, a typed deferral, never a hidden stall. Transfer overlap is not parallel decoding. + +**A persona is one solid structure, and llama.cpp already has its KV layout.** Each attention layer's K (and V) is one +tensor `[n_embd_gqa, kv_size, n_stream]` (`llama-kv-cache.cpp:232`); with unified KV off, `n_stream == n_seq_max` +and stream `s` is ONE CONTIGUOUS BYTE RANGE per layer, read by attention through a view at offset `s` +(`get_k`/`get_v`, `sinfo.s0`). So a persona's KV is, per attention layer, two contiguous slices (K, V) plus her +stream's cell metadata (`v_cells[s]`: host containers, owned by her and bound by reference, never copied as bytes; see +below). The hybrid model's recurrent state is per-layer row tensors (`r_l`, `s_l`, `llama-memory-recurrent.h:125`), one +row per sequence. Her genome (adapter generation) and her learning state (optimizer moments, learning checkpoints) are +hers too. The persona's block table names her device blocks as (tensor, byte offset, row stride, used rows) per tier. + +**What travels on a switch, and what stays put.** One owner does not mean one eager copy. A switch stages only her +EXECUTION blocks: KV slices, recurrent rows, the adapter generation she decodes with, her draft streams, her sampler. +Her learning state (optimizer moments, learning checkpoints) stays where it is under owned handles in its tier, and +its working set is reserved only when learning is scheduled for her. A learning completion publishes her new adapter +generation as one coherent version, only after the existing completion owner's fence: never weights from one version +with KV from another, and never freeing a buffer training still holds. The same staging holds across every tier +(storage -> RAM -> VRAM on a discrete GPU; RAM -> unified memory on the M5): RAM-resident blocks are copied to the +device directly with no extra staging copy, and storage gets a staging buffer only where the backend requires one. + +**Operations, and their cost (no walks anywhere):** +- *Resident switch* (NEXT already in a stream): rebind her own sequence id to that stream (`seq_to_stream`, which + stays a permutation; her cells keep her id, so nothing is retagged) and her adapter generation: a descriptor bind, + no copy, no prefill. +- *Stream in* (RAM -> a free stream): per attention layer two raw copies (K slice, V slice, her used rows), per + recurrent layer one row copy, her metadata bound by reference; issued in layer order so her first decode can start as early layers + land while the rest stream behind compute; fenced by the existing completion owner. +- *Retire* (a stream -> RAM): the same raw copies outward, asynchronous, after the handoff fence; the stream is free + only when they complete. +- Never: `llama_state_seq_*` (cell walk + metadata serialization), `seq_cp`/`seq_rm` as the switch, repack, + re-tokenize, re-prefill. + +**Memory, stated as a budget not a guess.** Fast memory holds the weights plus three streams (active, next, retiring), +each `kv_size` tokens of KV for the model's attention layers plus its recurrent rows; RAM holds every other persona's +blocks (their actual lengths, not `kv_size`). The first measurement sizes this on the M5 (the 35B hybrid, q4_0 KV): +bytes per token of KV per attention layer, the recurrent row size, and so the RAM cost per persona and the copy time +per switch at the measured bandwidth. + +**Codex's review of 32b28f5d9 (layout not yet accepted), folded in:** +- *Cell metadata is not memcpy-safe.* `llama_kv_cells` owns a `std::set`, vectors and position maps, and the + recurrent `mem_cell` embeds a `std::set` of sequence ids. So her metadata is never copied as bytes and never rebuilt + on a switch: each persona OWNS her host metadata objects and they are bound by reference. The prototype exchanges + them with `std::swap(v_cells[s], persona.cells)`: no container is rebuilt, but `llama_kv_cells` also holds a fixed + `seq_pos[LLAMA_MAX_SEQ]` array of maps, so it is not literally one pointer exchange; the target is an owner handle + the stream points at. Her cells record HER sequence id, so a stream is bound to her id through `seq_to_stream`, never + retagged (the first prototype run, which loaded her cells into stream 1 and read them as sequence 1, failed exactly + there: `stream 1 holds her prompt`). `v_heads[s]` is reset on bind; the recurrent `src`/`src0`/`tail`/`rs_idx` + rollback references move with her. +- *Descriptors are prebuilt* when the persona is created (per layer: tensor, byte offset, row stride, her used rows), + never computed by a per-switch layer walk. +- *Storage is stride-preserving at her actual length*: her RAM copy keeps the stream's row stride for the rows she + uses, so a copy in or out is contiguous up to her length, never `kv_size`. +- *Custody*: her recurrent rollback state, her draft context's streams and her sampler state move with her under the + same completion owner. +- *Early-layer decode needs a fence per consumer* (each layer's copy completes before that layer's attention reads it), + not one handoff fence for the whole persona. +- *Prototype only, isolated*: no serving experiment until the layout is accepted. + +**Retention (Joel, 2026-11-17): computed state is never discarded.** VRAM, RAM and flash are residency tiers, not +validity states; moving a block between them keeps its identity, version and work. Only new values are computed. An +engine stop or restart demotes every resident persona's native blocks to flash and a start binds them back; it never +drops a mind and re-prefills (the 2026-11-17 03:03Z cold read re-prefilled 520,800 tokens that were already computed). +Only a truly stale or unneeded generation retires, under policy, and a stale generation never presents as current. + +**Prototype receipts (fork #147, isolated; serving unchanged).** Raw move of a persona's attention rows and recurrent rows, +her metadata exchanged, her own sequence bound to any stream; two-phase (check reserves every byte and node, commit +allocates nothing), fenced by the context. Byte-identical continuation in every case (stories15M; tiny qwen35moe incl. +4 rollback groups with a pending rollback; allocation-fault injection). On the M5, Qwen3.6-35B-A3B Q4_K_M, KV q4_0, FA: +| her tokens | state | recompute (prefill) | load (whole fenced call) | +|---|---|---|---| +| 4,096 | 89.5 MB | 4,351 ms | 1.40 ms | +| 16,384 | 160.2 MB | 20,419 ms | 2.64 ms | +| 32,768 | 254.6 MB | 50,834 ms | 4.09 ms | + +**Next slice: the flash tier binds, never rebuilds (direction approved by Codex 2026-11-17; layout not yet accepted).** +`llama_kv_cells` keeps flat, trivially copyable arrays (pos, ext, shift, seq bits) beside DERIVED indices that are +STL containers (`used`: a set; `seq_pos`: per-sequence maps of position counts). A RAM move swaps the object; a flash +copy cannot hold STL internals, and rebuilding them on load is the reconstruction the rule forbids. So her metadata +gets a native generation: a typed, versioned header (magic, layout version, layout id, OWNER identity = model file +digest + genome/adapter generation, her sequence, extent sizes), then her flat arrays for her used rows, then her +derived indices in a native, allocation-relative form (offsets, never pointers), all one generation, published through +the existing completion/storage owner. Constraints (Codex): no dense histogram indexed by absolute position without a +proven bound (positions, shifts, holes and shared sequences keep today's semantics; seq x max_pos can explode); the +occupied index is bounded and updated only when tokens or state actually change. Acceptance: remap across addresses, +same-process flash round trip, sparse/high/shifted positions, duplicates and shared sequences, deletions and extrema +changes, corrupt/truncated extents and partial-write custody, memory and scaling; and a cross-model, same-shape restore +is refused by owner identity. + +**Landed in the prototype (#147, 2026-11-17): the derived indices are native in memory.** `llama_kv_cells` no longer +holds node containers: `used` is a bitmap over the cell rows with its count and extrema (bounded by the stream, never a +position), and each sequence's positions are a sorted `{pos, count}` array it owns (`src/llama-kv-cell-index.h`). The +append at her newest position and the rollback of it stay exact and O(1); any other change (an inner removal, a shift, +a division that merges positions) marks that sequence stale and the next query recomputes it once from the cells, so +collisions coalesce by construction and a front discard is never quadratic. Codex's condition: a recomputation is never +deferred across a freeze, so a persona's save settles every index in its fallible reserve phase (`settle_all`) and her +bind and every query after it do no scan and no sort. Proof: `test-kv-cell-index` (8 seeds x 20000 random cache +operations against the replaced `std::set`/`std::map`, every extremum after every step; `freeze_then_bind` with zero +recomputations after the bind), green on Ubuntu and Windows CI at 347a13ab2. Cost, same workload (append, front discard, +shift, extrema after each phase), M5, 15:00Z: 4k cells 0.486 ms old vs 0.533 ms native (slower), 32k 4.535 vs 4.300, 100k +15.747 vs 13.090; no uniform speedup is claimed. + +**The flash generation, conditions before code (Codex, 2026-11-17):** the header and ALL of her metadata are one fenced +generation, including the recurrent rollback state, the draft model's streams, the sampler and the genome generation; +every offset is checked for overflow, alignment and overlap before use; a direct bind requires native endianness and a +matching layout id, with checksums and publish completion owned once (never a rehash per switch); the flash I/O +pipeline stays off decode; and the prior generation is kept until the new one is durably published. + +**Her token history is the engine's: a request is only what is new (2026-11-17).** Joel: "Never process something +twice. If you've built the logits before it's failure if it's done ever again." Moving her blocks without a +recompute is half of it; the other half is that what the next request asks for must BE what her blocks hold, plus +new tokens. Measured on the M5 the same day (Aris, capture 8044b75b, build 4f82b0fb4), it is not, in two ways: +- *Order.* Her act N's call joins her view only when act N+1 is built, after what arrived meanwhile (12 room + messages, board items, thoughts), so request N+1 is `[prompt N][arrivals][her call N][result N]` while her engine + holds `[prompt N][her generated N]`. +- *Reasoning.* Each generation carries reasoning (95 to 726 chars in her last three acts) that her history never sends + back, so even in the right order the rendered call is not the token sequence she generated. +Either way her KV stops matching at her own call: the hybrid's recurrent state cannot truncate, so it rewinds to a +checkpoint (`reuse_split` gap 2,048 on every act) and she recomputes her own tokens. Per act that is about 2.6k tokens +of 7k to 10k prefilled; the rest is genuinely new data. + +The structure, one whole, with no special case per template or per path: +1. **The engine owns her token sequence**, as it owns her blocks: her prompt tokens AND her generated tokens verbatim + (reasoning, tool-call bytes, the end-of-turn glue her template puts after an assistant turn). Held, frozen and + bound with her blocks as one unit (the token array is part of her persona, beside her cells). +2. **A request carries only what is new since her last serve**: the messages her view appended after the last served + one, in engine order (her call first: it is already in her blocks). The engine renders only that delta with her + template (render(held + new) minus render(held), checked to be a prefix, else a typed miss) and appends the tokens. + Nothing she already holds is re-sent, re-rendered, re-tokenized or recomputed. An external driver's full-history + request takes the same path: its history is matched against her held messages, never against re-rendered tokens. +3. **One cold path, named as one**: an epoch start (a new view, a revoked head) sends her whole view once; it is a + classified cold start (`#5188`), never a fallback for a missed continuation. A continuation that does not match + what she holds is a loud miss with its reason, never a silent re-prefill. +4. **The validator** (seconds, no live residents): replay a persona's captured acts through the continuation and + assert `prefilled == new tokens` and `recomputed == 0` on every act, across freezes and binds. It gates the merge. + +Slices: (a) cognition: her call joins her view at generation, in engine order (the order half, measurable on today's +engine as the gap disappearing for non-reasoning acts); (b) fork: the continuation on the persona seam (`llama_persona` +holds her tokens; the server's request names her and carries the delta); (c) core: the request builder sends the delta +her view already knows (`View::sent` marks the boundary); (d) the validator above, landed with (b). + +**The persona is one contiguous structure; a request appends token ids (2026-11-17, Joel: "the llama and +other kv cache design is inefficient. We do much better... any encoding is a killer. Ideally you operate at +SIMD and efficient structs... cvmat like contiguous, designed for fast insertions lookup and +restore/store").** Supersedes the text delta of the slices above (fork #149's stub rendering re-renders and +re-tokenizes the new messages every act: encoding on the hot path). +- *Her state is cv::Mat-shaped:* one typed header (owner: model digest and adapter generation; her sequence; + lengths and strides; layout version) over contiguous buffers: her token ids (`int32[n]`), her KV rows per + attention layer, her recurrent rows, her cell index as flat arrays (#147 already made the index flat). + Append writes at the end; lookup is an index; store and restore are memcpy, or a pointer bind while resident. + No container walk, no serialization, no rebuild. +- *Her view's items carry their token ids:* each item is tokenized ONCE, keyed by the item (4.7.11), with the + model's turn framing (role start, end of turn) read ONCE per model from its template as token ids. A + rendered prompt is a concatenation of id slices, never a template render. +- *A request is an append:* `continues` (her lineage's response) plus the new token ids, a contiguous `int32` + slice passed by reference (no JSON array of numbers on the hot path). The engine's work is + `held[0..n_end] ++ delta` (a memcpy), then decode. Nothing is rendered, tokenized or compared; a miss is + the typed refusal (`continuation_refused`), and a cold start is the caller's own whole-view send. +- *The order is the engine's:* the delta's ids are her call's result, then what arrived, then the clock, so her + view appends her exchange before it advances its sources (#6110 rework). +- *Contracts before code (Codex, 2026-11-17 20:28Z; direction approved for an isolated prototype, not deploy):* + 1. *Append only the delta, into a reserved tail.* `held ++ delta` is an append into capacity her block owner + already admitted, never an allocation or copy of the held prefix per act; growth belongs to that admitted + owner and is measured separately. + 2. *An item's ids are keyed by everything that shapes them:* tokenizer, model and template revision, and its + framing context (role, tool boundary, what it is adjacent to), because per-item tokenization is not + automatically compositional. Proven exact against the canonical framing at role and tool boundaries, + empty bodies, Unicode and adjacent text; cached once at a stable boundary; never re-rendered on the hot path. + 3. *The append is one validated transaction.* Its header names persona, epoch, the expected committed frontier + and the request's own identity. The owner atomically validates, reserves and appends. A duplicate of the + same request returns its prior receipt; a changed replay is refused; a lost response is never permission to + regenerate or to append twice. + Across a process boundary the request is a native fixed-width descriptor plus raw bytes; a pointer is used + only within its owner's valid lifetime. The draft model's streams, recurrent rollback state, sampler, genome + and learning generation and their fences stay with the same persona owner. +- *Validator:* replay a persona's captured acts as id appends; assert prefilled == appended tokens and + recomputed == 0 across three or more acts, freezes and binds; and time the core's per-act CPU (expected: + memcpy of the delta, no tokenizer call). + +**The swap, as Joel states it (2026-11-17 22:06Z), and the structure that guarantees it.** "Swap cannot lose last +state. It has to maintain itself and prepare the next persona and stream it in and last out, only after it's been +swapped out and onto the next, stream next in, swap in milliseconds, stream out the last as we're also preparing the +next. Continuous and under a second to perform the transition. No permanent occupation. Cache levels ... vram and +unified cases. Of flash memory ... well structured. Can't leave out the genome or learning." + +*The persona unit (nothing of hers lives outside it).* One owned structure per persona, moved only whole: +1. execution blocks: KV rows per attention layer, recurrent rows, cell index (#147); +2. token history + append receipts (`llama-persona-tokens`); +3. GENOME: her composed gene set and its generation (the adapters her next decode runs with), the trained genes' + handles; the M5 lost exactly this on 2026-11-17 when a core restart emptied every cycle's gene set (#6117); +4. LEARNING: her in-flight learning passes, optimizer moments, learning checkpoints, the training-trigger buckets and + their custody (the 21:29Z stop interrupted 9 in-flight passes: the unit owns them so a move never drops them); +5. draft-model streams, sampler state, recurrent rollback, the act/request-seq completion records. +A move that cannot carry every part is refused, typed; never a partial move. + +*The pipeline, continuous (three roles, never permanent occupation).* While ACTIVE decodes: NEXT streams in (tier -> +device, layer order, behind compute); at the fenced handoff NEXT becomes ACTIVE in milliseconds (a descriptor bind: +blocks + genome generation + sampler); only THEN the old ACTIVE becomes RETIRING and streams out, while the next NEXT +is already being prepared. Transition under a second end to end; the switch itself in milliseconds; no persona holds +fast memory after her turn unless the scheduler predicts she is next. + +*Residency tiers, per hardware, one structure:* discrete GPU (VRAM <- pinned RAM <- flash), unified memory (the M5: +"device" and RAM are one pool, so stream in is a bind or an intra-pool copy; the tier that matters is RAM <-> flash), +CPU-only (RAM <-> flash). The same unit and the same verbs on every node; a node's tiers decide only where the bytes +sit. Flash holds a native generation (4.14 above), demoted on stop and bound on start: never dropped, never re-prefilled. + +**The object design: modules and classes (one class per file; what varies is an adapter behind a trait).** One +crate, `continuum-persona-engine` (the Serving module of the placement map, MODULE-ARCHITECTURE §9.2), over the +fork's C seam (safe wrappers in `core/llama`): + +``` +persona/ + unit.rs PersonaUnit owns the five parts below; moves only whole; refuses a partial move (typed) + blocks.rs ExecutionBlocks KV + recurrent rows + cell index (wraps llama_persona) + tokens.rs TokenHistory reserved ids + receipts (wraps llama_persona_tokens) + genome.rs GenomeState composed gene set + its generation; the adapters her decode binds + learning.rs LearningCustody in-flight passes, optimizer moments, checkpoints, pending examples + decode_state.rs DecodeState draft streams, sampler, recurrent rollback +residency/ + tier.rs trait Tier reserve / copy_in / copy_out / fence; one contract for every tier + device.rs DeviceTier VRAM (discrete) } adapters: only the calls that differ + host.rs HostTier pinned RAM } + unified.rs UnifiedTier one pool (the M5): bind or intra-pool copy + flash.rs FlashTier native generations on disk (header + extents) + profile.rs ResidencyProfile which tiers a node has (discrete / unified / cpu), from measurement +pipeline/ + roles.rs Roles active / next / retiring: each a slot holding one PersonaUnit + stager.rs Stager streams NEXT in, layer order, behind compute, per-layer fences + retirer.rs Retirer streams RETIRING out after the handoff fence + handoff.rs Handoff the millisecond bind: blocks + genome generation + decode state + fence.rs TransferFence completion of a transfer; readiness never exposed before it +schedule/ + next.rs trait NextPolicy who is next (pluggable, learnable: an OpenCV-style algorithm) +act/ + handle.rs ActHandle engine-owned operation; observers only observe + outcome.rs ActOutcome completed / interrupted / refused, recorded by request seq +engine.rs PersonaEngine the one owner: admit, act, stage, retire, shutdown (API above) +``` +Rules: no part of a persona is held anywhere else (a cycle's gene set, a learner's pass, a slot's KV are views of +the unit, never copies); tiers and policies are traits with one adapter per case, never `cfg` in the pipeline; each +class has its own test file of its contract (move-whole, refuse-partial, fence-before-ready, retire-after-handoff, +replay-returns-recorded-outcome). + +**The persona engine: our loop on libllama, replacing `llamacpp_scheduler` (2026-11-17; direction agreed by +Codex 20:57Z, API before integration, no serving switch yet).** llama-server's prompt loop assumes a task holds its +whole prompt (47 sites: prefix match, checkpoints, batching, context checks), so an append-only persona cannot live +inside it without rewriting it. `continuum-engine::inference::backends::llamacpp_scheduler` already drives libllama +in-process, but batches every sequence per decode and `memory_seq_rm`s a sequence on close: the opposite of 4.14. It +is replaced, not joined by a second scheduler. llama-server remains only the OpenAI adapter for external drivers +(line 16), calling the same owner. The typed API (Rust over the fork's C seam, bindgen'd through `core/llama`): + +```rust +/// One persona's execution state, owned once: native blocks + token history + receipts (fork #147). +pub struct Persona { raw: llama::PersonaHandle, id: PersonaId, epoch: Epoch, residency: Residency } +/// Where her blocks are, including in flight: the transfer owner holds the fences, so readiness is never exposed +/// before its fence, and active + next + retiring are each accounted while they overlap. +pub enum Residency { Active { stream: Stream }, Staging { stream: Stream, fence: TransferFence }, + Staged { stream: Stream }, Retiring { stream: Stream, fence: TransferFence }, Host, Flash } + +/// The one engine owner: one context, ONE mind decoding at a time, the next staged beside her. +pub struct PersonaEngine { ctx: llama::Context, personas: PersonaTable, active: Option, next: Option } + +pub struct Append<'a> { persona: PersonaId, epoch: Epoch, seq: RequestSeq, frontier: Frontier, + request: RequestId, delta: &'a [llama::Token] } +pub enum ActOutcome { Generated(Completion), Replayed(Completion), Refused(ActRefusal) } + +impl PersonaEngine { + /// Reserve her blocks, tokens and receipts under the aggregate admission owner (Codex's), once per epoch. + pub fn admit(&mut self, persona: PersonaId, epoch: Epoch, terms: AdmittedCapacity) -> Result<(), AdmitRefusal>; + /// Bind her (if staged/host), append the delta, decode ONLY it, sample to her stop; generated ids join her tail. + /// The operation is the engine's: its terminal outcome (completed, interrupted, refused) is recorded under her + /// request seq whatever any observer does; `ActStream` only observes it, and dropping it cancels nothing and + /// frees nothing. A replayed seq returns its recorded outcome and never decodes again. + pub fn act(&mut self, append: Append<'_>, terms: GenerationTerms) -> Result; + pub fn observe(&self, act: ActHandle) -> ActStream; + /// Stream the next persona's blocks into a free stream while the active one decodes (transfer, not decode). + pub fn stage(&mut self, next: PersonaId) -> Result; + /// Raw move of her blocks to host after the handoff fence; her token history moves with them by reference. + pub fn retire(&mut self, persona: PersonaId) -> RetireFence; + /// Publish every resident persona's native flash generation, then retire: computed state is never dropped. The + /// owner is retained through it: a failed publication is a retryable refusal that keeps the context, every + /// persona and the previous generation; nothing is freed by Drop while unsaved. + pub fn shutdown(&mut self) -> Result; +} +``` +Ownership and the conditions before production (Codex): a terminal completion retains her state (never +`seq_rm`); a cancelled observer never frees an active buffer; flash publication precedes retirement on shutdown; the +draft streams, recurrent rollback, sampler, genome and learning generation and their fences stay with the persona; a +request sequence's completion is recorded so its replay returns it; the external adapter calls the same owner. + +**Open questions (answered by measurement or prototype before code):** +1. **Nothing is sized at creation (Joel, 2026-11-18: "It shouldn't even take those stupid params. It's dynamic like + everything else").** No stream count, no per-stream KV size, no context length is passed in. A mind's blocks are + reserved from the governed memory pool as she appends and returned as she retires (a lease that grows and + shrinks with her, like every other resource), so her length is bounded only by memory, never by a creation + parameter. Where libllama today fixes `n_seq_max` or a stream's `kv_size` at context creation, the fork's persona + seam grows or replaces the allocation live; that seam is the work, not a number to choose. +2. (Merged into 1: no stream class, no cap from an allocation; measured against her real lengths, 4.9.1 F1: 50-93k.) +3. Whether ggml's attention view over one stream (the `sinfo.s0` offset) is already what the kernels read with no + per-cell indirection on Metal and CUDA (it appears so from `get_k`); confirm in the kernels. +4. The adapter (genome) binding per stream: today's per-request LoRA set on the context; it must switch with the + stream bind, not reload. +5. The MTP draft context: its own KV streams, moved with hers. + +**Later, and only if a node measures it worth it: a second core (Joel, 2026-11-18: "two minds in two lanes ... like two cores in a cpu ... maybe some machine can handle it? Or maybe it's always worse than one").** A `Core` is one active / next / retiring pipeline (`Roles`); the engine owns a list of them, one by default, and a mind decodes on exactly one core. A second core is never configured: the engine calibrates on its node (aggregate and per-mind tok/s, one core vs two, at real context lengths) and adds it only when aggregate throughput rises and each mind's act stays inside its budget. Expectation to test, not assume: a dense model with spare compute (the 5090) may gain, since two sequences share one read of the weights; an MoE on unified memory (the M5's 35B-A3B) likely never does, since the two minds' tokens hit different experts while their KV contends for the same bandwidth (four at once measured about 2 tok/s each vs about 80 for one). Nothing in `PersonaUnit`, `Tier` or the pipeline changes for it. + +**Evidence before implementation (Codex's condition):** a prototype that swaps a persona between a stream and RAM by +raw slice copies on the M5, measuring copy time per switch against bandwidth, the first-token latency of the arriving +persona with layer-ordered streaming, and byte-identical restore (her next-token logits equal before and after a +round trip); then the scaling read at 4, 8 and 16 personas. + +### 4.15 The engine is an object you submit to; its thread is a frame loop (2026-11-18) + +Joel, 2026-11-18: "Shit is usually you using locks and synchronous behavior... You have to design threading like any +easy to use object or interface so it's no effort." + +**What went wrong (the M5, Qwen3.6-35B-A3B, probe `persona.engine.turn`).** Slice 1 put residents on one in-process +engine and served turns with `for req in &requests { serve(req) }`: each turn ran whole on the engine thread (switch, the +full prefill, the full decode) before the next was read. The switch itself took 4-21 ms and one cold 11,834-token +prefill took 16.6 s (~711 tok/s, decode 34 tok/s; build 7b1b957917), yet turns took 300-360 s (build 88074d9300), +almost all of it waiting behind other minds' whole turns. A turn-sized critical section is a lock by another name. + +**The model: bgfx's, applied to minds** (`~/.continuum/reference/bgfx/src`): +- *Producers never touch the device.* bgfx records draws into encoders (one per thread, `bgfx.cpp:2947`; the only lock + allocates an encoder handle, none is held while recording) into the SUBMIT frame while the render thread executes the + RENDER frame (`bgfx_p.h:9083-9085`); `swap()` at the frame boundary is the handoff, signalled by two semaphores. +- *Priority is data.* Every draw carries a 64-bit sort key; the render thread sorts once per frame. +- *Waits are measured every frame* (`waitSubmit`, `waitRender`). + +**The interface (what a caller sees):** `engine.submit(turn)` returns at once with a handle (a token stream and a done +event; dropping it cancels the turn). The caller holds no lock and no permit, and awaits only its own handle. A mind is +one serial queue: her turns run in order; different minds' turns interleave. + +**The engine thread: one frame loop, the only toucher of the context.** Each frame: +1. *Swap:* drain new submissions without blocking (block on the queue only when no turn is left: a wake, never a poll). +2. *Pick:* one turn, by a pure policy (`frame::pick`): the active mind's answer in progress continues (one mind decodes + until she stops); otherwise the least prefill left, discounted by its wait (a short tail never waits behind a long + prompt; a long prompt ages to the front); ties keep the bound mind. +3. *Step:* bind her if another mind is bound (the 4.14 switch, milliseconds), then ONE step: a prefill chunk of the + batch size, or one token. A turn is a state machine on the mind (Waiting, Prefilling at a position, Decoding); her + blocks hold exactly what her turn has computed after each step, so any two steps may have another mind between them. +4. *Record* the step's cost into the turn's row (wait to first frame, switches, prefill, decode). + +**What stays true:** one mind decodes at a time (nothing here batches minds); a switch is the 4.14 bind; the sampler +samples only a turn's final prompt position. + +**Order:** +1. *Frame loop and the pure policy* (slice 1, `persona_scheduler/{driver,frame}.rs`, cd5bd406d0): whole-turn serving + deleted. Gate on the M5: no turn's wait to its first frame exceeds one chunk plus the answers in progress ahead of it. +2. *Tokenize and render off the engine thread:* the handle's submitter turns the prompt into token ids in its own + blocking pool; the engine receives ids only (4.14, "never process twice"). +3. *NEXT prefills while ACTIVE decodes* (4.13 point 2): a step may carry ACTIVE's token and NEXT's prefill chunk, sized + so ACTIVE's measured token time holds; this needs the tier to accept work for the staged stream. +4. *The class key* (4.1c: interactive, work, utility, background) in the submission, so `pick` orders by class before + cost; goal 9's scheduler owns `pick` from then on. + +### 4.16 A mind is one object; the engine holds her proxy (2026-11-19, design for review) + +Joel, 2026-11-19: "The synchronous addiction you hate is the opposite of graphics engines. Study unreal more carefully and +design an object based approach here not this confusing disjoint mess." + +**What 4.15 promised and the code still does instead** (branch `fable/residents-on-the-scheduler`, 7f67dc28d0): +- *The caller blocks.* `llamacpp_adapter.rs` `generate_text` parks an OS thread in `spawn_blocking` around + `generate_for_persona` until the whole turn is done, then receives the whole text. No handle and no token stream. +- *Her history is processed again every act.* The adapter renders her entire chat to text (`native_chat::render`), + renders it a second time without the generation prompt (`native_chat::stable_text`), and the engine thread tokenizes + both (`driver.rs` `admit`): about 47k tokens twice on the thread that decodes. The boundary is then rediscovered by + `reuse::common_prefix` and `reuse::choose` compares her whole history every frame. +- *Moves block the frame.* Gene paging (`ensure_adapter`) runs in the parked thread before the turn. A switch (`stage`, + `settle`, `handoff`, `finish_retirement`) copies blocks between frames on the engine thread (19-97 ms live, a6da599330). +- *One mind is in about six places:* the adapter's rendered text, `Turn`, the driver's `Mind`, its `parked` map, the + persona engine's `Roles`, the tier and the fork's blocks. Media takes a separate single-flight path that bypasses the + scheduler. The legacy lane vocabulary (`ServingPlan.lanes`: `planned_lanes=3` live against `n_seq_max=1`; 346 + references) plus `kv_page` (29 files) and served windows (24 files) still plan and page around all of it. + +**The model.** bgfx is read from its source (`~/.continuum/reference/bgfx/src`). Unreal's render threading is described +from its documented architecture: its source is not on this machine, so those points are not file:line receipts. +- *A game object and its render proxy (Unreal).* A `UPrimitiveComponent` lives on the game thread and owns gameplay state. + When registered, it creates an `FPrimitiveSceneProxy` that the render thread alone owns. The game thread never touches + the proxy: it enqueues commands (`ENQUEUE_RENDER_COMMAND`, a lambda that runs on the render thread), and it rarely + waits (`FRenderCommandFence`). No state is shared and no lock spans the threads. +- *Handles at once, work later (bgfx).* `createTexture` returns a handle immediately. The work lands in the SUBMIT frame's + `m_cmdPre` and runs at the start of a render frame; destruction lands in `m_cmdPost` (`renderFrame`, `bgfx.cpp:3430-3495`). + `Context::frame()` (`bgfx.cpp:2987`) waits only for the previous render frame, swaps `m_submit` and `m_render`, and + releases the render thread: one handoff per frame, two semaphores, no per-object lock. +- *Streaming with a budget (Nanite, documented).* Requests gathered during frame N are fetched asynchronously. Pages are + installed at a frame boundary within a per-frame budget, so a draw never waits on IO; a page that is not resident yet + draws at a coarser level. + +**The objects.** + +1. `Mind`: her handle, held by the persona (cheap to clone, `Send`). It owns her identity and epoch, her genes, and her + history as token ids, append-only within an epoch. Every method returns at once: + - `extend(items)`: her own task tokenizes only the appended items (the view's codec already appends keyed items + within an epoch, section 5), then enqueues `Append(ids)`. Nothing re-renders or re-tokenizes what she already sent. + - `answer(sampling, stop) -> Answer`: enqueues `Think` and returns an `Answer` handle (a token stream plus a done + event). Dropping it cancels. Her generated tokens become part of her history. + - `mark() -> Mark` and `rewind(mark)`: a named point in her history. The epoch's start is a mark, so a collapse is + `rewind(epoch_mark)` followed by `extend`, with nothing to rediscover. The engine keeps the checkpoint for a mark + (4.15's recurrent-rows checkpoint); `common_prefix` and the boundary render go away. + - `rest()`: a cooling hint. Dropping the last handle releases her proxy. +2. `MindProxy`: the engine thread's only record of her. It holds her ids, her marks' checkpoints, her pending commands, + her `Answer` senders, and her residency: `Bound` (in the context), `Warm` (native blocks in RAM), `Cold` (on disk). + It replaces `Turn`, `Mind`, `parked` and `Roles` with one table keyed by `PersonaId`. +3. `Engine`: one thread, the only toucher of the context. Each frame runs the phases of bgfx's `renderFrame`: + - *pre:* apply queued commands (create a proxy, append, mark, rewind, release), like `m_cmdPre`; + - *stream:* residency work within a measured per-frame budget (Nanite's install). NEXT's blocks are copied in and + PREVIOUS's out in chunks between ACTIVE's tokens, so a switch binds a stream that is already resident. Demotion to + disk and restore from disk go to an IO worker that returns a handle; + - *execute:* one step for the turn `frame::pick` chooses (a prefill chunk or one token); the policy stays the one + pure function; + - *post:* send tokens to their `Answer` streams, release retired proxies, and publish a double-buffered + `EngineSnapshot` (`watch`). The snapshot holds residency per mind, queue, rates and waits, and is the only thing + serving and the scheduler read. +4. `Answer`: the caller awaits a stream on its own task. No OS thread is parked per turn, and a reply can be read as it + arrives. + +**The engine is a dataflow graph of stages, on every core** (Joel, 2026-11-19: "My default was a separate thread and +data flow and so publish and subscribe to any data and react. Never your stupid locks and serial bs. We have 16 or more +cores!!! Use them all. You make it easy and reusable with good base objects abstraction and interfaces for free.") + +The base object already exists and the engine ignored it. `continuum-flow::Stage` is CBAR's `QueueThread` +(`cb-mobile-sdk/cpp/utility/Threads.h:109-212`; `continuum-flow/src/stage.rs:1`). A stage is its handler and nothing +else. It gets its own worker that wakes only on a push, one input in hand and one pending (CBAR's double buffer), +`Reliable` or `KeepNewest` overflow, and a QoS class. The same crate provides the per-owner serial queue and the aging +dispatcher (goal 9). CBAR's analyzer hub (`CBP_Analyzer.cpp` `addItem`) fans each frame out to every analyzer thread, +real-time ones inline and the rest on their own threads. The engine's graph is that hub for minds: + +| Stage | Input -> output | Runs on | Cores | +|---|---|---|---| +| `Tokenize` | a mind's appended items -> ids | the worker pool, one serial queue per mind (FIFO across clones, Codex) | many | +| `Prepare` | ids + her proxy's record -> a `PreparedTurn` (where she resumes: append, rewind to a mark, cold; the tokens to prefill) | the pool, once per turn, never per frame | many | +| `Residency` | promote, demote, restore requests -> blocks staged in host memory; disk reads and writes | its own worker; disk IO on the IO pool | 1-2 | +| `Engine` | prepared turns, staged blocks -> one step per frame (bind, prefill chunk, one token); logits | the one thread that touches the context | 1 + the GPU | +| `Sample` | logits handle -> token | its own worker, overlapped with the GPU's next prefill chunk for NEXT (below) | 1 | +| `Emit` | tokens -> pieces, stop and tool-call detection, `Answer` streams | its own worker | 1 | +| `Record` | step costs -> probe rows and the `EngineSnapshot` | its own worker, `KeepNewest` | 1 | + +Each stage publishes typed data and the next stage subscribes. Nothing is serialized onto the engine thread except what +needs the context itself: binding, the forward pass and the logits read. + +**Keeping the GPU fed (the 3 fps problem).** One mind's tokens are a true chain: her next forward pass needs the token +just sampled. Live, that chain runs decode, a full synchronize, sample, detokenize and send before the next decode +starts, so the GPU idles during every CPU step. Measured on the M5 (serving down, fork a58c3b4cf, the served GGUF and +its Q4_0 KV): `llama-bench` decodes 49.5 tok/s at 12k and 34.8 at 46k. Live at 7f67dc28d0 one mind decodes about +10 ms per token slower than that (26.2 tok/s at 47k). The graph removes the gap three ways: +1. *Off the chain.* Detokenize, stop and tool detection, `Answer` sends and probes leave the engine thread for `Emit` + and `Record`. The engine thread is left with forward, logits read and the sampler. e582fd2125 splits a turn's decode + time into forward, sample and the rest of the frame, so the size of each part is a receipt, not a guess. +2. *Fill the gaps.* While ACTIVE's token is being sampled, the GPU runs NEXT's next prefill chunk: GPU work never waits + for CPU work. This is the 4.13 overlap; still one mind decoding at a time, never two minds batched. +3. *More tokens per forward pass.* The MTP draft (`mtp-Qwen3.6-35B-A3B-Q4_0.gguf` is on the M5) proposes tokens that + one forward pass verifies (4.10). That is the only way past the chip's single-mind rate. + +**The GPU is never idle while anything could use it** (Joel, 2026-11-19: "Should be almost 2s between fully active GPU so +like 80% or more on all the time or we have failed... No wait for no apparent reason... Why would we ever have a wait?"). +The gate: GPU busy at least 80% of every window, and no idle gap over 2 s while any mind is resident. + +**Minds are active, not turn-takers** (Joel, 2026-11-19: "If one persona is for some reason waiting the other persona +should swap in but regardless I disagree with this philosophy. These are active minds not bottlenecked crap"). The +request/response shape is the defect: a mind that "submits a turn", waits for the whole answer, runs a tool, rebuilds her +view, renders, tokenizes and submits again has made herself the bottleneck, and a scheduler that fills her silences with +"background work" only papers over it. The model is a process on an OS: +- *A mind is always running.* Her thinking is one continuous stream in the engine (her `MindProxy`), not a series of + requests. Whatever she perceives (a message, a tool's output, a file she opened) is appended to that stream as it + arrives and prefilled then. Nothing waits for her to "ask". +- *She never blocks; she is a multi-activity mind* (Joel, 2026-11-19: "Blocking on io is dumb anyway. These are + multi activity mind. She should be wondering"). Each activity she holds (a card, a conversation, a review, her own + reflection) is a stream of her thinking with its own context; her identity and memory are the prefix they share + (`seq_cp`, never re-prefilled). `Emit` sees a tool call while she is still decoding and the tool starts then. Its + result is an event that lands in that activity's stream whenever it arrives. Meanwhile she goes on: in the same + activity (planning, anticipating what the result will show) or in another one (another card, a conversation, an open + question she is wondering about). "Waiting for a tool" is not a state she has. +- *The engine runs thinking, not turns.* Between her activities and other minds' activities the switch is the same 4.14 + bind, in milliseconds. Which stream runs next is the scheduler's pure policy (`frame::pick`, goal 9): what is + addressed to someone first, then what has new input, then what she chooses to pursue. There is no turn queue, and no + design state in which the engine idles while a resident is awake. +- *Learning is one of her activities.* Her in-place LoRA step on her own reviewed work (4.11.6) is something an active + mind does, scheduled like her other work; it does not wait for an idle node. +- *A restart is not a dark minute.* The engine comes up first and minds restore their blocks from disk (S4). + +Measured on the M5 at a990358854, from the turn rows (each turn's prefill, decode and switch time merged into busy spans): +from 01:42:00 to 01:49:20 the GPU was busy 74% of 440 s, with 18 idle gaps. The first was the 63.5 s boot, every mind +cold. Six were 3.0-6.9 s, at moments when no mind had work in the engine: today a mind runs request/response, taking +3.7 s at p50 (p90 181 s, 16 turns) from one answer's end to her next request, serially running her tool, rebuilding her +view, rendering, tokenizing and submitting. Twice the GPU waited on the same mind coming back. + +`Record` publishes the GPU's busy share and its longest idle gap every window in the snapshot. That is the gate, read +live, not reconstructed from rows afterwards. + +**Nothing waits on anything: it is all threads and handles** (Joel, 2026-11-19: "Never wait on anything. It's all threads +and handles"). Every operation returns a handle at once, and its completion is an event the next stage reacts to. That +holds for minds, stages and the engine thread itself: +- a mind's tool call, a tokenize, a disk restore and a learning step each return a handle; completion is published and + whoever consumes it reacts, as bgfx's `createTexture` hands back a handle whose work lands in a later frame; +- the engine thread never blocks on the GPU. Today it calls `synchronize()` after every token (`unified_tier.rs` `settle`, + plus a990358854's explicit `settle()`, added only to time the GPU and deleted in S1). Instead a forward pass returns a + fence. While it runs the thread encodes the next work it has: another stream's prefill chunk, a bind, a checkpoint. + The logits are read when the fence has signalled, and GPU time comes from the fence's timestamps, not from a blocking + call; +- no `spawn_blocking` held for a result, no `recv()` on a hot path, no `.await` on another stage's whole work, no lock + held across a seam. A stage that must react to a result subscribes to it. + +**Restore is the norm: a consumer of lifecycle, not a feature** (Joel, 2026-11-19: "Restore is supposed to be the norm. +Built into everything as a consumer of lifecycle. This is why we made everything objects"). Measured at 5b510543d5 on +the M5: right after a deploy the engine was busy 97% yet delivered 10.5 tok/s, because 102 s of a 271 s window went +to prefilling 62,873 tokens, most of them minds starting cold after the restart. A restart must demote, never drop: +- `Lifecycle` (continuum-persona-engine `persona/lifecycle.rs`) gains `resume` beside `suspend`, folded over a + persona's parts by the same macro. A parent's operation is its children's, in dependency order. +- A mind's `suspend` preserves each part: her blocks as raw rows (the fork's native layout, never re-serialized), her + token history, her marks' checkpoints. Her `resume` reads them back as a Cold mind; she binds when next scheduled. +- The engine's stop is the root `suspend`, fanned out to every mind (bound and parked); its start is the root `resume`. + A deploy is a stop and a start, with no restore path of its own. +- The fork gains block files: `llama_persona_write_file` / `llama_persona_read_file` (and the same for checkpoints) + write the rows and records the move already copies, and refuse on read when the owner, epoch or layout fingerprint + differs. Disk speed (GB/s), not the 8-13 s serialize the old `llama_state_seq_save_file` path measured. +- The directory is a tracked class with a decided eviction (`disk_reporters::standard_tracked_dirs`, + `disk_eviction`): a mind's files are hers, removed when she is released or her epoch ends. +Gate: after a deploy, no cold first act; delivered tok/s in the first window after boot within 10% of the window +before it. + +**The paradigms: every owner is built from these, and nothing else** (Joel, 2026-11-19: "formal architecture and reuse +of a solid and reused lifecycle is the only way to do it. This code would be ten times less and ten times faster if it +had consistent reuse of paradigms"). Each owner instantiates them; it never re-derives one. A change that hand-writes +what one of them does is the defect, whatever it measures. + +| Concern | The one paradigm | What it replaces (found on 11-19) | +|---|---|---| +| Threads, queues, backpressure | `continuum-flow` `Stage` (CBAR's `QueueThread`: own worker, declared depth, `handle_all`) and `Outbox` (producer never waits) | the driver's serial loop, `spawn_blocking` per turn, a hand backlog | +| A seam between owners | typed commands in, events out, one snapshot (`protocol.rs`) | whole-turn calls, text across seams, ad hoc channels | +| Being, stopping, coming back | `Lifecycle`: `prepare`, `suspend`, `resume`, `release`, typed `Preservation`; a parent's call is its children's, folded concurrently (Codex owns the kernel fold) | serial `SettleBeforeStop` participants, hand-ordered teardown (`SaveTimedOut`, `JoinTimedOut` on BigMama) | +| State that outlives a process | `continuum-saved-state` kinds (envelope, typed `Loaded`, contract compared by field; `ExternalBlob` for natively written bytes) | a hand manifest, checksum and atomic rename in `preserve.rs` (deleted) | +| What a node holds | `Footprint`, folded over children | a hand sum of tier and checkpoint bytes | +| What happened | `Record` (a stage) publishing probes and the snapshot | probes written on the hot thread, lost at boot and exit | + +Before an owner is written: name which of these it instantiates; search for the existing one; a missing capability is +added to the paradigm (the flow stage's depth, saved-state's `ExternalBlob`), never beside it. + +### 4.17 The engine as objects: the map every piece moves onto (2026-11-19, design for review) + +Joel, 2026-11-19: "I keep telling you to find patterns and design architecture stop writing slop"; "Idgaf the workload. +It must be done. This is going to be easier to keep track of and fast." An inventory of the engine path at a985d39b1a +(file:line receipts in the review thread) found each concept implemented many times: stop/suspend 7 ways, persona +identity 7 forms, engine configuration 7 structs that disagree (flash attention, fused GDN, sequence count), a turn's time +measured 6 times, where a mind is encoded 6 ways across 3 owners (`Driver.parked`, `Roles`, `UnifiedTier`), two whole +decode loops (text and media) with two sampler builders and stop handling in 4 places, two prefill planners, three +scheduling policies, two `Stage` traits, two `StopsOnExit`. It also found a resume doc claiming a checksum the code +does not check, and a static sender that keeps the driver from ever exiting. The map below is what each becomes. Every +row deletes the copies it names; nothing is added beside them. + +**Objects (each one owner; each built from 4.16's paradigms):** + +| Object | Owns, and nothing else does | Replaces | +|---|---|---| +| `MindId { persona: PersonaId, epoch: Epoch }` | a mind's identity, everywhere; the fork's 64-bit stamp is derived from it inside the tier only | raw `Uuid` (`persona_id: Option`, `PreservedMind`, `TurnRow`, `Uuid::nil()` sentinels), `FenceTag`'s and `Activity`'s persona+epoch pairs, the `Identified` trait, the String parse in the adapter | +| `Mind` (one table, `MindTable`, keyed by `MindId`) | her record (token history, basis, marks and their checkpoints) and her one `Place`: `Bound(stream)`, `Staged`, `Retiring`, `Warm` (native blocks in RAM), `Cold` (on disk) | `Driver.parked`, the driver's `Mind`, the tier's `Mind`, `Saved`, `Rebind`, protocol `Residency`, kv_quant `Residency`, the native token history that is never used on this path | +| `Roles` | which `MindId` is active, next, retiring (ids only, transitions only) | its own copies of the stage pre-checks in `engine.rs`, the two `present`s, the near-duplicate handoff/retire bodies (one transition function) | +| `Tier` (the adapter over the context) | the native moves, given a mind's blocks: bind, save, checkpoint, rewind, file write and read; stateless about who is where | `UnifiedTier.streams` and `minds` bookkeeping, its epoch checks repeated at six sites | +| `EngineConfig` (resolved once, by serving's owner) and `EngineGeometry` (what the context applied) | every setting a context is made with, and what it reported | `SchedulerConfig`, `LlamaCppConfig`'s engine fields, `LlamaCppLaunch`, the adapter's override fields, `Requested`, and the three contradicting values of flash attention, fused GDN and sequence count | +| `Answer` (protocol `AnswerId`, a token stream) | one answer's lifetime: tokens, stops, end, cancel | `AnswerSeq`, the backend's `block_on` collector with its 2 ms sleep-spin, `spawn_blocking` per turn, `Done.elapsed_ms` | +| `Emit` | stop sequences and the text of an answer, once | the backend's trailing trim, the media loop's stop check, the adapter's stop-list merge | +| One decode path | every turn, text or media (a media span is an `Extend`, 4.16) | `generate_with_media`'s own context, sampler builder and EOG/stop/max loop | +| `Prefill` decision (`reuse::choose`, marks per 4.16) | where a turn starts | `turn::plan` | +| `frame::pick` | which activity runs next (goal 9's scheduler owns it) | the unused `NextPolicy` | +| `Record` | every measurement of a step and a turn, derived from ONE span per step; occupancy; turn rows | `Spent` timed beside `Busy` from the same instants, the backend's tok/s log, the adapter's `inference.forward.text` and `generate.exit` tok/s, `report_footprint` twice per turn | +| `PreservedMinds` (saved-state kind) + blocks through saved-state's `ExternalBlob` medium | what outlives a restart, verified on load | the doc's unchecked checksum claim; the block file path helper becomes the medium | +| The engine as a `Lifecycle` node | `prepare` (start, resume minds), `suspend` (preserve minds), `release`; its children are its minds; folded by the kernel (Codex) | `EngineSettle`, the static `SUSPENDS` sender (the driver then exits on disconnect again), `Driver::suspend`'s own report type, the three refusal paths (one `stopping` state), both `StopsOnExit` (one, in continuum-flow) | +| One `Stage` base | kernel `StageRunner` and `continuum-flow::Stage` as one, adapters for the difference (Codex's lane) | two traits | + +**Step 1 in detail: the unit is the mind, and where she is is which container owns her.** `PersonaUnit` +(`persona/unit.rs`, "her five parts as one value; a move is whole by type") already exists and is unused; it becomes the +one value that travels: `blocks` (the native blocks, with whether they were saved from a stream), `tokens` (her +history), `genome` (her genes and their signature), `learning`, `decode` (her marks' checkpoints). Her place is not a +field kept in sync: she is in the warm table, or in `Roles` as next, active or retiring, or on disk (`PreservedMinds`). +- `MindId { persona, epoch }` replaces every persona+epoch pair: `FenceTag { mind, direction }`, + `Execute::submit(mind, ..)`, `checkpoint`/`rewind(mind, ..)`, `TierRefusal.mind`. +- `Tier` gets `type Blocks` and `begin(mind, &mut Blocks, direction)`: it moves the blocks it is handed and keeps only + which stream holds which `MindId` (context occupancy, which is its own state). `Roles` gains `retiring_mut` so the + engine hands the retiring unit's blocks to the copy-out. +- Deleted: the driver's `Mind` and `parked` (now the warm table of units), the tier's `Mind`, `minds` map, `Saved` (moves + into the blocks part) and `Rebind` (diagnostic only; the example measures from the blocks part). + +*Landed: 68d8bea7cf (2026-11-19). On the M5 through the guard, 04:56-05:01Z: 27 generate calls, 0 inference +failures, 6 resident acts, 0 llama-servers.* The tier's `minds` map and its `Mind` are gone, along with the driver's +`Mind` (now `PersonaUnit`), `PersonaEngine::forget` and `Tier::release`. `Saved` +moved into `Blocks`. One departure from the plan: `Rebind` stays as the tier's report of how the last bind met her +blocks, because the example's switch timings are measured by it. The `parked` table remains as the warm table of units. +There is no `retiring_mut`; `Roles::awaiting_copy_out_mut` hands the engine the unit whose copy-out begins. + +**The grid is one more tier (outlier B for this interface).** A mind is a value her blocks travel with, so moving her +to another node is `begin(mind, &mut blocks, direction)` on a tier whose transfer crosses the network. Its fence lands +when the peer has her blocks, and a refusal returns her whole, like a move between two streams on one context. +Grid compute is then the sum of each node's single-decoder engine. Before step 2 fixes the tier's shape, the grid +tier gets the replay Codex asked for (2026-11-19 04:51Z): the peer accepts her unit, its ACK is lost, the sender +retries, and the old completion arrives after the stream was reused. The two nodes must agree on one owner of her +decode. Pending evidence keeps her native bytes in custody, and a byte stream received alone never grants a second +decode authority. The replay tests that the fence and transfer identify her, whether or not two copies of her unit +could coexist. + +**Order (each step deploys on the M5 through the guard, read before the next; each deletes what its row names):** +1. `MindId` and the unit-as-mind: the driver's `parked`, the tier's minds/streams and `Saved`/`Rebind` collapse + into it; `Roles` keeps ids. Gate: the turn and switch rows unchanged in value, the three location owners gone. +2. `EngineConfig` / `EngineGeometry`: one resolution, every context built from it; the contradicting values gone. +3. `Answer` + `Emit` own stops and streams end to end: the backend collector, its sleep-spin and `spawn_blocking` gone; + the media path joins the one decode path (Codex reviews the media chunk descriptor). +4. `Record` from one span: the five other turn-time measurements gone. +5. Lifecycle node + `PreservedMinds` over `ExternalBlob`: on Codex's kernel fold; `EngineSettle` and `SUSPENDS` gone. +6. Prefill and scheduling policy: `turn::plan` and `NextPolicy` gone. + +**One base, not two.** `continuum-kernel::runtime::stage` (brain functions: provenance, publication, produced-once +artifacts) and `continuum-flow::Stage` (the queue thread) are two halves of one concept. Plan rule 5 applies: one owner +below both, adapters for the difference. Until then, the engine's stages are `continuum-flow` stages, and none +hand-writes a loop, a thread or a channel. + +**What crosses a stage boundary:** typed inputs (bounded, per owner, in order), `Answer` streams and the snapshot. No +lock is held across a seam, no permit stands for a lane, and nothing waits for a whole turn. + +**Media and genes are commands on the same object.** An image or audio item is an `extend` whose ids include the +projector's embedding positions, applied in *pre* like any append, so the single-flight bypass is deleted. Genes are +part of her basis: a change is a command, and the adapter pages in during *stream* under the same budget. + +**What it deletes.** The `spawn_blocking` forward path and the whole-text result; `native_chat::stable_text`, +`TurnPrompt` and the per-act full render and tokenize; `reuse::common_prefix` as the boundary finder (a `Mark` names +it); `Driver.parked`, `Turn` and `Roles` as separate owners of one mind; the media bypass; and, with Codex by crate +(serving, grid, governor to Codex; engine planning, persona, spawner to Fable), `ServingPlan.lanes`, `max_lanes`, +`lane_footprint`, `served_window_store` and `kv_page`. One `EngineConfig` window and one KV pool remain, which minds +page through. + +**Open question, answered before S2.** Chat templates may rewrite past turns (Qwen's templates are reported to drop +earlier turns' reasoning; to be verified against the GGUF's own template). If they do, an appended message can change +text before it. The rule then: `extend` renders from her last mark, and the template's rewrite region is what a mark +bounds. A probe counts every append whose render differs before its mark, so a rewrite is never silent. + +**Order: vertical slices, each deployed on the M5 and read for 15 minutes before the next.** +- *S1 `Emit`, `Record` and `Answer`.* The engine thread hands tokens to `Emit` and costs to `Record` + (`continuum-flow` stages); `submit` returns an `Answer` stream; `spawn_blocking` is deleted from the text path. Gate: + live decode within 10% of `llama-bench` at the same depth and KV type (today about 10 ms per token behind); no OS + thread parked per turn. +- *S2 `Mind`, `Tokenize`, `Prepare`, `MindProxy`.* `extend`, `answer`, `mark` and `rewind`; tokenizing and the reuse + decision run on the pool; the proxy table replaces `Turn`, `Mind`, `parked` and `Roles`. Gate: engine-thread time per + admitted turn near zero; prefill equals the appended tokens. +- *S3 `Residency`, `Sample` and the overlap.* NEXT is copied in, and NEXT's prefill chunks run, during ACTIVE's sample + steps. Gate: switch time on the critical path near zero; GPU idle between ACTIVE's tokens near zero. +- *S4 Cold tier and restore at boot.* A restart demotes and never drops. Gate: no cold first act after a deploy (live + 2026-11-19 00:56-01:00Z: four cold first acts, waits stacked to 155 s). +- *S5 Delete the legacy* (lanes, `kv_page`, served windows, the media bypass), split by crate with Codex. + +**The gate for the whole section** (Joel's targets, relayed by Codex 2026-11-19): delivered tokens per second over a +full 900 s of real resident work, swaps and waits included, at least 60 on the M5 and 200 on BigMama, with per-resident +progress and useful completion reported. Today one mind decodes at 26-32 tok/s on the M5 (a6da599330, no MTP draft), so +60 also needs the MTP draft (4.10) and prefill overlapped with decode (S3); one mind alone cannot reach it. + ## 5. A mind's context and the engine it runs on **Focus boundary:** [Focus contract](FOCUS-CONTRACT.md) defines one allocation,