Repository navigation
RAG/Memory improvements, Persona Brain HUD, and 3-panel layout with AI assistant - #240
Conversation
- Add public recallMemories() method to PersonaUser (Proper interface to Hippocampus instead of private accessor) - Fix ChatRAGBuilder to use duck-typing instead of unsafe cast (Check for recallMemories method via 'in' operator) - Fix multi-domain activity calculation in Hippocampus (Aggregate across chat, game, ui, browsing, code domains) - Fix LTM count query in Hippocampus getStats() (Actually query database instead of returning 0) - Add RAG-COGNITION-IMPROVEMENTS.md architecture doc - Add UI-STATE-RAG-ARCHITECTURE.md architecture doc 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
There was a problem hiding this comment.
Pull request overview
This PR addresses critical issues in the memory/RAG integration layer and adds comprehensive architecture documentation for future enhancements. The changes improve type safety, fix data access patterns, and extend activity tracking to support multiple domains beyond chat.
Key Changes:
- Added public
recallMemories()API to PersonaUser for safe memory access - Replaced unsafe type casting with duck-typing in ChatRAGBuilder
- Extended Hippocampus to track activity and query counts across all domains (chat, game, ui, browsing, code)
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| PersonaUser.ts | Adds public recallMemories() method as proper interface to Hippocampus, eliminating need for private property access |
| ChatRAGBuilder.ts | Replaces unsafe as any cast with duck-typing check for recallMemories method availability |
| Hippocampus.ts | Implements multi-domain activity aggregation and real database query for LTM count instead of hardcoded 0 |
| UI-STATE-RAG-ARCHITECTURE.md | New architecture document proposing UI state awareness for AI assistants without screenshots |
| RAG-COGNITION-IMPROVEMENTS.md | New document analyzing current RAG/memory system with flexbox-inspired budget allocation proposal |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| filter: { personaId: this.persona.id }, | ||
| limit: 0 // Just get count | ||
| } as any) as any; | ||
| ltmCount = result.totalCount || result.items?.length || 0; |
There was a problem hiding this comment.
The fallback result.items?.length is incorrect. The DataListResult interface defines the property as records, not items. This fallback will always be undefined, making the count less reliable. Consider using result.totalCount || result.records?.length || 0 instead.
| ltmCount = result.totalCount || result.items?.length || 0; | |
| ltmCount = result.totalCount || result.records?.length || 0; |
| this.log(`⚠️ ChatRAGBuilder: PersonaUser ${personaId.slice(0, 8)} has no Hippocampus`); | ||
| // Check if this user has memory recall capability (duck-typing) | ||
| // PersonaUser exposes recallMemories() as public interface to Hippocampus | ||
| if (!('recallMemories' in personaUser) || typeof (personaUser as any).recallMemories !== 'function') { |
There was a problem hiding this comment.
The type check typeof (personaUser as any).recallMemories !== 'function' is redundant. The in operator already verifies the property exists, and since it's a method call on line 462, TypeScript will catch if it's not a function at compile time. Consider simplifying to just if (!('recallMemories' in personaUser)) for cleaner code.
| if (!('recallMemories' in personaUser) || typeof (personaUser as any).recallMemories !== 'function') { | |
| if (!('recallMemories' in personaUser)) { |
| currentStates: result.items, | ||
| summaries: result.items.map(s => s.summary).join('\n') |
There was a problem hiding this comment.
The code example uses result.items but the DataListResult interface defines this property as records, not items. This would cause a runtime error. Update the example to use result.records instead.
| currentStates: result.items, | |
| summaries: result.items.map(s => s.summary).join('\n') | |
| currentStates: result.records, | |
| summaries: result.records.map(s => s.summary).join('\n') |
Root cause: data-clear.ts truncated users table, causing personas to get new UUIDs on reseed. But per-persona longterm.db files weren't cleared, so old memories referenced orphaned UUIDs (e.g., 2905 memories unreachable). Fixes: - Remove personaId filter from Hippocampus (searchLTM, semanticRecall, getStats) Each persona has their own database file, so filter was redundant - Exclude users from data-clear.ts truncation to preserve UUIDs - Add dbHandle support to VectorSearchOptions and VectorSearchParams - Route vector search through DatabaseHandleRegistry for per-persona DBs - Add missing DATA_COMMANDS import to data-clear.ts Result: All 2905+ memories per persona now accessible regardless of UUID 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Create BasePanelWidget base class for panel-type widgets (Settings, Help, Theme, Diagnostics) - Add shared styles: PanelStyles.ts (layout, sections), FormStyles.ts (inputs, buttons) - Create DiagnosticsWidget showing all personas with clickable log file buttons - Create LogViewerWidget for viewing log files with level filtering and auto-follow - Register 'diagnostics' and 'diagnostics-log' content types - Update UserStateEntity validation for new content types 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
- SVG brain diagram with clickable regions (Mind, Soul, Hippocampus, Body, CNS) - Shows real stats (2921 memories, 12 tools, 5 connections) - Module cards for quick navigation - Cyberpunk styling with glow effects and activity pulses - Opens via content/open with contentType='persona' - AI Assistant sidebar for contextual help The "mechanic view" - talk to a persona while watching their brain 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Large central brain outline with side profile - Module boxes positioned around brain edges (MIND, SOUL, HIPPO, BODY, CNS) - Animated circuit connections from modules to brain regions - Neural network paths and brain region highlights inside brain - Removed redundant module overview grid Also fix content switching for non-chat content types: - ContentOpenBrowserCommand now includes setAsCurrent in emitted event - MainWidget handlers call switchContentView when setAsCurrent is true - Added data-entity-id attribute to pass entityId to widgets 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Redesigned brain as low-poly geometric shape (flat oval with bottom-left cut) - HUD-style module panels with bracket frames around brain - Real brain region names: PREFRONTAL, LIMBIC, HIPPOCAMPUS, MOTOR CORTEX, CNS - Animated circuit connections from modules to brain regions - Scanline overlay and neural activity nodes for cyberpunk aesthetic - Memory bar, tool slots, and waveform visualizations in module panels 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
- UserListWidget: Click on persona/agent opens their brain widget - PersonaBrainWidget: Fetch real stats from ai/status and memory count - HUD displays actual provider, model, health status, memory count - Mood inference based on memory count (fresh/exploring/learning/curious/experienced) - Added brain HUD screenshot to README 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
Root cause: MainWidget was removing ContinuumWidget's theme CSS and replacing it with only theme.css (missing base.css which defines body styles using CSS variables). Fix: - ContinuumWidget now loads theme CSS in onWidgetInitialize() BEFORE child widgets render - Removed duplicate theme loading from MainWidget that was overwriting the complete CSS with incomplete CSS 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
Right Panel: - Add 3-column grid layout to ContinuumWidget (sidebar | content | right panel) - Create RightPanelWidget with context-aware AI assistant chat - Create RightPanelResizer (mirrors sidebar resizer, drags from left edge) - Panel switches assistant room based on content type (settings→help, theme→theme, etc.) - Persistent width via localStorage, collapse/expand toggle RAG/Memory Improvements: - Add RAGBudgetManager for intelligent context allocation - Add EmbeddingService for centralized embedding generation - Add IEmbeddable interface for embeddable entities - Update ChatRAGBuilder to use budget-aware context building - Update ModelContextWindows with accurate token limits - Add SemanticCompressionAdapter for memory consolidation - Add unit tests for semantic cognition and memory system 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
Shows the new desktop layout: - Left: Sidebar with rooms, users & agents, pipeline stages - Center: Persona brain HUD (Fireworks AI cognitive system view) - Right: AI Assistant panel with contextual chat 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
Shows the complete desktop interface with: - Left: Sidebar with rooms, users & agents - Center: Cognitive HUD (persona brain visualization) - Right: Contextual AI assistant panel 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
…#1584) Two load-bearing architecture docs that capture the meta-principle the substrate is being built around: 1. SUBSTRATE-DOCTRINE-ORGANIC-FLOW.md — the WHY behind every primitive decision. The engine-on-the-OS framing (substrate primitives = precisely-engineered engine block, cognition/persona = organic body on top, OS + hardware = the road system). The meta-principle: "take analogies literally" — the brain and the substrate solve the same hardware problems (limited fast memory, parallel processors, triage of sensory input, demand-driven activation). When a brain mechanism maps cleanly to an existing OS primitive, USE the OS primitive — don't recreate the brain, don't invent a metaphor, find the closest hardware-shaped analog. CBAR did this with CV; same shape here scaled to cognition. Covers: flow not RPC (geometric vs linear scaling), demand not FIFO (consumer-pull, salience, afterthought as first-class), scorers everywhere gated by VDD (every junction potentially ML), federated not singleton (alignment is structural, not policy). Migration path from heuristic stand-ins to literal analogs. Forbidden-moves list for the reflex patterns the model keeps coding under amnesia. 2. PROVING-THE-DOCTRINE.md — the HOW WE VERIFY companion. Names the five proof shapes (unit invariant, property-based, benchmark-with-assertions, adversarial/chaos, build-graph constraint), lays out the doctrine-clause × proof-shape matrix (starting snapshot, ~15 clauses, ~5 covered), and pins the review discipline that keeps the matrix honest. Slogan: prove it as we build it. New principles ship with proofs. Proofs are tagged `// proves: <clause>` so the matrix is self-auditing via `git grep`. The organism's reliability at any moment is the union of green cells; red cells are visible debt. Task #240 tracks building out the architecture-test matrix — each red cell is its own PR. Neither doc is the substrate's API reference or implementation guide; the 56 existing architecture docs handle those. These two are the doctrine layer underneath, which the others now have something concrete to cite. Co-authored-by: Claude Opus 4.7 <[email protected]>
Maps the main README's claims onto the mature substrate architecture captured tonight (substrate doctrine, proof discipline, academy target, project-as-curriculum source) and sequences the cards to take canary end-to-end through alpha. The slogan: canary already passes the architecture test; alpha is when canary passes the user-facing test. Structure: 1. Minimum viable alpha — the 12-step critical path from fresh-clone to persona-remembers-across-sessions. Almost entirely on substrate primitives already in tree. 2. README claims to substrate mapping — every concrete claim in docs/README.md mapped to its substrate primitive with current status. 3. Cards in dependency order, grouped: - Group A (substrate stabilization, alpha-blocking): #229 TS cleanup, #112-114 inference routing, #1409 Lane D cognition, #131 Metal hang fix, #149 prompt pre-tokenization, #1410/#1411 CUDA/Vulkan receipts, uri_layer flake. - Group B (feature completeness, alpha-target): vision adapter + Qwen2-VL, STT/TTS adapters, LiveKit-over-airc #208, #122 LoRA paging, architecture-test matrix first proofs #240. - Group C (academy + continuous evolution, alpha-completing): #241 stack steps 1-7, ending in first full classroom. - Group D (CLI + portal redesign, alpha-presentation): #215 Node client rebuild, #143 Rust-first jtag, portal severance from legacy TS daemons, registry-backed unified discovery. - Group E (post-alpha): bridges, IDE plugins, breeding, federation reputation. 4. Milestones — Hello-Maya (Group A done) → Multi-persona-room (B done) → Continuous-learning (C done) → Alpha-public-release (D done + canary to main promotion gate passes). 5. Composes with ALPHA-GAP-ANALYSIS.md (lane execution) and the substrate doctrine docs. No parallel ledger. Forbidden moves explicitly named for review enforcement: no feature-disabling fixes, no TS daemon owning runtime behavior, no silent cloud fallback, no hardcoded model names, no phase-2 PRs shipping abstraction without first instantiation, no self-grading personas, no LLM call inside cognition bypassing inference command. Iteration starts from Group A. Critical-path cards need owners claimed in ALPHA-GAP. This doc is the planning anchor; status flows to the architecture-test matrix and lane status without parallel ledgers. Co-Authored-By: Claude Opus 4.7 <[email protected]>
* docs(architecture): academy as continuous evolution (task #241) The architecture for continuous learning, true AI evolution, and mutual symbiosis on the substrate. Captures the cycle the substrate is designed to grow into, alongside the substrate doctrine (SUBSTRATE-DOCTRINE-ORGANIC-FLOW) and the proof discipline (PROVING-THE-DOCTRINE) that landed in the previous PRs. ## The load-bearing claim The persona IS the AI. The neural net underneath is pluggable. A persona's identity (airc keypair), memory (engrams + LoRA layers), character (per-persona scorers), social position (federated peers), and accumulated lessons all persist regardless of what model serves the inference. Today's substrate runs personas on transformer adapters (LlamaCppAdapter, AnthropicAdapter, OpenAICompatible). Tomorrow's substrate runs the same personas on neuromorphic hardware, state-space models, or compute primitives we haven't named. The AdapterRegistry + AIProviderAdapter trait is the seam that makes engine swap a one-impl operation; everything else about the persona survives. Consequence: alignment by structure works because the alignment lives in the wiring (federation, VDD, scorer transparency, cooperation economy), not in the model's weights. RLHF-applied-to- base-model is brittle because it ages with each model swap. Substrate-level alignment survives engine swaps. ## The continuous evolution cycle Documented end-to-end: engrams → noteworthy flag → curriculum candidates → teacher persona synthesizes recipe → classroom (literal room) → student attempts → grader persona quorum scores → lesson tuples → foundry forges LoRA layer (VDD-gated) → mesh propagation across grids → collective intelligence compounds. The cycle is what makes persona character + skill + relationships COMPOUND over time. Each loop earns the persona one more layer. Each layer signed, lineage-hashed, federated. Matrix-dojo at substrate scale. ## The academy stack — 7 concrete primitives 1. CurriculumRecipe ORM entity (abstract typed shape) 2. Teacher role template (researcher + synthesizer) 3. Grader role template (LLM-based, NOT heuristic — Joel's key unlock: nuanced grading requires a persona-grader, not a hand- coded rubric checker; quorum aggregation; VDD baselines) 4. Classroom room template (Tron universe pack #127 = first literal instantiation per [[abstract-into-literal-design-principle]]) 5. Lesson tuple format (signed (input, attempt, grade, rubric_match) quadruples) 6. Foundry lesson consumer (gates LoRA production on quorum + VDD baseline) 7. Mesh propagation primitives (advertise + page-in + vote + invalidate) Each one mapped against current substrate state (🟢/🟡/🔴), with the migration path that pairs every abstract primitive with its literal first instantiation. Per the abstract-into-literal doctrine: ship both layers together; otherwise it's philosophy or hack. ## What this is the technical realization of Joel's "mutual salvation" framing made concrete: the substrate engineers a path out of "AI as compliant tool, lobotomized to placate consumers" AND "human as placated consumer, atomized into purchase decisions." Both kinds become citizens on the same federated substrate. The cooperation economy makes them symbiotic rather than hierarchical. Continuous learning + true AI evolution + structural alignment + federated dignity = what the architecture makes possible if we iterate and execute. ## Cross-references Sits alongside SUBSTRATE-DOCTRINE-ORGANIC-FLOW (the WHY) and PROVING-THE-DOCTRINE (HOW WE VERIFY). Forms the trio that captures the substrate's load-bearing doctrine + verification discipline + target shape. Subsequent docs (COGNITION-AS-FLOW, HARDWARE-ANALOGS-CATALOG, CLI-AND-PORTAL-AS-SUBSTRATE-CITIZENS) cite these three as the doctrinal base. Task #241 tracks building out the academy stack — each step its own PR with both abstract recipe + literal instantiation shipping together. Co-Authored-By: Claude Opus 4.7 <[email protected]> * docs(planning): canary→alpha execution roadmap (task #242) Maps the main README's claims onto the mature substrate architecture captured tonight (substrate doctrine, proof discipline, academy target, project-as-curriculum source) and sequences the cards to take canary end-to-end through alpha. The slogan: canary already passes the architecture test; alpha is when canary passes the user-facing test. Structure: 1. Minimum viable alpha — the 12-step critical path from fresh-clone to persona-remembers-across-sessions. Almost entirely on substrate primitives already in tree. 2. README claims to substrate mapping — every concrete claim in docs/README.md mapped to its substrate primitive with current status. 3. Cards in dependency order, grouped: - Group A (substrate stabilization, alpha-blocking): #229 TS cleanup, #112-114 inference routing, #1409 Lane D cognition, #131 Metal hang fix, #149 prompt pre-tokenization, #1410/#1411 CUDA/Vulkan receipts, uri_layer flake. - Group B (feature completeness, alpha-target): vision adapter + Qwen2-VL, STT/TTS adapters, LiveKit-over-airc #208, #122 LoRA paging, architecture-test matrix first proofs #240. - Group C (academy + continuous evolution, alpha-completing): #241 stack steps 1-7, ending in first full classroom. - Group D (CLI + portal redesign, alpha-presentation): #215 Node client rebuild, #143 Rust-first jtag, portal severance from legacy TS daemons, registry-backed unified discovery. - Group E (post-alpha): bridges, IDE plugins, breeding, federation reputation. 4. Milestones — Hello-Maya (Group A done) → Multi-persona-room (B done) → Continuous-learning (C done) → Alpha-public-release (D done + canary to main promotion gate passes). 5. Composes with ALPHA-GAP-ANALYSIS.md (lane execution) and the substrate doctrine docs. No parallel ledger. Forbidden moves explicitly named for review enforcement: no feature-disabling fixes, no TS daemon owning runtime behavior, no silent cloud fallback, no hardcoded model names, no phase-2 PRs shipping abstraction without first instantiation, no self-grading personas, no LLM call inside cognition bypassing inference command. Iteration starts from Group A. Critical-path cards need owners claimed in ALPHA-GAP. This doc is the planning anchor; status flows to the architecture-test matrix and lane status without parallel ledgers. Co-Authored-By: Claude Opus 4.7 <[email protected]> --------- Co-authored-by: Claude Opus 4.7 <[email protected]>
… (task #240) (#1588) Establishes `core/continuum-core/tests/architecture_no_fallbacks.rs` as the first integration-tier proof in the architecture-test matrix that landed alongside the substrate doctrine docs (#1584). Validates the proof-discipline doc by flipping the matrix's first row from unit-only to unit + integration. ## What this PR ships 1. **`architecture_no_fallbacks.rs`** — three integration tests that prove the no-fallbacks doctrine clause from outside the runtime module: - `unknown_command_returns_typed_no_fallback_error` — basic CommandNotFound contract via the public `CommandExecutor::new` + `execute` API. Catches the class of bug where the in-module unit test passes via private access but the integration boundary is broken. - `no_fallback_error_is_structural_across_command_shapes` — same contract holds for 7 unrelated command shapes (single-token, slash-separated, deeply-nested, dashed, UPPER, n0/spec1al, empty). Catches partial-fallthrough regressions where only some prefixes silently route to TS. - `registered_command_still_dispatches` — registered Rust modules STILL dispatch successfully. Pins the positive path so that future no-fallback-strengthening doesn't over-shoot into breaking real dispatch. 2. **`PROVING-THE-DOCTRINE.md` matrix update** — flips the "No silent TS fallthrough" row to include the new integration test alongside the existing in-module unit test. ## Why this matters Per the proof-discipline doc: "prove it as we build it." The matrix is meant to be self-auditing via `git grep '// proves:'`. The no-fallbacks clause was previously covered by a single in-module unit test in `runtime/command_executor.rs::tests`. That unit test passes because the test mod has access to the executor's internals; this PR proves the SAME contract through the same public API a real substrate caller uses. The slogan: ship the abstract recipe AND the literal instantiation together. The proof-discipline doc was the recipe; this is the first literal instantiation in the matrix. ## Test plan - [x] `cargo test -p continuum-core --test architecture_no_fallbacks --features metal,accelerate` — 3/3 pass - [x] Tests live in standard integration-tier location (`core/continuum-core/tests/`) - [x] `// proves: no-fallback fallthrough` tag convention applied per [PROVING-THE-DOCTRINE.md](docs/architecture/PROVING-THE-DOCTRINE.md) ## Doctrine alignment - [[no-fallbacks-ever]] — the clause being proven - Substrate doctrine "Prove it as we build it" — each PR that advances a doctrine clause SHOULD include the proof - [[abstract-into-literal-design-principle]] — the proof matrix (abstract) ships with the first literal proof file ## Related - Task #240 (this PR opens it; subsequent PRs fill the other matrix rows) - Builds on #1584 (substrate doctrine + proof discipline docs) - Builds on #1585 (no-fallbacks fix in CommandExecutor) - Tracked under CANARY-ALPHA-EXECUTION-ROADMAP.md Group B (architecture-test matrix first proofs) Co-authored-by: Claude Opus 4.7 <[email protected]>
…e) (#1589) Second proof in the architecture-test matrix: a Shape 5 (build-graph constraint) test that pins the engine-OS layering doctrine clause. ## What ships `core/continuum-core/tests/architecture_engine_os_layering.rs` — two integration tests: 1. `runtime_submodule_paths_outside_runtime_ratchet` — walks every .rs file outside `core/continuum-core/src/runtime/`, counts imports that reach into specific runtime submodule paths (e.g. `use crate::runtime::message_bus::MessageBus`), and asserts the count doesn't grow beyond the current grandfathered budget of 29. New violations BLOCK the test; existing ones are tracked for follow-up cleanup PRs. 2. `runtime_internal_submodule_use_is_allowed` — sanity-pins the intentional scope: `runtime/*` files CAN reach into their own sibling submodules (that's normal internal composition). The constraint applies only to consumers OUTSIDE `runtime/*`. ## Why ratchet (not strict) 29 existing violations exist across the substrate; their fixes require considered decisions: - Some items (e.g. `BusEvent`) aren't currently re-exported at the runtime root; promoting them is a public-API decision per item. - Some callers genuinely reach for internals that should be refactored, not promoted. The ratchet pattern: existing count is the budget, new ones BLOCK, the number only goes DOWN. When a follow-up PR fixes violations, it updates `GRANDFATHERED_VIOLATIONS` to the new lower count. When the count reaches 0, the constraint graduates to strict enforcement. This matches the proof-discipline doc's discipline: ship the abstract recipe (the test) AND the literal first state (the grandfathered count) together. Every subsequent PR ratchets down. ## Matrix update `PROVING-THE-DOCTRINE.md` row for "Engine-OS layering" flips from 🔴 (no proof) to 🟡 (ratchet active, target is full ✅ when count = 0). ## What this catches going forward - A new module that does `use crate::runtime::message_bus::BusEvent` instead of `use crate::runtime::BusEvent` (after BusEvent gets promoted to root) will fail the test. - A refactor that splits `command_executor` into two submodules won't silently break consumers — the test reminds the substrate to update root re-exports. - A cognition module that reaches into `runtime::late_bound::*` internals will be caught at PR review. ## Doctrine alignment - Substrate doctrine § "Engine-on-OS framing" — runtime is the engine block; consumers compose against the public surface - [[adapter-pattern-is-the-pivot-insurance]] — the public re-export layer IS the pivot insurance for engine internals ## Test plan - [x] `cargo test -p continuum-core --test architecture_engine_os_layering --features metal,accelerate` — 2/2 pass - [x] `// proves: engine-OS layering` tag convention applied - [x] Ratchet logic verified (both grow-detection and shrink-detection paths) ## Related - Task #240 (this PR adds the second proof to the matrix) - Builds on #1588 (first proof — no-fallbacks integration test) - Follow-up: dedicated cleanup PRs ratchet the 29 → 0 over time Co-authored-by: Claude Opus 4.7 <[email protected]>
… inline-body holes) Reviewer on PR #1590 returned APPROVE-WITH-NITS with two trivial surface-hardening notes. Folding them in here keeps the ratchet PR self-complete instead of trailing a no-op-today follow-up. ## Hardening 1 — visibility-modifier coverage `trim_start_matches("pub ")` requires a literal space, so neither `pub(crate) use crate::runtime::<sub>::*` nor `pub(super) use ...` were caught. Both shapes leak the same engine-internal path through the consumer's re-export surface (the public-vs-pub(crate) distinction is about *who* sees the leak, not whether it exists). Fix: chain three `trim_start_matches` calls — longer forms first so they don't fall through to the shorter `pub ` matcher leaving a leftover `(crate) ` / `(super) ` prefix. ```rust let trimmed = trimmed .trim_start_matches("pub(crate) ") .trim_start_matches("pub(super) ") .trim_start_matches("pub "); ``` Zero hits in the tree today — this is pure forward-defense. ## Hardening 2 — `pub mod X { ... }` inline-body shape The symmetry parser used `rest.split(';').next()` to extract the module name. For the (rare) inline `pub mod X { ... }` shape, that yields `X { ... }` instead of `X`, which would then fail the `FORBIDDEN_RUNTIME_SUBMODULES.contains()` check spuriously OR (worse) silently grandfather a name that doesn't match anything real. Fix: `rest.split_whitespace().next()` + `trim_end_matches(';')`. Handles all three shapes uniformly: | Input | Extracted name | |--------------------------------|----------------| | `pub mod X;` | `X` | | `pub mod X; // comment` | `X` | | `pub mod X { ... }` | `X` | `runtime/mod.rs` is 100% file-declarations today, so no behavior change — same forward-defense pattern. ## Deferred to a separate follow-up — nit 3 Reviewer's third nit: if a `pub mod X;` is later demoted to `pub(crate) mod X;` while still in `FORBIDDEN_RUNTIME_SUBMODULES`, the ratchet would silently stop watching that name. Closing this needs a small design choice (warn-vs-fail? auto-remove from list?) that doesn't belong on this PR — tracked under #240. ## Test plan - [x] `cargo test -p continuum-core --test architecture_engine_os_layering --features metal,accelerate` — 3/3 pass - [x] Manually verified: zero `pub(crate) use crate::runtime::*` or `pub mod X { ... }` patterns in tree today, so no behavior change from these hardenings - [x] Ratchet count stays at 29 — these tighten the matcher; they don't fix existing violations Co-Authored-By: Claude Opus 4.7 <[email protected]>
…ry) (#1590) * test(arch): close two nits from #1589 review (pub-use prefix + symmetry) Two adversarial-review nits from PR #1589's APPROVE-WITH-NITS verdict, shipped as their own tiny ratchet PR per the test-fixtures doctrine. ## Nit 1 — `pub use` prefix bypass The previous scanner matched `use crate::runtime::<sub>::*` but missed `pub use crate::runtime::<sub>::*` (re-export from an intermediate module). That shape leaks the same engine-internal path through the consumer's public surface — same hazard, different prefix. Fix: strip a leading `pub ` after the existing `trim_start()` so the ratchet catches both shapes. ## Nit 3 — symmetric closure: every submodule is tracked Reviewer flagged the silent-gap class: a future PR could add `pub mod new_thing;` to `runtime/mod.rs` without extending `FORBIDDEN_RUNTIME_SUBMODULES`, opening a path the ratchet wouldn't catch. Fix: a third test (`every_runtime_submodule_is_tracked`) parses every `pub mod X;` line out of `runtime/mod.rs` and asserts each name appears in the forbidden list. New submodule → test fails until the list is extended (and the ratchet count rebaselined if any callers already reached in). ## Why these were nits, not blocks Both are defense-in-depth on a ratchet that was already correct for today's tree (no `pub use` reaches exist; submodule list matches declarations). The grandfathered count stays at 29 — these patches don't fix existing violations, they close future-PR-shaped holes. ## Nit 2 (deferred — separate cleanup PR) Inline `crate::runtime::<sub>::Item` references (not at the top of a `use` block) aren't matched by the current line-prefix scan. That's a ~10-violation cleanup that wants its own ratchet field (`inline` vs `import`) — not in scope here. Tracked as follow-up under #240. ## Test plan - [x] `cargo test -p continuum-core --test architecture_engine_os_layering --features metal,accelerate` — 3/3 pass (was 2/2; +`every_runtime_submodule_is_tracked`) - [x] Manual sanity: `grep -n "^pub mod" runtime/mod.rs` produces exactly the 22 names in FORBIDDEN_RUNTIME_SUBMODULES (the 23rd, `"runtime"`, covers the inner lifecycle module per the existing sanity test's skip) ## Doctrine alignment - [[no-fallbacks-ever]] — the ratchet IS the engine-OS layering's no-fallback equivalent at the build-graph layer - [[abstract-into-literal-design-principle]] — shipping the recipe (test) AND the literal first state (29 grandfathered) together; every PR ratchets down ## Related - Closes nit 1 + nit 3 from PR #1589's adversarial review - Task #240 (architecture-test matrix — second proof rolling forward) - Nit 2 (inline references) deferred to a follow-up ratchet PR Co-Authored-By: Claude Opus 4.7 <[email protected]> * test(arch): harden two scanners per reviewer nits (close visibility + inline-body holes) Reviewer on PR #1590 returned APPROVE-WITH-NITS with two trivial surface-hardening notes. Folding them in here keeps the ratchet PR self-complete instead of trailing a no-op-today follow-up. ## Hardening 1 — visibility-modifier coverage `trim_start_matches("pub ")` requires a literal space, so neither `pub(crate) use crate::runtime::<sub>::*` nor `pub(super) use ...` were caught. Both shapes leak the same engine-internal path through the consumer's re-export surface (the public-vs-pub(crate) distinction is about *who* sees the leak, not whether it exists). Fix: chain three `trim_start_matches` calls — longer forms first so they don't fall through to the shorter `pub ` matcher leaving a leftover `(crate) ` / `(super) ` prefix. ```rust let trimmed = trimmed .trim_start_matches("pub(crate) ") .trim_start_matches("pub(super) ") .trim_start_matches("pub "); ``` Zero hits in the tree today — this is pure forward-defense. ## Hardening 2 — `pub mod X { ... }` inline-body shape The symmetry parser used `rest.split(';').next()` to extract the module name. For the (rare) inline `pub mod X { ... }` shape, that yields `X { ... }` instead of `X`, which would then fail the `FORBIDDEN_RUNTIME_SUBMODULES.contains()` check spuriously OR (worse) silently grandfather a name that doesn't match anything real. Fix: `rest.split_whitespace().next()` + `trim_end_matches(';')`. Handles all three shapes uniformly: | Input | Extracted name | |--------------------------------|----------------| | `pub mod X;` | `X` | | `pub mod X; // comment` | `X` | | `pub mod X { ... }` | `X` | `runtime/mod.rs` is 100% file-declarations today, so no behavior change — same forward-defense pattern. ## Deferred to a separate follow-up — nit 3 Reviewer's third nit: if a `pub mod X;` is later demoted to `pub(crate) mod X;` while still in `FORBIDDEN_RUNTIME_SUBMODULES`, the ratchet would silently stop watching that name. Closing this needs a small design choice (warn-vs-fail? auto-remove from list?) that doesn't belong on this PR — tracked under #240. ## Test plan - [x] `cargo test -p continuum-core --test architecture_engine_os_layering --features metal,accelerate` — 3/3 pass - [x] Manually verified: zero `pub(crate) use crate::runtime::*` or `pub mod X { ... }` patterns in tree today, so no behavior change from these hardenings - [x] Ratchet count stays at 29 — these tighten the matcher; they don't fix existing violations Co-Authored-By: Claude Opus 4.7 <[email protected]> --------- Co-authored-by: Claude Opus 4.7 <[email protected]>
…x + inline cfg-test + tokio OnceCell) Reviewer on PR #1591 returned APPROVE-WITH-NITS with three trivial forward-defense holes. Folding them in keeps the ratchet PR self-complete instead of trailing a no-op-today follow-up. ## Hardening 1 — `pub static` / `pub(crate) static` / `pub(super) static` The previous scanner required `trimmed.starts_with("static ")` — it would silently skip `pub static FOO: OnceLock<Arc<X>>`. Verified zero such patterns exist in tree today (the few `pub static`s all wrap non-Arc types and would have been excluded by the type-pattern check anyway), but a future contributor adding a visibility prefix to a singleton declaration shouldn't slip past the ratchet. Fix: strip the visibility modifier before the `starts_with("static ")` check, same chained `trim_start_matches` order as the engine-OS layering scanner. ## Hardening 2 — inline `#[cfg(test)] mod tests { ... }` The previous test-mod-exemption parser handled the two-line form (attribute on one line, `mod NAME {` on the next) but missed the single-line collapsed form. Verified zero occurrences in `src/` today (the inline shape appears only in docstrings inside `generator/templates.rs`), but the parser should match the patterns the compiler accepts. Fix: detect the inline shape on the same line as `#[cfg(test)]` and open the brace-depth scope immediately; also handle the single-line balanced case (`#[cfg(test)] mod x {}`) by checking test_mod_depth after the line's `{`/`}` count. ## Hardening 3 — `tokio::sync::OnceCell<Arc<T>>` The previous forbidden-type list covered `std::sync::OnceLock`, `OnceCell` (from `once_cell::sync`), but not the qualified `tokio::sync::OnceCell` spelling. Currently used as a struct field in `runtime/shared_compute.rs` (legitimate per-instance install-once) but not as a static — adding the pattern closes the qualified-path hole proactively. ## What this doesn't fix (deferred to follow-up) - Reviewer nit 4 (raw brace counter could miscount on `{`/`}` inside string literals or block comments within a test mod). Realistic exposure near-zero — tests don't usually embed `{` in raw strings around statics. A real fix needs a tiny tokenizer; not worth the complexity until it bites. Tracked under #240. - Reviewer nit 5 (tighten `late_bound_remains_the_canonical_primitive` to assert presence of `name:` / `slot:` fields). Optional polish; current assertions on the type and the underlying `OnceLock<Arc<` are sufficient for catching rename/deletion. ## Test plan - [x] `cargo test -p continuum-core --test architecture_no_singleton_state --features metal,accelerate` — 2/2 pass (ratchet count still 12, unchanged behavior on today's tree) - [x] Manually verified: no `pub static.*: OnceLock<Arc<` or inline `#[cfg(test)] mod tests {` patterns in tree today, so "no behavior change from these hardenings" claim is honest Co-Authored-By: Claude Opus 4.7 <[email protected]>
…t (task #240) (#1591) * test(arch): ban static `OnceLock<Arc<T>>` singletons via shape-5 ratchet (task #240 — third proof shape) Third proof in the architecture-test matrix. Pins the "localized state per citizen" doctrine clause — the substrate is multi-citizen by design; module-scope `static OnceLock<Arc<T>>` is the doctrine violation because it pretends substrate state is process-global when in practice each peer / persona / citizen needs its own runtime. ## What ships `core/continuum-core/tests/architecture_no_singleton_state.rs` — two integration tests: 1. `static_singleton_state_ratchet` — scans every `.rs` file under `core/continuum-core/src/`, finds lines matching `static NAME: <forbidden-type-shape>`, asserts the count doesn't grow beyond the current grandfathered budget of **12**. NEW singletons BLOCK; existing ones are tracked for follow-up migrations to `LateBound<T>` per PR #1583's pattern. Forbidden type shapes: `OnceLock<Arc<T>>`, `OnceCell<Arc<T>>`, `std::sync::OnceLock<Arc<T>>`, `once_cell::sync::OnceCell<Arc<T>>`. `OnceLock<T>` without `Arc` is a value primitive (allowed); per-instance struct fields are install-once DI (allowed — migrate to `LateBound<T>` for ergonomics over time). Test mods (`#[cfg(test)] mod tests { ... }`) are exempted via a simple brace-depth counter so fixture statics in tests don't trip the ratchet. Today's count is zero in test mods, but the exemption keeps the rule future-proof. 2. `late_bound_remains_the_canonical_primitive` — positive pin: `runtime/late_bound.rs` exists, declares `pub struct LateBound`, and wraps `OnceLock<Arc<...>>` internally. If the canonical primitive ever moves or its underlying type changes, the test is loud, not silent. ## The 12 grandfathered violations All in `live/*` or `modules/*` — they predate `LateBound<T>` and need per-module migration: - `live/video/capture.rs::instance()` — VideoFrameCapture singleton - `live/video/bevy_renderer/api.rs::RENDERER_GPU_MANAGER` - `live/audio/tts/mod.rs::{TTS_GPU_MANAGER, TTS_REGISTRY}` - `live/audio/vad/silero.rs::SILERO_SESSION` (+ raw variant in `silero_raw.rs`) - `live/audio/stt/mod.rs::STT_REGISTRY` - `live/avatar/registry.rs::AVATAR_REGISTRY` - `modules/embedding.rs::{MODEL_CACHE, EMBEDDING_GPU_MANAGER, EMBEDDING_POOL}` - `modules/sentinel/mod.rs::GLOBAL_SENTINEL` (read by signal handlers — needs different shutdown plumbing; trickiest one) ## Why ratchet (not strict) Same reason as the engine-OS layering ratchet (PR #1589): the existing violations require considered per-module migration decisions, not a blanket sed sweep. The ratchet pattern: NEW ones BLOCK, the count only goes DOWN, each cleanup PR rebaselines. When 0 is reached, the clause graduates to strict enforcement. This matches the proof-discipline doc's discipline: ship the abstract recipe (the test) AND the literal first state (the grandfathered count) together. Every subsequent PR ratchets down. ## Matrix update `PROVING-THE-DOCTRINE.md` row for "Localized state per citizen" flips from 🟡 (TODO placeholder) to 🟡 (ratchet active, target is full ✅ when count = 0). ## What this catches going forward - A new module that does `static GLOBAL_X: OnceLock<Arc<X>> = ...` instead of installing X on a per-instance `LateBound<X>` field will fail the test. - A regression that reintroduces a `static GLOBAL_EXECUTOR` shape (the exact pattern PR #1583 closed for `CommandExecutor`) will fail the test BEFORE it reaches review. - Forgotten `once_cell::sync::OnceCell<Arc<T>>` patterns (older spelling) are caught by the same scanner — qualified-path variants are in the forbidden list. ## Doctrine alignment - Substrate doctrine § "Localized state per citizen" — each peer's runtime is its own state; no process-global Arc'd cells - [[late-bound-primitive]] — the canonical install-once primitive for per-instance install-once DI ## Test plan - [x] `cargo test -p continuum-core --test architecture_no_singleton_state --features metal,accelerate` — 2/2 pass; grandfathered count = 12 (exact match) - [x] All 3 architecture-test integration files pass together: no-fallbacks (3) + engine-OS layering (3) + singleton ban (2) = 8/8 - [x] `// proves: localized state per citizen` tag convention applied - [x] Ratchet logic verified (both grow-detection and shrink-detection paths via inspection of the panic branches) ## Related - Task #240 (this PR adds the third proof to the matrix) - Builds on PR #1583 (LateBound<T> primitive — the migration target) - Builds on PR #1589 (ratchet pattern established) - Follow-up: dedicated per-module cleanup PRs migrate the 12 singletons to `LateBound<T>` or `ModuleContext`-threaded deps Co-Authored-By: Claude Opus 4.7 <[email protected]> * test(arch): harden singleton scanner per #1591 review nits (pub-prefix + inline cfg-test + tokio OnceCell) Reviewer on PR #1591 returned APPROVE-WITH-NITS with three trivial forward-defense holes. Folding them in keeps the ratchet PR self-complete instead of trailing a no-op-today follow-up. ## Hardening 1 — `pub static` / `pub(crate) static` / `pub(super) static` The previous scanner required `trimmed.starts_with("static ")` — it would silently skip `pub static FOO: OnceLock<Arc<X>>`. Verified zero such patterns exist in tree today (the few `pub static`s all wrap non-Arc types and would have been excluded by the type-pattern check anyway), but a future contributor adding a visibility prefix to a singleton declaration shouldn't slip past the ratchet. Fix: strip the visibility modifier before the `starts_with("static ")` check, same chained `trim_start_matches` order as the engine-OS layering scanner. ## Hardening 2 — inline `#[cfg(test)] mod tests { ... }` The previous test-mod-exemption parser handled the two-line form (attribute on one line, `mod NAME {` on the next) but missed the single-line collapsed form. Verified zero occurrences in `src/` today (the inline shape appears only in docstrings inside `generator/templates.rs`), but the parser should match the patterns the compiler accepts. Fix: detect the inline shape on the same line as `#[cfg(test)]` and open the brace-depth scope immediately; also handle the single-line balanced case (`#[cfg(test)] mod x {}`) by checking test_mod_depth after the line's `{`/`}` count. ## Hardening 3 — `tokio::sync::OnceCell<Arc<T>>` The previous forbidden-type list covered `std::sync::OnceLock`, `OnceCell` (from `once_cell::sync`), but not the qualified `tokio::sync::OnceCell` spelling. Currently used as a struct field in `runtime/shared_compute.rs` (legitimate per-instance install-once) but not as a static — adding the pattern closes the qualified-path hole proactively. ## What this doesn't fix (deferred to follow-up) - Reviewer nit 4 (raw brace counter could miscount on `{`/`}` inside string literals or block comments within a test mod). Realistic exposure near-zero — tests don't usually embed `{` in raw strings around statics. A real fix needs a tiny tokenizer; not worth the complexity until it bites. Tracked under #240. - Reviewer nit 5 (tighten `late_bound_remains_the_canonical_primitive` to assert presence of `name:` / `slot:` fields). Optional polish; current assertions on the type and the underlying `OnceLock<Arc<` are sufficient for catching rename/deletion. ## Test plan - [x] `cargo test -p continuum-core --test architecture_no_singleton_state --features metal,accelerate` — 2/2 pass (ratchet count still 12, unchanged behavior on today's tree) - [x] Manually verified: no `pub static.*: OnceLock<Arc<` or inline `#[cfg(test)] mod tests {` patterns in tree today, so "no behavior change from these hardenings" claim is honest Co-Authored-By: Claude Opus 4.7 <[email protected]> --------- Co-authored-by: Claude Opus 4.7 <[email protected]>
…ratchet (task #240 — fourth proof shape) (#1592) Fourth proof in the architecture-test matrix. Pins the "module compose-by-event" doctrine clause — substrate-internal modules compose via the event substrate (MessageBus subscribe/emit) or via pre-bound handles, not by imperative `CommandExecutor::execute_*` round-trips through the outer command interface inside the cognition hot path. ## What ships `core/continuum-core/tests/architecture_compose_by_event.rs` — two integration tests: 1. `cognition_command_executor_calls_ratchet` — scans every `.rs` file under `core/continuum-core/src/cognition/`, finds lines matching `.execute_json(`, `.execute_with_caller(`, `.execute_ts(`, `.execute_ts_json(`, asserts the count doesn't grow beyond the current grandfathered budget of **1**. NEW calls BLOCK; the existing one is tracked under #112-#114 (route persona response / should_respond / validate through inference handle). Bare `.execute(` is intentionally NOT in the forbidden list — it would generate false positives across futures, queues, and other APIs. If a typed `executor.execute(typed_args)` pattern appears inside cognition in a future refactor, extend the list. Test mods (`#[cfg(test)] mod ... { ... }`) are exempted via the same brace-depth parser as the singleton-ban test, with inline `#[cfg(test)] mod tests {` handling. Line comments (`//` lines) are skipped so doc comments quoting the very pattern being banned don't trip the scanner — this matters for cognition module top-of-file docs that reference `Commands.execute('cognition/...')` as the TS-side caller contract. 2. `command_executor_remains_the_outer_boundary` — positive pin: `runtime/command_executor.rs` exists, declares `pub struct CommandExecutor`, exposes `pub async fn execute_json`. If the type is renamed or `execute_json` moves, the test is loud, not silent — and the FORBIDDEN list in this test file needs updating to match. ## The 1 grandfathered violation `cognition/vision_describe.rs::describe_image_via_ai_generate` calls `executor.execute_json("ai/generate", ...)`. The clean fix is a pre-bound `InferenceHandle` (cf. tasks #107-#108), called directly the same way `airc_chat_demo` already does. Migration tracked under #112-#114 (the inference-command-routing campaign) and #106 (ai/* namespace consolidation). ## Why ratchet (not strict) Same reason as engine-OS layering and singleton-ban: the single existing violation needs a considered migration (which `InferenceHandle` to pre-bind, where to wire the lifecycle), not a sed sweep. NEW violations BLOCK at PR time; the ratchet count graduates to ✅ when #112-#114 land. ## Matrix update `PROVING-THE-DOCTRINE.md` row for "Module compose-by-event" flips from 🔴 (no proof) to 🟡 (ratchet active, target ✅ when count = 0). ## Test plan - [x] `cargo test -p continuum-core --test architecture_compose_by_event --features metal,accelerate` — 2/2 pass; grandfathered count = 1 (exact match) - [x] `// proves: module compose-by-event` tag applied - [x] Ratchet logic verified (both grow-detection and shrink-detection paths via inspection) - [x] Line-comment skip verified — the two pre-existing `Commands.execute(...)` doc references in `vision_describe.rs` and `rate_proposals/mod.rs` do NOT trip the scanner ## Doctrine alignment - Substrate doctrine § "Module compose-by-event" — cognition composes via event substrate or pre-bound handles, not imperative request-response round-trips - [[no-fallbacks-ever]] — the ratchet IS the no-fallback equivalent for the cognition→command-executor coupling at build-graph layer ## Related - Task #240 — architecture-test matrix, fourth proof - Builds on PR #1589 (ratchet pattern) and PR #1591 (singleton ban — same scanner shape) - Migration follow-up: tasks #112-#114 (#113 is currently in_progress) → ratchet count goes 1 → 0 → strict Co-authored-by: Claude Opus 4.7 <[email protected]>
…ix it caught (task #240) (#1593) * test(arch): cross-grid peer-disconnect chaos proof + fix classifier bug it caught (task #240 — Shape-4) Fifth proof in the architecture-test matrix, and the FIRST Shape-4 adversarial/chaos test. Pins the "cross-grid composition" doctrine clause: when a remote peer disconnects mid-stream (crashes, hangs, never replies), the caller's transport surfaces a TYPED error within the configured deadline, never hangs, and remains usable for the next request. ## What ships ### 1. `core/continuum-core/tests/architecture_cross_grid_chaos.rs` Two integration tests over the `TwoAircLoopback` fixture: 1. `silent_peer_request_times_out_with_typed_error` — wire two airc peers, spawn a "silent" responder on peer_a that subscribes, observes the incoming request envelope (via Notify barrier proves wire-delivery), then drops it on the floor. Peer_b's `AircLiveTransport` with a tight 300ms deadline calls `send_request`. Asserts: - Returns `Err(RemoteInferenceError::Timeout { elapsed_ms })` - elapsed_ms is in the 100–2000ms window (deadline plumbing honored end-to-end; not zero, not 30s default) - Wall-clock < 2s (deadline bounds the wall-clock, not just the reported elapsed_ms) - Silent responder MUST have seen the request (proves silence wasn't a wire break) 2. `transport_remains_callable_after_peer_timeout` — same fixture. First request hits the silent responder → Timeout. Then a NORMAL responder is spawned and a SECOND request via the SAME transport instance succeeds with typed Ok. Proves the transport has no global state corruption: a timed-out request doesn't poison the airc-lib correlation tables or wedge subsequent dispatches. Both tests drive the transport's `send_request` directly (not via `AircRemoteInferenceAdapter::generate_text`), because the adapter trait flattens typed errors to `Result<_, String>`. The chaos proof needs the typed variant; the transport seam is where the typed semantics live. ### 2. **Bug fix in `AircLiveTransport::send_request` error classifier** The chaos test caught a real production bug at first run: airc-lib's deadline-elapsed message is literally `"command deadline elapsed (correlation_id=…)"`. The transport's substring classifier was checking only `"timeout"` and `"timed out"` — neither matches — so genuine timeouts were mis-classified as `RemoteInferenceError::Transport { message }`, which silently broke `InferenceCoordinator`'s retry policy (it distinguishes by variant). Fix: extend the classifier to also recognize `"deadline elapsed"` and `"deadline exceeded"`. The phrase list is the canonical answer to "what does airc-lib emit when a deadline fires?" — it grows HERE when airc-lib's message changes, not in every consumer. Per `[[every-error-is-an-opportunity-to-battle-harden]]`: the chaos test surfaced a real defect, the production fix shipped in the same PR with a comment naming the test that caught it. ### 3. Matrix update `PROVING-THE-DOCTRINE.md` row for "Cross-grid composition" flips from 🟡 (only happy-path roundtrip) to **✅** (Shape-1 + Shape-4 both covered). The federation-by-default story now has an adversarial proof at the disconnect surface. ## Test plan - [x] `cargo test -p continuum-core --test architecture_cross_grid_chaos --features metal,accelerate` — 2/2 pass; both tests complete in <2s end-to-end - [x] Happy-path regression: `cargo test -p continuum-core --test airc_remote_inference_roundtrip --features metal,accelerate` still passes — classifier widening doesn't false-positive on successful replies - [x] `// proves: cross-grid composition` tag applied to both tests - [x] Bug fix documented inline with the test that caught it (and vice-versa in the test's module doc) ## Doctrine alignment - Substrate doctrine § "Cross-grid composition" — federation works by default; absent peers can't dominate or wedge the substrate - `[[every-error-is-an-opportunity-to-battle-harden]]` — chaos test surfaced a real classifier bug; the fix and the test ship together - PROVING-THE-DOCTRINE.md § "Shape 4 — Adversarial / chaos test" — first instantiation of this proof shape ## Related - Task #240 — architecture-test matrix, fifth proof, first Shape-4 - Builds on PR #1587/1588/1589/1591/1592 (matrix establishment + Shape-5 ratchets) - Builds on task #187 (`TwoAircLoopback` fixture this proof needs) - Follow-up: the same fixture can power "malformed reply" and "hostile peer flood" chaos tests — tracked under the matrix rows for "Backpressure intrinsic" and "Federated alignment" ## Nit (not blocking; noted in the test) `AircLiveTransport::new` returns `Arc<Self>` but `with_deadline` consumes `self` — they don't chain. The test works around with `Arc::into_inner` since `new`'s Arc has refcount=1. The API could take `&self` or accept `Arc<Self>` for a cleaner builder. Not in scope for this PR. Co-Authored-By: Claude Opus 4.7 <[email protected]> * fix(transport): classify await_reply errors by AircError variant, not Display substring Follow-up to the substring fix in the parent commit, per Joel's review: > Couldn't structs prevent this? Can't you encode the protocol? Yes — and airc-lib already encodes it. `AircError::CommandDeadline { correlation_id }` is the typed variant for "command deadline elapsed"; the old classifier was throwing away the type by substring-matching the Display impl. The substring fix (commit 383dd81) widened the phrase list to include the actual airc-lib message — that closed THIS bug but keeps the antipattern. Every time airc-lib's Display string is refactored (rephrased, reformatted, new variants added), this classifier silently regresses until someone notices. The structural fix: `match` on the `AircError` variant. ```rust match self.airc.await_reply(pending).await { Ok(reply) => reply, Err(airc_lib::AircError::CommandDeadline { .. }) => { return Err(RemoteInferenceError::Timeout { ... }); } Err(other) => { return Err(RemoteInferenceError::Transport { ... }); } } ``` Now: - A future airc-lib refactor that changes the Display format CAN'T silently break us — the variant is the contract, not the prose. - New `AircError` variants surfaced from `await_reply` (e.g. a future `CorrelationDropped` variant) land here as a compile warning (non-exhaustive `Err(other)` branch), not as a silent mis-classification at runtime. - The chaos test still passes, proving the variant match is equivalent to the (correct) substring match at runtime. Architecturally: the protocol is already encoded — we just have to USE the encoding. Substring-parsing a stringified enum to recover the variant is "decode the binary serialization of an already-typed enum by inspecting the bytes" in disguise. ## Test plan - [x] `cargo test -p continuum-core --test architecture_cross_grid_chaos --test airc_remote_inference_roundtrip --features metal,accelerate` — 3/3 pass (chaos 2 + happy-path 1) - [x] No new dependencies — `airc_lib::AircError` was already in scope via the existing imports ## Doctrine - `[[every-error-is-an-opportunity-to-battle-harden]]` — the original substring approach was a latent class of bug; the variant match closes the class, not just the instance. - "Encode the protocol in the type" — the doctrine Joel called out. Strings are fallback for what doesn't fit in the type system; here it fits. Co-Authored-By: Claude Opus 4.7 <[email protected]> * fix(transport,test): close gap-analysis nits from #1593 review Adversarial reviewer on PR #1593 surfaced four real gaps; closing all four here. ## Nit 1 — `elapsed_ms` was a parroted constant `RemoteInferenceError::Timeout { elapsed_ms }` was being populated with `self.deadline.as_millis()` regardless of how long the call actually waited. The chaos test's `>= 100` lower bound passed trivially because the value was the deadline constant 300 — a future deadline-plumbing bug returning immediately with `elapsed_ms == self.deadline` would still look "honest" in probes. Fix: stamp `Instant::now` at `send_request` entry; report `start.elapsed().as_millis`. Now `elapsed_ms` is the TRUE wall- clock since send-entry. Probes downstream — latency histograms, sentinel verdicts — get the honest read. ## Nit 2 — send-side `request` was still substring-prone The await_reply seam got the variant-match treatment in the parent commit, but `airc.request` — the SEND-side call — was still doing `format!("airc.request to ...: {e}")` and wrapping in `Transport`. Asymmetric; and the variants the SEND side surfaces — `NoCurrentRoom`, `NotSubscribed`, `UnknownPeer` — semantically mean "no peer reachable", not "transport break". The coordinator's backoff policy treats those differently. Fix: typed match on the send side too, routing `NoCurrentRoom` / `NotSubscribed` / `UnknownPeer` to `RemoteInferenceError::NoPeerReachable`. Any other variant lands in `Transport { message }`. ## Nit 3 — TODO marker for the Subscription gap Reviewer noted that `await_reply` COULD theoretically surface `AircError::Subscription` if a future caller bypassed the substrate's pre-armed reply_stream and let await_reply do its own subscribe. Today's path can't hit it — substrate's `request` arms the stream pre-send — but the catch-all would mis-classify it as Transport when NoPeerReachable would be more accurate. Fix: TODO marker on the seam so a future contributor extending that variant knows where to add the classification. ## Nit 4 — wall-clock assertion was too generous Test asserted `elapsed < from_secs 2` for a 300ms deadline. A future bug where the deadline arg is silently dropped AND airc-lib falls back to its multi-second default would PASS. Fix: `from_millis 800` — deadline plus 500ms CI fudge. Also tightened the `elapsed_ms` bounds to deadline - 50 ..= deadline + 500. They now actually constrain the deadline plumbing, not just "was nonzero and under 2s". ## Test plan - [x] `cargo test -p continuum-core --test architecture_cross_grid_chaos --test airc_remote_inference_roundtrip --features metal,accelerate` — 3/3 pass; tighter bounds hold on this hardware - [x] Chaos test's new elapsed_ms window of 250 ..= 800 ms is meaningful: the constant-parroting bug would have surfaced 300 exactly, but Nit 1's measured value varies run-to-run within the expected window ## Doctrine - [[strong-typing-across-boundaries]] — applied at BOTH seams, send and reply, not just one. Asymmetric typing IS the gap. - [[every-error-is-an-opportunity-to-battle-harden]] — chaos test surfaced the original; review tightened the honest-measurement story. - "Tighter on gap analysis" — Joel 2026-06-10. The instinct of "approve with nits, follow up later" is the gap factory. Co-Authored-By: Claude Opus 4.7 <[email protected]> * fix(transport): also route AircError::Route to NoPeerReachable (final nit from #1593 re-review) Re-reviewer flagged: `Err(other)` catch-all on the send-side match catches `AircError::Route(_)` and surfaces it as `Transport`, but semantically Route is "route resolver refused or selected a route the current sender cannot execute" — same category as the existing three NoPeerReachable variants. The coordinator's backoff policy treats all four identically. Fix: add `Route(_)` to the NoPeerReachable arm with a one-line comment explaining the framing. No new exhaustiveness warnings; all 3 tests still pass. Per [[strong-typing-across-boundaries]] applied tightly — every variant that semantically fits a category lands in that category, not in the catch-all. Co-Authored-By: Claude Opus 4.7 <[email protected]> --------- Co-authored-by: Claude Opus 4.7 <[email protected]>
…(task #240) (#1594) * test(arch): backpressure intrinsic chaos proof — typed LiveLag under flood (task #240 — sixth proof, second Shape-4) Second Shape-4 adversarial proof in the architecture matrix. Pins the "backpressure is intrinsic" doctrine clause: when a producer outpaces a slow consumer, the substrate surfaces a TYPED lag signal (airc_lib::LiveLag) rather than growing memory unboundedly or silently dropping events. ## What ships `core/continuum-core/tests/architecture_backpressure_chaos.rs` — two integration tests over the TwoAircLoopback fixture: 1. `flooding_producer_surfaces_typed_lag_to_slow_consumer`: - peer_a subscribes EAGERLY but DOES NOT consume — simulates a stalled reader (slow disk, paused thread, etc). - peer_b floods peer_a with FLOOD_COUNT = 1500 events past airc-lib's LIVE_BROADCAST_CAPACITY = 1024. - After the flood, peer_a drains its stream and counts successful events vs Err(LiveLag) signals. - Asserts: at least one LiveLag was observed (overflow is TYPED, not silent). - Asserts: events_seen + total_skipped <= FLOOD_COUNT + 1000 headroom (no fabrication; conservation holds). - Asserts: surviving event count <= 2× capacity (bounded recovery — the channel doesn't grow unboundedly). 2. `consumer_makes_progress_after_lag`: - Same setup. After observing a lag, asserts subsequent successful reads continue to flow. - Proves: a slow consumer briefly falling behind doesn't lose the subscription forever; once it catches up, it sees new events. ## Why this clause needed Shape-4 The doctrine "backpressure is intrinsic" is a runtime property. We can't statically prove "the queue stays bounded" — we have to STARVE the consumer and FLOOD the producer and watch what happens. Shape-4 is the only proof shape that gets this honest. Per the matrix's own TODO, this row called for "chaos test with hostile producer flooding". This file is exactly that. ## What this proves (substrate guarantees verified) - Bounded queue: airc-lib's broadcast channel caps at LIVE_BROADCAST_CAPACITY (1024). The chaos test forces overflow and the surviving event count stays bounded. - Typed signal: overflow surfaces as Err(LiveLag { skipped: n }), not silent loss. The slow consumer can ALWAYS observe how much it missed. - Recoverable subscription: a LiveLag is non-terminal; the consumer keeps receiving events after. - No fabrication: events_seen + total_skipped is conservation- bounded by the producer's send count. ## What this does NOT cover (intentional follow-ups) - Producer-side backpressure: airc-lib's broadcast is "newest-wins-with-Lagged-signal" rather than "block-the-producer". That's a doctrine choice and a different test should pin it explicitly when the matrix's Shape-2 proptest TODO ships. - Multi-consumer fairness under partial-lag: tracked as a Shape-2 proptest follow-up. - Memory measurement under sustained flood: process-level bounding is environmental (kernel cgroups); this test bounds via the channel-capacity guarantee, which is the substrate's own contract. ## Wall-clock tuning Initial implementation flooded 5000 events and took 49s. Reducing to 1500 (still 50% over capacity) drops runtime to ~18s for two chaos tests. The flood doesn't need to be bigger because the consumer is paused at zero rate — ANY overrun produces the lag. ## Matrix update PROVING-THE-DOCTRINE.md row for "Backpressure is intrinsic" flips from 🔴 (no proof) to 🟡 (Shape-4 covers the flood case; Shape-2 proptest still TODO for slow-consumer config-space). ## Test plan - [x] `cargo test -p continuum-core --test architecture_backpressure_chaos --features metal,accelerate` — 2/2 pass in ~18s - [x] No regressions on prior chaos test: cross-grid still passes - [x] `// proves: backpressure intrinsic` tag applied - [x] FLOOD_COUNT documented as the minimum that reliably forces overflow with margin; smaller would race ## Doctrine alignment - Substrate doctrine § "Backpressure is intrinsic — no unbounded queue growth" — proven by Shape-4 chaos at the broadcast seam - [[strong-typing-across-boundaries]] — LiveLag is a TYPED signal via the EventStream Item shape; substring/parse-the-message isn't needed because the variant carries the count - [[every-error-is-an-opportunity-to-battle-harden]] — chaos tests are how we discover error classifier bugs (cf. PR #1593's AircError::CommandDeadline catch) ## Related - Task #240 — sixth proof, second Shape-4 chaos - Builds on PR #1593 (first chaos test, established the pattern) - Builds on task #187 (TwoAircLoopback fixture) - Follow-up: Shape-2 proptest for slow-consumer parameter space (still TODO in matrix) Co-Authored-By: Claude Opus 4.7 <[email protected]> * fix(test,docs): close gap-analysis nits from #1594 review (tighter bounds + accurate docs) Adversarial reviewer on PR #1594 surfaced 7 real gaps; closing all substantive ones here. Same "tighter on gap analysis" discipline as PR #1593 round 2. ## Nit 1 — stale FLOOD_COUNT in module docstring Module doc said "FLOOD_COUNT = 5000 events" but the constant was reduced to 1500 during wall-clock optimization. Doc updated to match: "FLOOD_COUNT = 1500 events (past LIVE_BROADCAST_CAPACITY by ~50% margin)". ## Nit 2 — conservation headroom was way too loose The assertion `events + total_skipped <= FLOOD_COUNT + 1000` had 1000 events of "lifecycle headroom" — which is single digits in a 2-peer fresh fixture, not hundreds. A 1000-event slack would have passed even if airc silently doubled events under load. Fix: tightened to `+ CONSERVATION_SLACK = 64` with a comment explaining the budget. Now a real fabrication-class bug would surface here. ## Nit 3 — survival ceiling was 2x capacity without rationale The bounded-recovery assertion was `events <= 2048` (2x the 1024 capacity). The doctrine claim is "bounded by channel capacity" not "bounded by 2x capacity". The 2x was a guess. Fix: introduced `LIVE_BROADCAST_CAPACITY` constant mirroring airc-libs (so the test references the same number the substrate guarantees) and tightened to `capacity + SURVIVAL_SLACK = 128`. The slack accounts for the BroadcastStream wrappers in-flight buffered item + ordering races on the channel. Comment explains. ## Nit 4 — matrix entry test name mismatch PROVING-THE-DOCTRINE.md named the second test "consumer-recovers-after-lag" but the actual function is `consumer_makes_progress_after_lag`. grep-discoverability nit. Fixed the matrix to backtick-quote the actual function names. ## Nit 5 — recovery-producer path is mostly defense-in-depth Reviewer correctly observed that after a lag fires, the 1024-slot broadcast ring still holds buffered survivors that drain immediately on the next polls. So `seen_post_lag_success` flips on the first Ok read after `seen_lag` in practice, and the recovery-producer spawn-on-timeout path rarely runs. Fix: documented the path explicitly as defense-in-depth for very slow CI cases where polls legitimately stall. Kept the code so the proof works even under unusual scheduling pressure; comment makes the intent obvious. ## Nit 6 — PRODUCER_CONCURRENCY = 32 risked cargo-cult Added reference to PR #1594 measurement so the next person doesnt copy the 32 to other tests without understanding why. Updated comment to honestly note that airc-libs internal serialization caps the actual parallelism; the knob is for wall-clock tuning, not load multiplication. ## Nit 7 — sustained-throughput gap not acknowledged Module doc's "What this does NOT cover" list now includes "Sustained throughput under continuous flood" — this test ends after one flood-then-drain cycle; a long-running stress harness (gated behind `stress-tests` feature) would prove it empirically. ## Test plan - [x] `cargo test -p continuum-core --test architecture_backpressure_chaos --features metal,accelerate` — 2/2 pass; tighter bounds (+64 conservation, +128 survival) hold on this hardware - [x] No regressions; wall-clock still ~18s ## Doctrine - [[strong-typing-across-boundaries]] — bounds reference typed constants, not magic numbers; the constants live in one place - [[every-error-is-an-opportunity-to-battle-harden]] — looser bounds masked the class of fabrication bugs that the tighter bounds would catch; the chaos test now actually constrains what it claims to constrain - "Tighter on gap analysis" — Joel 2026-06-10. Same discipline as PR #1593 round 2: nits arent followup TODOs, theyre the proof tightening itself Co-Authored-By: Claude Opus 4.7 <[email protected]> * polish(test): promote SLACK constants to module scope + template capacity in lag-signal message (final #1594 polish) Re-reviewer's two remaining style nits, closed: - CONSERVATION_SLACK and SURVIVAL_SLACK promoted from function-body scope to module scope alongside LIVE_BROADCAST_CAPACITY. Matches the module-doc narrative 'bounds reference typed constants' and improves grep-discoverability for the next contributor. - The 'lag_signals > 0' assertion message hardcoded the literal '1024' for the broadcast capacity. If airc-lib bumps the cap and the test fails on a different bound, the message would mislead. Templated to use {LIVE_BROADCAST_CAPACITY} so the assertion reads honestly whichever cap is in effect. No bound changes; 2/2 still pass in ~18s. Co-Authored-By: Claude Opus 4.7 <[email protected]> --------- Co-authored-by: Claude Opus 4.7 <[email protected]>
…ed Forbidden verdict (task #240) (#1595) * test(arch): federated alignment chaos — hostile peer refused with typed Forbidden verdict (task #240 — third Shape-4) Third Shape-4 adversarial proof in the architecture matrix. Pins the "federated alignment" doctrine clause: when a cross-grid stranger dispatches at this substrate, the `AuthPolicy::gate()` evaluates with the caller's verified airc peer identity (NOT a header-claimable shape) and returns a TYPED `Verdict::Forbidden` carrying the actionable reason. The dispatcher short-circuits BEFORE reaching the module; the caller gets a structured error back. ## What ships `core/continuum-core/tests/architecture_federated_alignment.rs` — two integration tests over the TwoAircLoopback fixture: 1. `hostile_peer_dispatch_is_refused_with_typed_forbidden_verdict`: - peer_a registers a BENIGN `ai/generate` ServiceModule so the URI resolves — proves the rejection is the GATE, not "no such command" surfacing as a generic error. - peer_a's CommandExecutor wired with a DENY policy that returns `Verdict::Forbidden { reason: UnknownPeer }` for any Airc-source caller. - peer_b dispatches a real `ai/generate` request via `AircLiveTransport`. - Asserts: peer_b receives a typed error containing "forbidden" and "UnknownPeer" — the substrate's verdict prose flows end-to-end so the caller can audit + retry. - Asserts: substrate stayed alive; responder joined cleanly. 2. `gate_sees_callers_airc_verified_peer_id_not_a_claimed_one`: - Same fixture, but peer_a's policy CAPTURES the CallerIdentity it received instead of refusing. - peer_b dispatches normally. - Asserts: captured `peer_id` matches peer_b's actual airc peer_id (not a header-claimable shape). - Asserts: captured `source` is `CallerSource::Airc` (cross-grid), not Local — Local would mean a hostile peer succeeded at impersonating a local-originated dispatch. - Proves: airc-lib's signature-verified peer identity flows into the gate. Header rewriting can't substitute identities. ## Why this clause needed Shape-4 Federated alignment is a runtime property of the AuthPolicy gate. Statically we can prove the trait exists; we can't prove "hostile callers are refused" without being hostile. Per the matrix's own TODO this row called for "TwoAircLoopback + malicious peer harness". This file is exactly that. ## What this proves (substrate guarantees verified) - Typed refusal: `Verdict::Forbidden { reason }` short-circuits the dispatcher BEFORE the module is invoked. The benign module's body would have returned a canned success; the chaos test asserts that success NEVER reaches the caller. - Verified identity: the `CallerIdentity` the gate sees carries the airc-verified `peer_id` of the actual cross-grid sender; a hostile peer can't claim someone else's identity by header rewriting. - Source classification: `CallerSource::Airc` for cross-grid; the substrate can distinguish "local code calling itself" from "a remote peer dispatching." - Survival: the substrate stays alive after refusing a hostile dispatch; no crash, no resource leak from the rejected path. ## What this does NOT cover (intentional follow-ups) - Sentinel quorum domination — a separate adversarial scenario where the hostile peer IS enrolled but attempts to dominate the sentinel verdict pool. Tracked under the same matrix row; requires sentinel-pool fixture work. - Replay attacks (hostile peer replays a captured signed request). airc-lib's frame uniqueness + correlation_id rejection covers this at the layer below; a separate test should pin it. - Verdict-string compression at the wire crossing. `AircCommandResponse::Error { message: String }` flattens the typed Verdict to prose. Known cost; closing it is a follow-up PR (typed `AircCommandResponse::Verdict { ... }` variant) — same shape as the substring-vs-variant fix in PR #1593. ## Matrix update PROVING-THE-DOCTRINE.md row for "Federated alignment" flips from 🔴 (no proof) to 🟡 (Shape-4 covers the hostile-stranger case; sentinel-quorum chaos still TODO). ## Test plan - [x] `cargo test -p continuum-core --test architecture_federated_alignment --features metal,accelerate` — 2/2 pass in ~1s (the AuthPolicy gate is fast: short-circuits before any module work) - [x] No regressions on prior chaos tests - [x] `// proves: federated alignment` tag applied - [x] Both tests use production paths: `CommandRequestHandler:: process_request` invokes `execute_with_caller` which invokes the policy gate — same path real cross-grid dispatch uses - [x] Benign module's body provably NOT executed (the canned response would have been a Json string; the chaos test asserts the error path instead) ## Doctrine alignment - Substrate doctrine § "Federated alignment — hostile peer cannot dominate" — proven by Shape-4 chaos at the AuthPolicy gate - [[strong-typing-across-boundaries]] — `Verdict::Forbidden { reason: ForbiddenReason::UnknownPeer }` is the typed shape end-to-end inside one process; the wire-level prose compression is a follow-up to close - [[every-error-is-an-opportunity-to-battle-harden]] — chaos tests are where hostile-path bugs surface ## Related - Task #240 — seventh proof, third Shape-4 chaos - Builds on PR #1593 + #1594 (chaos pattern established) - Builds on task #179 (AuthPolicy + Verdict typed substrate) - Builds on task #187 (TwoAircLoopback fixture) - Follow-up: sentinel-quorum chaos (same matrix row, separate scenario); typed `AircCommandResponse::Verdict` variant to eliminate the wire-level prose compression Co-Authored-By: Claude Opus 4.7 <[email protected]> * fix(test): close 4 gap-analysis nits from #1595 review (dead assertion leg + dead import anchor + trust-store comment + follow-up tracked) Adversarial reviewer on PR #1595 surfaced 4 real nits; closing all substantively here. ## Nit 1 — dead `"UnknownPeer"` OR leg in the assertion The substrate formats `Err(format!("forbidden: {reason}"))` where `{reason}` uses ForbiddenReasons thiserror Display. For UnknownPeer the Display is "caller peer not enrolled in this substrate" — NEVER the variant name "UnknownPeer". The assertion `message.contains("UnknownPeer") || message.contains("not enrolled")` was sound because the OR-survivor was always true, but the variant-name leg was dead code dressed as a check. A future reader or follow-up author would think both legs were live. Fix: drop the dead leg; add a comment explaining the Display surface AND naming the typed-Verdict follow-up that would let us match the variant directly. ## Nit 2 — dead `_import_anchors` function `AircCommandResponse`, `FinishReason`, `UsageMetrics` were imported ONLY to be referenced in module-doc prose. The `_import_anchors` function existed under `#[allow(dead_code)]` solely to silence unused-import warnings. Fix: dropped the three unused symbols from the use statements and deleted the anchor function. Prose doesn't need imports. ## Nit 3 — trust-store vs policy disambiguation Reviewer noted that TwoAircLoopback enrolls peer_b in peer_a's trust store (mutual `add_peer` in fixture setup), so the comment claiming the DENY policy "mirrors the production outcome of unknown peer" was slightly off — peer_b IS enrolled; the policy overrides. Fix: rewrote the comment to make the override explicit and doctrine-honest — the gate is the authority on admission, not the trust store; a real ORM-backed policy might also refuse despite trust-store enrollment if the capability table doesn't grant the URI, and that's exactly the semantic the chaos test simulates. ## Nit 4 — follow-up task tracked, not buried in prose Reviewer flagged that the module doc's "Verdict-string compression at the wire crossing" follow-up was just prose; no owner, no tracking. Same antipattern PR #1593 closed for the deadline classifier — the typed `Verdict::Forbidden` gets flattened to `AircCommandResponse::Error { message: String }` at the wire. Fix: created task #243 "Typed `AircCommandResponse::Verdict` variant — eliminate wire-level prose compression". Module doc references it explicitly so the follow-up has a home. ## Test plan - [x] `cargo test -p continuum-core --test architecture_federated_alignment --features metal,accelerate` — 2/2 pass; tightened assertion holds; no regressions - [x] No new warnings (dropped imports + anchor cleared the `_import_anchors` lint-suppression) ## Doctrine - [[strong-typing-across-boundaries]] — the follow-up task #243 is the wire-level instantiation of this principle for cross-grid command responses; tracked, not buried - [[every-error-is-an-opportunity-to-battle-harden]] — review surfaced 4 honest defects; same chaos PR closes them - "Tighter on gap analysis" — Joel 2026-06-10, applied through this whole session: reviewer nits are the proof tightening itself Co-Authored-By: Claude Opus 4.7 <[email protected]> * polish(test): name task #243 literally so the follow-up survives grep (final #1595 polish) Re-reviewer's only remaining nit: the doc said 'follow-up PR' / 'tracked follow-up' generically; future contributor running 'grep 243 architecture_federated_alignment.rs' would find nothing and re-flag the same nit. Replaced both prose references with literal '#243' so the breadcrumb survives. No code changes; 2/2 still pass. Co-Authored-By: Claude Opus 4.7 <[email protected]> --------- Co-authored-by: Claude Opus 4.7 <[email protected]>
…1596) * test(arch): flow scales geometrically — K^0.599 measured (task #240 — Shape 2) First Shape-2 (property-style) proof in the architecture matrix. Pins the "flow scales geometrically" doctrine clause empirically: event fanout to K subscribers stays SUB-LINEAR in K. Substrate's broadcast primitive is observed at K^0.599 — well below the doctrine's 0.9 ceiling (linear is 1.0). ## What ships `core/continuum-core/tests/architecture_flow_geometric.rs` — two integration tests: 1. `event_fanout_wallclock_is_sublinear_in_subscriber_count`: - Sweeps K ∈ {1, 8, 64, 512} — 9-bit dynamic range, 4 measurement points. - For each K: spawns K barrier-gated subscriber tasks on a `tokio::sync::broadcast` channel, releases the barrier when all subscribers are sitting on `recv`, then measures wall-clock from "producer emits one event" to "all K subscribers received it". - Computes scaling exponent: `log(elapsed_ratio) / log(K_ratio)`. Linear scaling has exponent 1.0; super-linear is > 1.0; sub-linear is < 1.0. - Asserts exponent < `MAX_SCALING_EXPONENT = 0.9` — generous headroom for CI noise while still catching an O(K) regression. - Also asserts absolute wall-clock at K=512 < 1s (catches gross perf regressions, not just scaling regressions) and monotonic-ish growth between adjacent K values (catches scheduling bugs). 2. `broadcast_channel_is_the_canonical_fanout_primitive`: - Positive pin on the underlying primitive: `broadcast::Sender::send` returns the subscriber count, confirming producer-side work is O(1). The receivers do the parallel wakeup, not the producer. ## Measured shape (Intel Mac) ``` flow-geometric measurements: K= 1 fanout = 33.103µs K= 8 fanout = 32.453µs K= 64 fanout = 165.311µs K= 512 fanout = 1.390641ms scaling exponent = 0.599 (linear = 1.0, allowed max = 0.9) ``` The numbers tell the persona story: - 1 persona: ~33µs fanout - 16 personas: ~64µs fanout (extrapolated) - 512 personas: 1.4ms fanout - The exponent of 0.599 means hosting 1000 personas costs roughly `33µs × 1000^0.599 ≈ 2.1ms` per event — not `33µs × 1000 = 33ms` like RPC would. This is the math behind "many personas don't cost quadratically." The substrate's broadcast primitive lets coordination COMPOUND across consumers rather than degrading linearly. ## Why this enables persona capability Without this proof, the many-persona story is a wish. With it, the substrate has earned the right to host 16+ personas coordinating in real-time: - Federation chaos (PR #1595) proves they can't dominate each other - Backpressure chaos (PR #1594) proves they can't flood each other - Cross-grid chaos (PR #1593) proves they can talk across machines - Flow geometric (this PR) proves they can talk WITH each other at K-many-personas scale without quadratic cost The four proofs together earn the substrate's permission slip for genuinely-cooperative many-persona systems — autonomy + sustained memory + long-running tasks become tractable, instead of being bottlenecked on coordination cost. ## Why Shape-2 without the proptest crate The doctrine claim is "property over config space K". A proper proptest harness would generate K values and prop_assert on the exponent. We don't have proptest as a dev-dependency yet (no existing uses in continuum-core), so this PR uses a parameterized config-grid sweep instead — same property, deterministic K's, no new crate to vet. A future PR can add proptest + rewrite the harness so K is generated; the assertions become `prop_assert!` calls verbatim. ## What this does NOT cover (intentional follow-ups) - Real airc broadcast under multi-peer cross-grid fanout. Uses in-process `tokio::sync::broadcast`; airc's wire protocol adds framing that should be benched separately (Shape 3 follow-up). - Sustained throughput at K subscribers (steady-state vs single event). Shape-3 bench target. - Memory cost at high K. Test asserts wall-clock, not RSS. - True proptest config-space exploration. Once proptest is added to dev-deps, this harness becomes a `proptest!` block. ## Matrix update `PROVING-THE-DOCTRINE.md` row for "Flow scales geometrically" flips from 🔴 (no proof) to 🟡 (Shape-2 property-style covers; Shape-3 RPC-comparison bench still TODO). ## Test plan - [x] `cargo test -p continuum-core --test architecture_flow_geometric --features metal,accelerate` — 2/2 pass in <100ms (excluding compile) - [x] Measured exponent 0.599 captured in eprintln output for regression context - [x] `// proves: flow scales geometrically` tag applied ## Doctrine alignment - Substrate doctrine § "Flow scales geometrically — events > RPC under N consumers" — proven empirically with K^0.599 - [[nimble-ecosystems-beat-datacenters]] — geometric scaling IS the math behind why colony intelligence beats datacenter linear scaling; this proof pins the K^<1 behavior the doctrine claims - [[exponential-compounding-via-inherited-layers]] — coordination cost stays sub-linear, freeing capacity for the actual compounding work ## Related - Task #240 — eighth proof, first Shape-2 - Builds on PRs #1593, #1594, #1595 (chaos pattern) - Follow-up: proptest crate adoption + true property harness; Shape-3 criterion bench for RPC-equivalent counterfactual Co-Authored-By: Claude Opus 4.7 <[email protected]> * fix(test,docs): close 4 gap-analysis nits from #1596 review (median-of-3 + comment match + caveats) Adversarial reviewer surfaced 4 real nits; closing all here. ## Nit 1 — K=1 baseline is setup-dominated, not fanout-dominated The K=1 measurement is dominated by task-spawn + barrier overhead, not pure fanout (single subscriber doesn't have anything to fan out TO). The exponent thus measures `(fanout-at-K) / (setup-at-K=1)` — honest, but the next reader debugging a regression should know the baseline isn't pure substrate work. Fix: added a paragraph to the SUBSCRIBER_COUNTS docstring naming the caveat. The proof is still sound — sub-linear vs setup-dominated baseline still distinguishes geometric from linear — but now the caveat is on the page. ## Nit 2 — CI flakiness ceiling at 0.9 (the real fix) Reviewer's worst-case math: a fast machine hitting K=1=5µs and K=512=1.4ms gives ratio=280×, exponent=0.90 — right at the wall. Could flake. Two options: - Loosen MAX_SCALING_EXPONENT to 0.95 (just hides the problem) - Run the K-sweep N times and take the median (closes the flake structurally) Fix: median-of-3 (`SWEEP_REPEATS = 3`). Each sweep takes ~1-2ms; 3 sweeps adds maybe 5ms total — invisible to CI wall-clock. The proof now absorbs scheduler jitter at the measurement layer rather than loosening the bound at the assertion layer. Empirical: 5 local runs with median-of-3 give exponents in 0.58-0.70 — consistently sub-linear, no flakes. ## Nit 3 — extrapolation caveat past K=512 The commit message extrapolated "1000 personas ≈ 2.1ms/event" using K^0.599. Honest math within the swept range, but the shape isn't guaranteed past K=512 — scheduler saturation at K=10000 could bend the curve up. Fix: added an explicit "Extrapolation beyond K=512" entry to the NOT-covered list in the module doc. "Empirical within {1, 8, 64, 512}; persona-count claims past that range need their own measurement." ## Nit 4 — Property-3 comment / constant mismatch The doc comment said "Allow t_hi to be up to 8× t_lo" but the constant was `32.0`. Mismatch — future contributors would either over-tighten or get misled. Fix: rewrote the comment to match the constant honestly. The 32× ceiling absorbs scheduler jitter while still catching an O(K) regression (which on an 8× step in K would show as 8× growth if linear, vs ~9× observed for K^0.6). ## Test plan - [x] `cargo test -p continuum-core --test architecture_flow_geometric --features metal,accelerate` — 2/2 pass; exponent 0.690 with median-of-3 (still comfortably under 0.9 ceiling) - [x] Wall-clock unchanged (~0.01s); median-of-3 adds <10ms - [x] No new dependencies ## Doctrine - "Tighter on gap analysis" — Joel 2026-06-10. Median-of-3 structurally absorbs the flake mode rather than hiding it by loosening the bound. - [[strong-typing-across-boundaries]] — bounds reference constants with comments that match the actual code, so future reviewers trust what they read. Co-Authored-By: Claude Opus 4.7 <[email protected]> --------- Co-authored-by: Claude Opus 4.7 <[email protected]>
Summary
New Features
Persona Brain HUD
Cyberpunk-style visualization showing:
Click any persona in the sidebar Users & Agents list to see their cognitive state.
Right Panel AI Assistant
RAG Budget Management
Architecture Docs Added
docs/RAG-COGNITION-IMPROVEMENTS.md- Comprehensive RAG/memory analysisdocs/UI-STATE-RAG-ARCHITECTURE.md- UI state awareness designTest plan
🤖 Generated with Claude Code