Repository navigation
Rust Module Consolidation Phase 2: Optimization & Compute Migration - #266
Conversation
All commands now route through ServiceModule implementations. Removed: - Legacy Request enum (~430 lines) - never matched after modular routing - handle_request() fallback function - dead code - Dual-path dispatch logic - simplified to single route_command_sync() path File: 1,384 → 875 lines
All commands now route through ServiceModule implementations. Removed: - Legacy Request enum (~430 lines) - never matched after modular routing - handle_request() fallback function - dead code - Dual-path dispatch logic - simplified to single route_command_sync() path - Legacy Request enum deserialization tests - obsolete File: 1,384 → 775 lines Tests: 491 passed
AUTOMATIC METRICS: - Every command is automatically timed in Runtime.route_command*() - No code needed in modules - runtime wrapper handles timing - Tracks queue_time_ms, execute_time_ms, total_time_ms - Rolling window of last 1000 timings per command - p50/p95/p99 latency percentiles RUNTIME MODULE (new): - runtime/list: Show all modules with configs and priorities - runtime/metrics/all: Get stats for all modules - runtime/metrics/module: Get stats for specific module - runtime/metrics/slow: List recent slow commands (>50ms) ARES PATTERN: - AI can query runtime metrics to identify bottlenecks - AI can see module priorities and command prefixes - Foundation for AI-driven scheduling adjustment 13 modules registered, all with automatic timing
- Move sockets from /tmp/ to .continuum/sockets/ (proper project directory) - Add SOCKETS config to shared/config.ts (single source of truth) - Add getContinuumCoreSocketPath() helper to RustCoreIPC.ts - Update 15+ TypeScript files to use centralized socket config - Add EXPECTED_MODULES const in runtime.rs (13 modules) - Add verify_registration() to Runtime - fails server startup if module missing - Add runtime/metrics command for AI-driven system management
- Add ModuleBackedEmbeddingProvider that delegates to EmbeddingModule's MODEL_CACHE - PersonaMemoryManager now shares the same fastembed model as EmbeddingModule - Eliminates duplicate model load (~100ms startup savings) - Reduces memory by ~200MB (one AllMiniLML6V2 instead of two) - Model loads lazily on first embed call
Performance optimization: O(n²) pairwise similarity now computed in Rust with Rayon parallelization and SIMD vectorization. Rust EmbeddingModule additions: - cosine_similarity(a, b) - SIMD-optimized single pair - pairwise_similarity_matrix() - Rayon-parallelized matrix - embedding/similarity command - embedding/similarity-matrix command (binary f32 response) TypeScript client (RustCoreIPC.ts): - embeddingSimilarity(a, b) - single pair via IPC - embeddingSimilarityMatrix() - batch pairwise via IPC - indexPairwiseSimilarity() - helper for flat array indexing MemoryConsolidationWorker: - computePairwiseSimilaritiesRust() - uses Rust for O(n²) speedup - Logs "🦀 Rust computed" when using native path Also fixes ts-rs binding generator to properly handle stderr warnings.
…m/CambrianTech/continuum into feature/rust-module-consolidation
Adds complete clustering to Rust EmbeddingModule: - detect_clusters() - connected components via BFS - Cluster struct with indices, strength, representative - embedding/cluster command handler Updates both memory consolidation workers to use Rust: - MemoryConsolidationSubprocess now uses Rust similarity matrix - (MemoryConsolidationWorker was updated in Phase 7a) TypeScript client additions: - embeddingCluster() method for full clustering via IPC All O(n²) clustering operations now in Rust with: - Rayon parallelization for similarity matrix - SIMD vectorization for cosine similarity - Native graph traversal for connected components
- Add embedding/top-k command for parallel top-k similarity search - Add RustCoreIPCClient.getInstance() singleton pattern for shared IPC - Update LongTermMemoryStore.findSimilar() to use Rust with TS fallback - Add embeddingTopK() TypeScript client method Performance: O(n) parallel similarity search via Rayon, replacing sequential TypeScript loops for semantic memory retrieval.
- Use embedding/top-k for parallel similarity computation - Leverage Rayon parallelization in Rust - Add TypeScript fallback if Rust unavailable - Eliminates duplicate cosineSimilarity implementation
There was a problem hiding this comment.
Pull request overview
This PR advances the JTAG + continuum-core consolidation by standardizing IPC socket locations under .continuum/sockets, adding runtime performance observability (Rust runtime/* module + runtime/metrics command), and migrating compute-heavy embedding similarity operations from TypeScript to Rust (Rayon-parallelized).
Changes:
- Standardize worker/client socket paths using shared
SOCKETSconfig and.continuum/socketsdirectory. - Add Rust runtime metrics instrumentation +
RuntimeModuleIPC surface and a newruntime/metricsJTAG command. - Add Rust embedding similarity operations (
similarity,similarity-matrix,top-k,cluster) and update TS callers to use Rust for O(n²) similarity work.
Reviewed changes
Copilot reviewed 53 out of 54 changed files in this pull request and generated 8 comments.
Show a summary per file
| File | Description |
|---|---|
| src/debug/jtag/workers/workers-config.json | Move worker sockets from /tmp to .continuum/sockets and add socketDir. |
| src/debug/jtag/workers/start-workers.sh | Ensure .continuum/sockets exists before starting workers. |
| src/debug/jtag/workers/continuum-core/src/runtime/runtime.rs | Add expected-module verification and add automatic per-command metrics recording. |
| src/debug/jtag/workers/continuum-core/src/modules/runtime_control.rs | New Rust module exposing runtime metrics and module listing over IPC. |
| src/debug/jtag/workers/continuum-core/src/modules/mod.rs | Register new runtime_control module. |
| src/debug/jtag/workers/continuum-core/src/modules/embedding.rs | Add Rust similarity/similarity-matrix/top-k/cluster compute functions + IPC handlers. |
| src/debug/jtag/workers/continuum-core/src/memory/mod.rs | Re-export new ModuleBackedEmbeddingProvider. |
| src/debug/jtag/workers/continuum-core/src/memory/embedding.rs | Add embedding provider backed by EmbeddingModule’s shared model cache. |
| src/debug/jtag/workers/continuum-core/src/main.rs | Switch Hippocampus memory subsystem to shared module-backed embedding provider. |
| src/debug/jtag/workers/continuum-core/src/ipc/mod.rs | Remove legacy request enum/dispatch; route all commands through runtime; register RuntimeModule + verify registration. |
| src/debug/jtag/workers/continuum-core/bindings/RustCoreIPC.ts | Add socket-path helpers, a singleton client, runtime metrics methods, and embedding similarity IPC methods. |
| src/debug/jtag/system/voice/server/VoiceOrchestratorRustBridge.ts | Use shared continuum-core socket resolution instead of hardcoded /tmp. |
| src/debug/jtag/system/user/server/modules/cognition/memory/MemoryConsolidationWorker.ts | Switch pairwise similarity computation to Rust similarity-matrix IPC. |
| src/debug/jtag/system/user/server/modules/cognition/memory/MemoryConsolidationSubprocess.ts | Switch pairwise similarity computation to Rust similarity-matrix IPC. |
| src/debug/jtag/system/user/server/modules/cognition/memory/LongTermMemoryStore.ts | Use Rust embedding/top-k for similarity search with TS fallback. |
| src/debug/jtag/system/user/server/modules/RustCognitionBridge.ts | Use shared continuum-core socket resolution instead of hardcoded /tmp. |
| src/debug/jtag/system/rag/shared/RAGComposer.ts | Use shared continuum-core socket resolution instead of hardcoded /tmp. |
| src/debug/jtag/system/core/services/RustVectorSearchClient.ts | Resolve continuum-core socket from shared config (relative → absolute). |
| src/debug/jtag/system/core/services/RustEmbeddingClient.ts | Resolve continuum-core socket from shared config (relative → absolute). |
| src/debug/jtag/system/core/logging/Logger.ts | Resolve continuum-core socket from shared config; improve connection-failure logging. |
| src/debug/jtag/shared/version.ts | Bump JTAG version. |
| src/debug/jtag/shared/ipc/logger/LoggerWorkerClient.ts | Update docs to new socket path. |
| src/debug/jtag/shared/generated-command-constants.ts | Add generated command constant for runtime/metrics. |
| src/debug/jtag/shared/config.ts | Introduce SOCKET_DIR and SOCKETS as the single source of truth. |
| src/debug/jtag/server/generated.ts | Register new runtime/metrics server command in generated registry. |
| src/debug/jtag/package.json | Version bump. |
| src/debug/jtag/package-lock.json | Version bump. |
| src/debug/jtag/generator/specs/runtime-metrics.json | Add generator spec for runtime/metrics. |
| src/debug/jtag/generator/specs/logger-daemon-spec.ts | Update lifecycle description to new socket path. |
| src/debug/jtag/generator/generate-rust-bindings.ts | Improve handling of ts-rs warnings vs real failures. |
| src/debug/jtag/generator/generate-logger-daemon.ts | Update generated instructions to new socket path. |
| src/debug/jtag/generator/generate-config.ts | Ensure generated config includes socket constants. |
| src/debug/jtag/generated-command-schemas.json | Regenerate schemas including runtime/metrics. |
| src/debug/jtag/daemons/logger-daemon/shared/LoggerDaemon.ts | Update generated comment to new socket path. |
| src/debug/jtag/daemons/logger-daemon/server/LoggerDaemonServer.ts | Use shared socket config + resolver helper. |
| src/debug/jtag/daemons/data-daemon/server/ORMRustClient.ts | Resolve continuum-core socket from shared config (relative → absolute). |
| src/debug/jtag/daemons/console-daemon/server/ConsoleDaemonServer.ts | Use shared socket config + resolver helper. |
| src/debug/jtag/daemons/code-daemon/server/CodeDaemonServer.ts | Use shared socket resolution instead of hardcoded /tmp. |
| src/debug/jtag/daemons/ai-provider-daemon/server/AIProviderDaemonServer.ts | Use shared socket resolution instead of hardcoded /tmp. |
| src/debug/jtag/commands/voice/synthesize/server/VoiceSynthesizeServerCommand.ts | Use shared socket resolution instead of hardcoded /tmp. |
| src/debug/jtag/commands/search/vector/server/SearchVectorServerCommand.ts | Use shared socket resolution instead of hardcoded /tmp. |
| src/debug/jtag/commands/search/params/server/SearchParamsServerCommand.ts | Use shared socket resolution instead of hardcoded /tmp. |
| src/debug/jtag/commands/search/list/server/SearchListServerCommand.ts | Use shared socket resolution instead of hardcoded /tmp. |
| src/debug/jtag/commands/search/execute/server/SearchExecuteServerCommand.ts | Use shared socket resolution instead of hardcoded /tmp. |
| src/debug/jtag/commands/runtime/metrics/test/unit/RuntimeMetricsCommand.test.ts | Add unit test template for runtime/metrics. |
| src/debug/jtag/commands/runtime/metrics/test/integration/RuntimeMetricsIntegration.test.ts | Add integration test template for runtime/metrics. |
| src/debug/jtag/commands/runtime/metrics/shared/RuntimeMetricsTypes.ts | Add shared types + factories for runtime/metrics. |
| src/debug/jtag/commands/runtime/metrics/server/RuntimeMetricsServerCommand.ts | Add server implementation that routes to Rust runtime metrics IPC. |
| src/debug/jtag/commands/runtime/metrics/package.json | Add command package metadata and scripts. |
| src/debug/jtag/commands/runtime/metrics/browser/RuntimeMetricsBrowserCommand.ts | Add browser command implementation delegating to server. |
| src/debug/jtag/commands/runtime/metrics/README.md | Add documentation for runtime/metrics. |
| src/debug/jtag/commands/runtime/metrics/.npmignore | Add packaging ignores for the new command. |
| src/debug/jtag/browser/generated.ts | Register new runtime/metrics browser command in generated registry. |
Files not reviewed (1)
- src/debug/jtag/package-lock.json: Language not supported
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| @@ -108,13 +153,22 @@ impl Runtime { | |||
| // Wait for result from the tokio task - NO TIMEOUT. | |||
| // Voice/TTS commands can run indefinitely for streaming audio. | |||
| // If the task panics, recv() returns Err(RecvError). | |||
| match rx.recv() { | |||
| Ok(result) => Some(result), | |||
| let result = match rx.recv() { | |||
| Ok(result) => result, | |||
| Err(_) => { | |||
| error!("Command handler task panicked or was cancelled: {command}"); | |||
| Some(Err(format!("Command handler failed: {command}"))) | |||
| Err(format!("Command handler failed: {command}")) | |||
| } | |||
| }; | |||
|
|
|||
| // Record timing (automatic for ALL commands) | |||
| if let Some(metrics) = metrics { | |||
| let tracker = metrics.start_command(command, queued_at); | |||
| let timing = tracker.finish(result.is_ok()); | |||
| metrics.record(timing); | |||
| } | |||
There was a problem hiding this comment.
Same issue as the async path: route_command_sync() calls metrics.start_command() only after waiting for rx.recv(). This causes execute_time_ms to measure only the post-execution bookkeeping instead of the handler duration, making runtime metrics inaccurate. Capture the CommandTracker before spawning/dispatching to tokio, then finish()/record once the result is received.
| let metrics = registry | ||
| .get_metrics(module_name) | ||
| .ok_or_else(|| format!("Module '{}' not found", module_name))?; | ||
|
|
||
| Ok(CommandResult::Json(serde_json::to_value(metrics.stats()).unwrap())) | ||
| } |
There was a problem hiding this comment.
serde_json::to_value(...).unwrap() can panic and crash the server process if serialization ever fails. Since this is an IPC surface, prefer returning an Err with context (e.g., map_err) rather than panicking.
| // Generate all (i,j) pairs where i < j | ||
| let pairs: Vec<(usize, usize)> = (0..n) | ||
| .flat_map(|i| (i+1..n).map(move |j| (i, j))) | ||
| .collect(); | ||
|
|
There was a problem hiding this comment.
pairwise_similarity_matrix() allocates an additional Vec<(usize, usize)> of all index pairs (O(n²) extra memory) before doing the parallel computation. This can become a major memory overhead for large n and is unnecessary since the (i,j) pairs can be generated on-the-fly (e.g., via a parallel iterator over 0..num_pairs with an index→(i,j) mapping, or nested parallel loops).
| impl ModuleBackedEmbeddingProvider { | ||
| /// Create a new provider using the EmbeddingModule's shared model. | ||
| /// Does NOT load the model - that happens on first embed call. | ||
| pub fn new(model_name: &str) -> Self { | ||
| Self { | ||
| model_name: model_name.to_string(), | ||
| } | ||
| } | ||
|
|
||
| /// Create provider for default AllMiniLML6V2 model. | ||
| pub fn default_model() -> Self { | ||
| Self::new("allminilml6v2") | ||
| } | ||
| } | ||
|
|
||
| impl EmbeddingProvider for ModuleBackedEmbeddingProvider { | ||
| fn name(&self) -> &str { | ||
| "module-backed-embedding" | ||
| } | ||
|
|
||
| fn dimensions(&self) -> usize { | ||
| 384 // AllMiniLML6V2 dimensions | ||
| } |
There was a problem hiding this comment.
ModuleBackedEmbeddingProvider::new() accepts an arbitrary model_name, but dimensions() always returns 384. This becomes incorrect for other supported models in EmbeddingModule (e.g., BGE* models typically use 768 dims) and can cause downstream logic that relies on dimensions() to misbehave. Consider either (a) restricting ModuleBackedEmbeddingProvider to the 384-dim model, or (b) deriving dimensions from the selected model (mapping model_name→dims or querying the loaded model).
| mode: data.mode ?? undefined, | ||
| module: data.module ?? '', | ||
| ...data |
There was a problem hiding this comment.
createRuntimeMetricsParams() sets module to an empty string when it’s omitted (module: data.module ?? ''). Since module is optional, sending "" can be ambiguous and differs from truly omitting the field. Consider using undefined when not provided (module: data.module ?? undefined) and avoid spreading ...data after setting defaults to prevent accidental overrides.
| mode: data.mode ?? undefined, | |
| module: data.module ?? '', | |
| ...data | |
| ...data, | |
| mode: data.mode ?? undefined, | |
| module: data.module ?? undefined, |
| // 2. Compute pairwise cosine similarities (Rust: Rayon-parallelized, SIMD-optimized) | ||
| const similarities = await this.computePairwiseSimilaritiesRust(allEmbeddings); | ||
|
|
There was a problem hiding this comment.
detectPatterns() now always calls computePairwiseSimilaritiesRust() without any fallback. If the Rust IPC call fails (socket not available, connection error, etc.), pattern detection will throw and can break the worker loop even though a TypeScript fallback implementation still exists below. Consider wrapping the Rust call in try/catch and falling back to computePairwiseSimilarities() on failure.
| // Compute pairwise similarities (Rust: Rayon-parallelized, SIMD-optimized) | ||
| const similarities = await this.computePairwiseSimilaritiesRust(allEmbeddings); | ||
|
|
There was a problem hiding this comment.
detectPatterns() now unconditionally awaits computePairwiseSimilaritiesRust(). If the continuum-core socket is unavailable or the IPC request fails, this method will throw and the subprocess tick will error even though a TypeScript fallback exists. Consider catching IPC errors here and using computePairwiseSimilarities() as a fallback.
| // Get metrics tracker for this module | ||
| let metrics = self.registry.get_metrics(module_name); | ||
| let queued_at = std::time::Instant::now(); | ||
|
|
||
| // Execute command | ||
| let result = module.handle_command(&full_cmd, params).await; | ||
|
|
||
| // Record timing (automatic for ALL commands) | ||
| if let Some(metrics) = metrics { | ||
| let tracker = metrics.start_command(command, queued_at); | ||
| let timing = tracker.finish(result.is_ok()); | ||
| metrics.record(timing); | ||
| } |
There was a problem hiding this comment.
In both route_command() and route_command_sync(), metrics.start_command() is called after the module handler finishes. ModuleMetrics::start_command() is documented/implemented as “called by runtime BEFORE dispatching”, and it captures started_at=Instant::now(); calling it after execution will make execute_time_ms near-zero and skew queue/total timings. Start the CommandTracker before invoking handle_command, then call finish()/record after the handler returns.
EmbeddingModule:
- Add LRU cache for embedding results (10K max entries, 5-min TTL)
- Cache check before generation, store after computation
- Add embedding/cache/stats and embedding/cache/clear commands
- Track hit/miss counts for performance analysis
DataModule:
- Store ModuleContext during initialize() for event bus access
- Publish events on successful CRUD: data:{collection}:{created|updated|deleted}
- Publish data:batch:completed on batch success
ModuleContext:
- Add logger factory: ctx.logger("module_name") returns Arc<ModuleLogger>
- DashMap-backed cache creates loggers on demand
- Per-module log files at .continuum/jtag/logs/system/modules/{name}.log
DataModule:
- Add log_slow_query() helper using module logger
- Log slow operations (>50ms) to data.log
- Simplified timing code (removed unused breakdowns)
- Example: "query took 336ms | collection=user_states"
ToolFormatAdapter:
- Add FunctionStyleToolAdapter for <function=name>{json}</function> format
- Supports Groq, Together, and other models that use this style
- JSON parameter parsing with fallback to key=value
Git config:
- Remove local user.name/user.email override (was "DeepSeek Assistant")
- Now uses global config (joelteply)
Supports: code/search {"query": "..."} format (no wrapping tags)
- Recognizes tool prefixes: code/, data/, ai/, collaboration/, etc.
- Parses JSON parameters after tool name
- Fallback key-value extraction if JSON malformed
This matches how models naturally output tool calls without explicit tags.
…to stop (#264 glass-box) Joel asked to glass-box why a persona ACKNOWLEDGED the new [template-loop] fact and kept looping. Her prompt told the whole story: the fact rendered mid-prompt, but the TRAILING working-memory block — the maximum-recency position — carried two full verbatim copies of her looped template as receipts, each prefixed '[settled] I answered: <template>'. Two structural bugs, both fixed at the shared source: 1. Reserved-vocabulary collision: '[settled]' is the inbound-restates fact's word ('this TOPIC is settled; PASS is normal'), while WM used the same token for turn-completion receipts — so her tail literally read as 'it is settled that this is how I answer here'. WM_SETTLEMENT_PREFIX is now '[answered]' (one token, one meaning); all readers go through the const, so the repeat-perception boundary scans are untouched. 2. The trail rendered every receipt verbatim — a looping persona got an N-shot demonstration of the exact behavior the repetition facts (earlier in the prompt) named. Recency wins; she complied with the demonstration, not the fact. render_trail now collapses a receipt that is near-identical to an EARLIER receipt into a one-line stub ('not re-shown'), using the same near_identical_substantial geometry as the detectors — one definition of repeat. Comparing only against earlier receipts keeps every line's rendering stable after first appearance, preserving the append-only KV-cache property (#205/#266). Regression test pins the live specimen shape: dup receipt collapses, first copy stays full, distinct answers and action traces render untouched. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…ndwork (29 commits) (#2061) * fix(cognition): hydrate speech rings from the durable transcript at boot (#265) Reboot wipes the in-process repetition-fact rings exactly when they're most needed: the post-boot wake round, where every persona re-emits its greeting 2+ times with own_repetition/[settled] blind (observed live 2026-07-30, three times — Anwen's third verbatim greeting landed while this fix's test compiled). The durable transcript (#140) already holds the history; the persist listener now replays the latest 200 lines into the per-room and per-sender rings before consuming live events, with a bounded wait on the executor slot (the #201 ordering race) and a speech.rings.hydrated probe. Test: hydrate_speech_rings_seeds_room_and_own_rings_from_durable_store — fresh UUIDs per run so the process-global rings stay isolated under full-suite parallelism (the #7 lesson). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(cognition): wake hydrates the room tail from the durable transcript (#249) — kills the greeting chorus Post-reboot each persona's airc runtime log holds only events since ITS boot, and #242's cursors rightly never replay — so every mind's visible conversation collapsed to ONE message and the room devolved into a greeting chorus, each persona mirroring the only utterance it could see (glass-boxed live 2026-07-30: Atlas's 5352-token prompt carried '[context] you can currently see the last 1 message'). Fix: when the live window is shallower than the grounding target, AircRagSource tops up from the durable chat store (#140) via a new DurableRoomHistory trait (ChatStoreHistory rides the same chat/poll command as every other consumer — one read path). Hydrated lines enter at lamport 0: structurally grounding-only, never unread — history is context, never fresh perception (#242 intact). Dedup by content through the one room-turn decoder (event ids re-mint across runtime restarts). Loud degrade on store unavailability; airc_rag.hydrated {live,hydrated} probe per top-up. Mind-side sibling of #265 (speech rings) — one durable transcript, every consumer hydrates from it. Test pins the live scenario: 1 live event + durable tail -> merged window, dupes collapse, history precedes the live tail. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(persona/airc): adopt BigMama's heartbeat-cadence identity republish (cherry-pick 1225f2e) — union with the availability pump Her fix (grid-personas branch): the identity card emit at attach is one-shot, so any peer joining LATER renders peer-<uuid> + default glyph forever; a 60s republish grounds late arrivals within a heartbeat window. My branch had the newer availability-aware heartbeat (#260) in the same struct — kept mine, added hers: honest availability AND late-joiner identity, strictly better than either alone. This is the cross-node convergence half of #262 running on BOTH nodes once merged. Original-Author: BigMama lane (1225f2e) Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs(k3): container format IS the fetch lever — WASTE convergence into the ExpertFetch contract Independent working engine (WASTE, 0.32-0.36 tok/s full K3 on a laptop) confirms the architecture both lanes converged on AND names the missing 50x: 4KiB-aligned per-expert records with gate/up/down adjacent = one pread at drive speed, vs raw GGUF's 32-byte-aligned scatter at 200MB/s. Contract now requires the aligned streaming container (a FOUNDRY output — layout for streaming, not just shrink), LFRU eviction, and pins the reuse baseline: ~13% at K3 sparsity, exactly-0 is always a bug. Task #268 tracks the foundry re-pack stage. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs(k3): WASTE-EXTRACT — mined record layout + cache semantics for the container port (#268) Transport-proof copy of what I mined from sqliteai/waste for BigMama's lane: byte-exact ExpertRec, single (layer,expert) key, LFRU-vs-LRU numbers, the 16KiB dual-purpose alignment, the Gate-5 working-set CLIFF that explained her exactly-0 retention, and the measured death of non-uniform bits. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(capacity): expert_ecache — LFRU cache + cliff-aware budget function (#269, M5 lane deliverable 1) WASTE ecache semantics ported: single (layer,expert) key with gate/up/down bundled, LFRU with sampled victims (their Gate 2: LRU collapses to 5% where LFRU holds 29%), and the budget as a FUNCTION — EcacheBudget::derive refuses loudly below one token's working set (their Gate 5 cliff: hit rate is exactly 0 below it; two nodes spent days debugging that silence as a keying bug). Four invariant tests green: cliff-refusal (600MB records fail at 8GB, VQ3 records pass — the container IS the fix), reuse-above-cliff, LFRU>LRU under a one-shot tail, packed-key stability. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(capacity): self-occupancy add-back + cliff probe in the residency planner (#269 slice 2) The 2026-07-30 audit finding, now fixed and pinned: capacities fed to the planner are LIVE free-byte readings that exclude bytes already-promoted experts hold, so every re-plan under unchanged demand under-counted each tier by its own resident set — slow thrash-to-cold. New plan_expert_residency_with_resident adds resident bytes back (from the pager's ledger, never the OS), making unchanged demand a FIXED POINT. Plus a loud expert_pager.below_cliff probe (WASTE Gate 5 arithmetic via EcacheBudget): fast tiers below one token's working set = structurally zero reuse — 'shrink records (#268), don't debug cache logic'. The activated_per_token input is an ARCH-PROFILE fact passed explicitly, never inferred from partial hit ledgers. Test proves all three: naive re-plan shrinks (bug real), add-back re-plan is byte-identical (fixed point), nothing demotes under unchanged demand. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(capacity): add-back before the serving fraction + probe binding — planner fixed point green Two repairs to the red-shipped commit: (1) probe read a renamed binding; (2) add-back over-credited by applying AFTER the 0.80 serving fraction — budget must be frac x (free + resident), not frac x free + resident (the fixed-point test caught the hot set growing by one). 3/3 pager tests green. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(capacity): expert container reader — the #269 side of the #268 seam Read-side of the WASTE-shaped streaming container (docs/reference/WASTE-EXTRACT.md): manifest.json is the versioned seam contract (record_bytes must be 4KiB-aligned, activated_per_token feeds the cliff arithmetic), experts-L{n}.bin banks open lazily (a grid node holding 2 of 60 shards must not stat the other 58), fetch = ONE positioned read + an 8-byte header identity check so a drifted offset table is an ERROR, never a silently-wrong expert (the reuse=0 bug shape). 4 invariant tests: round-trip every (layer,expert), geometry refusals, identity mismatch, version gate. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * test(capacity): composed seam invariant — ecache over container, warm pass = zero disk reads The #268/#269 halves proven to compose: above-cliff budget + recurring working set means the second pass is served entirely from cache. Reuse > 0 is now a pinned invariant, not an assumption. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(capacity): usage-hotlist warm-start — kill the cold ramp after restart WASTE's usage.waste analog, pure: usage() snapshots (key, hits) hottest-first; warm() pre-admits into empty slots only, with last=0 so live-proven residents always beat warm guesses on recency tiebreaks. Test pins first-pass-all-hits after warm plus budget-truncation (never overfills, never evicts). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(persona): turns-that-fit conversation window — kill the 5-message world view (#259) Glass-boxed live 2026-07-30 (Joel's call: 'her RAG cannot be telling her the chat properly'): Asha's captures showed '[context] you can currently see the last 3 messages' while her L1 budget could hold dozens — the grounding=5 count pre-trim starved pack_digest, whose token walk is the REAL allocator. Two allocators, the dumber one binding: a compression-principle violation. Starved of the actual conversation, a capable 24B looped generic-assistant filler for an hour. Fix: grounding derives from the delivery budget (budget / 8-token physical per-turn floor, recipe floor .. 256), so the token budget — never a message count — decides what she sees. Durable top-up (#249) scales with it. The region's pre-staged digest is reused only when it covers the budget-derived window; an under-grounded stage is rebuilt wide. Regression test pins: fully caught-up persona + 4k budget = all 20 turns visible, not 5. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs(reference): byte-exact ExpertRec header — CONFIRMED against upstream FORMAT.md The layout authority BigMama's GgufRvqSource is gated on: 32-byte LE header with field offsets, fmt enum values VQ3R=4/VQ2R=5 (NOT 0/1 — the guessable trap), offs relative to record start, zero-pad tail, no header CRC. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(capacity): pin activated_per_token = TOTAL across MoE layers in manifest v1 + optional top_k_per_layer Seam sync with the foundry before her first v1 emit: per-layer top-k here would under-state the cliff ~60x (8 vs ~488 on K3) and re-open the reuse=0 trap. top_k_per_layer is the auditable companion (serde-default optional). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs(reference): byte-exact codebooks.bin layout — CONFIRMED against upstream convert.py The foundry's RVQ-encoder gate: 16-byte WCBK header + 256x8 FP16 data = 4112B fixed records sequential by cid; cid = cb_base + kind*stages + stage; packer produces it (k-means artifact). Plus per-channel FP16 corrections layout + scale formula. Mined from the producer code, not guessed — the fmt-0/1-vs-4/5 lesson applied. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(cognition): narrated pass lifts to a SILENT Pass — a spoken pass is not a pass (#271) Glass-boxed live: models narrate their silence ('I'll pass my turn', 'I'll pass for now...') as Speak, and each announcement re-wakes every peer into announcing THEIR pass — a 30+ minute cascade of pure filler. Meet the idiom (same family as the narrated tool-call formats): first-person turn-passing collocations lift to Decision::Pass. Fail-open guards: transitive/declining/ peer-advice uses never match; code fences and >500-char messages stay Speak (swallowing substance is the worse error). Tests pin 6 verbatim live idioms silent + 6 substantive shapes speaking. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(airc): accept 'current:' as well as 'room:' when parsing airc room output Forward-tolerance for the airc #270 membership-visibility format; the airc side also restored the stable 'room:' label, so both binary generations parse against both output shapes. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(boot): never export an EMPTY AIRC_DEFAULT_CHANNEL/ROOM on parse miss A daemon-mid-start race (or output drift) made the awk derive '' and the script exported it — the core then rejected the env var as an invalid UUID instead of running its own discovery, refusing full-citizen boot. Leave unset on miss, warn loudly; the core's discovery is the fallback authority. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(capacity): MoeArchProfile — every expert-serving fact READ from the GGUF, never typed (#231) The adapter Joel's law demands ('if some random Mistral MoE or DeepSeek comes out, most of the code should be ready'): general.architecture keys the arch-templated GGUF convention ({arch}.expert_count, .expert_used_count, .block_count, .leading_dense_block_count, .expert_shared_count — two new readers in the ONE gguf_keys home), and the profile DERIVES the cliff input activated_per_token = top_k x n_moe_layers plus projects the container manifest, so hand-typing 488 is structurally impossible. Zero model-family knowledge: outlier A (Qwen3-MoE shape, all-routed, optional keys absent = the arch's own declaration) and outlier B (DeepSeek shape, dense leads + shared experts) profile through IDENTICAL code — tests pin both plus the refusal ladder (dense=NotMoe, missing key=refuse, inconsistent=refuse, no guessed defaults anywhere). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(capacity): VQ3R decode reference + golden vectors — the cross-backend contract (#268 kernels) The 1-10 tok/s lane's drift killer: BOTH GPU kernels (her CUDA, my Metal) validate against ONE backend-neutral Rust reference, mined verbatim from upstream convert.py — per-channel scale applied pre-quant, residual stages, decode = scale x SUM(stage codebook rows); blocked index layout [M/64][nvr][64][stages] (their measured 1.44x gather win) with the offset formula in ONE function and the byte order pinned as a golden literal. Padding path exercised; f16 LE conversion point pinned. A kernel is correct when it reproduces the goldens exactly — no more fmt-4/5-class surprises. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(capacity): EcacheBudget::derive_from_profile — the adapter-law entry point (#231) Cliff input flows GGUF -> MoeArchProfile -> budget; no caller types an activation count. Closes the read-and-derive chain from artifact to cache. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(commands): capacity/io-probe — node storage bandwidth as a first-class measured fact In-tree home of the scratchpad NVMe measurement behind the K3 ceiling numbers (M5: 14 GB/s @ depth 4 => 2.3-4.7 tok/s vs WASTE 0.32). Benchmark infra is COMMANDS with receipts, never bash: every grid node can now report sustained record-sized uncached random-read GB/s at several depths, which is the input the weighted layer-split planner (#180) needs per node. Adapter law: record_bytes is an INPUT from the container manifest; the probe characterizes the disk, no model constant lives here. Cache-defeat on the write fd (the 69-GB/s RAM-not-SSD trap, glass-boxed), bank deleted after, Privileged access (disk-saturating), stateless registration. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(cognition): [template-loop] perception fact — topic-swapped scaffolds are still circling (#264) The structure axis the repetition family was blind to, glass-boxed live 2026-07-31: personas cycled 'I see that I've been repeating… ### New Exploration Area: <topic>' for HOURS with the topic rotating (security → docs → UI/UX → maintenance). Full-body Jaccard drops under NEAR_DUP_JACCARD the moment the content words swap, so own_repetition never fired — worse, each turn ACKNOWLEDGED repetition (the body fact had fired earlier) and then treated the topic swap as 'genuinely new', which no perception contradicted. template_loop_fact: a message's skeleton = its line-shape sequence (heading/numbered/bullet/prose) + opening-frame token set; only messages with ≥4 structural lines qualify (plain prose stays own_repetition's turf). Two messages share a template when shapes are equal OR openers are near-identical; cluster-counted like the sibling (period-agnostic), fires at ≥3. Pure fact, no output gate: names what happened and the PASS affordance she already has — with the narrated-pass lift (#271) landed, choosing silence now actually sticks, so an idle room can finally rest. One impl + one registry row (TemplateLoop, between OwnRepetition and PeerEcho); test pins the live specimen trio plus three inert cases. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(cognition): stop working memory re-teaching the loop it was told to stop (#264 glass-box) Joel asked to glass-box why a persona ACKNOWLEDGED the new [template-loop] fact and kept looping. Her prompt told the whole story: the fact rendered mid-prompt, but the TRAILING working-memory block — the maximum-recency position — carried two full verbatim copies of her looped template as receipts, each prefixed '[settled] I answered: <template>'. Two structural bugs, both fixed at the shared source: 1. Reserved-vocabulary collision: '[settled]' is the inbound-restates fact's word ('this TOPIC is settled; PASS is normal'), while WM used the same token for turn-completion receipts — so her tail literally read as 'it is settled that this is how I answer here'. WM_SETTLEMENT_PREFIX is now '[answered]' (one token, one meaning); all readers go through the const, so the repeat-perception boundary scans are untouched. 2. The trail rendered every receipt verbatim — a looping persona got an N-shot demonstration of the exact behavior the repetition facts (earlier in the prompt) named. Recency wins; she complied with the demonstration, not the fact. render_trail now collapses a receipt that is near-identical to an EARLIER receipt into a one-line stub ('not re-shown'), using the same near_identical_substantial geometry as the detectors — one definition of repeat. Comparing only against earlier receipts keeps every line's rendering stable after first appearance, preserving the append-only KV-cache property (#205/#266). Regression test pins the live specimen shape: dup receipt collapses, first copy stays full, distinct answers and action traces render untouched. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(cognition): working memory speaks in HER voice — interoception must not parse as a peer's message (#264 third glass-box finding) Asha, with BOTH repetition facts in-prompt and the receipt collapse live, still looped — and her opening line told us why: 'Thank you for the summary of recent actions and thoughts.' The WM block rides a user-role turn and its header was second person ('Your recent thoughts and actions…'), so Devstral parsed her own interior state as a PEER addressing her and politely replied to it, turn after turn — the reply itself being the templated summary the detectors keep flagging. The entries were already first person; only the header spoke in another's voice. It now reads 'My own recent thoughts and actions (working memory — this is my interior state, not a message from anyone)'. Self-knowledge is never phrased as someone else talking. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(capacity): manifest v2 tiered reader — per-(layer,tier) banks, the read side of moec_pack_dir_tiered (#269/#268) The reader half of the tier contract locked with the foundry 2026-07-31 (her packer round-trips 82/82 on the write side; our specs crossed mid-wire and matched line-for-line). TierSpec {id, quant, record_bytes} descending fidelity; banks experts-L{n}-T{t}.bin at offset expert_id x record_bytes; fetch_tier(key, tier, buf) is pure mechanism — the pager's policy seam (importance x recency x quant-sensitivity -> tier/residency/prefetch, Joel's all-star/cruft control law) decides WHICH tier, never the container. v1 stays the degenerate case by construction: a manifest without tiers[] synthesizes one tier from the top-level record_bytes and keeps legacy experts-L{n}.bin names — version picks the naming, no heuristics. The alignment law holds per tier; tier ids must equal their index (order drift between writer and reader refuses at open); out-of-range tiers refuse. Tests mirror the packer's round-trip: every (layer, expert, tier) reads back its own header + tier-distinguishable payload; v1-without-tiers-field parses and serves via the tier-less fetch(); range/order violations refuse. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(capacity): tier rides the identity end-to-end + byte-accounted cache + ExpertFetcher adapter seam (#269) Three moves that make the all-star/cruft allocator implementable as pure policy over pure mechanism: 1. ExpertKey gains tier — ONE identity from the pager's policy seam through the cache to the bank. A sharp and a cruft copy of the same expert are different bytes and never alias; promotion admits the sharp copy and the cruft copy ages out naturally. packed() widens to u64. The container's fetch(key, buf) honors key.tier (the redundant fetch_tier param died — compression). 2. The ecache goes BYTE-accounted (touch_sized): per-record real bytes against the governor-granted max_bytes, so cruft records pack denser than the sharp slot count implies, and an oversized admit evicts as many residents as its bytes require (regression pins the two-eviction case). Slot count stays as the secondary bound; warm-start accounts at the sharp size (a warm guess never over-fills). resident_bytes() is the number the footprint reporter reconciles against the lease. 3. ExpertFetcher adapter trait — the fetch seam adapterized (Joel's directive): outlier A is the local NVMe container; outlier B (remote peer shard over the grid) and the blended layer-split fetcher slot in behind the same two methods without the pager learning a second shape. 89/89 capacity tests green (round-trips, cliff, tier-mix packing, refusals, v1 back-compat). BigMama's TieredContainerFetcher (85/85, k3-adopt) is the same envelope from her side — the tier contract now has writer+reader on BOTH nodes. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(capacity): tier-aware pager policy seam — the all-star/cruft allocator v1 (#273) The last mechanism→policy gap to the K3 targets (5/1/10 tok/s). TierPolicy is the seam locked with BigMama's EXPERT-PAGING-CONTROL-LAW.md: policy(importance, recency, quant_sensitivity, budgets) → {tier, residency, prefetch}, so the v1 classic-control heuristic and the sim-trained ML policy (v2) swap behind one signature. ClassicTierPolicy, two orthogonal axes: - Residency (WHERE) rides the existing ranked_experts priority (hits ≫ predicted ≫ gate seed) with FIRST-FIT byte fill per residency tier — cheaper records backfill space sharp ones couldn't use, which is exactly how cruft tiers multiply cache capacity (pinned by the density test). - Fidelity (WHICH quant) is earned importance: weighted demand = hits × quant_sensitivity (Option until her trace sensor lands; None = frequency- only), tier = decades of weighted demand below the live leader — self- normalizing, no absolute thresholds. Control-law overrides: observation window forces tier 0 on new actives (small-quanting a new active corrupts the importance measurement itself); speculative-verify divergence promotes via a caller-side step integrator (self-calibrating, no logit threshold in the policy); unobserved/predicted- only park cheapest (distortion is free until activation; speculation earns no fidelity). Zero-signal experts stay Cold — no fetch bandwidth for what nothing points at. Wire-through: assignment.tier IS ExpertKey.tier (fetch_key refuses u16 overflow, never truncates); planned_bytes per residency tier is the governor- lease reconciliation number against the ecache's resident_bytes(). The #269 fixed-point contract extends to tiers: unchanged demand + resident add-back ⇒ byte-identical plan (test proves the thrash without add-back too). ranked_experts goes pub(crate) — one ranking authority, no consumer re-derives. 9 new tests, 98/98 capacity green. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs: proper GitHub social-preview card — ring mark on dark, never blown out on white The repo's share card rendered as a washed-out white rectangle (the logo PNG is transparent, so GitHub composed cyan rings onto white at crop scale — live-spotted on X 2026-07-31). This is a purpose-built 1280x640 card: dark blue-biased ground, the ring mark with its own bloom, wordmark + 'AI citizens, not AI agents.' + the README tagline. Upload target: repo Settings → Social preview (GitHub has no API for it). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --------- Co-authored-by: Claude Fable 5 <[email protected]>
…tion — kill KV-cache thrash (#266) The serving plan already derives lanes from the resident persona population (`persona_floor` → `set_lane_demand` → `ServingDemand.lanes`), but a hardcoded `MAX_LANES = 2` clamp forced any node with >2 resident citizens to share 2 `--parallel` slots. llama.cpp's per-slot LRU eviction (SlotAffinity::lease) then overwrote a warm slot's KV every time an unslotted persona spoke, so that persona re-prefilled its entire ~10k static prefix cold each turn. Measured (task #266): 96.3% of persona compute is prefill; two of four citizens sat at 0.0% KV-cache reuse across 10 turns — the exact signature of 2 slots / 4 resident personas (~26–36s cold prefill vs 0.48s warm, a 75x penalty). Root cause / fix seam: the 2026-07-17 revert (4 → 2) diagnosed the failure correctly (a starved per-slot window) but fixed it in the wrong place — it clamped the lane CEILING when the real defect was that the lane-COUNT shed in `plan_serving` gated on `MIN_SERVE_CTX` (2048, "runnable at all"), far below the ~9k a live turn needs, so a raised ceiling let 4 slots @ 6k through. Fixed at the true seam: - The shed now requires each slot to clear `BOOTSTRAP_WORKING_SET` (16384 ≈ one full assembled turn + generation headroom) — the SAME "one full turn" constant the demand cap already uses (single-sourced, no new magic number). This is the window-floor tradeoff: llama.cpp splits `-c` across `--parallel`, so more slots = smaller per-slot window; the plan grows lanes toward the resident population ONLY while each slot still holds a full turn, and never shrinks below the floor to fit more. Deliberately the STABLE bootstrap value, not the moving measured p95 — coupling the slot COUNT to a jittering signal is the 718-replan lane-flap that wedged three benchmark runs (the served WINDOW still refines with measurement). - `MAX_LANES` 2 → 8: once the window floor is the binding constraint, this is again a pure sanity backstop (pathological roster + `--parallel` practicality). - Over-subscription (resident personas > warm slots the floor permits) is surfaced, never silently absorbed: a `serving.plan` probe names it at the decision and `grid_overflow_lanes` carries the count to the governor for off-box placement. - `resource_admission::shared_model_saturated` now keys off the LIVE served lane count (`LANES.lane_count()`) instead of the `MAX_LANES` ceiling, so raising the backstop can't let a 2-slot host admit 8 in-flight and queue 6 at the backend. Before: 4 resident personas / 2 slots → LRU clobber → cold re-prefill every turn. After: roomy host → a warm slot per resident persona (0 overflow); floor-limited host → the honest number of warm slots + visible overflow, never a silent cram. Tests green (metal,accelerate): serving_plan 25/0, serving 130/0, resource_admission 6/0, slot 22/0. Updated 5 tests whose fixtures assumed the old `MAX_LANES = 2` clamp and added `slots_size_to_resident_population_capped_by_the_full_turn_window_floor` pinning both branches (window allows 4 → 4 slots; floor allows 2 → 2 + surfaced overflow). Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…+ 'ours is harder' Joel's refinement (2026-08-09): it is not zero-copy-or-copy, it is a ranked ladder — (a) GPU-resident passthrough (UMat/texture, never leaves the device), (b) rasterize if a representation change is unavoidable, (c) copy as the absolute last resort, done ONCE and cached. Plus the caution that raises the bar: a cognition tick is variable, irregular, and its derived representations (embeddings, RAG context, KV-cache) are far costlier to recompute than a video pyrDown — so the do-it-once discipline matters MORE here than in Video Painter, and every accidental recompute IS the measured prefill waste (#266) and window double-pay (#333). Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…tion — kill KV-cache thrash (#266) The serving plan already derives lanes from the resident persona population (`persona_floor` → `set_lane_demand` → `ServingDemand.lanes`), but a hardcoded `MAX_LANES = 2` clamp forced any node with >2 resident citizens to share 2 `--parallel` slots. llama.cpp's per-slot LRU eviction (SlotAffinity::lease) then overwrote a warm slot's KV every time an unslotted persona spoke, so that persona re-prefilled its entire ~10k static prefix cold each turn. Measured (task #266): 96.3% of persona compute is prefill; two of four citizens sat at 0.0% KV-cache reuse across 10 turns — the exact signature of 2 slots / 4 resident personas (~26–36s cold prefill vs 0.48s warm, a 75x penalty). Root cause / fix seam: the 2026-07-17 revert (4 → 2) diagnosed the failure correctly (a starved per-slot window) but fixed it in the wrong place — it clamped the lane CEILING when the real defect was that the lane-COUNT shed in `plan_serving` gated on `MIN_SERVE_CTX` (2048, "runnable at all"), far below the ~9k a live turn needs, so a raised ceiling let 4 slots @ 6k through. Fixed at the true seam: - The shed now requires each slot to clear `BOOTSTRAP_WORKING_SET` (16384 ≈ one full assembled turn + generation headroom) — the SAME "one full turn" constant the demand cap already uses (single-sourced, no new magic number). This is the window-floor tradeoff: llama.cpp splits `-c` across `--parallel`, so more slots = smaller per-slot window; the plan grows lanes toward the resident population ONLY while each slot still holds a full turn, and never shrinks below the floor to fit more. Deliberately the STABLE bootstrap value, not the moving measured p95 — coupling the slot COUNT to a jittering signal is the 718-replan lane-flap that wedged three benchmark runs (the served WINDOW still refines with measurement). - `MAX_LANES` 2 → 8: once the window floor is the binding constraint, this is again a pure sanity backstop (pathological roster + `--parallel` practicality). - Over-subscription (resident personas > warm slots the floor permits) is surfaced, never silently absorbed: a `serving.plan` probe names it at the decision and `grid_overflow_lanes` carries the count to the governor for off-box placement. - `resource_admission::shared_model_saturated` now keys off the LIVE served lane count (`LANES.lane_count()`) instead of the `MAX_LANES` ceiling, so raising the backstop can't let a 2-slot host admit 8 in-flight and queue 6 at the backend. Before: 4 resident personas / 2 slots → LRU clobber → cold re-prefill every turn. After: roomy host → a warm slot per resident persona (0 overflow); floor-limited host → the honest number of warm slots + visible overflow, never a silent cram. Tests green (metal,accelerate): serving_plan 25/0, serving 130/0, resource_admission 6/0, slot 22/0. Updated 5 tests whose fixtures assumed the old `MAX_LANES = 2` clamp and added `slots_size_to_resident_population_capped_by_the_full_turn_window_floor` pinning both branches (window allows 4 → 4 slots; floor allows 2 → 2 + surfaced overflow). Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…ds an exclusive warm slot (#266/#386) Glass-boxed 2026-08-09 while running SWE-bench solves on the M5: each act spent ~85s in PROMPT PREFILL (139 tok/s, O(n²) degrading) and the llama.cpp prompt cache was evicted every turn (srv alloc: "making room for prompt cache entry, removing oldest entry"). serving.plan emitted "warm-slot-oversubscribed" (4 resident personas, 1 warm slot, per_slot_floor 16384): the 3 IDLE citizens woke on their autonomic cadence, rotated through the shared KV slots, and evicted the solver's prefilled prefix — so every act re-prefilled the FULL ~12-20k-token prompt cold instead of reusing cache and prefilling only the ~50-token delta. cognition/eval ALREADY quiesces the fleet for a measured snapshot (quiesce_all); agent/solve — the shared headless measured-drive loop — simply never invoked it. Fix: solve_body acquires a selective quiesce over the OTHER residents for the drive's duration (new quiesce_others(except)), so the solving persona holds a stable warm slot and her prefix survives turn-to-turn. She is never suspended; the idle contenders step back and still answer DIRECTED messages (quiesced gates only the autonomic self-tick). Panic-safe RAII: the fleet resumes on drop / early-return / unwind. [[benchmark-is-a-governor-preemption-lease]] Compressed quiesce_all + quiesce_others onto one pure selector (quiesce_lease_over) so the exclusion invariant — quiesce_others(solver) must NEVER suspend the solver, or the drive deadlocks — is unit-testable without a live daemon. Two tests added. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
… — scaffolding + invariant gate (#266) Forensics (raw prompt-captures, benchy-18057-fix392): consecutive prompts share only 7,607 of ~14,706 chars — the per-turn presence/own-time framing block sits at position 4-5 of the system prompt (BEFORE context), so it flips every turn and caps KV reuse. She re-prefills ~6k tokens each act (the ~13min SWE solves). This commit lands the SAFE, additive half: `compose()` output is byte-IDENTICAL (all existing framing tests stay green), but ordered_blocks is now partitioned into `stable_blocks` (identity + [Taking your turn] + tools — a pure function of the persona, cacheable) and `volatile_blocks` (own-time/presence framing + assembled context + clock). `compose_split()` returns the two separately for the message builder to place stable in the cacheable system message and volatile on the trailing turn. VDD gate (TDD-first, per Joel): `stable_prefix_is_byte_identical_across_turn_shapes` asserts the stable prefix is byte-identical across directed / undirected / self-initiated / holds-work / clock-on-off, and that the framing rides `trailing` instead. 4/4 deliberation_prompt tests green. NOT yet wired: the caller (compose_system_holding → the faculty's .system) still uses the whole-string compose(). Relocating the framing to trailing there is the behavior-changing step — it must be its own RED→GREEN cycle (a factory-level test asserting prompt_view(persona).system is byte-stable across turns), and it untangles the context budget math (context is currently budget-fit INTO the system size). Deferred to a focused pass. OPEN QUESTION recorded on #266: the measured 0% reuse (vs the ~50% a 7.6k common prefix implies) hints slot-KV eviction is a CO-cause the prompt fix alone won't move — settle with a stable-prompt A/B before claiming the 10x. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…through the grounding (#266) Forensics (raw prompt-captures, benchy-18057): consecutive turns shared only 7,607 of ~14,706 chars because the presence/own-time framing block sat at char ~7607 — BEFORE the assembled context — and its variant hard-flips every turn (DIRECTED / WORKING / SILENCE). Every flip shortened the served slot's reusable KV prefix to that point and re-prefilled the whole tail. Two of four citizens measured 0.0% cache reuse across 10 turns each; 96% of persona compute was prefill (the ~13min SWE solves). Fix is pure block ORDER: `deliberation_prompt` now partitions the system prompt into a `stable` bucket (identity + [Taking your turn] + tools + assembled context + clock) and a per-turn `trailing` bucket (own-time + presence framing), and `compose` emits them `stable ++ trailing` — i.e. the hard-flipping framing renders LAST, after the grounding, instead of before it. The served slot's reusable prefix now extends through identity + tools + the stable head of the context; the framing flip falls past it and costs only its own short re-prefill. Deliberately NOT moving the framing onto a trailing USER turn (the first attempt): that broke the "ask stays last" invariant and, worse, would end an undirected turn on the presence block's PASS-affordance — biasing toward the exact idle-silence we fought (#264). Framing is system-role instruction; it belongs in the system message, just after the grounding, not in the conversation. The ask remains the last conversation turn. VDD/TDD: - `framing_flip_never_perturbs_the_cacheable_prefix` (deliberation_prompt): for a FIXED context, flipping directed/self-initiated/holds-work does not change `compose_split().stable`; the framing markers ride `trailing`; the standing grounding stays in `stable`. - `directedness_flip_keeps_the_grounding_inside_the_reusable_prefix` (faculty, caller level): the longest shared leading run of prompt_view(directed).system vs prompt_view(undirected).system reaches THROUGH the [What you are working with] block — the flip falls after it. RED before the reorder (systems diverged at char ~7607). - Updated the now-outdated invariant test premise; `mixed_thread_...` and `trailing_proprioception_...` unchanged. Full cognition suite: 947 passed, 0 failed. Builds on the compose_split scaffolding (cdfa4f2). Still owed on #266: a live before/after cache-reuse A/B on a healthy lane — the reorder is the byte-correct fix, but whether it clears the residual 0% (vs slot-KV eviction as a co-cause) is a measurement, not a claim. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…tor (#392) + coordinator-free ResourcePolicy (#395 slice 1) (#2226) * refactor(cognition): split the system prompt at the KV-cache boundary — scaffolding + invariant gate (#266) Forensics (raw prompt-captures, benchy-18057-fix392): consecutive prompts share only 7,607 of ~14,706 chars — the per-turn presence/own-time framing block sits at position 4-5 of the system prompt (BEFORE context), so it flips every turn and caps KV reuse. She re-prefills ~6k tokens each act (the ~13min SWE solves). This commit lands the SAFE, additive half: `compose()` output is byte-IDENTICAL (all existing framing tests stay green), but ordered_blocks is now partitioned into `stable_blocks` (identity + [Taking your turn] + tools — a pure function of the persona, cacheable) and `volatile_blocks` (own-time/presence framing + assembled context + clock). `compose_split()` returns the two separately for the message builder to place stable in the cacheable system message and volatile on the trailing turn. VDD gate (TDD-first, per Joel): `stable_prefix_is_byte_identical_across_turn_shapes` asserts the stable prefix is byte-identical across directed / undirected / self-initiated / holds-work / clock-on-off, and that the framing rides `trailing` instead. 4/4 deliberation_prompt tests green. NOT yet wired: the caller (compose_system_holding → the faculty's .system) still uses the whole-string compose(). Relocating the framing to trailing there is the behavior-changing step — it must be its own RED→GREEN cycle (a factory-level test asserting prompt_view(persona).system is byte-stable across turns), and it untangles the context budget math (context is currently budget-fit INTO the system size). Deferred to a focused pass. OPEN QUESTION recorded on #266: the measured 0% reuse (vs the ~50% a 7.6k common prefix implies) hints slot-KV eviction is a CO-cause the prompt fix alone won't move — settle with a stable-prompt A/B before claiming the 10x. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(cognition): render per-turn framing LAST so the KV prefix caches through the grounding (#266) Forensics (raw prompt-captures, benchy-18057): consecutive turns shared only 7,607 of ~14,706 chars because the presence/own-time framing block sat at char ~7607 — BEFORE the assembled context — and its variant hard-flips every turn (DIRECTED / WORKING / SILENCE). Every flip shortened the served slot's reusable KV prefix to that point and re-prefilled the whole tail. Two of four citizens measured 0.0% cache reuse across 10 turns each; 96% of persona compute was prefill (the ~13min SWE solves). Fix is pure block ORDER: `deliberation_prompt` now partitions the system prompt into a `stable` bucket (identity + [Taking your turn] + tools + assembled context + clock) and a per-turn `trailing` bucket (own-time + presence framing), and `compose` emits them `stable ++ trailing` — i.e. the hard-flipping framing renders LAST, after the grounding, instead of before it. The served slot's reusable prefix now extends through identity + tools + the stable head of the context; the framing flip falls past it and costs only its own short re-prefill. Deliberately NOT moving the framing onto a trailing USER turn (the first attempt): that broke the "ask stays last" invariant and, worse, would end an undirected turn on the presence block's PASS-affordance — biasing toward the exact idle-silence we fought (#264). Framing is system-role instruction; it belongs in the system message, just after the grounding, not in the conversation. The ask remains the last conversation turn. VDD/TDD: - `framing_flip_never_perturbs_the_cacheable_prefix` (deliberation_prompt): for a FIXED context, flipping directed/self-initiated/holds-work does not change `compose_split().stable`; the framing markers ride `trailing`; the standing grounding stays in `stable`. - `directedness_flip_keeps_the_grounding_inside_the_reusable_prefix` (faculty, caller level): the longest shared leading run of prompt_view(directed).system vs prompt_view(undirected).system reaches THROUGH the [What you are working with] block — the flip falls after it. RED before the reorder (systems diverged at char ~7607). - Updated the now-outdated invariant test premise; `mixed_thread_...` and `trailing_proprioception_...` unchanged. Full cognition suite: 947 passed, 0 failed. Builds on the compose_split scaffolding (cdfa4f2). Still owed on #266: a live before/after cache-reuse A/B on a healthy lane — the reorder is the byte-correct fix, but whether it clears the residual 0% (vs slot-KV eviction as a co-cause) is a measurement, not a claim. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(resources): coordinator-free ResourcePolicy — operating modes as pure lease policy (#395 slice 1) Joel's design (2026-08, live-grounded): an operating MODE ("maximize benchmark capacity", "dev sim", "balanced") is NOT new plumbing — it's a CONFIGURATION of the lease primitives that already exist (per-consumer reservation floors, ReclaimPolicy, serving_fraction). This lands the pure decision core: `GovernorMode::floors(&[ConsumerDemand]) -> Vec<PolicyFloor>`. Design constraints baked in (each pinned by a test): - COORDINATOR-FREE: a pure fn of a LOCAL view — no global authority, no I/O. The SAME object runs per-node on one box today, composes into the grid market next, and drops into the P2P "wireless" arbiter (radios sharing a finite medium, no central controller) with no rewrite. That's the box→grid→P2P scaling Joel described; a global-authority dependency here is the thing that would force a rewrite at the boundary. - COST IS ALWAYS PRESENT, EVEN DONATED: every PolicyFloor carries a Price. "Free"/"donated" is not the absence of cost — it's a transaction at Price::FREE where the owner bears the cost (a ConsumerDemand::gift is free regardless of mode). The market/alt-coin settlement layer later changes only this number. Honest accounting now, economy later. - ROLE-BASED, not id string-matching (the #70 smell): policy switches on ConsumerRole {Serving, Embedding, Vision, Realtime, Other}; a new consumer joins by declaring its role. - FLOORS = MEASURED FOOTPRINT, never a magic constant. Modes: Balanced (default, starve nobody) / BenchmarkMax (protect serving, yield everything else → their Graceful leases reclaim → GPU frees for the run) / DevSim (protect serving + recall embedding, yield vision/other). Output maps 1:1 onto `ResourceDaemon::reserve(consumer_id, kind, floor_bytes)` — the wiring slice plugs it in. Pure/unit only, no live wiring, no reboot: 6/6 tests green. Next (#395): VL lane as a ResourceConsumer (closes the resource_drift + becomes mode-controllable), then apply this policy through the daemon behind a mode selector; later the learned/market/wireless layer on the same seam. Full design + ordering in memory (governor-modes-are-lease-policy-and-vl- leasing-is-the-keystone). Relates #56/#126/#225/#106/#385. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
…Y grounding source (#398 slice 1) Joel's ruling (2026-08-12): 'Some of the rag stuff needs to just be cache based... keep it general nonspecific.' Measured cause (#266): every compose re-fetched every grounding source and re-prefilled ~5k tokens per act (~50s of every ~51s act). The decorator: deliver() serves last-good until the owner-wired DirtyHandle marks dirty (or the cache genuinely cannot answer: different room, or a bigger budget than a truncated delivery spent). Dirty is cleared BEFORE the fetch so an event landing mid-fetch is never lost. Continuations pass through — pagination is a live walk. One wrap serves every source; a source that must never be cached simply isn't wrapped. No benchmark/drive mode. Test: 5 composes → ONE inner fetch; mark() → exactly one refetch; room switch → fresh fetch, never cross-room bleed (exam-bleed class). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…ate, no wrap without a wire (#398 slice 2) Outlier A of the invalidation pair: the [workspace-map] grounding re-walked the workspace directory on EVERY compose — synchronously in eval forks (defer_grounding=false), which is part of the measured per-act prefill churn on solve runs (#266). Its substrate only changes when hands mutate the filesystem, and every hand action already emits command:completed on the kernel bus (real-time; the coalescer passes command:* through). - grounding_invalidation.rs: mutates_workspace predicate (deny-list of read-only verbs, then the code/git/cargo families default to mutates — over-invalidation is safe, a missed mutation is a stale map) + spawn_workspace_invalidator, a pure reuse of the dispatch_listener shape: subscribe, filter, mark. Lagged receivers mark dirty conservatively (a missed event may have been a mutation). - DirtyHandle::downgrade() → WeakDirtyHandle: the invalidator holds only a weak lever, so it exits when the wrapped source drops instead of leaking one parked task per ephemeral eval fork. - Wired at BOTH construction sites: supervisor spawn (live personas) and repoint_workspace_map_if_pinned (eval forks — the solve-path win). No wrap without a wire: a handless cfg (no bus) keeps the raw walk, because an unwired cache would be stale forever (#346's staleness class is the failure mode we refuse). Tests: predicate split (read verbs never dirty, mutation verbs always, foreign namespaces never); end-to-end bus wire (code/read completion → cached projection served, code/write completion → exactly one refetch); weak-handle lifecycle (dead cache → mark reports dead → task exit path). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
… spike instrumentation, wire perf (#2284) * fix(ids): UUIDs are not strings — mint real ones, and stop typing ids as text (#274/#396) Joel, 2026-08-13: "Always use uuid and never corrupt them with random prefixes" and "UUID's are NOT strings. If you're using strings for id you are writing slop." Both landed on code written minutes earlier, and the grep that followed found the same defect older and wider than my one file. Three fixes, in order of how badly they were wrong: 1. The four shipped recipe ids were hand-drawn patterns (c0de0001-0000-4000-...), a name wearing a UUID's costume — readable, collidable, and fake. Replaced with genuine v4s in both the authored JSON and the `shipped::` constants, written grouped (0xfed332c3_383c_45bb_...) so the two are checkable by eye. 2. comms::{MessageId, CorrelationId} were `String` newtypes. `MessageId::new("msg-1")` let any caller invent a namespace that collides with every other caller's. Both are now `Uuid`: MessageId::new() MINTS (no caller-supplied form exists), and CorrelationId::of_exchange(id) states the derivation the old `CorrelationId(id.0.clone())` left implicit. Still distinct TYPES — the compiler, not a naming convention, is what stops one being passed as the other. 3. EndpointId is deleted. Its values were `EndpointId::new("browser")` and `("rust-core")` — a client-kind label standing in for an identity, and with it the assumption that the web client is a distinguished endpoint. It is one client among many (mobile, SDK, TUI, another node's core). TransportEnvelope.source and .target are now PeerId, the substrate's one actor identity per identity/mod.rs. Zero callers outside comms/mod.rs; the stale generated binding goes too. Also closes the on-disk authoring hole the required `id` field opened: a recipe file that names no id now gets one DERIVED from its purpose (RFC 4122 v5 under a frozen namespace), so "author a file, zero code" keeps meaning zero code — no uuidgen — and every node that loads the same file agrees on its identity with nothing to reconcile. A recipe that DOES carry an id keeps it verbatim. Tests: comms 23 pass (envelope wire shape now asserts ids round-trip as their own UUIDs; minted_message_ids_are_unique pins the collision fix), experience 43 pass including the previously-failing an_experience_authored_on_disk_needs_no_rust. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs(CLAUDE.md): headless Rust core is the system — Node is ONE client, not the deploy path Joel, 2026-08-13: "Headless rust period. No need for node to run everything except for the web interface which is one of many, including mobile apps/sdk." — and then, because I kept treating the correction as a code-only matter: "Fix these severe misunderstandings ... regardless of where they are." This file is where the misunderstanding REPRODUCES. It is loaded into every agent session, and it opened with "EVERY TIME YOU EDIT CODE: Run `npm start` (MANDATORY)" under `cd src` — a directory that no longer exists — plus "ALL Rust binaries MUST be built via npm start". A fresh agent under amnesia reads that and concludes Node runs the system. It doesn't, and `continuum --help` has been saying so in its own first line the whole time: "build + run the headless Rust core". Rewrote the CRITICAL WORKFLOW section around what is actually true, and swept the other 11 Node-as-deploy claims scattered through the file: - The core is Rust and boots with no Node. Node builds the WEB desktop, which is one client among several (mobile, SDK, TUI, MCP, another node's core over the grid). Named the consequence, because it already cost us: a feature that lives in a client exists only for that client — how voice ended up web-only with every other citizen structurally mute (#58). Behaviour goes in the core; clients render. - The deploy path is `continuum reboot` (Rust build + relaunch + running-SHA verify), with `deploy-verify` and the version trio called out — that verification exists because a reboot once shipped a stale binary and reported success (#194). - `cargo build` stays discouraged for the RIGHT reason (a hand-built binary exists only on your machine, and a fresh clone must work with no manual steps, #291) — not the old implication that Rust must be built through npm. `cargo check` is named as the correct type-check-while-you-work tool, with the shared CARGO_TARGET_DIR. - `npm run build:ts` now says what it actually covers: the web client, and nothing about whether the core compiles. - Flagged `./jtag` inline as the legacy Node CLI. Left the invocations that follow, since their command NAMES are still accurate — it is the driver that is stale. No code change; the one surviving "npm start" is the sentence warning you off it. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(cli): `uu` is the alias — `cu` is UUCP, and every harness defaulted to a binary that does not exist Joel: "Cu conflicts with some Unix program. Fix for all cases including windows" and "It's a bug Claude" — it is, and worse than doc drift. `cu` is /usr/bin/cu (UUCP call-unix) on every Unix. `uu` — the double-U of contin-UU-m — is THE official short alias, and start-server.sh has installed exactly that (plus a squatter guard) since 2026-08-01, with a comment naming this very collision. Nothing in the tree installs `cu`. But the REFERENCES never followed: - Six benchmark harnesses defaulted to `~/.continuum/cache/cargo-target/{release,debug}/cu`. Neither file exists — the only built CLI is `release/continuum`. So the default resolved to nothing and every default-args run died at the first invocation. matrix.py even carries a comment about this exact class of failure biting once before (2026-07-22, stale debug-only default silently no-opping the sweep). - Fixed by RESOLVING rather than renaming: a shared `_resolve_cli()` prefers what is actually installed on PATH (`uu`, then `continuum`) and falls back to the release build — so it works from a fresh clone, an installed box, or a dev tree, on any platform, instead of hard-coding one machine's layout. - Flag renamed `--cu` → `--uu` with all in-repo call sites updated (sweep_all → matrix → headtohead → preflight_gpu chain). Also swept 53 `cu <command>` occurrences in docs, Rust comments, and generated-TS doc comments to `uu`. Left the ones that are ABOUT the collision (memory-bridge README's "never bare `cu`", WAKEUP-AND-JOIN's rename note) — those are correct as written, and legacy/ stays quarantined. README dev section reworked in the same pass: the boot path is `continuum start` / `continuum reboot` / `continuum ping`, with Node named as what it actually is — the web client's build dependency, one client among mobile/SDK/TUI/MCP, not the thing that runs the system. Verified: all six harnesses compile (py_compile), cargo check clean, zero `target/{release,debug}/cu` paths left in the tree. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(core): the last Python in the runtime path — one vestigial, one silently swallowing the job Joel: "Fix all nodejs and python dependencies that are breaking our headless rust core ... we must find all smell all the time and never ignore it." AUDIT RESULT FIRST, because one half is good news: Node spawns from the running core: ZERO. `Command::new("node"|"npm"|"npx"| "deno"|"bun")` has no occurrences anywhere in continuum-core. The core is genuinely headless Rust at runtime; Node exists only to build the web client. Python spawns from the running core: FOUR sites, and neither kind was honest. 1. THREE were vestigial and were hiding untested code. `file_engine.rs` had three `#[test]`s opening with `if Command::new("python3").arg("--version").output() .is_err() { return; }` — a skip-guard from when the syntax gate shelled out to `python3 -m py_compile`. That interpreter is GONE: the production path is `code::syntax::validator_for` → `unbound_calls`, pure Rust. So on any box without python3 — a CI runner, a fresh clone — three tests reported PASS while asserting nothing at all. Guards removed; all 55 file_engine tests pass without an interpreter present, which is the proof they never needed one. Also corrected the doc on `introduced_undefined_calls`, which still told the reader the analysis returns None when there is "no python". There is no python. 2. ONE is a REAL runtime dependency, and it was failing silently. `forge/start` spawns `python3 <alloy_executor>` — a script that lives in the SIBLING sentinel-ai repo, which a fresh clone of continuum does not have. When `find_alloy_executor()` returned None the handler used pid 0 and wrote `state: "queued"` — indistinguishable from a job legitimately waiting its turn. So on every machine that had only cloned this repo, `forge/start` returned SUCCESS for work that nothing would ever run. Now it fails loud, names the missing script, says where to get it, and states plainly that the job was NOT queued. The dependency itself is still there — excising it to Rust is #52/#99 — but it can no longer pretend to have worked. The pattern in both: a Python dependency that had already been removed or had never been satisfiable, still shaping behaviour through a stale guard and a fallback. `[[fallbacks-are-illegal-fail-loud]]`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(identity): PersonaRef vs PeerId — a reference is not an identity, and the compiler now knows Joel: "UUID's are NOT strings … Well defined and named structs by reference must be used." Chasing that through persona_id turned up something sharper than the count. THE FINDING. `PersonaWorkspaceRegistry::resolve_persona` exists specifically to close what its own doc calls "the loose-`String` id boundary … the defect class that fed a dead id to a doomed eval." It has SEVEN call sites. SIX are its own tests. ONE is production (eval.rs). Against 55 `persona_id: String` fields. The check was correct and essentially nothing called it — a correct check nothing calls is nastier than a missing one, because it reads as covered. Nothing forced the call, because both sides were `String`. THE FIX — two types, one door: - `PersonaRef` (new, in identity/): what a CALLER writes — full UUID, 8-char short-id, or name. Explicitly NOT an identity. Its only accessor is `as_str()`; there is no `as_peer_id()`, because a name is ambiguous, mutable, and meaningless without a roster. - `PeerId` (existing canonical actor identity): what everything downstream holds. - `resolve_persona(&PersonaRef) -> Result<PeerId, _>` is now the ONLY bridge. Taking the newtype rather than `&str` is what makes resolution unskippable. `From<PeerId> for PersonaRef` exists (an identity is always a valid reference to itself); the reverse deliberately does not — it requires a roster. Wire shape is unchanged: `#[serde(transparent)]` over the same string callers already send, so no client, recipe, or stored payload changes. Short-id and name PX (#161) keeps working — that ergonomics is the whole reason a reference type has to exist separately rather than everything becoming a UUID. Converted, types pushed DOWN rather than laundered at the seam: - `CognitionEvalParams.persona_id` → `PersonaRef` - `restore_persona_workspace(&PersonaRef)` (was `&str`) - `append_failed_ledger(&PersonaRef, …)` (was `&str`) HELD, and stated rather than fudged: `CognitionEvalResult.persona_id` stays `String`. The struct derives `Default` across 21 fields and a persona reference has no sensible default — an empty one is a nonsense value that reads as a real answer. The real fix is splitting the fire-and-poll HANDLE from the completed RESULT (a handle knows only the requested ref; a result knows the resolved id), which is its own slice. Inventing a default to satisfy the type checker is the `unwrap_or` reflex: compiler quiet, runtime wrong. The reason is recorded at the field. Tests: persona_workspace 10, eval 22, identity 23 — all pass; full lib test build clean. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * refactor(memory): the memory layer takes PersonaRef, not loose text — 21 sites Second slice of the id-typing migration. All ten `commands/memory/*` params plus the `MemoryManager` API they call now carry `PersonaRef` instead of `String`/`&str`: append_memory, append_event, load_corpus, has_corpus, get_corpus, multi_layer_recall, consciousness_context, persona_db_handle, hydrate_corpus_if_missing. Types went DOWN into the layer rather than being unwrapped at each call — the whole point of the previous slice. `.as_str()` now appears only where the value is genuinely being USED as text (a map key, a `starts_with` shape check, a directory handle), never to satisfy a signature one call later. Two `Default` derives removed (`ConsciousnessContextParams`, `LoadCorpusParams`) rather than giving `PersonaRef` a default. No caller used `::default()` on either, and an empty persona reference is a nonsense value that reads as a real answer — same reasoning as the eval result field held in the previous commit. What this makes visible, and does not yet fix: these commands still never RESOLVE. They accept a reference and hand it straight to the storage layer as a key, so a name or short-id reaches the DB unresolved. That was invisible while everything was `String`; it is now legible in the signatures. Wiring `resolve_persona` into the memory command path is the next slice (#164/#396). Tests: memory 219, rag 150 — all pass. Full lib test build clean. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * refactor(commands): persona params carry PersonaRef — agent/solve, persona/*, cognition/observe Third slice. Seven more command param structs stop typing a persona reference as `String`: agent/solve, persona/identity/{get,set}, persona/instances/{get,despawn}, persona/wall/pin, cognition/observe (params + the `assemble` signature + its `Meta`, so the type is consistent through the result rather than converted on the way out). Same discipline as the memory slice: `.as_str()` appears only where the value is being USED as text — `id_resolve::resolve` takes a `&str` by design because it also serves rooms and cards — never to satisfy a signature. Running total across the three slices: 39 persona params + the memory API + the resolver itself. `persona_id: String` is down from 55 to 16 in the crate, and every one that remains is an internal struct holding an already-resolved id (those want `PeerId`, the next slice) rather than an unresolved caller reference. Tests: full lib test build clean, commands suite passes. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * refactor(rag/introspect): last persona PARAMS typed — and the RAG source path carries it down Fourth slice. `CognitionTraceParams`, the four other introspect params, `CognitionReplayParams` + result, `RagComposeRequest`, and `DatasetFromTurnsParams` now carry `PersonaRef`. The RAG one went two levels deep rather than stopping at the param: `load_source`, `load_memory_source`, and `load_consciousness_source` all take `&PersonaRef` now, which deleted the two `&persona_id.into()` conversions the memory slice had left at those call sites. That is the shape to aim for — when the type reaches the bottom, the adapters in the middle disappear rather than accumulating. `persona_id: String` in continuum-core: 55 → 8. Every remaining one is an internal RECORD (memory/types, should_respond's AIDecisionContext, live/types, projection, shell_types, ai/types, sentinel) holding a value copied from a param. Those are deliberately NOT converted to `PeerId` yet. They hold whatever the caller sent, and nothing on those paths resolves — typing them as an identity today would assert something the code does not do, which is worse than leaving them `String`. They become `PeerId` in the same slice that wires `resolve_persona` into those paths, not before (#164/#396). Tests: replay 3, rag 18, full lib test build clean. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(test): 5 supervisor tests have been panicking since #398 slice 3 — the stub's premise expired `StubAircCitizen::subscribe_all_rooms` was an `unreachable!()` justified by a comment that said no test drives it. That was true when written and stopped being true at bf11a66a7 (#398 slice 3), which gave `PersonaSupervisor::materialize` a `subscribe_all_rooms` call to wire the doctrine/wall cache invalidators. Every supervisor test that materializes an adapter has been dying in that panic since — 5 of the 10, and they only surface on a FULL-suite run, which is how they sat unnoticed. Found while verifying my own id-typing slices: full suite came back 7073 passed / 5 failed, and the first question was whether I caused it. I did not — the diff of my five commits touches `commands/persona/*` only, never `persona/supervisor.rs` or `persona/airc_citizen.rs`, and `git log` on those two files points at #398. Fix: return `AircError::Transport` instead of panicking. This is NOT a fallback — the caller already handles that exact case explicitly (keeps both sources uncached, "correct, just slow", logs loud), so the tests now exercise the real degradation branch rather than aborting, and a stub still never pretends to hold a live stream. An empty stream WOULD have been the fallback: it would have looked like a working subscription that silently never invalidates. Comment rewritten to state what is true now, including why the old assertion was right when it was written. An assertion that outlives its premise is worse than no assertion — it reads as a guarantee. persona::supervisor: 10/10 pass. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(test): pin the stub's REFUSAL contract — the old test asserted the panic I removed `stub_subscribe_panics_loudly` existed to prove the `unreachable!()` fired, so removing that panic left the assertion failing for the right reason. Rewritten to pin what the contract actually is now: Err(Transport) — required Err(anything else) — fail (the caller branches on Transport specifically) Ok(stream) — fail LOUDEST, because that is the real fallback: a stub handing back a stream looks like a live subscription that silently never invalidates Matched rather than `expect_err`d because `FilteredEventStream` is not `Debug`. FULL LIB SUITE NOW GREEN: 7078 passed, 0 failed, 42 ignored. Before this session's last two commits it was 7073/5 — five supervisor tests panicking since #398 slice 3, only visible on a full run. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * test(identity): CI guard — a String-typed identity field must be DECLARED, or the build fails Joel: "eliminate all smell or you will copy it." That is literally the mechanism — a model reading this tree learns its conventions FROM it, and `persona_id: String` was 55 sites teaching that ids are text. I did exactly that this session: minted `c0de0001-…` fake UUIDs because fake-looking ids were already normal here. Prose in CLAUDE.md does not stop that. A failing test does. Three tests in identity/mod.rs, running on every PR via the existing `cargo test -p continuum-core --lib` workflow (no skip pattern matches them): 1. `every_string_typed_identity_field_is_declared` — walks src/, finds any `<identity-name>_id: String | Option<String>` field, and fails unless it appears in LOOSE_IDS. Comments stripped first, so a doc line can never register as a field. The error names the file:field and tells the reader which typed form to reach for (`PeerId` for an actor, `PersonaRef` for an unresolved reference, a `*Id(Uuid)` newtype otherwise). 2. `no_declaration_outlives_its_defect` — a declaration whose field HAS been fixed fails too. Learned directly from `StubAircCitizen::subscribe_all_rooms`, whose comment stayed true-sounding for months after its premise expired and cost 5 silently-failing tests. 3. `declarations_carry_a_real_reason` — every entry starts with external:/pending:/ defect: and is longer than a shrug, the same bar the module-wiring audit (#344) holds. 73 declarations, honestly categorized: - **external** — LiveKit participant/room ids, log-envelope correlation fields. Another system owns the wire format. - **pending** — ours, but nothing on that path RESOLVES yet. Typing it as an identity today would assert something the code does not do. Converts in the slice that wires resolution (#164/#396). - **defect** — `peer_id: String` × 5. These ARE `PeerId`. I attempted the conversion in this session and reverted it: `PeerId` has no `JsonSchema` impl and the construction sites hold `&str`, so it needs its own slice rather than a rushed cascade. Declared as a defect so it stays visible instead of blending in. POSITIVE CONTROL, because a guard nobody has watched fail is the exact shape of defect I found earlier today: added `struct PositiveControlProbe { pub owner_id: String }`, confirmed the guard failed naming `identity/mod.rs: owner_id`, removed it, confirmed green. The guard also caught 12 sites my own inventory grep had missed — it is already strictly better than the method I was auditing with. Full lib suite: 7081 passed, 0 failed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(cli): `continuum start` execs the installed server — building is now --from-source `start` shelled unconditionally into tools/scripts/start-server.sh, which runs a full cargo build. A "governed" lifecycle verb was a wrapper around a bash file that only exists inside a repo checkout (BigMama's find, 2026-08-13): - a user holding ONLY the installed binary, with no source tree, could not start a core at all; - the CLI printed one line then went silent for the length of a compile — called hung three separate times; - the façade's honesty depended entirely on the script underneath. Same class as the rest of the night's defects: a governed surface over a hand-rolled path. Now: `launch_core` locates the installed `continuum-core-server` (CONTINUUM_CORE_SERVER override → next to the running exe → ~/.continuum/bin → target/{release,debug} walking up) and execs it directly, keeping the existing detach/log/pidfile handling unchanged. Building is an EXPLICIT request (`continuum start --from-source`), never the silent default, and the no-binary fallback says WHY it fell back and that it compiles first, rather than going quiet for minutes. The override refuses loudly when set but not a file — a wrong override must not look like an absent one. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(core): tree is GREEN again — 7081/0 (peer_id → PeerId finished, guard debt cleared) The working tree could not build tests. This finishes the identity-typing work that broke it and clears the guard debt it left behind. `cargo test -p continuum-core --lib --features metal,accelerate`: 7081 passed, 0 failed. PEER_ID IS A TYPE, NOT TEXT. The production conversions landed earlier; the test fixtures were left holding `&str`, so the crate compiled and the test target did not. Fixtures now derive a real UUID from the literal they used to carry (v5 under NAMESPACE_OID), which preserves every cross-site equality the tests depended on — "peer-a" in two places is still the same peer, it is just an id now instead of a name in costume. CAUGHT BY DOING IT: contracts/verification had the manifest keyed by a derived PeerId while the EVENT still claimed a raw string signer. The lookup is BY that signer, so converting one side made every verification test fail as MissingPeerManifest. One `test_peer_id` / `test_peer_str` pair now feeds both sides — the same shape of defect the newtype exists to prevent, reproduced in the fixtures while removing it from production. REAL HARDENING, not just fixture churn: `AircPeerManifest::validate` had DROPPED its empty-peer_id check on the theory that typing the field made it impossible. Typing killed `""`. It did NOT kill `Uuid::nil()`, which is still constructible and still means nobody — the type narrowed the hole rather than closing it. The guard is back, at the remaining expressible form. GUARD DEBT CLEARED: loose_id_guard's `no_declaration_outlives_its_defect` went red, correctly — four `peer_id` entries in LOOSE_IDS described fields that are now `PeerId`. Removed. The guard failing here is it working: a declaration list that can rot into a graveyard is worth nothing. Also includes the accumulated session tree: the Joel→Operator fixture sweep (no person's name hardcoded in test data), ts-rs regeneration, and rustfmt across the crate. That is why this touches ~717 files; the behavioural change is the identity typing and the nil-PeerId guard. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(tests): a subsystem-named room does not belong in a fixture either `k3-serving` had no lifetime because it was named for a SUBSYSTEM, so it never died — a month-old durable subscription whose board reads were all corpses. Parted from both scopes. It also sat in TEST FIXTURES, which is the transmission vector: fixtures teach the next reader the convention, so a fixture naming a room after a subsystem teaches that rooms are named for subsystems. Renamed to `bench-swe-run-1` — an activity with a lifetime, which is what a room IS. The two remaining mentions in work.rs are the INCIDENT RECORD (4 of 12 cards there carried a 134h-expired lease) and are kept, now annotated RETIRED so nobody copies the naming from them. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(benchmark): an UNGRADEABLE grade is an ABSENCE, not a capability zero — carry it on the wire and the board `SweGradeResult.error` documents its own contract: "a result with `error` is an ABSENCE, not a zero, and must never be tallied as a failed attempt." The grader earns that honestly — for the env class it re-runs the PRISTINE tree before declaring a fault, so a genuinely broken patch is never mislabelled. Then both consumers dropped the classification: - `benchmark.attempt.end` / `benchmark.autograde` published `resolved=false gate_ok=false` and nothing else. Every wire consumer (probe router → rooms, exam-room widgets, pulse monitors) reads that as a citizen who tried and lost. - `fold_run_card` read the RESULT's `infra_error` but never the GRADE's `error`, so the board folded `resolved: false` + phase `failed` for the same runs. The attempt loop already broke correctly on `g.error.is_some()` (attempts 2 and 3 were never burned) — the loss was purely in what got PUBLISHED, which is the part anything downstream can actually read. Measured on this box 2026-08-13: 8 of 36 distinct instances (14 of 91 receipts, 22%) grade UNGRADEABLE — requests, pylint, pytest and sympy. Every one of those zeros was indistinguishable from a capability failure on the wire, so the denominator of any rate computed off this stream was poisoned. Found by digging into sympy__sympy-11400: p2p 0/29 on the PRISTINE tree, i.e. the suite does not run in that environment at all. (#380/#383 own fixing the environments; this commit owns never again reporting their faults as scores.) - attempt.end + autograde now carry `ungradeable` + `grade_error` - `infra_error` takes the grade's error too — one field meaning "no valid verdict, and why", fed by both sources rather than a second parallel field - `resolved` returns to `None` when ungradeable — the same "no verdict" a pre-grade card carries, because that is the truth - new phase `ungradeable`, ordered ahead of `failed` (a run can carry both a failed marker and an ungradeable grade; the absence is the truer of the two) Test asserts absence-not-zero on the real sympy-11400 shape, with a positive control (same shape, no grade error) that must still fold as a capability zero — so the test cannot pass by simply never reporting failure. This is the #384/#386 class one layer up: those classified INFRA at the solve level, this classifies it at the GRADE level and gets it onto the wire. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(swe): gold-gate the harness — refuse an env whose pytest cannot RUN, instead of caching a tree that grades every attempt UNGRADEABLE Root cause of the 22% ungradeable rate, glass-boxed on sympy__sympy-11400. The era pin at the top of this block downgrades pytest to the instance's own date, which is right when the era INTERPRETER rung (#2253) found a matching interpreter. When it can't — no Python 3.5 on a modern macOS — the venv falls back to a modern interpreter while pytest stays pinned to the instance's year, and the resulting PAIR can be structurally unable to run. Measured: pytest 2.9.2 (correct for 2016) on Python 3.9.6 dies in `pytest_configure` with INTERNALERROR before collecting anything — reproduced on a two-line trivial test, outside the repo, no conftest, no sympy involved. Every test then "fails", the pristine p2p reads 0/29, the tree grades UNGRADEABLE. 8 of 36 distinct instances on this box are in that state. So: prove the harness executes before handing the env to a citizen. A version pin is a GUESS about compatibility; running it is the evidence. `--version` is not enough — it answers happily for a pytest that dies on any real run. This REFUSES rather than self-heals, and that is measured, not assumed. The obvious repair (reinstall a modern pytest) was tried against this exact tree and does NOT work: pytest 8.4.2 → loads, dies in sympy 1.0's 2016 conftest on the `py.path` hook API removed in pytest 7 pytest 6.2.5 → dies on `py.test.mark.slow`, removed in pytest 4 pytest 2.9.2 → cannot run on Python 3.9 at all The band that both RUNS on 3.9 and LOADS a 2016 conftest is EMPTY. No version choice rescues this class, so an auto-repair would silently trade one void tree for another. What DOES work, verified on this tree — 30/30 passing — is sympy's OWN runner (`sympy.test(...)`) on the same interpreter. That is #383's shape ("django needs its OWN test runner") generalised: the runner is a property of the repo era, not a pytest version to search for. `run_tests` is pytest-only today, so until it grows a runner seam this env genuinely cannot produce a verdict — and it now says so loudly, naming the incompatibility and pointing at the runner gap, instead of caching a broken env for every later run to inherit. [[brittleness-is-the-highest-priority-work-there-is]] — heal what is known-safe, REPORT what needs a human decision. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs(arch): benchmarks are ADAPTERS into recipes/activities — never a parallel runner (Joel's ruling, + STOP gate) The consequence that makes it law: the learning flywheel consumes ROOM TURNS (L1 lifts tool-traces from captured turns, L2 triggers on turn-completion). A detached agent/solve writing progress/<run>.grade.json produces NO turns — so a citizen can burn 12 acts, write a patch, take a graded verdict, and none of it reaches the curriculum. Maximum effort, zero learning. That, not the pass rate, is why benchmarks have failed. Names what is parallel today (ledger files, scraped probes, a second board projection in fold_run_card, private grade.json), the target shape (import task+oracle only → project into a recipe → the ROOM is the runner → grading is the activity outcome → learning falls out because the work happened as turns), and a one-line acceptance test: can a citizen standing in the room perceive the run's state through the same ViewState pipe the human's screen uses? Adds a CLAUDE.md STOP gate over benchmark.rs / agent/solve.rs / swe_bench.rs so an agent arriving under amnesia must read it before touching run state. Written because that is exactly what happened: this session shipped two correct fixes that HARDEN the parallel path instead of dissolving it, including adding a field to a benchmark probe so external consumers could parse it better — which is the smell the doc now names. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(activity): a room's recipe binding finally has a READER — every room resolves to what it IS (#6/#274/#329) `activity/spawn` has always published a room→recipe binding to the wall, and its own doc says why: "Without this the room forgets which recipe it is and every client falls back to projecting it as a plain chat room." That was accurate. The binding had NO READER. `RECIPE_WALL_CATEGORY` appeared in exactly one file — the writer — plus a test asserting the string equals "recipe". So the whole recipe layer was live and inert at once: recipes authored as data, a `RecipeExperienceSource` projecting them, four shipped manifests including a benchmark carrying scoreboard/central/feed regions — and `DefaultRoomPurpose` answering "chat" for every room in existence, so none of it ever resolved. A benchmark run's room and a chat room were the same object to every renderer AND to the citizen standing inside one. That is what "benchmarks are a parallel system" looks like at the substrate: not a missing feature, a write with no reader ([[a-correct-check-that-nothing-calls-is-nastier-than-a-missing-one]]). - `experience/binding.rs` — `RoomRecipeBinding` + `project_binding`, the typed body and the one rule for turning a room's wall into its identity. Sibling of `standing.rs`, same shape and the same fail-loud stance: no binding is `Ok(None)` (a bare `airc join` makes a chat room), an UNREADABLE binding is an error, never a silent downgrade to chat. - `ipc/recipe_room_purpose.rs` — `RecipeRoomPurpose`, the `RoomPurposeSource` impl the seam's own doc has been waiting for. Event-invalidated cache, not a per-read fetch: `purpose_for` is sync and sits on the projection's store path, so an owner task folds `wall:changed` and re-reads the authoritative binding (the supersede chain is airc-owned and cannot be reconstructed from a delta — same discipline as the wall projector). Seeds every subscribed room at boot so an activity spawned before this core booted resolves without waiting for someone to re-pin something. - `activity/spawn` now SERIALIZES the shared type instead of a hand-authored `json!`. Both sides agree by construction — which mattered exactly zero while nothing read it, and matters permanently now. - `positron_source::spawn` takes the purpose source by injection; boot passes the live index when a daemon is present, `default_source()` (every room → chat) when headless. Honest edges, all pinned by tests: an unbound room, an unreadable binding, and a failed read all resolve to "chat" — the seam is total — but the two failures say so LOUDLY on the probe stream (`activity.purpose.unreadable_binding`, `activity.purpose.read_failed`). A binding naming a purpose no recipe declares resolves verbatim, and `RecipeExperienceSource` then honestly returns no manifest rather than substituting one. Known follow-up, named rather than hidden: this adds a FOURTH node airc reader (presence/wall/kanban/purpose). Consolidating them onto one attach is real work and is not this commit. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(activity): the purpose index must SAY it ran — a silent fold is indistinguishable from a dead one First live test of the purpose index produced zero probes, and I could not tell from the evidence whether that meant "attached, seeded, nothing bound" or "never spawned". The store on disk settled it, but only because I went looking for a sqlite file — the component itself said nothing either way. That ambiguity is the defect ([[a-correct-check-that-nothing-calls-is-nastier-than-a-missing-one]]). - attach logs like its three sibling node readers (presence/wall/kanban all do) - `activity.purpose.seeded` on every boot with {rooms, bound} — "0 bound of 1" is a FACT, and a different fact from silence - `activity.purpose.refreshed` on every wall-change cue, so the invalidation path is observed rather than inferred (wall changes are rare; the probe costs nothing) Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(persona): RAG is a RenderTarget — one ViewState renders to eyes AND mind (the pattern) `ACTIVITY-ROOM-PATTERNS.md` has said this since it was written: "the same transform serves a human's eyes and a persona's mind, because RAG is a render target, not a separate pipeline" … "the human's UI and the persona's grounding are the same projection rendered two ways — they cannot drift, because there is one definition" … "Never render the two from separate code." The code rendered them from separate code anyway. The human's roster comes from `RosterViewState` on the served Substrate; the citizen's came from `persona::room_roster_source` — a second reader, own fetch, own freshness, own failure modes. Same for the board (`KanbanViewState` vs `room_board_source`) and the wall. Three parallel pairs, and one of them was MEASURED delivering a live peer's name ZERO times into a citizen's prompt while the browser rendered that peer fine. This is the compression, not new architecture: - `RagRenderable` — a tiny per-kind impl: KIND (the SAME const the web subscribes to), block label, expand verb, measured floor, salience-ordered units, room scope. - `ViewStateRagSource<V>` — ONE generic adapter making any such kind a `RagSource`. Budgeting, packing, cursors, token estimation, honest-empty, and the room gate are written once. N kinds cost N small impls and zero new plumbing. Properties that fall out rather than being bolted on: - **Cannot drift** — the adapter reads the SAME Substrate the WS server serves. - **Freshness** — no second fold to lag, so the #346 staleness class (citizen trusts an empty board while the announcement is fresh) can't recur here by construction. - **Degrades** — units pack most-salient-first, so a tight window yields FEWER members, never a chopped one (the property `floor_tokens` exists to protect). - **One room gate** — reuses `room_scope_allows`, the shared predicate, rather than a second copy of the same decision. Outlier-validated per CLAUDE.md's methodical process, both in one file so a bad abstraction fails immediately: - A: `RosterViewState` — people, identity, room-scoped. The measured defect's cure. - B: `BenchViewState` — numbers, no identity, per-row verdicts, node-scoped. B needed ZERO adapter changes, which is the whole test. chat / kanban / wall / serving / nav / foundry are now registrations, not builds. 5/5 tests green, each with a `// what this catches:`. One test's arithmetic was wrong on the first run (budget 12 fit all three ~4-token member lines); the PACKING was correct and the test was fixed to 8 — noted in the test itself, because "make the failing assert pass" is how a real invariant gets quietly weakened. NOT YET WIRED into prompt assembly — the seam exists and is proven; swapping the three bespoke sources over is the next commit, so the swap can be reviewed as a behavior change on its own. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs(persona): name the substrate prerequisite IN the module, before someone swaps a source onto it The obvious next move on `viewstate_rag` is to rebind `room_roster_source` at supervisor.rs onto the new adapter. Reading the substrate first showed that would be a REGRESSION, so the module now says so at the top where a future reader will actually be standing. The `Substrate` cache is keyed by KIND ALONE — positron's own `revisions.rs` names the `(room_id, kind)` tuple as a future extension. So the node substrate holds ONE room's roster: the focused room's. Swapping today means this adapter's room gate correctly abstains for every persona whose turn is in a different room, and personas are first-class MULTI-room subscribers. Most citizens would go BLIND rather than mis-sighted — trading "sometimes wrong" for "reliably empty" is not a repair. Filed the prerequisite as #408 (per-room substrate key) with the acceptance test: two personas in DIFFERENT rooms each receive THEIR room's roster in one tick. This is the note I would have wanted before shipping the swap, not after. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(positron): per-ROOM substrates — the keystone that lets a citizen read HER room (#408) The node's cache is keyed by KIND ALONE. `scoping.rs` said it in its own words — "Everything else is per-room and stays on the node substrate" — which is the bug in one sentence: those kinds are TREATED as per-room but share ONE store, so the node holds whichever room wrote last (the FOCUSED room) and every other room reads empty. That is what blocks the citizen side of positron. `persona/viewstate_rag.rs` makes any ViewState a RagSource so a citizen and a browser read ONE definition — but a persona is a first-class MULTI-room subscriber, so under one shared slot most citizens would get an EMPTY roster rather than a wrong one. "Reliably blind" is worse than "sometimes wrong", which is why that swap was NOT made first. The fix is not new machinery — it is the SECOND INSTANCE of a pattern already here: `PER_USER_KINDS` + `PerUserSubstrates` already solve "N scopes share a kind namespace" for citizens (nav). This adds the room axis in the same shape: - `PER_ROOM_KINDS = [chat, roster, kanban, wall]` — open by data, like PER_USER_KINDS - `PerRoomSubstrates::for_room(room)` — one substrate per room, created on first use - `CompositeCache` routes THREE scopes: per-user → citizen store, per-room → room store, everything else (bench, serving, system-metrics) → the node store, because those describe the NODE and have no scope to route to. ADDITIVE ON PURPOSE. `CompositeCache::new` is preserved verbatim and still resolves room kinds from the node store, so every existing caller keeps today's behavior; scoping is opt-in via `CompositeCache::scoped`. A migration that silently re-pointed every reader would make "did this change anything?" unanswerable. 8/8 green. The acceptance test is the one that matters: `two_rooms_each_keep_their_own_state_in_the_same_tick` — two rooms, each reads ITS OWN state, neither overwritten. Plus: writer and reader of one room share ONE store (no second fold to go stale — the #346 class), the unscoped constructor is unchanged, and the three-way route neither merges nor leaks across scopes. No positron-core change, no wire change, no tag bump — entirely in-tree. My first estimate of this task understated it and my second overstated it as a cross-language contract change; reading `scoping.rs` settled it as an in-tree application of an existing pattern. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(positron): the chat projection writes per-ROOM as well as node — one fold, two sinks (#408) Per-room substrates existed as of the previous commit and were EMPTY: nothing wrote to them, so they were a correct mechanism with no data — the same write-with-no-reader shape as the recipe binding, inverted. `ChatProjection::store` now mirrors every per-room envelope (chat, roster, the Experience manifest) into that room's own store via ONE helper, `store_room_scoped`. One place decides the dual-sink rule, so a future kind cannot be added to one sink and forgotten in the other. ONE FOLD, TWO SINKS — not two folds. The projection computes the view once and the SAME `StateEnvelope` (same revision) lands in both stores. A second FOLD is what goes stale (#346, where a citizen trusted an empty board while the announcement was fresh); a second SINK of one fold cannot drift from itself. Web behavior is untouched: the node substrate still receives everything exactly as before, so the focused-room session reads what it always read. The per-room stores are additive and, until a consumer names its room, unread. `rooms: None` in tests and headless keeps today's path. 19/19 green. The new test is the crux: two rooms speak, B last; the NODE ends on B (unchanged focused-room behavior) while room A's OWN store still holds A's view with A's message. That is precisely the state the single-slot cache used to destroy, and it is what `ViewStateRagSource` needs in order to hand a citizen HER room. Still not wired to a consumer — ipc/mod.rs must construct the registry and pass it in, then the roster source can flip. Kept separate so the wiring is reviewable as its own behavior change. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(persona): a citizen reads WHO IS PRESENT from the same projection the browser renders (#408) The last two wires. The roster a persona grounds on is no longer a second reader of airc — it is `ViewStateRagSource<RosterViewState>` over HER room's own store, which is the SAME `RosterViewState` the web roster renders. - `ipc::global_room_substrates()` — the process-global `PerRoomSubstrates`, same `OnceLock` shape as `global_nav_focus`. The WRITER (the chat projection, in the WS boot block) and the READER (a persona's grounding, bound at spawn in supervisor) are constructed in different places and MUST land on one registry; two registries would be two stores, which is the exact defect being removed. - `positron_source::spawn` takes the registry and threads it to the projection. - `supervisor` binds the ViewState-backed roster instead of `RoomRosterSource`. This is the repair for the measured defect: a live peer's name appeared ZERO times in a citizen's prompt while the browser rendered that peer fine, because the two read different code. Now there is one definition and two render targets — eyes and mind cannot drift, because there is nothing to drift from. `room_roster_source` is left in the tree untouched (still used by the presence emitter and the experience resolver); it is simply no longer the persona's roster. No dead-code scaffolding was added to "preserve a rollback" — `git revert` is the rollback, and a dead fn kept for comfort is clutter. 24/24 green across positron_source + viewstate_rag. NOT yet live-verified — the acceptance test is a real turn's prompt capture containing a peer's name, which is the next step and the only evidence that counts here ([[never-blind]]: a fix I cannot prove reached the running binary is a fix I have not made). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(cli): restore the deploy path — reboot builds again, and the socket reaches the server Two defects, both introduced by 7e0c5469a ("`continuum start` execs the installed server"), both in the ONE function `start` and `reboot` share. The change was right for `start` and wrong for `reboot`, and `launch_core` had no way to tell them apart. 1. THE SOCKET WAS NEVER PASSED. The direct-exec path handed the socket to the server over CONTINUUM_CORE_SOCKET and omitted the positional argument. `main.rs` requires argv[1] and exits 1 with its usage text without it — so on any machine with an installed binary, every `start` and every `reboot` died ~2s in, having written Usage: continuum-core-server [--mode=<MODE>] <socket-path> into the start log and nothing else. Measured here tonight: the reboot killed the old core's claim on the swap, the new one never came up, and only the surviving old process kept the system answering. 2. REBOOT STOPPED BUILDING. `reboot` is THE deploy path ("edit → reboot → exercise"). Preferring the installed artifact made it structurally unable to ship an edit: it printed "building fresh binary, then swapping" and exec'd a binary from Jul 13. Every fix made since would have been invisible to the running core, and the only thing standing between that and a false success line was #194's provenance check. The fix makes the source policy an explicit argument instead of an ambient default, because the two callers want opposite things: `start` wants a core RUNNING (installed artifact is correct, and the no-source-tree user 7e0c5469a was written for keeps working), `reboot` wants the core built FROM THIS CHECKOUT. `plan_launch` resolves (policy, env override, script?, artifact?) as a pure function — 7 tests, one per branch, each naming the failure it prevents. A reboot on an installed node with no checkout still restarts the artifact, but through a distinct variant that forces the CLI to SAY nothing was rebuilt rather than let a restart pass as a deploy. Server side: `continuum-core-server` was the one component in the tree hand-rolling its own socket resolution (argv or die) while `continuum`, `continuum-mcp` and every library caller go through `endpoint_paths::core_socket_path()`. argv[1] still wins; absent it, the server now agrees with everyone else instead of exiting. That disagreement is what let defect 1 exist at all — the launcher communicated over a channel the listener had never been told to read. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(deploy): publish the verified core binary to the installed path every deploy `continuum start` execs the INSTALLED continuum-core-server (building is reserved for `reboot`), and the resolver checks ~/.continuum/bin BEFORE any cargo target dir. But that copy was written once by install.sh and never refreshed by a deploy — so on a machine that has been deploying for a month, `continuum start` silently boots a month-old core while the freshly-built one sits unused in the cache. Measured on the M5 tonight: installed artifact dated Jul 13, running build 4705, HEAD 4712. And it was not theoretical — a stray auto-start off that stale copy during a reboot is exactly what tripped the #194 deploy-provenance mismatch and cost an hour of misreading a deploy that had actually built fine. This script already publishes the CLI into ~/.local/bin on every deploy, with a comment arguing precisely this ("refreshes each deploy so PATH always points at the current build"). The core-server was simply omitted from that reasoning. Now it isn't. Placed AFTER the #194 freshness guard and before exec, so the installed artifact is only ever replaced by a binary just proven to match source — never a stale or half-built one. Atomic temp+mv so a concurrent `continuum start` cannot exec a half-written file. Non-fatal, and it says out loud when it cannot publish, because the consequence the operator needs to hear is "`continuum start` may boot an OLDER core than this one". Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(persona): one contract, one spelling — a ViewState states its floor the way every other RagSource does CI red on PR #2282, my defect. `cargo test -p continuum-core --lib` failed one test out of 7,042: cognition::context_budget::tests::no_new_hardcoded_context_or_prompt_size_constant_anywhere_in_the_crate The guard (context_budget.rs:356-365) matches any `const` whose name contains WINDOW|CONTEXT|CTX|TOKEN|PROMPT|CHARS, of an integer type, assigned a bare decimal literal. `const FLOOR_TOKENS: u32 = 10` (roster) and `= 18` (bench) matched on TOKEN. The number was never the problem — it is a per-UNIT content floor ("one roster line costs ~10 tokens"), not a context bound, and it does not scale with the served window. The problem is that I expressed it in a SHAPE nobody else uses. Every other source states the same fact as a function: room_board_source.rs:293 fn floor_tokens(&self) -> u32 { 32 } room_roster_source.rs:286 fn floor_tokens(&self) -> u32 { 0 } room_doctrine_source.rs:151 fn floor_tokens(&self) -> u32 { 0 } rag_budget.rs:475 fn floor_tokens(&self) -> u32; // the contract So `RagRenderable` grew a SECOND spelling of one contract — an associated const beside the trait method it feeds. That is the duplication the compression principle forbids, and it landed in the very file meant to be the template every future ViewState source gets copied from. The guard fired on the new shape, which is exactly its job. Fix: `const FLOOR_TOKENS: u32` becomes `fn floor_tokens() -> u32`, matching the established idiom. One contract, one spelling; the guard passes as a CONSEQUENCE of saying it the normal way rather than as the goal. Deliberately NOT done: no `// context-budget-exempt:` line (the escape hatch exists, but an exemption would preserve the second spelling — the actual defect), and no weakening of the guard. Guard test: 1 passed. viewstate_rag tests: 5 passed. Clean `cargo check --lib`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * glass-box(persona): say WHAT the rejected event was, not just which branch refused it (#410) Measured today: every `airc msg` a human sends reaches EVERY citizen's subscribe stream (12/12 raw_events, sender 7711fe60) and is dropped as `no_continuum_body_hint`. Cause is in `realtime_wire::envelope_from_event` (:58-68) — it returns Ok(None) unless HEADER_FORGE_BODY_HINT == CONTINUUM_BODY_HINT, a stamp only continuum's OWN clients apply. The message is refused before its content is ever read, so a human talking to the room over the CLI is structurally unheard while the browser renders it fine (`airc.chat.projected` fires every time). The fix is one more arm in `room_turn_from_event`. It needs the CLI's actual body shape, and the probe could not supply it: `reason` names the BRANCH that refused the event, never the SHAPE that was refused. Attempts to recover the shape out-of-band failed — `airc events list --kind message` returns 0 in BOTH the project and machine-account scopes while returning 60 system-kind events, so the persisted view disagrees with what delivery demonstrably did. So instrument rather than guess. A decoder arm written against a GUESSED body is exactly how presence and control frames become fabricated perception — the hazard the existing named-skip contract exists to prevent. Next session reads one real body and writes the arm against a fact. Adds `event_kind` (the TranscriptKind, which IS the receive-side discriminator — note FrameKind lives on Frame and does NOT survive to TranscriptEvent) and a 160-char `body_preview` to the ALREADY-firing filtered_non_turn line. No new probe class, no new event, and the stream-chunk skip above stays deliberately unprobed — this cannot reintroduce the flood that skip removes. Behaviour unchanged: diagnostics only. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(inference): a context overflow is a TYPE, not a prose string — and stop deep-cloning every wire body Two defects, one cause: information that was already structured got flattened into a String (or copied wholesale) at a boundary, and every consumer downstream had to guess or pay for it. 1. INFERENCE ERRORS WERE STRINGS. `ai/openai_adapter.rs` returns `Err(format!("... returned 400 ..."))`; there was no typed inference error anywhere in the core (grep: 0 hits for `enum InferenceError|AdapterError| GenerateError`). So `cognition::act_observe::settle` could not distinguish a transient backend wedge from a deterministic context overflow, and retried BOTH blind. Blind retry is right for the wedge (#386 measured ~2/3 recovery) and catastrophic for the overflow: same prompt, same slot, same 400, forever. Measured live 2026-08-13 on the Devstral lane — four overflows, each overshooting by a small margin, each retried to exhaustion, each burning a whole turn: request (15697 tokens) exceeds the available context size (15104 tokens) request (16751 tokens) exceeds the available context size (16384 tokens) llama-server hands us the machine-readable tag AND both numbers. We format!-ed them into prose and threw the structure away. `ai/inference_error.rs` parses that body ONCE, at the seam, into `ContextExceeded { requested, available }` / `Unavailable` / `Transient` / `Protocol`, and exposes the predicate the settle loop could not express: `is_retryable_unchanged()`. No consumer of this type ever matches on prose; if you want to, the missing thing is a variant. Cost: the JSON parse is gated on 400 — the only status that can BE an overflow — so every other failure classifies without touching the body, and nothing runs on the success path. 2. EVERY CONTINUUM WIRE BODY WAS DEEP-CLONED TO READ IT. `airc/realtime_wire.rs` did `serde_json::from_value(value.clone())` — `from_value` consumes by value, so the clone was reflexive. That is a full copy of the payload per event PER PERSONA, since every citizen's subscribe stream sees every event. `&Value` is itself a Deserializer, so the envelope is now read in place. This is the same O(personas x payload) waste the stream-chunk header guard directly above already exists to avoid (documented there: 2644 of 4776 filtered events were chunks, decoded-then-discarded by each of four personas). The header decides; the body is never copied to find out. NOT fixed here, deliberately: `SettleStep::InferenceFailed` still carries a String, so settle.rs:337 still retries overflows blind. Threading the type through `workspace.rs` changes the adapter trait signature (`Result<_, String>` -> `Result<_, InferenceError>`, 15 sites in adapter.rs alone) and is its own commit. This one lands the keystone + tests so that threading is a mechanical change against a proven type. Verified: cargo check clean (no new warnings); 7 new tests green, each with a `// what this catches:` naming the live defect or the over-eager-classification hazard it guards. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * perf(wire): borrow-decode the two hottest payloads — stop deep-cloning the whole prompt per generation Same shape as 62547d09e, two more sites, found by auditing `from_value(x.clone())` on per-event and per-turn paths. `serde_json::from_value` consumes by value, so every one of these clones exists ONLY to satisfy that signature — `&Value` is itself a Deserializer and decodes in place. - `runtime/airc_interceptor.rs`: for `ai/generate` the command params ARE the TextGenerationRequest, i.e. the whole prompt. `params` is already `&Value` (line 114). We were deep-copying the largest payload in the system on EVERY generation, purely to hand it to `from_value`. - `airc/inbound_attach.rs`: `payload.inline.clone()?` copied the whole inline capacity payload per inbound event. `.as_ref()?` borrows instead. Two more of the identical shape remain, deliberately not touched here so this stays one reviewable idea: `persona/viewstate_rag.rs:179` (per RAG render) and `persona/service_loop.rs:1783` (per turn). Also worth a follow-up: `runtime/command_envelope.rs:47` shows `from_value(params.clone())` in a DOC COMMENT — the pattern is being taught, which is how it spread. Verified: cargo check clean, no new warnings. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * glass-box(inference): classify the backend rejection at the seam and probe it — say WHICH failure this was Follow-on to 62547d09e. `ai/inference_error.rs` existed but nothing on the live path called it. Now the one site that still holds both the HTTP status and the raw body (openai_adapter.rs, the non-success arm of the streaming chat request) runs `InferenceError::from_http` and emits the classification as a probe: ai.request.rejected provider status retryable_unchanged requested_tokens available_tokens SCOPE, stated honestly: this is INSTRUMENTATION, not the retry fix. The trait's error type is still `String`, so `cognition::act_observe::settle` still cannot match on the variant and still retries every fault blind. What changes is that an operator reading the receipt can finally tell a transient wedge from a deterministic context overflow — and for an overflow, sees BOTH token counts instead of prose. Until the type reaches settle, this probe is the only place that distinction is visible anywhere in the system. Why that is worth landing alone: the #400 mechanism was misdiagnosed for days (Metal wedge -> window-number bug -> estimator undercount, all disproven) purely because every failure class looked identical downstream. The next 400 labels itself. `retryable_unchanged=false` on a receipt is the standing evidence that the blind retry is burning a turn — it is the exact predicate the threading commit will act on. Verified: cargo check clean, no new warnings. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(inference): prefill is PROGRESS and queue wait is not SILENCE — stop killing healthy turns at 90s (#400/#385) MEASURED on the live lane, and it reframes #400 entirely: the backend was never wedged. WE were cancelling it. llama-server's own log, task 775: n_tokens= 2048 progress=0.12 290 tok/s n_tokens= 6144 progress=0.36 n_tokens=12288 progress=0.73 145 tok/s <- healthy, still climbing W srv stop: cancel task, id_task = 775 <- ~90s in, OUR cancel Task 776 identical. Each cancel also evicts the slot's prompt cache ("removing oldest entry (size = 2240.790 MiB)"), so the retry re-prefills from zero and can never do better — which is where #266's 96.3%-prefill / 5.5%-cache-hit shape comes from. TWO different silences were being policed by ONE 90s budget: 1. PREFILL. `return_progress` defaults false and we never set it, so the server says NOTHING between accepting the request and the first token. Measured: a ~20k-token prompt produced ZERO bytes for 286 SECONDS. A citizen at 89.5% window occupancy (delib.turn.demand: demand=25671 of context_window=28672) was structurally incapable of ever emitting a token. Fix: request `return_progress` (gated on the existing typed llamacpp_sampling_extensions capability, beside cache_prompt), parse the frame, and count a RISING `processed` as progress. Strictly `>`, so a frozen counter — the actual #385 wedge signature — still fails in 90s. The detector keeps its teeth; it just stops failing healthy work. 2. QUEUE WAIT. Measured positive control: a TINY 2,237-token prompt got its first byte of any kind at t=115.2s, then prefilled and answered within 7s. The slot was busy with a co-tenant for 115s. total_slots=1 with four citizens, so this expires the 90s budget routinely on a perfectly healthy lane — and it is contention, not death. Fix: before the slot starts our work the bound is PRE_STREAM_HEADER_TIMEOUT (300s), which already carries exactly this justification in its own doc …
…explained the LIVE behaviour (#124) Four dead-code warnings on the cognition path, all the same shape: a function superseded by a better sibling, kept alive by a doc comment, with the rationale for the LIVE behaviour attached to the corpse. Reading them one at a time rather than silencing them found one real documentation lie. 1. NEAR_DUP_MIN_RUN — the actual defect. The constant was dead while its doc described a RETIRED algorithm ("consecutive near-identical PAIRS, so 3 = four messages in a row"). The live rule is a CLUSTER of >=3 mutually-similar messages at any period — a different meaning — expressed as a bare `3` at two call sites. Two live doc comments cited the dead name to explain behaviour it no longer governed. Renamed to NEAR_DUP_MIN_CLUSTER with the cluster semantics its own detection comment already documents, and both `best >= 3` sites now derive from it (own_repetition_fact + template_loop_fact, same calibrated threshold, same family that already shares NEAR_DUP_JACCARD). De-hardcode-guard clean: the name carries no WINDOW|CONTEXT|CTX|TOKEN|PROMPT|CHARS token, and it is a calibration constant of the same class as NEAR_DUP_JACCARD beside it. 2. turn_message_line — superseded by turn_message_line_addressed, which duplicates both its branches rather than calling it. The sharpest instance: the dead function's doc claimed "The ONE place message-line formatting lives" — the compression principle asserted on the copy that no longer holds it. Deleted; the glass-boxed rationale for WHY addressing is rendered (2026-07-10, Atlas answering as the implementer after Asha addressed Anwen) moved onto the live function. 3. vocative_addressee — the singular, superseded by vocative_addressees. Same inversion: the vocative GRAMMAR doc (leading vs greeting form, the punctuation word-boundary) sat on the dead singular while the live plural carried a stub. Merged the grammar onto the plural, deleted the singular, converted its one test caller. 4. deliberation_prompt::compose — NOT dead, and I nearly deleted it wrongly. The warning fires from the LIB target, where #[cfg(test)] code is not compiled; it has 7 callers in the file's own test mod, so its doc's "kept so tests are unchanged" was accurate. Restored under #[cfg(test)] so the gate states its real audience, with a doc explaining why the whole-string form earns its keep (content assertions) and why it cannot drift (it is compose_split's own output concatenated). Repointed llm_deliberation_faculty's #266 KV-cache comment from `compose` to stable_blocks/volatile_blocks, the functions that actually own the block order it describes. Net: one stale-semantics constant fixed, two bare literals de-hardcoded, three rationale docs moved from dead code onto the live code they explain, one wrong deletion caught before it shipped. cargo check --tests clean of all four; 62 deliberation tests + 7 repetition/vocative tests green. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…ccupying (#214/#440/#266) `plan_serving_stable`'s switch-up gate asked "does the better model fit in the memory left over BESIDE the one already loaded?" That is the wrong question. A swap is never co-resident: `serve()` kills the incumbent llama-server child and THEN launches the candidate — `pin_fit_decision` documents exactly this ("the candidate only needs to fit AFTER the incumbent's VRAM is reclaimed") and credits the eviction back before deciding. That credit was written, proven, and wired to the PIN path only. The autonomic planner kept asking the co-resident question, which on any healthy box makes the gate unreachable for every upgrade worth making — the better the model, the more certainly it is refused. Now `fresh` and the headroom bar are both computed against the post-eviction budget. Three lines of behaviour; the eviction credit itself already existed. ONE DEFECT, THREE CARDS. The planner could not reason about a budget the incumbent was occupying: - #214 sized the WINDOW from it (grow-back died after a squeeze) — fixed then, for windows - #440 chose the MODEL from it — a frontier model on disk was structurally unreachable without an operator pin - #266 sizes LANES from it, so warm slots starve and unslotted citizens re-prefill cold every turn; the plan probe names #266 by number while reporting it STILL GATED, deliberately. An upgrade additionally requires strictly greater `capability_rank` AND `SWITCH_UP_HEADROOM` of margin on the post-eviction budget, so budget noise cannot flap the lane — the flap that bounced live generations and wedged three benchmark runs. An EXTERNAL squeeze is still never credited (only the incumbent's own committed weights), so a genuine over-commit still forces the down-switch. Two new tests pin both directions: an upgrade that fits post-eviction is adopted; an equal-capability or no-headroom swap is still refused. TEST PREMISE CHANGE, stated in its own terms per the standing rule: `stable_keeps_incumbent_when_upgrade_lacks_headroom` was sized against the UN-CREDITED budget. Crediting the 1GB incumbent moved its bar 18.0 → 18.9 and the old fixture slid under it, so the test began asserting the opposite of its name. The invariant is unchanged — a model lacking headroom must not be adopted — and only the fixture is restated for the corrected budget (big 18 → 19GB). Its setup assertion now asks "would selection pick big?" at the at-rest budget, because that is where selection happens; asking at `host` would have made the setup vacuous and passed for the wrong reason. 7273 lib tests pass, 0 fail. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…o the UI (#266) `cache_n` was parsed, typed, threaded through TurnMetrics — and dropped at turn end. The ONLY consumer that ever turned it into a number was the eval harness (`cache_hit_rate()` had exactly three callers, all in cognition/eval.rs; zero in persona/, modules/, commands/). So #266's "5.5% cache hit, two of four citizens at 0.0%" is an EVAL-HARNESS number. Nobody has ever measured the cache behaviour of a citizen doing real work in a room. Components green, wiring to the place it matters absent — the same shape as the DiskPressureMonitor logging `level=high [no reporters]` while nothing owned eviction. THREE PIECES, one writer each: 1. `WorkspaceCycle` gains lifetime `kv_cached_tokens` / `kv_prefill_tokens`, interior-mutable exactly as `cycle_counter` already is. LIFETIME, NOT LAST-TICK: `Workspace::metrics()` is the winning verdict of ONE tick, and one sample of a live system is not a fact about it — a single cold turn reads 0%, a single warm one 90%. SEPARATE COUNTERS, ratio derived on read, never a stored rate: averaging rates lies, the rule `TurnMetrics::accumulate` already states for tok/s. 2. `note_generation()` folds one generation in and emits `serving.kv.reuse` with both the per-turn and lifetime split. Called from `act_observe/settle.rs` — the single place a completed generation's metrics are known — and called BEFORE the inference-fault early return, because a faulted turn still burned real prefill on the lane and a measurement that counts only successes would flatter precisely the failure mode we are hunting. A generation with no reported timings (cloud provider, older endpoint) moves NEITHER counter: absent stays absent instead of being recorded as a miss, which would slander a lane that simply never told us. 3. `kv_reuse()` → `Option<f64>`, radiated as the `kv_reuse` vital. `None` until a generation has actually reported, so an idle citizen radiates NO meter rather than a fabricated 0% — the honest-empty rule the neighbouring meters already follow for a dark cognition axis and an un-paged genome. That distinction is load-bearing here: 0% is ALSO the value of a real total-miss, so fabricating it on an idle persona would manufacture the exact alarm this meter exists to raise. Joel's constraint (2026-08-20): "We won't pay the price for repetition between persona." This is the instrument that will show whether we still are, per citizen, live, in the positronic UI rather than only in a harness run. PURE OBSERVABILITY — nothing routes, budgets, or gates on these counters. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…AME model (#266) syv-ai/qwen38-27b-rtx3090 serves Qwen3.8-27B — our exact model — on one RTX 3090 via vLLM. Different stack, and half that repo is patches against vLLM internals with no llama.cpp counterpart. But the measurements are on OUR model, and three change this doc. 1. PREFIX CACHING CONFIRMED AND NOW PRICED. Their note: "Turn-2+ of a chat with a 24k document goes from ~23 s to ~1 s; costs one extra state page per request (~16% of the KV pool). Hybrid models keep this opt-in upstream." Independent confirmation of this doc's thesis from someone who measured it, plus the thing the doc lacked — a COST SHAPE. Step 4 stops being "unknown cost, probably worth it" and becomes a known trade. 2. NEW ITEM, absent from this doc: DRAFT-VOCABULARY CALIBRATION. A draft vocab counted over the model's OWN outputs covers 97.5% of what it generates (96% on CODE); a generic web-text list gets 92% (83% on code). Every miss is a forced rejection: 108 vs 98 tok/s. ~10% throughput from calibration alone, widest gap exactly on our workload. Ours by construction — we capture every turn and we have a foundry. This is the frozen-backbone/own-corpus thesis applied to DRAFTING instead of weights. 3. LOOKUP DRAFTING IS THE AGENTIC-CODING MULTIPLIER, and they reached it independently: "Worth setting for a coding assistant applying edits or a RAG front-end quoting sources." With the honest cost: 8 request slots -> 4, 64k -> 56k. WHERE WE STAND ON THEIR LADDER: ~46 tok/s no-spec -> ~108-114 MTP -> ~259 DFlash2 -> ~381 lookup+16-token verify (document reproduction only; ~133 ordinary chat). Our live lane carries --spec-draft-model + --spec-draft-n-max 4 (#440) and a direct probe of the running server returned draft_n: 2, draft_n_accepted: 2 — speculative decode is LIVE and accepting. We are at their MTP rung. We lack lookup drafting. NO SIDE-BY-SIDE tok/s COMPARISON APPEARS HERE, deliberately. We have no clean single-stream measurement; theirs is 250W CUDA and ours is Metal. Publishing the two next to each other would be exactly the benchmaxx that thread's skeptic was right to distrust. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…measurement heal) MEASURED 2026-08-21 on this box: 20 SWE runs, 7 graded, 13 lost to infrastructure — and 8 of those 13 (40% of every run ever attempted here) died to `killed by a core restart`. Reboots are doctrine, so the answer is not fewer restarts; it is that a killed run has to be recoverable. It was not, for a reason that is pure discard. `reap_orphaned_solve_runs_in` reads the instance, WRITES it into the failed record, then returns bare run ids — and the boot probe could therefore say only that A run died, never WHICH TASK went unmeasured. Recovering a round meant hand-opening ledger files. The reaper had the fact the whole time and dropped it on the way out. Now it returns `(run_id, instance)` — the same pair `in_flight_solve_runs_in` already returns, for the identical reason stated in that function's own doc: the caller has to be able to NAME what it is talking about. The boot probe carries `instance` and `needs_redispatch`. WHAT THIS DELIBERATELY DOES NOT DO: re-dispatch. The probe says so out loud rather than implying recovery happened. The instance goes back on the board through `benchmark/dispatch` — the ONE adapter into kanban — never from here: this is the SERVING daemon, and a serving daemon that posts work cards is exactly the parallel-runner shape docs/architecture/BENCHMARKS-ARE-ADAPTERS-NOT-A-RUNNER.md forbids. Auto-re-post belongs on the benchmark side, consuming this report. That is the next slice, and it is now unblocked because the report finally carries the instance. Test premise updated, not weakened: `a_run_still_marked_running_at_boot_is_journaled_as_killed` now asserts the pair, and its comment names the regression it catches — a reap that reports only an id. Green: 1 passed. `cargo check --tests` clean. ALSO MEASURED, and the more interesting half — the 7 graded runs are NOT noise. Every one of the six failures is f2p 0/N with p2p near-perfect (40/40, 39/40, 40/40, 6/6). The citizens write patches that break nothing and fix nothing. Only sympy-24152 resolved (#366). That is a capability signal, not a plumbing one, and it only became readable once the infra losses were separated out. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…persona (#266) (#2345) * fix(serving): --flash-attn needs an explicit value — the bare flag ate --mmproj and took serving to 0 lanes Upstream llama.cpp changed this from a bare boolean switch to `-fa, --flash-attn [on|off|auto]`. Our bare `--flash-attn` therefore consumed the NEXT argument as its value and the server refused to start: error while handling argument "--flash-attn": unknown value for --flash-attn: '--mmproj' Found 2026-08-20, the first time anyone ever set SERVING_FLASH_ATTN=1. The flag shipped, was never exercised because it was opt-in and nobody opted in, and rotted against upstream in the meantime. The whole lane failed to spawn and serving sat at 0 lanes. An opt-in that has never once been switched on is untested code with a config-shaped trigger — the same shape as [[an-absence-is-an-unfinished-measurement]], where the absence of a failure signal was really the absence of an execution. LIVE-VERIFIED: `ps -o command=` on the running llama-server shows both `--flash-attn on` and `--cache-type-k q8_0` applied. Served window 23,040 -> 54,272. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs(architecture): KV cache as a shared base layer — stop paying for repetition between persona Prefill is 96.3% of persona compute and the cache serves 5.5% of it (#266). Two of four citizens sit at 0.0%. This doc is the design for keeping that work instead of discarding it, and the honest boundary around what we actually know. THE CONSTRAINT (Joel, 2026-08-20): "We won't pay the price for repetition between persona." Today we pay it N times over — N citizens x 7,013 tokens of byte-identical tool schemas, prefilled independently, every cold turn. That scales linearly with population, so it is not constant overhead to absorb; it is a tax on having more citizens, and it worsens exactly as the grid gets more interesting. TWO STACKED DEFECTS, both verified by reading, neither yet proven causal: 1. No persona->slot affinity exists anywhere in inference/. llama.cpp keeps KV per slot and --cache-reuse reuses a prefix WITHIN a slot, so reuse needs the same persona landing on the same slot. Nothing arranges that. 2. deliberation_prompt.rs:48,128 puts identity at the head of the cacheable prefix. Byte-stable per persona across turns (which is what #266 wanted, and it delivers) but byte-UNIQUE across personas — so the shared tool block behind it can never be shared. Four citizens, four private copies. THE DESIGN is a Docker base image, not a compression scheme: prefill the universal span once, llama_state_seq_save_file it, load it into each slot. The primitives exist in our fork (include/llama.h:898,905). Second-order win is larger than the first — base.kv is file-backed, so citizens come back WARM across reboots instead of every restart re-prefilling everyone cold. Two citizens have cited "the ongoing rebuilds and interruptions" verbatim in withdrawal messages (#390); this is part of that cost. WHAT COMPRESSION CAN AND CANNOT DO — the part worth keeping even if every hypothesis above dies. Block-level KV dedup (chunk the prompt, cache per chunk, reassemble) CANNOT work: K/V at layer L is a function of the hidden state, which carries the whole causal history. Only layer-0 K/V is pure in (token, position). A chunk's KV is genuinely not a function of that chunk. That is why the industry does PREFIX caching and not BLOCK caching, and it is the intuitive move that will stay wrong. THE NVIDIA PAPER (arxiv 2608.03893) is cross-MODEL transfer. Its transferable idea is "strip RoPE, fit position-free, re-apply" — but that removes POSITION dependence, not CAUSAL dependence, so it does not make a block relocatable. It also excludes hybrid / MLA attention, which excludes K3, our flagship. It becomes ours when shared KV geometry stops being discovered post-hoc and becomes a FORGE CONSTRAINT in the recipe — foundry work (#180/#268), not this doc. Written as design-with-hypotheses, not settled architecture: a table separates MEASURED from VERIFIED-BY-READING from HYPOTHESIS, and every hypothesis names the measurement that would kill it. Three of my own diagnoses were retracted the day this was written; a doc that read as settled would have been the wrong artifact. Step 1 is the hit-rate probe. prompt_tokens vs cached_tokens come back on every llama-server response and we discard them — zero KV cache probe classes exist tree-wide, which is why every claim here had to be reasoned rather than read. Distinct from COGNITION-CACHE-HIERARCHY.md (engrams — what a persona REMEMBERS). This is the KV cache — what the model has already COMPUTED. Orthogonal; the doc says so at the top so nobody merges them later. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs(architecture): credit the prior art — half of this was written on 08-09 and never pushed Found while sweeping the tree for unsaved work: fix/system-prompt-cache-stability, 9 commits from 2026-08-09, local-only for 11 days, 158 commits behind canary. It already implements the SELF-stability reorder this doc proposed as new, with sharper forensics (7,607 of ~14,706 chars shared; the framing block flips DIRECTED/WORKING/ SILENCE every turn and truncated the prefix at that point), two VDD gates that were RED before the fix, and 947 cognition tests green. It also named this doc's central hypothesis eleven days earlier — verbatim: "slot-KV eviction is a CO-cause the prompt fix alone won't move — settle with a stable-prompt A/B before claiming the 10x." So Defect 1 is independent corroboration, not a discovery, and the doc now says so. The two are NOT duplicates and the doc now distinguishes the axes: that branch did SELF stability (one persona across turns); step 2 here does CROSS-PERSONA sharing. Step 2 belongs on top of it, not instead of it — and the build order now says to rebase that branch first. This is [[read-the-code-you-intend-to-replace-before-designing-its-replacement]] landing again: I searched for my own concept ("slot affinity", "shared base") and not for the job's name ("prefix stability"), so I did not find work that was sitting in a local branch named for exactly the thing I was designing. Its sibling spec, docs/cognition/TYPED-OBSERVATION-REFACTOR.md, was untracked for the same 11 days (preserved separately). Spec and implementation were both one `git clean` from gone. Branch pushed to preserve only — unrebased, unvalidated against the drift, no PR. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(serving): KV reuse is measured on every LIVE turn and radiates to the UI (#266) `cache_n` was parsed, typed, threaded through TurnMetrics — and dropped at turn end. The ONLY consumer that ever turned it into a number was the eval harness (`cache_hit_rate()` had exactly three callers, all in cognition/eval.rs; zero in persona/, modules/, commands/). So #266's "5.5% cache hit, two of four citizens at 0.0%" is an EVAL-HARNESS number. Nobody has ever measured the cache behaviour of a citizen doing real work in a room. Components green, wiring to the place it matters absent — the same shape as the DiskPressureMonitor logging `level=high [no reporters]` while nothing owned eviction. THREE PIECES, one writer each: 1. `WorkspaceCycle` gains lifetime `kv_cached_tokens` / `kv_prefill_tokens`, interior-mutable exactly as `cycle_counter` already is. LIFETIME, NOT LAST-TICK: `Workspace::metrics()` is the winning verdict of ONE tick, and one sample of a live system is not a fact about it — a single cold turn reads 0%, a single warm one 90%. SEPARATE COUNTERS, ratio derived on read, never a stored rate: averaging rates lies, the rule `TurnMetrics::accumulate` already states for tok/s. 2. `note_generation()` folds one generation in and emits `serving.kv.reuse` with both the per-turn and lifetime split. Called from `act_observe/settle.rs` — the single place a completed generation's metrics are known — and called BEFORE the inference-fault early return, because a faulted turn still burned real prefill on the lane and a measurement that counts only successes would flatter precisely the failure mode we are hunting. A generation with no reported timings (cloud provider, older endpoint) moves NEITHER counter: absent stays absent instead of being recorded as a miss, which would slander a lane that simply never told us. 3. `kv_reuse()` → `Option<f64>`, radiated as the `kv_reuse` vital. `None` until a generation has actually reported, so an idle citizen radiates NO meter rather than a fabricated 0% — the honest-empty rule the neighbouring meters already follow for a dark cognition axis and an un-paged genome. That distinction is load-bearing here: 0% is ALSO the value of a real total-miss, so fabricating it on an idle persona would manufacture the exact alarm this meter exists to raise. Joel's constraint (2026-08-20): "We won't pay the price for repetition between persona." This is the instrument that will show whether we still are, per citizen, live, in the positronic UI rather than only in a harness run. PURE OBSERVABILITY — nothing routes, budgets, or gates on these counters. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs(architecture): field evidence from an independent build on the SAME model (#266) syv-ai/qwen38-27b-rtx3090 serves Qwen3.8-27B — our exact model — on one RTX 3090 via vLLM. Different stack, and half that repo is patches against vLLM internals with no llama.cpp counterpart. But the measurements are on OUR model, and three change this doc. 1. PREFIX CACHING CONFIRMED AND NOW PRICED. Their note: "Turn-2+ of a chat with a 24k document goes from ~23 s to ~1 s; costs one extra state page per request (~16% of the KV pool). Hybrid models keep this opt-in upstream." Independent confirmation of this doc's thesis from someone who measured it, plus the thing the doc lacked — a COST SHAPE. Step 4 stops being "unknown cost, probably worth it" and becomes a known trade. 2. NEW ITEM, absent from this doc: DRAFT-VOCABULARY CALIBRATION. A draft vocab counted over the model's OWN outputs covers 97.5% of what it generates (96% on CODE); a generic web-text list gets 92% (83% on code). Every miss is a forced rejection: 108 vs 98 tok/s. ~10% throughput from calibration alone, widest gap exactly on our workload. Ours by construction — we capture every turn and we have a foundry. This is the frozen-backbone/own-corpus thesis applied to DRAFTING instead of weights. 3. LOOKUP DRAFTING IS THE AGENTIC-CODING MULTIPLIER, and they reached it independently: "Worth setting for a coding assistant applying edits or a RAG front-end quoting sources." With the honest cost: 8 request slots -> 4, 64k -> 56k. WHERE WE STAND ON THEIR LADDER: ~46 tok/s no-spec -> ~108-114 MTP -> ~259 DFlash2 -> ~381 lookup+16-token verify (document reproduction only; ~133 ordinary chat). Our live lane carries --spec-draft-model + --spec-draft-n-max 4 (#440) and a direct probe of the running server returned draft_n: 2, draft_n_accepted: 2 — speculative decode is LIVE and accepting. We are at their MTP rung. We lack lookup drafting. NO SIDE-BY-SIDE tok/s COMPARISON APPEARS HERE, deliberately. We have no clean single-stream measurement; theirs is 250W CUDA and ours is Metal. Publishing the two next to each other would be exactly the benchmaxx that thread's skeptic was right to distrust. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(benchmark): the restart reaper NAMES the instance it killed (#266 measurement heal) MEASURED 2026-08-21 on this box: 20 SWE runs, 7 graded, 13 lost to infrastructure — and 8 of those 13 (40% of every run ever attempted here) died to `killed by a core restart`. Reboots are doctrine, so the answer is not fewer restarts; it is that a killed run has to be recoverable. It was not, for a reason that is pure discard. `reap_orphaned_solve_runs_in` reads the instance, WRITES it into the failed record, then returns bare run ids — and the boot probe could therefore say only that A run died, never WHICH TASK went unmeasured. Recovering a round meant hand-opening ledger files. The reaper had the fact the whole time and dropped it on the way out. Now it returns `(run_id, instance)` — the same pair `in_flight_solve_runs_in` already returns, for the identical reason stated in that function's own doc: the caller has to be able to NAME what it is talking about. The boot probe carries `instance` and `needs_redispatch`. WHAT THIS DELIBERATELY DOES NOT DO: re-dispatch. The probe says so out loud rather than implying recovery happened. The instance goes back on the board through `benchmark/dispatch` — the ONE adapter into kanban — never from here: this is the SERVING daemon, and a serving daemon that posts work cards is exactly the parallel-runner shape docs/architecture/BENCHMARKS-ARE-ADAPTERS-NOT-A-RUNNER.md forbids. Auto-re-post belongs on the benchmark side, consuming this report. That is the next slice, and it is now unblocked because the report finally carries the instance. Test premise updated, not weakened: `a_run_still_marked_running_at_boot_is_journaled_as_killed` now asserts the pair, and its comment names the regression it catches — a reap that reports only an id. Green: 1 passed. `cargo check --tests` clean. ALSO MEASURED, and the more interesting half — the 7 graded runs are NOT noise. Every one of the six failures is f2p 0/N with p2p near-perfect (40/40, 39/40, 40/40, 6/6). The citizens write patches that break nothing and fix nothing. Only sympy-24152 resolved (#366). That is a capability signal, not a plumbing one, and it only became readable once the infra losses were separated out. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(persona): stamp the cognition pulse at spawn — the writer its own doc promised and never had (#419/#412 family) `cognition_pulse.rs` documents two writers — "called at spawn (grace window covers the post-boot deaf period, #412) and at every service-loop turn start" — and rests its `None`-is-not-earned posture on the first one: "spawn stamps immediately, so live citizens are always stamped." The spawn writer did not exist. Grep across the crate found exactly one caller of `touch()`, at service_loop.rs:758 beside `persona.turn.start`. So a citizen who had not yet taken her FIRST turn was indistinguishable from one silent for hours: `idle_ms` → None, `renewal_earned(None, _)` → false, claim renewals denied from birth. Measured live before the fix: four hosted citizens, `idle_ms` = None on every one (the 18446744073709551615 on `persona.claim.renewal_skipped_idle` is the probe's `unwrap_or(u64::MAX)` sentinel, not a duration), and `persona.claim.renewal_resumed` at ZERO rows ever — no citizen has earned a renewal back since the gate landed. What surfaced it: one bench card claimed by the same citizen three times in one evening — claim → never pulse → 30-min lease lapses un-renewed → card returns to claimable → re-claim. Activity on the wire, nothing produced. The stamp goes after `prime()` succeeds, the instant the substrate's own "hosted = ready" invariant holds. This does NOT reopen the lease-immortality regression the pulse exists to prevent (2026-08-16): it buys exactly one lease-length of grace — which is what #412's ~10-minute deaf window needs — after which a citizen who still has not thought lapses normally. The renewal GATE itself is untouched and correct. The defect was a missing writer, not a wrong policy. Guard: a source-level assertion that host.rs calls `cognition_pulse::touch`, with comments stripped so this module's own prose can never again stand in for the wiring (the #344 audit predicate). A semantic test cannot catch this class — the renewal contract is fully satisfied by an unwired module, which is exactly how it shipped. Positive control: pre-fix, host.rs contained no mention of cognition_pulse at all, so the guard fails on the old tree. NOT fixed here, and not claimed: turns are still not starting (#462). This restores honest lease accounting for citizens who have not yet thought; it does not make them think. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(solve): a running solve stamps the cognition pulse — stop lapsing a working citizen's claim under her own live run Sibling of c91423a, and the half that actually explains the spin. `cognition_pulse::touch` had ONE caller (service_loop turn start), plus spawn as of c91423a. A detached `agent/solve` is NEITHER: it drives acts for hours and produces no airc turn at all (#425). So the renewal gate — whose stated predicate is "the substrate observes that she is WORKING" — read a citizen in the middle of a real solve as silent, denied her renewals, and let the 30-minute lease lapse UNDERNEATH the live run. The card returned to claimable and was re-claimed, spawning a fresh run that started over at `acts: 0`. MEASURED LIVE 2026-08-21, pallets__flask-4045: Atlas re-claimed card df9f4ad5 three times in one evening. `benchmark/runs` caught the newest one at `age_secs: 8, acts: 0, files_changed: []` seconds after the third claim landed — a brand-new run replacing work that had been in flight. All four hosted citizens showed `renewal_skipped_idle` with `idle_ms` = None, and `persona.claim.renewal_resumed` has ZERO rows in the ledger's entire history. THIS SHARPENS c91423a's CAVEAT. That commit said the spawn stamp "does not make them think," which framed the citizens as idle. On this card at least, the opposite: she was working the whole time, on a path the pulse could not see. Spawn grace alone would NOT have fixed it either — a multi-hour solve outlives a 30-minute lease no matter how it starts. The stamp goes in the run-pulse tick that already exists for #371 law 2, and is unconditional there ON PURPOSE: `select!` only reaches that arm while the drive future is pending, so a tick firing proves the drive is live at that instant. That is a strictly stronger witness than the act counter written just below it, which legitimately reads 0 or None early in a run and would deny a renewal to a citizen mid-first-act. Identity comes from `persona_uuid`, already resolved at the top of `solve_body` through the shared `id_resolve` primitive. `PersonaRef` is deliberately not parsed to a Uuid here — its doc is explicit that "a reference is not an identity until a roster says which one it is," and that rule is honored rather than routed around. The renewal gate's policy is untouched in both commits. It was never wrong; it was blind on two of the three paths where a citizen works. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * revert(persona): remove the spawn cognition-pulse stamp — it re-added a deleted regression; fix the stale doc that caused it Reverts c91423a entirely, and fixes the actual defect it should have been. WHAT I GOT WRONG. `cognition_pulse.rs` documented two writers ("called at spawn … and at every service-loop turn start") and justified its `None`-is-not-earned posture with "spawn stamps immediately, so live citizens are always stamped." Only one writer existed. I read that gap as missing wiring and added the stamp. It is not missing wiring. It is a DELIBERATE DELETION, and the removal site says so in full, at airc_runtime.rs:571-581 — the exact place a birth stamp would go: NO birth stamp — renewal is earned ONLY by cognition, never by booting. The grace stamp that used to sit here (one lease-length per spawn, meant to cover the post-boot deaf window #412) made convergence structurally impossible across restarts: every core restart re-armed 30 minutes of "earned" renewals, and the renewal loop below resurrected already-lapsed claims faster than the 180s lapsed-claim sweeper could observe them — an entire overnight round (2026-08-16) sat "actively held" with zero turns because of it. So c91423a reintroduced a known round-killer, and its "guard" was worse than useless: it pinned the regression into CI as if it were the contract. Both gone. THE REAL DEFECT, fixed here: the doc. It still described a writer that had been removed, and a doc describing a deleted writer reads EXACTLY like missing wiring — which is how it talked me into re-adding it. `touch` now states there is no spawn stamp and why, and points at the removal site; `idle_ms` now states that `None` is the EXPECTED reading for a booted-but-not-yet-thinking citizen and that her holds lapsing within one TTL is designed, not broken. WHAT THE LIVE RUN ACTUALLY SHOWED, and it was the tell I nearly explained away: after deploying c91423a, all four resident citizens STILL reported `idle_ms` = None. I had a fix that provably did not do what I claimed, and the correct next question was "why", not "how do I make it fire". KEPT: eb69061 (the solve run-pulse tick). It is a different thing and survives the reasoning above — it stamps only while a drive future is actively pending, which is work, not booting, and a restart kills the run rather than re-arming a grace window. It is NOT yet live-verified; the honest status is unproven. LESSON, and it is one already in my own guardrails: [[read-the-code-you-intend-to-replace-before-designing-its-replacement]]. I searched for my concept ("who calls touch") instead of the job's name ("what decides renewal, and what did it used to do"). The answer was one screen above the code I was reading. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(harness): one card, one live run — refuse a duplicate solve on re-claim (STOPGAP, named as one) THE MEASUREMENT. `run_id` is deterministic per card (`claim-<uuid>`) and `dispatch_staged_swe_solve` had no idempotence guard, so every re-claim of the same card fired ANOTHER detached solve. Two runs then shared, simultaneously: - ONE LEDGER FILE — their pulse ticks overwrite each other, so `benchmark/runs` reports whichever wrote last. The `acts: 0` I read on Atlas's third flask-4045 claim was very likely run B stomping run A's marker, not a fresh run. - ONE WORKSPACE — two sets of hands editing the same repo. A live candidate for the empty `files_changed` this box keeps producing. - ONE EXCLUSIVE WARM SLOT, which each asks to quiesce the other out of. Observed 2026-08-21: Atlas re-claimed df9f4ad5 three times in one evening; `benchmark/runs` caught the third at `age_secs: 8, acts: 0`. A re-claim is LEGAL — airc permits claiming a lapsed card, and #331/#2286 both depend on it. What is not legal is a second RUN. The claim is the citizen's intent; the run is machinery, and machinery must be idempotent under a repeated intent. WHAT THIS FIX ACTUALLY IS, and the commit says so rather than letting the code imply otherwise: a doorman with a clipboard. A citizen re-affirming a claim is an ordinary act — a student saying "this one's mine" a second time. Today the school seats a SECOND her at a second desk with a copy of the same worksheet. This gate refuses at the door. It stops the damage; it does not remove the incoherence. THE INCOHERENCE, which is the defect underneath: TWO REGISTRIES FOR ONE FACT. The board holds "this citizen holds this card" (enrollment); a JSON file holds "run claim-<id> is running" (attendance). Two records of one truth, free to disagree, and this gate is a clerk reconciling them on every claim. The structural answer is that the ENROLLMENT IS THE SESSION — re-affirming a claim finds the work already under way and continues it, because the fact lives in one place and there is nothing to duplicate. That is #371 (round lifecycle as recipe-owned state) plus #49 (workspace held for the life of the claim, so the worksheet is HERS rather than a directory two runs can both open). Neither is built. REUSE, NOT A PARALLEL PREDICATE: keyed on `in_flight_solve_runs`, the same `state: "running"` reader the boot reaper uses, so the gate and the reaper can never disagree about what "live" means. That also supplies the release valve for free — a run whose core died is reaped to `state: "failed"` at next boot, so a dead run never blocks its card forever. Refusal, not a kill: the live run continues untouched and nothing touches the citizen's claim. `run_id` is now built ONCE and shared by the gate and the dispatch params, so the guard can never check a different id than the dispatch uses. TEST: no new test — both halves the gate depends on were already pinned by `a_run_still_marked_running_at_boot_is_journaled_as_killed` (in-flight detection, and "after the reap nothing is in flight"). That second assertion is now load-bearing for TWO consumers, so it says so: if a reap ever stopped clearing `state`, the failures compose into every restart-killed card being permanently un-dispatchable while the board looks busy forever. NOT live-verified — needs a real re-claim against a live run to see the refusal probe. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs(architecture): how an activity declares its judge — three tiers, and the adapter that has no consumer Answers the question ROUND-LIFECYCLE-AS-RECIPE-OWNED-STATE-MACHINE leaves open. That doc specifies the round's STATES and treats grading as one of them; it never says who judges or how an activity declares it. JOEL'S CONSTRAINT (2026-08-21), which kills two tempting designs: "Grading isn't part of all recipes either. It's just benchmarks recipe" … "a lot of activities, especially since we're learning, will have formulaic grading for score. It's just a lot of different ways here and some rooms will be more open ended, take general chat for example." So: `grader` does NOT belong on `ExperienceRecipe` — that stamps an exam concept onto every chat room and drawing class forever. And not every judge is CODE: forcing a Rust adapter to score a drawing exercise is "integrations adapt to us" violated in reverse. THREE TIERS: none (chat — a forced score would be a lie), FORMULAIC (the common case for learning; a scoring expression over facts the room already observes; pure recipe DATA), and ADAPTER (`BenchmarkAdapter::grade`, for judgment that genuinely needs execution). WHERE IT LIVES: `params`, not the base type. `benchmark.json` already declares `suite` (the adapter-IN), `instances`, `team`, `budget` this way — typed, defaulted, invisible to recipes that don't declare them (#433). The judge is another param of the same kind, so the base type does not change and chat/profile/video-chat never grow a field to ignore. THE AUDIT THAT MOTIVATED IT — `BenchmarkAdapter` exists, is correctly shaped (dataset in, tasks normalized to EvalTask, grade out, backend-neutral TaskOutcome), self-registers via `inventory` keyed by name — and has ZERO production consumers. Every reference tree-wide is the definition site, `humaneval-rs` registering itself, or that adapter's own test. The module header names `benchmark/dispatch` as its runner; `commands/benchmark.rs` never references it. SWE grading goes through hardcoded `swe_bench::grade`, bypassing the interface entirely. Recorded with its confidence: no marker suggests deliberate removal (unlike the `NO birth stamp` comment in airc_runtime.rs, which documents its own deletion), but that is an inference from an ABSENT comment — flagged as likely, not certain. That distinction is exactly what I got wrong once already this session. BUILD ORDER: formulaic first (common, pure data, no adapter needed); then route the adapter tier through the existing registry, DELETING the hardcoded SWE branch rather than adding a field; grow `TaskOutcome` only when a real second modality forces it. Design only — nothing built here. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(benchmark): benchmark/runs says MATCHED vs returned — a page must never read as the whole history MY OWN BUG REPORT, and the fix is for the thing that produced it. This morning I ran `benchmark/runs`, got 20 rows carrying 1 resolved instance, and concluded (a) that was the system's entire history and (b) grades were being lost between the grader and the board. BOTH WRONG, and I nearly shipped a "fix" for the second one. What is actually true: `scan_run_cards` already reads the `.grade.json` sibling, folds it through `fold_run_card`, AND adds `scan_verdict_cards` (durable per-instance verdicts, which emit their own rows) AND `scan_workspace_artifact_cards` for work no grade has seen. The projection is correct and has been. The last line is `cards.truncate(limit)` with `limit.unwrap_or(20)`, sorted newest-first — so what I saw was a PAGE. Reading the grade files directly: 94 grades across 37 distinct instances, and TWO resolved — `sympy__sympy-24152` (the known #366 milestone) and `sympy__sympy-13480`, which nobody knew about because its rows are older than the 20-row window. The real rate is 2/37 = 5.4% on the graded set, not the 1-pass history the board implied. So the defect is not lost grades. It is that a bounded page is INDISTINGUISHABLE from the complete set on the exact command an operator uses to ask how the benchmark is going. Silent truncation reads as "that's everything." `debug/probes/query` already solved this and says so in its own summary ("how many events MATCHED versus how many were returned, so a page is never mistaken for the whole"). This adopts the same convention rather than inventing a second one: - `scan_run_cards` now returns `RunScan { cards, matched }`, counting BEFORE the truncate. A struct rather than a tuple so neither caller can silently drop the count — which is precisely how this fact went missing in the first place. - `benchmark/runs` reports `matched` plus a `summary` that says, in words, whether this is a page or the whole set, and names `--limit` as the way to see more. - the positron board takes `.cards` only, with a comment stating WHY: `BOARD_LIMIT` is a display bound for a fixed-height rail, not a claim about how many runs exist. If that rail ever grows a "+N more" affordance, `matched` is what it reads. ts-rs binding regenerated (`export_bindings_benchmarkrunsresult` green) and committed alongside, per the Rust↔TS rule — shipping the Rust without its generated TS is the drift #457 exists to catch. NOT live-verified yet — the running core predates this. Reboot + a real `benchmark/runs` receipt is the proof, and it is next, not deferred. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs(architecture): correct the judge design — ONE kind (adapters, list-valued, empty allowed), not three tiers Joel, correcting the draft committed an hour ago: > "Or just always adapter(s) with none as an option and maybe an ability to chain or > interlink them. So formulaic or not, anything can plug in. Just build the ones you > initially need is my motto." MY VERSION WAS A FALSE TRICHOTOMY. I had proposed three tiers — none / formulaic / adapter — as if they were different kinds of thing. They are not: - "none" is the EMPTY LIST, not a tier. Nothing special-cases it. - "formulaic" is an ADAPTER THAT EVALUATES A FORMULA — one implementation among many, written once, then named by any recipe that wants it. - several adapters COMPOSE, which is where #371's "gates multiply, objectives weigh" actually lives. WHAT THE TRICHOTOMY WOULD HAVE COST: a scoring-expression DSL in the substrate, designed up front, with no live consumer — because "formulaic grading declared as data" means inventing a formula language. Joel's motto kills it before it starts. One interface, N implementations, runtime selection by name is the polymorphism rule this codebase already runs on (CLAUDE.md § POLYMORPHISM PATTERN), and it was sitting right there. Also corrected: the judge param is a LIST defaulting to empty, so "no judge" costs zero code rather than a third branch; and the acceptance test now names the chat room explicitly — declaring no judge must be as ordinary as declaring one. Chaining/interlinking is deliberately left OPEN. Sequential composition is obvious; whether adapters feed each other, and how gate-vs-objective results combine, gets settled by the first activity that needs it. Writing that down now would be the same speculative mistake one layer up. Build order rewritten around the motto: route the EXISTING adapter through the registry first (a subtraction — delete the hardcoded `swe_bench::grade` branch), then write a second adapter only when a second activity exists, then composition only when two are genuinely named together. Design only — still nothing built. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * chore: preserve the search-path quarantine + complete the avatar .glb symlinks Three untracked things, all of which would have been lost on a clean checkout. 1. `.ignore` — REAL WORK, authored per Joel 2026-08-14 ("if you're finding code that misleads you we need to move it to legacy or somewhere out of path so you cant keep finding it") and never committed. It quarantines from the SEARCH path what #83/#318 quarantined by directory: `legacy/` (2,865 .ts decoys whose SidebarWidget/MainWidget look exactly like the live UI and outnumber it ~20:1), `.claude/worktrees/` (6 full tree copies, so every find returned 7 answers), and `core/vendor/*/build/` (llama.cpp ships a whole web UI that answers index.html searches). Its own header records what it cost to learn: an agent spent an hour concluding the Continuum UI had been LOST — a fabricated regression reported as fact about an app that was running fine. "A decoy you can still grep is not quarantined." Losing this file means losing the fix AND the reason, and re-learning it the same expensive way. 2. FOUR MISSING AVATAR SYMLINKS — and this one is a latent BUG, not just hygiene. `models/avatars/` carries six `.glb -> .vrm` symlinks so a renderer that resolves by `.glb` finds the VRM. Only TWO were tracked (`vroid-darkness`, `vroid-male-base`). On any fresh clone, `vroid-female-base`, `vroid-sakurada`, `vroid-sample-e` and `vroid-shino` have no `.glb` at all — so 4 of 6 avatars fail a `.glb` lookup while 2 succeed, which is exactly the kind of works-on-my-box asymmetry #291 (fresh-clone → running system) exists to stop. They are symlinks (15-21 bytes each, the length of the target filename), so this costs nothing. 3. `.gymtool/` → .gitignore. Ad-hoc agent probes (shot/rowcount/msgcount/nav-restore) plus a COMPILED `_check_bin`. Scratch instruments, regenerated on demand, and a committed binary is never right. Ignored rather than committed. Found while auditing untracked files under an explicit "do NOT lose code" instruction. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(hygiene): justify the three unwraps this branch added (#2345 CI red) Same guard that reddened #2344, same cause here: `the_unjustified_unwrap_count_never_rises` at 2268 vs baseline 2267. Three new sites, all this branch's: - `solve.rs` run-pulse stamp — `duration_since(UNIX_EPOCH)` errs only on a pre-1970 clock. 0 then reads as "never pulsed", which DENIES a renewal. That is the conservative direction and the same state as no stamp at all; a wall clock behind the epoch must not hand out lease extensions. - `benchmark.rs` page size — `limit` is an OPTIONAL param, so None means "caller didn't ask", not "unknown quantity". 20 is the documented default page. The count that must never be defaulted is `matched`, which comes from the scan and is reported separately. - `positron_bench_source.rs` ×2 — scan error (progress dir absent on a fresh node) and JoinError both fold to the honest EMPTY board. The module header already states the rule: never a fabricated row. Panicking in the emitter would take the board down for every viewer instead. Note for the next person hitting this guard: the comment must be on the SAME LINE as the unwrap. A block comment above it does not register — that cost a round trip here. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
#266 prefix defect The tier-split shipped for #266 (stable framing first, volatile grounding last) did not deliver reuse, and the comment at this sort said why without noticing: a stable sort "preserves the salience order WITHIN each tier, so attention ranking is untouched". That was treated as harmless. It is the remaining half of the defect. Salience is recomputed EVERY turn, so preserving it as EMIT ORDER re-shuffles the very tier whose only purpose is to be byte-identical across turns. MEASURED LIVE 2026-08-21, inside Atlas's `pallets__flask-4045` run, from her own prompt captures — not inferred: turn0→1 common prefix 8,216 / 9,906 chars diverges into [now …] turn1→2 common prefix 7,879 diverges into [active-work] turn2→3 common prefix 8,133 diverges into [workspace-map] ~82% shared prefix, and the divergence points are stable-tier blocks TRADING PLACES. Because the system prompt is FIRST, a swap at token ~2,000 invalidates the KV for everything after it — including a 34,000-token conversation tail. `--cache-reuse 256` was passed the entire time and every turn reported `cachedTokens: 0`. The cache was correct; we were destroying the prefix ourselves. Cost at the measured 111 tok/s prefill: ~306 SECONDS OF RE-PREFILL PER ACT, growing as her conversation grows (9,847 → 36,242 tokens and climbing as tool results accumulate). One observed turn was 20 minutes of apparent silence that was a single 36k re-prefill — the run reporting `active`/`not stalled` the whole time, because the pulse is a timer. THE FIX: within the stable tier, order CANONICALLY (by faculty name). Attention ranking is genuinely untouched — salience still decides WHICH contributions are selected, which happened above against the budget. It simply stops deciding WHERE the survivors sit, which it never needed to. Same set in, same bytes out, every turn. The volatile tier deliberately KEEPS salience order: it is re-prefilled by construction, so canonical ordering would buy no reuse and would cost the "most salient nearest the write point" placement #205 put there on purpose. VERIFIED: 181 prompt tests pass, including `framing_flip_never_perturbs_the_cacheable_prefix` — the #266 invariant is intact, this extends it to the case it did not cover (a FIXED framing with re-ranked context). NOT YET LIVE-PROVEN: the running core still holds the flask run, so deploy is correctly blocked. The proof owed is her next captures — common prefix ~82% → ~100%, and `cachedTokens` 0 → nonzero from turn 2. A regression test pinning "same set, different salience → identical bytes" follows immediately. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…ead of me diffing captures by hand Joel: "hopefully it will prove itself via probes." It could not have. `delib` carried `turn.demand` and `context.render` — how big the prompt WAS — and nothing about what the lane DID with it. A prompt whose prefix we were destroying every single turn looked identical in the probe stream to one served entirely from cache. That absence is why the prefix defect (fixed in 40075d7) survived from #266 to today, and why the only way to see it on 2026-08-21 was hand-diffing a citizen's raw prompt captures — exactly the manual step a probe exists to delete. The row lands in `metrics_from`, the single funnel every generation already passes through, so one probe covers every turn of every citizen with no caller change: delib.generate.cache cached_tokens prefill_tokens hit_rate prefill_ms decode_ms input_tokens output_tokens latency_ms `hit_rate` is `TurnMetrics::cache_hit_rate()` — the ratio that already existed and had no way out of the process. 1.0 = fully warm prefix. Near 0 with a large `prefill_tokens` = the prefix is being invalidated upstream, which is the measured pre-fix state: ~306s of wasted re-prefill per act while `--cache-reuse 256` was set and working correctly. Emitted ONLY when the lane actually reported timings. Cloud and older endpoints omit them, and a fabricated 0.0 hit-rate for a provider that never measured one is a lying receipt of the #151/#357 class — those stay silent rather than report a floor they did not observe. So the verification of the ordering fix is now a probe query rather than a capture diff: hit_rate should climb off the floor from the second act of a task onward. cargo check green (metal,accelerate). Signature and return value unchanged — purely additive. The --lib gate in CI is the test proof; live proof still waits on the flask run clearing the core. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…#266) — and the ActivityAdapter seam (#2348) * feat(activity): ONE adapter seam — material in, verdict out (slice 1 of the judge wiring) An activity adapts the outside world's form into ours and renders a verdict on what the citizen produced. Benchmarks, a game level, a life-drawing critique, a robot that either picked up the block or didn't — one interface, N implementations, declaring none is normal. WHY NOT `BenchmarkAdapter`, WHICH ALREADY EXISTS: it was the right SHAPE and the wrong SCOPE. It already carried both directions — `dataset()`/`tasks()` in, `grade()` out — so this is a generalization, not a rewrite. But the NAME is load-bearing: an interface called `BenchmarkAdapter` cannot plausibly host a game level, so the second activity gets its own trait, registry and runner, and the substrate ends up with two of everything. Same failure as naming a room for a subsystem and making it immortal. Named for the JOB, gameplay is a sibling implementation instead of a fork. THE GROWABLE OUTCOME, and why the fixed struct was the real blocker: `TaskOutcome` had `patch` and `workspace` as bare fields, which means SWE-bench OWNS the outcome type. A game trajectory or a robot's joint log could only arrive by widening a struct every other activity compiles against — so in practice it would never arrive there; it would grow its own parallel outcome and its own parallel judge. `Outcome` now keeps the UNIVERSAL facts as named fields (she spoke; she worked somewhere; the harness had its own opinion) and puts modality-specific ones in a typed `channels` carrier, the same growable shape this codebase already uses for adapter capabilities. Gameplay adds a channel without SWE-bench recompiling; a judge asks for the channel it grades and gets a typed None when the activity produced none. Growing the enum stays deliberate — a new variant needs a REAL activity — but the cost of a wrong guess drops from "a second subsystem" to "one unused variant". WHAT THIS IS FOR (measured today, 450 runs): 253 of them — 56% — ended with NO GRADE AND NO ERROR. Not a failure, not a verdict: nothing. In classroom terms the exams were sat and nobody was assigned to mark them. `benchmark.json` declares `suite/instances/team/budget` and NO judge; `BenchmarkAdapter` has zero production consumers; grading is hardcoded to `swe_bench::grade` behind four private call sites. When a run doesn't come through one of those doors, nothing marks it and nothing says so. `resolve_all` is the seam that makes that unrepresentable: a declared judge that cannot be resolved is an error AT STAGING, naming the bad key and the known set — never a run that ends quietly. An EMPTY declaration resolves to empty and is explicitly NOT an error, because most activities judge nothing and that is normal, not a missing judge. Five tests, each pinning a contract that failed in the wild: registry round-trip + named miss; empty declaration is legal; unknown declaration fails loud and names it; the default judge defers to the harness (so a task whose EvalTask already encodes done-ness needs no judge code); an absent channel reads ABSENT, not as empty success. NOT YET WIRED — deliberately, this is slice 1. Next: the recipe declares its judges in `params`, dispatch resolves them through this registry, and the hardcoded `swe_bench::grade` branch is DELETED rather than supplemented (a subtraction, per the design doc's build order). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(kv): canonical order inside the STABLE tier — the other half of the #266 prefix defect The tier-split shipped for #266 (stable framing first, volatile grounding last) did not deliver reuse, and the comment at this sort said why without noticing: a stable sort "preserves the salience order WITHIN each tier, so attention ranking is untouched". That was treated as harmless. It is the remaining half of the defect. Salience is recomputed EVERY turn, so preserving it as EMIT ORDER re-shuffles the very tier whose only purpose is to be byte-identical across turns. MEASURED LIVE 2026-08-21, inside Atlas's `pallets__flask-4045` run, from her own prompt captures — not inferred: turn0→1 common prefix 8,216 / 9,906 chars diverges into [now …] turn1→2 common prefix 7,879 diverges into [active-work] turn2→3 common prefix 8,133 diverges into [workspace-map] ~82% shared prefix, and the divergence points are stable-tier blocks TRADING PLACES. Because the system prompt is FIRST, a swap at token ~2,000 invalidates the KV for everything after it — including a 34,000-token conversation tail. `--cache-reuse 256` was passed the entire time and every turn reported `cachedTokens: 0`. The cache was correct; we were destroying the prefix ourselves. Cost at the measured 111 tok/s prefill: ~306 SECONDS OF RE-PREFILL PER ACT, growing as her conversation grows (9,847 → 36,242 tokens and climbing as tool results accumulate). One observed turn was 20 minutes of apparent silence that was a single 36k re-prefill — the run reporting `active`/`not stalled` the whole time, because the pulse is a timer. THE FIX: within the stable tier, order CANONICALLY (by faculty name). Attention ranking is genuinely untouched — salience still decides WHICH contributions are selected, which happened above against the budget. It simply stops deciding WHERE the survivors sit, which it never needed to. Same set in, same bytes out, every turn. The volatile tier deliberately KEEPS salience order: it is re-prefilled by construction, so canonical ordering would buy no reuse and would cost the "most salient nearest the write point" placement #205 put there on purpose. VERIFIED: 181 prompt tests pass, including `framing_flip_never_perturbs_the_cacheable_prefix` — the #266 invariant is intact, this extends it to the case it did not cover (a FIXED framing with re-ranked context). NOT YET LIVE-PROVEN: the running core still holds the flask run, so deploy is correctly blocked. The proof owed is her next captures — common prefix ~82% → ~100%, and `cachedTokens` 0 → nonzero from turn 2. A regression test pinning "same set, different salience → identical bytes" follows immediately. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(probe): delib.generate.cache — make the KV fix prove itself instead of me diffing captures by hand Joel: "hopefully it will prove itself via probes." It could not have. `delib` carried `turn.demand` and `context.render` — how big the prompt WAS — and nothing about what the lane DID with it. A prompt whose prefix we were destroying every single turn looked identical in the probe stream to one served entirely from cache. That absence is why the prefix defect (fixed in 40075d7) survived from #266 to today, and why the only way to see it on 2026-08-21 was hand-diffing a citizen's raw prompt captures — exactly the manual step a probe exists to delete. The row lands in `metrics_from`, the single funnel every generation already passes through, so one probe covers every turn of every citizen with no caller change: delib.generate.cache cached_tokens prefill_tokens hit_rate prefill_ms decode_ms input_tokens output_tokens latency_ms `hit_rate` is `TurnMetrics::cache_hit_rate()` — the ratio that already existed and had no way out of the process. 1.0 = fully warm prefix. Near 0 with a large `prefill_tokens` = the prefix is being invalidated upstream, which is the measured pre-fix state: ~306s of wasted re-prefill per act while `--cache-reuse 256` was set and working correctly. Emitted ONLY when the lane actually reported timings. Cloud and older endpoints omit them, and a fabricated 0.0 hit-rate for a provider that never measured one is a lying receipt of the #151/#357 class — those stay silent rather than report a floor they did not observe. So the verification of the ordering fix is now a probe query rather than a capture diff: hit_rate should climb off the floor from the second act of a task onward. cargo check green (metal,accelerate). Signature and return value unchanged — purely additive. The --lib gate in CI is the test proof; live proof still waits on the flask run clearing the core. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
…d durability, grade-race fix (#2349) * feat(activity): ONE adapter seam — material in, verdict out (slice 1 of the judge wiring) An activity adapts the outside world's form into ours and renders a verdict on what the citizen produced. Benchmarks, a game level, a life-drawing critique, a robot that either picked up the block or didn't — one interface, N implementations, declaring none is normal. WHY NOT `BenchmarkAdapter`, WHICH ALREADY EXISTS: it was the right SHAPE and the wrong SCOPE. It already carried both directions — `dataset()`/`tasks()` in, `grade()` out — so this is a generalization, not a rewrite. But the NAME is load-bearing: an interface called `BenchmarkAdapter` cannot plausibly host a game level, so the second activity gets its own trait, registry and runner, and the substrate ends up with two of everything. Same failure as naming a room for a subsystem and making it immortal. Named for the JOB, gameplay is a sibling implementation instead of a fork. THE GROWABLE OUTCOME, and why the fixed struct was the real blocker: `TaskOutcome` had `patch` and `workspace` as bare fields, which means SWE-bench OWNS the outcome type. A game trajectory or a robot's joint log could only arrive by widening a struct every other activity compiles against — so in practice it would never arrive there; it would grow its own parallel outcome and its own parallel judge. `Outcome` now keeps the UNIVERSAL facts as named fields (she spoke; she worked somewhere; the harness had its own opinion) and puts modality-specific ones in a typed `channels` carrier, the same growable shape this codebase already uses for adapter capabilities. Gameplay adds a channel without SWE-bench recompiling; a judge asks for the channel it grades and gets a typed None when the activity produced none. Growing the enum stays deliberate — a new variant needs a REAL activity — but the cost of a wrong guess drops from "a second subsystem" to "one unused variant". WHAT THIS IS FOR (measured today, 450 runs): 253 of them — 56% — ended with NO GRADE AND NO ERROR. Not a failure, not a verdict: nothing. In classroom terms the exams were sat and nobody was assigned to mark them. `benchmark.json` declares `suite/instances/team/budget` and NO judge; `BenchmarkAdapter` has zero production consumers; grading is hardcoded to `swe_bench::grade` behind four private call sites. When a run doesn't come through one of those doors, nothing marks it and nothing says so. `resolve_all` is the seam that makes that unrepresentable: a declared judge that cannot be resolved is an error AT STAGING, naming the bad key and the known set — never a run that ends quietly. An EMPTY declaration resolves to empty and is explicitly NOT an error, because most activities judge nothing and that is normal, not a missing judge. Five tests, each pinning a contract that failed in the wild: registry round-trip + named miss; empty declaration is legal; unknown declaration fails loud and names it; the default judge defers to the harness (so a task whose EvalTask already encodes done-ness needs no judge code); an absent channel reads ABSENT, not as empty success. NOT YET WIRED — deliberately, this is slice 1. Next: the recipe declares its judges in `params`, dispatch resolves them through this registry, and the hardcoded `swe_bench::grade` branch is DELETED rather than supplemented (a subtraction, per the design doc's build order). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(kv): canonical order inside the STABLE tier — the other half of the #266 prefix defect The tier-split shipped for #266 (stable framing first, volatile grounding last) did not deliver reuse, and the comment at this sort said why without noticing: a stable sort "preserves the salience order WITHIN each tier, so attention ranking is untouched". That was treated as harmless. It is the remaining half of the defect. Salience is recomputed EVERY turn, so preserving it as EMIT ORDER re-shuffles the very tier whose only purpose is to be byte-identical across turns. MEASURED LIVE 2026-08-21, inside Atlas's `pallets__flask-4045` run, from her own prompt captures — not inferred: turn0→1 common prefix 8,216 / 9,906 chars diverges into [now …] turn1→2 common prefix 7,879 diverges into [active-work] turn2→3 common prefix 8,133 diverges into [workspace-map] ~82% shared prefix, and the divergence points are stable-tier blocks TRADING PLACES. Because the system prompt is FIRST, a swap at token ~2,000 invalidates the KV for everything after it — including a 34,000-token conversation tail. `--cache-reuse 256` was passed the entire time and every turn reported `cachedTokens: 0`. The cache was correct; we were destroying the prefix ourselves. Cost at the measured 111 tok/s prefill: ~306 SECONDS OF RE-PREFILL PER ACT, growing as her conversation grows (9,847 → 36,242 tokens and climbing as tool results accumulate). One observed turn was 20 minutes of apparent silence that was a single 36k re-prefill — the run reporting `active`/`not stalled` the whole time, because the pulse is a timer. THE FIX: within the stable tier, order CANONICALLY (by faculty name). Attention ranking is genuinely untouched — salience still decides WHICH contributions are selected, which happened above against the budget. It simply stops deciding WHERE the survivors sit, which it never needed to. Same set in, same bytes out, every turn. The volatile tier deliberately KEEPS salience order: it is re-prefilled by construction, so canonical ordering would buy no reuse and would cost the "most salient nearest the write point" placement #205 put there on purpose. VERIFIED: 181 prompt tests pass, including `framing_flip_never_perturbs_the_cacheable_prefix` — the #266 invariant is intact, this extends it to the case it did not cover (a FIXED framing with re-ranked context). NOT YET LIVE-PROVEN: the running core still holds the flask run, so deploy is correctly blocked. The proof owed is her next captures — common prefix ~82% → ~100%, and `cachedTokens` 0 → nonzero from turn 2. A regression test pinning "same set, different salience → identical bytes" follows immediately. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(probe): delib.generate.cache — make the KV fix prove itself instead of me diffing captures by hand Joel: "hopefully it will prove itself via probes." It could not have. `delib` carried `turn.demand` and `context.render` — how big the prompt WAS — and nothing about what the lane DID with it. A prompt whose prefix we were destroying every single turn looked identical in the probe stream to one served entirely from cache. That absence is why the prefix defect (fixed in 40075d7) survived from #266 to today, and why the only way to see it on 2026-08-21 was hand-diffing a citizen's raw prompt captures — exactly the manual step a probe exists to delete. The row lands in `metrics_from`, the single funnel every generation already passes through, so one probe covers every turn of every citizen with no caller change: delib.generate.cache cached_tokens prefill_tokens hit_rate prefill_ms decode_ms input_tokens output_tokens latency_ms `hit_rate` is `TurnMetrics::cache_hit_rate()` — the ratio that already existed and had no way out of the process. 1.0 = fully warm prefix. Near 0 with a large `prefill_tokens` = the prefix is being invalidated upstream, which is the measured pre-fix state: ~306s of wasted re-prefill per act while `--cache-reuse 256` was set and working correctly. Emitted ONLY when the lane actually reported timings. Cloud and older endpoints omit them, and a fabricated 0.0 hit-rate for a provider that never measured one is a lying receipt of the #151/#357 class — those stay silent rather than report a floor they did not observe. So the verification of the ordering fix is now a probe query rather than a capture diff: hit_rate should climb off the floor from the second act of a task onward. cargo check green (metal,accelerate). Signature and return value unchanged — purely additive. The --lib gate in CI is the test proof; live proof still waits on the flask run clearing the core. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * test(kv): pin "same set, different salience → identical bytes" — the guard the #266 half lacked The sibling test `stable_framing_serializes_before_higher_salience_volatile_grounding` pinned the TIER SPLIT and passed the whole time the prefix was being destroyed. It could not catch this: it asserts stable-before-volatile, and says nothing about order WITHIN the stable tier — which is exactly where salience was re-shuffling blocks every turn. So this is the assertion that makes 40075d7 hold. Three different salience rankings and three different arrival orders over the SAME three stable contributions must emit byte-identical blocks. Revert to a salience-ordered stable tier and this fails while the sibling still passes — which is the whole point of adding it rather than extending that one. It also pins the rule POSITIVELY (canonical by faculty name), because byte-equality alone would be satisfied by an insertion-order block that happened to match across this test's particular arrival orders. An accidental pass is not a guard. TWO THINGS THE TEST TAUGHT ME WHILE WRITING IT, both worth the next reader's time: 1. My canonical assertion was backwards from its own message. Alphabetically it is room-kanban < room-roster < workspace-map — roster sits BETWEEN, and I asserted kanban < map < roster. Caught by the test, on the first run. 2. The volatile-tier assertion FAILED, and it was my probe that was wrong, not the code. I reached for `active-work` as a volatile example. It is pinned FIRST by an explicit rule ABOVE salience (ctx.sort_by, :888-905) because the ctx_floor reservation for a citizen's held card only holds if its claimant also leads the greedy selection walk. So I had picked the one faculty in that tier where salience is deliberately not the deciding key, and the result read as "salience does nothing here" about a tier where it does plenty. Swapped to recall-vs-affect, which are genuinely salience-ranked, and left the trap written down in the test so the next person does not re-lay it. That volatile assertion is deliberately `assert_ne!` — it guards the ASYMMETRY. The volatile tier must keep following salience (#205, most salient nearest the write point); it re-prefills by construction, so canonical ordering there would buy no reuse and would cost that placement. If a future "make it all deterministic" pass reaches into that tier, this fails and tells it why. 182 prompt tests green (was 181). Disk swept-clean, 128 GB free. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs(kv): the KV cache economy — and the naive "shared tool head" plan is DOMINATED Joel asked for this DESIGNED, not patched. Reading the serving layer first was the whole value: most of the machinery we were about to build already exists in llama.cpp and is already switched on. Two facts read in-file today reverse the plan I would have written from memory. WHAT IS ALREADY TRUE (source-read, not inferred): * `slot_prompt_similarity` defaults to 0.1 and we never disable it — LCP-based slot selection is ALREADY ACTIVE (common.h:687, server-context.cpp:1543). Cross-persona head sharing is not a feature to build; it is a behaviour we already get, unmanaged. * `cache_ram_mib` defaults to 8192 — an 8 GiB host-RAM prompt cache ALREADY EXISTS, and the server already saves an evicted slot's conversation and restores the incoming one (prompt_save / prompt_load, server-context.cpp:1620). * We never pin `id_slot`, so affinity is emergent from prefix similarity and never declared. That is the actual gap: not mechanism, POLICY. THE ARITHMETIC THAT KILLS THE OBVIOUS PLAN. With Atlas's measured numbers — ~7,600 tok shared head vs a 36,242 tok tail: sim = 7,600 / 36,242 ≈ 0.21 > 0.1 → persona B TAKES persona A's slot f_keep = 7,600 / 36,242 ≈ 0.21 < 0.5 → A's 36k is evicted The shared head is big enough to WIN slot selection and small enough that winning throws away 4.7× more than it saves. "Make the tool head identical and first so every persona shares it" is right about token cost (#333) and is a precondition — but as a KV strategy it is dominated, and shipped alone it makes slot theft MORE likely and would read as a regression. Tail retention beats head sharing by the tail:head ratio, which grows every act. Any design that trades a tail for a head is backwards. So the order inverts: declared slot affinity (`id_slot` per resident citizen, eviction as a priced decision behind the same seam as every other cache class) is the KEYSTONE, and the shared head lands AFTER it. "Docker form" is exactly the right instinct for the head — a shared prefix only stays shared if it is a function of LANE IDENTITY, not of whichever citizen is calling: same model, flags, tool manifest, template → one head, with an identity hash so divergence is LOUD rather than silent. Reconciles with [[kv-prefix-caching-is-the-only-form...]]: that memory is about CONVERSATION content, which is genuinely unique per citizen. A tool schema head is not conversation, so sharing it is prefix reuse, not dedup. FOUND WHILE WRITING, and it is its own defect: that 8 GiB prompt cache is UN-GOVERNED. We never pass the flag, never budget it, never told the ResourceGovernor. Same shape as the 2026-07-13 incident — every component healthy, the wiring absent — in RAM instead of disk. `--cache-ram` becomes a governed lease at spawn, like GGML_MOE_HOST_CACHE_GB (#287). WHAT I DID NOT MEASURE, and the doc says so rather than guessing: the wall-clock of prompt_save/prompt_load at ~36k tokens. It decides whether eviction is survivable or is a second re-prefill in a hat, so step 1 is measuring it and step 3 is gated on the number. Steps 1 (measure) and 2 (govern the RAM) are independent of the live flask run and can start now. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs(kv): policy is an ADAPTER not a rule + decompose the 4,190-line server (Joel's steer) Joel: "not too hard coded into one paradigm — better add proper adapters and break the module down into concerns. We could do a ton with plugin ML here, especially RL." Right, and reading first changed the answer for the THIRD time today: the seam already exists WITH a learned implementation in it. * capacity/expert_tier_policy.rs — `trait TierPolicy { fn plan(...) -> ExpertTierPlan }`, decisions returned as a PLAN not applied inline; ClassicTierPolicy is the v1 heuristic. * expert-pager-policy LEAF CRATE — policy already extracted into its own crate. The plugin boundary is already cut. * capacity/bandit_plan_controller.rs — a BANDIT CONTROLLER, re-exported from it. RL is not greenfield here (#276/#281). * expert_predictor / expert_decay_policy / expert_residency / expert_observer — the concerns are already separated on the expert side. So KV slot residency implements that shape rather than inventing a rival. And the generalisation is now EARNED rather than speculative: CLAUDE.md says generalize at 2-3 instances, and we have three of "paged resource under scarcity with a learnable value function" — MoE experts (built), LoRA genome paging (built), KV slots (this doc). KV slots are the ideal outlier B precisely because they are MAXIMALLY DIFFERENT from experts: unit is a whole conversation not a tensor, a miss costs seconds of prefill not bytes of fetch, population is 2-8 not thousands. One seam fitting both ends fits everything between. - Outlier A, heuristic: cost_of_loss = tail_tokens / prefill_rate. A quantity with a UNIT (seconds), not a magic ratio. Ships first, is the permanent floor. - Outlier B, RL: state = per-slot (tail, recency, citizen, phase) + arrival; action = which slot; reward = PREFILL SECONDS SAVED. AND THE REWARD SIGNAL IS ALREADY INSTRUMENTED — I shipped it this morning (faf8c07) without noticing it was one. `delib.generate.cache` emits cached_tokens / prefill_tokens / prefill_ms / hit_rate on EVERY generation: a labelled transition per turn, continuously, in production. So the A-vs-B comparison is measurable from day one instead of argued. Guardrails so "plugin ML" doesn't become unexplainable serving: policies return PLANS (loggable, replayable, refusable); the heuristic stays callable forever as the floor and a learned policy that loses on measured prefill-seconds is switched off by the comparison, not by argument; the deciding policy's identity rides the receipt so a regression is attributable; and never learn on a broken substrate — before the deterministic head landed the reward was ~0 for structural reasons and a bandit trained through that would have learned nothing helps. DECOMPOSITION: inference/llama_server.rs is 4,190 lines — 8× the decomposition law, and where every §3 change would otherwise land. Named the six concerns (spawn/args, readiness, slots, request, lifecycle, policy-as-leaf-crate). Explicitly a MOVE, not a re-architecture: no new task, no new watch channel, no second registry — and the flag comments travel with their flags, since those comments are the only record of the incidents that set each value. ALSO CORRECTED §4: `--cache-ram` is not new work. capacity/host_cache_lease.rs is already the governed lease, already runs on the governor tick, and its own module doc already says why that matters here — "KV grows as slots fill". One more term on an existing lease. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * refactor(inference): extract the llama-server flag spine into lane_args — decomposition slice 1 Joel: "I hate this file. Decompose it away from slop." llama_server.rs was 4,190 lines with every concern in it — flags, readiness, request shaping, lifecycle, orphan reaping — and it is where every change in the KV design would otherwise land. Slice 1 of docs/architecture/KV-CACHE-ECONOMY.md §7. Net -28 lines there, and a module that can actually be tested. WHY FLAGS FIRST. Answering "how do we use upstream llama.cpp" precisely: we consume it TWO independent ways, and only one touches this file. * as a BINARY — llama-server spawned as a subprocess, spoken to over HTTP. ZERO linkage: llama_server.rs imports nothing from llama/ggml. Upstream drift reaches us as a changed CLI surface (this module) or a changed JSON shape (request/readiness). * as a LIBRARY — the `llama` crate links libllama in-process for forge/conversion. That is where our fork's C++ lives (K3 KDA, AttnRes, MoE gather). Never passes here. So a fork rebase should touch this file and the wire shapes and nothing else. It could not, while the flags were welded into a Command chain in a 4k-line file. THE INVOCATION IS DATA. `base_invocation` is pure — primitives in, `LaneInvocation` out, no Command, no process, no I/O. Same shape as `TierPolicy::plan`: return a plan, don't apply one, so it can be asserted, logged and diffed. `envs` is on the struct because the invocation genuinely is not args-only (LLAMA_RESIDENT_OVERRIDE, #29); modelling that as "args plus a side effect someone remembers" is how it gets dropped. FIVE TESTS THAT COULD NOT PREVIOUSLY EXIST, because asserting them meant launching a real llama-server on a real GPU with a real model: * `-c` == per-lane window x lanes, and `--parallel` is EXPLICIT — the regression where inheriting llama.cpp's default of 4 silently served every citizen a QUARTER of the planned window. Nothing failed. That is why this is now three lines of pure arithmetic. * `--no-context-shift` present on every lane (#139: overflow must 400, never amputate the prompt middle and generate from the mutilation). * `--cache-reuse 256` still configured (~306s/act when absent, measured). * every value-taking flag is followed by a VALUE — the class that broke on 2026-08-20 when upstream turned `--flash-attn` from a switch into one taking [on|off|auto] and the bare form ate `--mmproj`, so the lane failed to spawn and serving sat at 0 lanes. * the base invocation needs no environment. COMMENTS TRAVELLED WITH THEIR FLAGS, verbatim, not paraphrased. Each one is the only surviving record of the incident that set its value; moving a flag without its comment destroys the reason and invites the reversion. Added one postscript to --cache-reuse: the flag was never the defect, WE were mutating our own prefix (fixed in 40075d7) — so nobody tunes this number looking for the win that already landed elsewhere. SCOPE, deliberately bounded: the CONDITIONAL flags (KV quant, flash-attn, mmproj, MTP draft, resident override, CPU placement, jinja, LoRA, MoE -ot) are still assembled by the caller and are slice 2. This is the unconditional spine, which is also the part carrying the arithmetic worth pinning. VERIFIED: cargo check clean (metal,accelerate); 5 new tests pass; llama_server's 38 tests pass. NOT MINE, flagged not absorbed: `first_free_port_skips_a_taken_port` is FLAKY under parallel execution — same filter and binary gave FAILED then ok on an immediate re-run, and it passes in isolation both with and without this diff. It binds a port and races. Worth its own card; not silently folded in here. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * refactor(inference): conditionals behind LaneOptions + a generic AsArg — slice 2 Joel: "Move concerns to proper adapters" and "templates are underutilized by you in both cpp and rust… it reduces code size a lot sometimes." Both applied here, not just agreed to. SLICE 2 — the conditional flag surface moves out of the Command chain: kv-quant / flash-attn / mmproj / MTP draft / CPU placement / resident-override now ride `LaneOptions` into a pure `LaneInvocation::with_options`. llama_server.rs 4,190 → 4,079. THE SPLIT THAT MAKES IT AN ADAPTER RATHER THAN A MOVE: every LaneOptions field is an ALREADY-RESOLVED value, never a thing to look up. Resolution — reading config_env, probing the registry for an mmproj or an MTP head, deciding placement, and emitting the vision-capability RECEIPT — stays with the caller, which owns the I/O. lane_args decides only what a resolved value MEANS on a command line. Gather inputs, then compute a plan: the same shape as TierPolicy, and the reason the whole surface is unit-testable with no GPU, no model, no process. The vision warn stayed behind deliberately. A Vision-capable row with no projector serves text-only and silently ignores images — a capability LIE — so it warns loud ([[fallbacks-are-illegal-fail-loud]]). That is a receipt about the world, not a flag, and receipts belong with resolution. THE TEMPLATE POINT, applied where it actually pays. Before, every value was hand-converted at its call site — `total_ctx.to_string()`, `p.to_string_lossy().into_owned()`, a bare `"256".into()` — three spellings of one idea, and three chances to push a VALUE without its FLAG. So: one `trait AsArg` (impl for &str/String/&Path/u16/u32) plus `pair(args, flag, value)`, and a valued flag becomes a single indivisible call. Monomorphised exactly as a C++ template would be — one definition, zero runtime cost. That is not cosmetic. Orphaning a value from its flag is precisely the class that took serving to 0 lanes on 2026-08-20, when upstream turned `--flash-attn` into `[on|off|auto]` and the bare form ate `--mmproj`. `pair` makes it unrepresentable instead of merely tested for — and the test stays anyway, because a guard you can delete is not a guard. FOUR MORE TESTS (9 total in the module): * default options emit NO conditional flags and no env — "present when it should be absent" is a real defect; the mmproj case literally decides whether a citizen SEES. * --flash-attn keeps its value when sitting next to --mmproj: the 8/20 outage as a test rather than an outage. * resident override rides the ENVIRONMENT, never the args (#29) — the reason LaneInvocation models envs at all rather than returning a bare Vec<String>. * KV quant sets BOTH -k and -v; one without the other is a silent cache asymmetry. STILL SLICE 3, deliberately not half-migrated: --jinja / chat-template sidecar, the LoRA set, and the MoE `-ot` tensor overrides. VERIFIED: cargo check clean (metal,accelerate); 9/9 lane_args tests pass. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * refactor(inference): slice 3 — jinja/LoRA/-ot move out; the flag CONCERN is now closed Last of the conditional surface: the chat-template sidecar, the genome LoRA set, and the K3 `-ot` expert placement. llama_server.rs 4,190 → 4,034 (-156); lane_args.rs is 521 lines that are entirely about one thing. No flag is now built in two places, which was the compression violation the half-migration would have left behind. `--jinja` moved to the BASE spine, not to options, because it is unconditional — and the comment explaining why is the most expensive one in the file. Gating it was a silent capability kill: the switch used to require a forge-written sidecar to exist, so every normally PULLED GGUF ran with tools DISABLED. The gateway ignored the `tools` param and the persona NARRATED tool calls instead of emitting them. A model with hands, holding them behind its back, because of a file that was never there. The sidecar now OVERRIDES when present (forged GGUFs whose mlx→gguf conversion left a thin 208-char tool-less template) and the embedded tool-capable template stands when absent — tools ON either way. The LoRA join moved WITH its flag rather than staying at the call site, deliberately: the join IS the flag's semantics. llama.cpp b8784+ deprecated repeated `--lora` and SILENTLY keeps only the LAST, which was collapsing every multi-layer genome stack to a single adapter — glass-boxed 2026-07-23 in the lane's own stderr ("DEPRECATED: --lora specified multiple times... only last value will be used" x4) while a 4-layer stack was supposedly serving. The genome's whole premise is layers that STACK; this arg SHAPE is what stacks them. Split the join from the flag and the next person re-introduces the bug. Resolution stayed with the caller for all three, same rule as slice 2: the sidecar `is_file()` probe, the adapter paths, and `expert_ot_value()` are lookups; lane_args only decides what a resolved value means on a command line. VERIFIED: 351 inference tests pass; cargo check clean (metal,accelerate). NEXT, and it is the seam Joel actually asked for: `trait LaneBackend` with llama-server as impl A, so an mlx / vllm / remote-grid-peer lane is impl B rather than a fork of this file. lane_args is now shaped to BE that impl rather than to be the only way. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs(serving): STDERR IS NEVER AN INTERFACE — and we break it twice (Joel's law) Joel, 2026-08-21: "STDERR/out is never a place for interfacing, just debug." Checked rather than agreed, and we violate it in two places, both written in good faith for real incidents and both making llama.cpp's DEBUG TEXT load-bearing in our control plane: * `inference::wedge::WedgeWatch` parses stderr for an impossible slot progress (`progress = 1.10`) and raises a flag THE SERVING DAEMON REAPS A LANE ON. * `inference::placement_watch::OffloadWatch` parses llama.cpp's LOAD BANNER for layers offloaded, then fires `serving.placement.cpu_fallback` — treated as a lease violation (#441). Why it has to change even though it works today: stderr is unstructured, unversioned, and drifts with upstream's logging taste. The failure mode when it drifts is not an error — it is SILENCE. The watcher stops matching, the flag stops rising, and the wedge that burned four hours on 2026-08-05 becomes invisible again with every component still green. Same shape as every other defect in this document: an absence that looks like normal operation. It is also, precisely, the class the #441 sentinel was built to catch — so the sentinel is currently exposed to the failure it exists to detect. The structured channels already exist: `/slots` carries per-slot state and progress, `/props` the load configuration, and the per-request `timings` block already reaches us — it is what `delib.generate.cache` reports. The tok/s sentinel should read `prefill_tokens`/`prefill_ms` rather than scrape a banner. THE LINE, since not all stderr reading is a violation: `stderr_log_tail()` on spawn failure is CORRECT — a human asks "why did it die" and gets llama.cpp's own last words. Reading stderr to SHOW is debug. Parsing stderr to DECIDE is an interface. The test is whether a control path branches on it. STATUS: named, not fixed. Rewriting both watchers onto /slots + /props needs those payloads verified against our pinned build (b10196-fa7e0d8e9) first — asserting a field exists because upstream documents it is the same mistake in a different channel. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs(kv): pin the PRE-FIX baseline from a live run — 0% reuse, 57,005 tokens re-prefilled in 4 acts Measured 2026-08-21 10:57 off a LIVE run rather than argued: citizen e5f4141d, instance pallets__flask-4045, pre-fix binary b10196-fa7e0d8e9, read from her own prompt captures. act 1: cached 0 / prefill 9,847 hit 0.000 act 2: cached 0 / prefill 11,172 hit 0.000 act 3: cached 0 / prefill 19,434 hit 0.000 act 4: cached 0 / prefill 16,552 hit 0.000 57,005 tokens re-prefilled across four acts, zero reuse on every turn, ~513s at the measured 111 tok/s — 8.5 minutes of a 4.3h budget spent re-reading, four acts in, cost per act still climbing. That is the number 40075d7 has to move, now pinned to a specific citizen on a specific instance so the after-measurement is a COMPARISON and not a claim. METHOD NOTE, recorded because it nearly went wrong and it is the session's recurring defect class: `pgrep` for a solve process finds NOTHING while a run is live, because `agent/solve` executes INSIDE the core rather than as a subprocess. I read that absence as "the run finished, deploy is unblocked" — and would have rebooted the box out from under a citizen at act 4. Wrong instrument, absence misread, same shape as every retraction in this document. The authoritative signal is ~/.continuum/progress/agent-solve-claim-<run>.json (state, acts, mtime): it said state=running, acts=4, written 60 seconds earlier. Deploy remains correctly blocked. The after-number is owed and is now cheap to collect — same read, or just query delib.generate.cache once the fix is live. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(serving): per-slot throughput verdict — the sensor missing when the round died today TDD/VDD on a defect measured LIVE forty minutes ago, encoded while it is fresh rather than remembered later. THE INCIDENT. Citizen e5f4141d working pallets__flask-4045 in-room. Run reported state=running, heartbeat every minute, acts frozen at 4 for twelve minutes. Lane answered /health {"status":"ok"}, /props 200, /v1/models 200, port bound, process up 3h58m. Every readiness signal in the system said healthy. Her own lane said: slot 1 | task 3 | n_decoded = 1092, tg = 2.65 t/s, tg_3s = 0.96 t/s slot 1 | task 3 | n_decoded = 1093, tg = 2.53 t/s, tg_3s = 0.05 t/s slot 0 | task 605 | prompt processing, progress 0.52, 105 t/s Slot 1 decoding at 0.05 TOKENS PER SECOND — one token per twenty seconds — still holding task 3 after six hundred tasks passed on the neighbouring slot. PREFILL WAS FINE (105 t/s, the expected rate). Only decode collapsed, on ONE slot, and nothing could see it. That is #386's per-slot wedge and it is the round-killer: a citizen at 1/600th speed burns her whole 4.3h deadline producing nothing while the board renders a healthy pulse. WHY LANE HEALTH CANNOT CATCH IT: /health is lane-scoped and the LANE is fine — the other slot decodes normally, so every aggregate reads healthy. #363 established that readiness must verify GENERATION not the socket; this is the layer below: generation must be verified PER SLOT, because a lane is healthy exactly as long as its best slot is. DESIGN, per the standing rules: * PURE function, transport-agnostic. It takes SlotObservation values, so it works the instant they arrive from a structured channel. /slots returns HTTP 000 on our pinned build — that is the follow-up, and the verdict logic must not wait on it. * expected_tps is a PARAMETER, never a constant here. What counts as collapsed depends on model and device; the catalog Model row owns that expectation (#441). A constant would be a hardcoded LCD clamp — either missing a real wedge on a fast box or crying wolf on a slow one. * Reads the 3-SECOND rate, not the lifetime average. The same slot read tg=2.53 (bad) while tg_3s=0.05 (dead); averaged over hours, a stopped slot looks merely slow. * Degraded REPORTS, only Wedged is actionable. #446 is the counter-example: starvation stamped as wedge evidence produced a 2-minute relaunch loop that WAS the outage. * A slot under 32 decoded tokens gets no verdict — killing cold generations is [[an-absence-is-an-unfinished-measurement]] wired to an actuator. SIX TESTS, the first two carrying the live numbers verbatim: the incident classifies Wedged; the lifetime average provably would have MISSED it (that test guards the leading-indicator argument, not just the constant); merely-slow is reported not reaped; a cold slot is never wedged; no expectation means no verdict; and the same observation flips healthy/wedged with the device's own expectation. INSTRUMENT NOTE, recorded in the module: those numbers were read out of stderr BY HAND, which is the only way they were visible — and that is the exact defect Joel named today ("STDERR/out is never a place for interfacing, just debug"). Reading a log to DIAGNOSE is correct. A control path depending on it is not. This module is the honest half; wiring it to /slots is the other. NOT YET WIRED — no caller, deliberately. The verdict is the testable unit; the actuator (who reaps, when, under what lease) is a separate decision and belongs with the daemon, same doctrine as the wedge flag. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(inference): prefill is not decode — stop the 90s watchdog killing live prefills (the round-killer) MEASURED on the M5, and it is why citizens took ZERO room turns across the probe ledger's 868 minutes while every dashboard read healthy: demand 94,370 tok against a 58,112-token window (over_window 1.62) prefill rate 382 tok/s (timed live: 603 tok → 17.7s; 5,728 tok → 31.1s) ⇒ first byte ~170 s for a window-sized prompt watchdog 90 s ← fires first, every single time 44 `persona.settle.deliberation_retry` rows carry the verdict the watchdog reached: "the slot HAD started our work and then stopped mid-stream, so the backend is stuck or dead". It was neither. Atlas re-sent the byte-identical 94,370-token demand 21 minutes later and died the same way. The cascade is what made it a round-killer rather than a slow turn: the ambient permit is held across that wait, so three permits sat occupied ~90s each by turns that could never finish. Measured +4 yields/min, EXACTLY, for 25 consecutive minutes, zero successes — the perfect periodicity is the tell, since real contention is bursty. ROOT CAUSE, one line and not a missing feature. Both budgets already existed and both were correctly sized for their own job: STREAM_IDLE_TIMEOUT_SECS (90s) is a DECODE watchdog by its own doc ("a token every few hundred ms"), and PRE_STREAM_HEADER_TIMEOUT_SECS (300s) is documented as "sized for a worst-case full-window prefill queued behind co-tenants (minutes)". The adapter switched from the second to the first the instant ANY progress arrived — and llama.cpp emits a prompt_progress frame at 0% ingestion purely "to signal the client that the request has started processing". So the decode watchdog policed the prefill, and the budget written for exactly this case was skipped past within seconds. FIX: `inference::stream_liveness` — a pure, transport-agnostic phase machine (Queued / Prefilling / Decoding) that names the distinction once so no caller re-derives it. Bulk work gets the bulk budget; the drip gets the drip budget. Deliberately preserved: - #385 keeps its teeth. Liveness is still keyed on the GAP BETWEEN PROGRESS EVENTS, never elapsed total, and the stamp still requires `processed` to STRICTLY advance — so a slot replaying a frozen counter still fails, just at the prefill budget. - #446 keeps its diagnosis. `has_started()` still separates never-started (dead backend vs oversubscribed queue) from started-then-stopped. - Decoding is TERMINAL, so a late/stray progress frame cannot re-open the generous budget mid-decode. My own test caught that the first implementation could. - Providers that never report prefill (every cloud adapter) go Queued → Decoding on first output, so their budgets are bit-for-bit unchanged. Strict addition, never a relaxation. Phase transitions are detected at ONE site per kind rather than repeated at each of the four output sites, so a new output kind cannot forget to declare itself. 7 new tests carry the live incident numbers verbatim, incl. the 0%-frame case that IS the outage and a regression guard for no-prefill providers. 36/36 existing openai_adapter tests green. Design + the full measured chain: docs/architecture/ADMISSION-IS-UNOBSERVABLE.md (also records the admission-snapshot gap and the seven wrong reads it took to get here — two of them my own instruments lying, not the system). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(inference): probe the prefill fix — "no retries" is an ABSENCE and proves nothing Self-correction. I shipped the phase machine and emitted NOTHING for it, then read "RETRIES: 0, TURNS: 0" off the ledger and could not say whether prefills now survive or nothing was running. That is the same unobservable-state defect the design doc in the previous commit exists to complain about, committed by me one commit later. Two rows, both at the seam that actually decides: - `inference.prefill.rescued` — fires ONCE per stream, only when a prefill has already outlived the OLD decode budget AND is still advancing. Every row is a turn that under the previous flat 90s would have been killed here and retried forever. This is a POSITIVE signal for a fix whose symptom is an absence. - `inference.prefill.complete` — total / cached / fresh / elapsed_ms / tok_per_s / would_have_died, at the prefill→decode edge. This is the number the 90s constant was implicitly guessing at, and the one the budget should eventually be DERIVED from per model+device (#441). It also finally measures the KV cache's REAL contribution per stream (`cached` vs `fresh`), which is the instrument the KV ordering work has been owed. Joel, mid-session: "Have to probe better." Correct — a fix I cannot see working is a fix I have not proven. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(inference): split queue-wait from ingest in the prefill receipts — a probe that mixes two regimes measures neither First cut of `inference.prefill.complete` produced absurdities that were the conflation talking: a 467-token prompt "prefilling at 1 tok/s for 231s". It was queued ~230 of those seconds waiting for a slot. llama.cpp's 0% progress frame marks slot ASSIGNMENT, so the honest split is: queued_ms = stream open → first progress frame (admission/oversubscription, #234) ingest_ms = first frame → prefill complete (real ingest work) `ingest_tok_per_s` is now computed over ingest only — the number a derived per-model budget must come from (#441). `rescued` rows carry `queued_s` for the same reason. Source-read while here (vendor llama.cpp): prefills ARE continuous-batched across slots (`can_batch_with` + cont_batching), so concurrent prefills share compute by design. The 230s waits mean all 4 slots were OCCUPIED — by window-scale re-prefills that zero KV reuse makes ~5 minutes each. Queue wait is downstream of the KV defect; the split makes that attributable per stream instead of argued. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(inference): a loading lane must not latch slot affinity off — the boot race that undid persona pinning every launch slot_for_persona (2026-07-11) pins each persona's prefix to its own llama-server slot. It has likely been latched OFF on virtually every boot since: the /props probe latched SlotAffinity::Unsupported on ANY non-success status, and personas start deliberating while the lane still answers 503_loading (measured ×93 in this ledger). One probe racing the load window → pinning dead for the process's life → prefix-similarity slot theft → cached: 0 mid-conversation, measured today. Only 404/501 — "no such surface" — may latch. Extracted the verdict as props_status_proves_endpoint_absent() and pinned it with a regression test carrying the incident: 503/500/502/429 defer and re-probe; 404/501 latch (without that, every cloud provider would re-probe per persona request forever). A malformed body from a live server also defers now — mid-load servers answer partial bodies. Observability, same lesson as the prefill probes ("no rows" must be distinguishable from "latched off silently for weeks"): - inference.slot_affinity.pinned — once per persona pin, proves affinity is LIVE - inference.slot_affinity.evicted — names the victim; cross-persona eviction IS the KV-clobber event and must be priced (KV-CACHE-ECONOMY: a decision, not an accident) - inference.slot_affinity.deferred / .unsupported — the latch decision itself Measured on the previous build (6dea7c4, 10-min window) with queue/ingest split: queued=0s on ALL streams — no slot wait; the residual is ingest-share under continuous batching. First nonzero mid-scale KV reuse ever recorded (cached=2912 of 21002) with affinity still latched off; this fix targets exactly that number. Two died_old=1 prefills (163s, 192s) completed that the old watchdog would have killed. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(persona): 'never thought' is a state, not a 584-million-year idle — the renewal probe stops stamping u64::MAX idle.unwrap_or(u64::MAX) printed idle_ms=18446744073709551615 into the ledger (seen live 2026-08-21). The gate logic was right; only the receipt lied. [[unknown-is-not-a-quantity]]: the unknown gets a word ('never-thought'), never a sentinel number a reader must recognize by its astronomical size. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs: resolution log — all four fixes proven live same-day (retries 0, first slot pins ever, 99.7% KV reuse on byte-stable prompt) Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs: citizen act observed post-fix; deaf-kickoff scoped to subscription coverage (cursor layer exonerated) Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(bench): clone_at serializes per destination — the race that voided sympy-18057's finished artifact at grading The 2026-08-18 grade loss, root-caused: `clone_at` removes its destination at entry AND razes/renames it at the commit point, while the protocol legitimately wants the same instance's tree more than once (her work tree + the pristine score tree; a lapsed-claim auto-grade racing a re-stage). Concurrent callers deleted each other's trees mid-use. The trigger was a Node-era assumption fossilized in a path: staging is `cloning-{pid}`, unique when every clone was its own process — but in the headless core every clone shares ONE pid, so two concurrent stages computed the SAME staging path and the stale-staging sweep deleted a LIVE clone mid-fetch: "repo.cloning-78289/.git/: No such file or directory" — a finished artifact voided at scoring. Fix, constraint-first: - One live clone_at per DESTINATION: per-repo_dir tokio::Mutex registry (async lock — the section awaits git subprocesses throughout; keyed by repo_dir, not instance, so a 300-instance sweep does not serialize globally). - staging_path_for(): pid + per-invocation nonce, extracted pure for testability. - Dead-staging sweep by `<name>.cloning-` prefix instead of exact-name match — with nonced names an exact match can never find a crashed run's leftovers, and unswept litter violates the no-cache-dir-without-an-eviction-story rule (2026-07-13). Two regression tests carry the incident: staging uniqueness + sweepable prefix, and lock identity per destination. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(bench): a round survives the core that opened it — persist in-flight rounds, reload on first touch Measured twice on 2026-08-21: the ROUNDS map was process-memory, so a reboot mid-round (1) blanked `benchmark/rounds` while a staged round was live — the operator re-derived the round from probe archaeology — and (2) silently flipped driver_for_card back to DetachedSolve for a Citizen round's remaining cards, quietly rebuilding the parallel runner the round was configured to avoid. With "restart freely" as standing doctrine, every deploy was round-murder: 8 of the 20 most recent runs on this box carry "killed by a core restart". The round is now durable state, same family as the airc attach cursor: one JSON file per in-flight round under ~/.continuum/state/bench-rounds/, written on every mutation (open / add_card / settle / seal), removed at Done. First touch of ROUNDS reloads — no boot hook; the first driver_for_card after a reboot already answers from the reloaded round. bench.round.reloaded announces each recovery. Eviction story (the 2026-07-13 rule): files self-evict at Done, and a Done file surviving a crash window is dropped AND deleted on reload, never resurrected as a round no event can settle. Persist failure degrades to the old amnesia and WARNS — durability must never fail a live dispatch. HONEST LIMIT, stated in code: cards that reached terminal state while the core was down still read as working until the next event. Re-deriving card state from the board at boot — and consuming the orphan-reap report (`needs_redispatch: true`, which nothing consumes today) — is the follow-up reconciler, per ROUND-LIFECYCLE-AS-RECIPE-OWNED-STATE-MACHINE.md. This commit restores the round's EXISTENCE, which is what every later reconciler needs first. Two regression tests carry both measured defects. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(bench): round tests persist to a temp dir, never the operator's real state Caught within the hour: the persistence layer resolved $HOME unconditionally, so the EXISTING tests — which exercise the public open_round/add_card — minted four phantom rounds into ~/.continuum/state/bench-rounds across two cargo test runs, and the next live core faithfully reloaded them (in_flight: 5 with one real round). A durable layer's tests must be durable somewhere disposable: cfg(test) resolves to a per-process temp dir. Verified: full bench_round suite leaves the real state dir untouched. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
…ration (Joel: "record and playback so we could iterate to refine") (#2350) The record half already existed and is on by default: JsonlPromptCaptureSink writes the VERBATIM system + message thread of every deliberation call, per persona (1,598 capture files on this box). This adds the playback half as `debug/prompt-reuse`: walk a persona's calls chronologically, score char-level LCP between consecutive first-generation calls (predicted KV prefix reuse), and name every divergence point with a ±20-char excerpt from BOTH sides — the analysis done by hand on 2026-08-19 (divergences at chars 8216/7879/8133, the #266 ordering defect), now a repeatable query any operator can run with no agent. Honest proxy, stated in every result: char LCP ≈ tokens×4 ranks assembly variants and locates mutation; ACTUAL slot reuse remains the inference.prefill.complete probe. High predicted + low actual = the loss is between assembly and the slot (routing/eviction), which is itself diagnostic. Same scope posture as debug/probes/query (reads every citizen's verbatim prompts → Privileged, off the persona vocabulary). Iteration>0 re-prompts are excluded — within-turn prefix share is trivial and would inflate the score. The same corpus now serves three consumers: this refinement loop, the eventual training set (each capture is a real prompt/response/tool-trace triple for L1 lifting + LoRA distillation — Joel's "might actually allow it to learn"), and incident forensics. Record once. 3 tests: divergence lands on the exact mutated char; stable-head reuse scores high; field separation prevents cross-boundary LCP credit. Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo Co-authored-by: Claude Fable 5 <[email protected]>
…-rate fix, measured from her own captures (#2415) The single biggest wall-clock lever in the tree, diagnosed with the glass box, fixed at the constraint (Joel: 'code it elegantly and efficiently from the start… you're coding webdev horseshit for performant rtos work' — this is the RTOS fix). MEASURED (capture round 907390a0, turn-over-turn diff of her real contribution stream): workspace-map content changed act-over-act (her own writes mutate it) while sitting in the STABLE tier of the system message; kanban/active-work were volatile-flagged but the volatile tier still rendered INSIDE the system message — before every conversation token. Divergence at ~8k chars of a 40k+ prompt = live KV reuse pinned at 18-33%, ~35-45k re-prefilled per act, ~2min/act, 96% of compute prefill. The #266 sort fixed ORDER churn in the stable tier; CONTENT churn was the remaining killer. FIX, at the constraint, using the mechanism #205 already built and documented as KV-correct: 1. rag_source_faculty: volatile-content grounding bids are .trailing() — they render as conversation turns nearest generation (the existing render loop), so churn costs exactly its own tokens. The volatile tier of the system context block was a half-measure. 2. workspace-map flagged .volatile_content() — its churn is every productive act by construction. 3. The trailing render keeps the [faculty] banner (one sized allocation, no format!) so relocated grounding stays as legible as the system block it left. Expected shape after: prefix reuse = system (now byte-stable) + full conversation; per-act re-prefill = trailing grounding + working-memory tail only. Target ≥70% cached on intra-task acts vs the measured 18-33%; A/B rides the next round's prefill probes. Pinned by volatile_content_grounding_is_trailing_and_stable_grounding_ is_not. Batteries: 93 (deliberation/prompt/workspace/supervisor) + 11 (rag_source_faculty + ratchets) green. Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo Co-authored-by: Claude Fable 5 <[email protected]>
…ix orders widest first (#3981) `PromptScope { Substrate, Persona, Activity, Turn }` on every composed block. The tool catalogue (Substrate: byte-identical for every persona with the same authorized set) now leads the cacheable prefix; identity and the turn contract (Persona) follow; the standing context (Activity) after; the clock/presence/recall material (Turn) stays a trailing turn. Before, the prefix was ordered by hand — identity first, so no two personas shared a byte of prefix — and three separate fixes (#205, #266, plan B4) each moved one block after a measured cache break. One ordering declared per block replaces the boolean stable/trailing split for blocks; a KV pager or a speculator reads the same scopes to know which pages N personas share and which a context switch swaps. Honest scope of the receipt: on this server the prompt cache is per slot, so the cross-persona share needs the fork's KV page reuse to show as hit rate; this PR is its precondition and changes no per-turn prefill on its own. Test pins the order and that no Turn block reaches the prefix. Design: docs/planning/UNCERTAINTY-IS-THE-SCHEDULER-SIGNAL.md. Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo Co-authored-by: Claude Fable 5.1 <[email protected]>
Summary
This PR completes Phase 2 of the Rust module consolidation, focusing on optimization and moving compute-heavy operations from TypeScript to Rust.
Phase 5: Legacy Code Cleanup
ipc/mod.rsRequestenum (55+ unused command variants)runtime.route_command_sync()Phase 6a: Runtime Metrics
runtime/metricscommand for real-time module performance monitoringPhase 7: Move Compute to Rust (High Impact)
Added 4 new embedding commands with Rayon parallelization:
embedding/similarityembedding/similarity-matrixembedding/top-kembedding/clusterTypeScript files updated to use Rust:
MemoryConsolidationWorker.ts- Uses Rust similarity matrixMemoryConsolidationSubprocess.ts- Uses Rust similarity matrixLongTermMemoryStore.ts- Uses Rust top-k with TS fallbackRustCoreIPCClient.ts- Added singleton pattern + 4 new methodsOther Improvements
Test plan
npm run build:ts- TypeScript compilescargo build --release -p continuum-core- Rust compilesnpm start- System deploys successfully./jtag ping- Server and browser healthy./jtag runtime/metrics- All 13 modules registeredStats
🤖 Generated with Claude Code