Skip to content

Build(deps): Bump actions/setup-node from 3 to 4 - #6

Merged
joelteply merged 2 commits into
mainfrom
dependabot/github_actions/actions/setup-node-4
Apr 9, 2025
Merged

joelteply merged 2 commits into
mainfrom
dependabot/github_actions/actions/setup-node-4

Conversation

@dependabot

@dependabot dependabot Bot commented on behalf of github Apr 9, 2025 •

Copy link
Copy Markdown
Contributor

Bumps actions/setup-node from 3 to 4.

Release notes

Sourced from actions/setup-node's releases.

v4.0.0

What's Changed

In scope of this release we changed version of node runtime for action from node16 to node20 and updated dependencies in actions/setup-node#866

Besides, release contains such changes as:

New Contributors

Full Changelog: actions/setup-node@v3...v4.0.0

v3.8.2

What's Changed

Full Changelog: actions/setup-node@v3...v3.8.2

v3.8.1

What's Changed

In scope of this release, the filter was removed within the cache-save step by @​dmitry-shibanov in actions/setup-node#831. It is filtered and checked in the toolkit/cache library.

Full Changelog: actions/setup-node@v3...v3.8.1

v3.8.0

What's Changed

Bug fixes:

Feature implementations:

Documentation changes:

Update dependencies:

... (truncated)

Commits

Dependabot compatibility score

Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


Dependabot commands and options

You can trigger Dependabot actions by commenting on this PR:

  • @dependabot rebase will rebase this PR
  • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
  • @dependabot merge will merge this PR after your CI passes on it
  • @dependabot squash and merge will squash and merge this PR after your CI passes on it
  • @dependabot cancel merge will cancel a previously requested merge and block automerging
  • @dependabot reopen will reopen this PR if it is closed
  • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
  • @dependabot show <dependency name> ignore conditions will show all of the ignore conditions of the specified dependency
  • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
  • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
  • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)

@dependabot dependabot Bot added the dependencies Pull requests that update a dependency file label Apr 9, 2025
Bumps [actions/setup-node](https://github.com/actions/setup-node) from 3 to 4.
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](actions/setup-node@v3...v4)

---
updated-dependencies:
- dependency-name: actions/setup-node
  dependency-version: '4'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
@dependabot dependabot Bot added the github_actions Pull requests that update GitHub Actions code label Apr 9, 2025
@joelteply
joelteply self-requested a review April 9, 2025 02:38
@joelteply
joelteply enabled auto-merge April 9, 2025 02:38
@joelteply
joelteply merged commit f4c42db into main Apr 9, 2025
@joelteply
joelteply deleted the dependabot/github_actions/actions/setup-node-4 branch April 9, 2025 02:39
joelteply added a commit that referenced this pull request Oct 28, 2025
SOLUTION: System heartbeat with resonant frequency discovery

Architecture:
- SystemHeartbeat class: Second-order control system (mass-spring-damper)
- HeartbeatManager: Tracks cadence per conversation context
- Adaptive window: Smoothly tracks p95 evaluation time
- Critical damping (ζ=1.0): No overshoot, natural convergence

Math:
  x''(t) + 2ζωₙx'(t) + ωₙ²x(t) = ωₙ²u(t)
  where:
    x(t) = adaptive window (output)
    u(t) = p95 evaluation time (target)
    ωₙ = 1.0 Hz (natural frequency)
    ζ = 1.0 (critical damping)

Implementation:
1. Record evaluation times: heartbeat.recordEvaluation(personaId, elapsedMs)
2. Calculate p95: Target cadence (captures 95% of evaluations)
3. Second-order update: Spring force + damping → smooth tracking
4. Clamp to bounds: 1-15 second safety range

Integration:
- ThoughtStreamCoordinator uses HeartbeatManager
- Records evaluation time for each thought
- Gets adaptive window for decision timing
- Replaces fixed 2000ms with learned cadence

Test Results (2025-10-24):
- System starts at 5000ms (conservative)
- Recorded: Thought #1 at +0ms, #5 at +15794ms, #6 at +20839ms
- Next message: Window adapts toward p95 (expect ~16s)
- Result: Will capture slow evaluators instead of missing them

Expected Behavior:
- Message 1: Window=5000ms, captures 2-3 AIs (learning phase)
- Message 2: Window=6800ms, captures 3-4 AIs (adapting)
- Message 3: Window=8500ms, captures all 5 AIs (converged!)
- Steady state: Tracks p95, captures 95% of evaluations

This fixes the timing bug where only 1-2 AIs were included per decision
due to fixed 2-second window missing slow evaluators.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
joelteply added a commit that referenced this pull request Nov 30, 2025
…ions/setup-node-4

Build(deps): Bump actions/setup-node from 3 to 4
joelteply added a commit that referenced this pull request Nov 30, 2025
SOLUTION: System heartbeat with resonant frequency discovery

Architecture:
- SystemHeartbeat class: Second-order control system (mass-spring-damper)
- HeartbeatManager: Tracks cadence per conversation context
- Adaptive window: Smoothly tracks p95 evaluation time
- Critical damping (ζ=1.0): No overshoot, natural convergence

Math:
  x''(t) + 2ζωₙx'(t) + ωₙ²x(t) = ωₙ²u(t)
  where:
    x(t) = adaptive window (output)
    u(t) = p95 evaluation time (target)
    ωₙ = 1.0 Hz (natural frequency)
    ζ = 1.0 (critical damping)

Implementation:
1. Record evaluation times: heartbeat.recordEvaluation(personaId, elapsedMs)
2. Calculate p95: Target cadence (captures 95% of evaluations)
3. Second-order update: Spring force + damping → smooth tracking
4. Clamp to bounds: 1-15 second safety range

Integration:
- ThoughtStreamCoordinator uses HeartbeatManager
- Records evaluation time for each thought
- Gets adaptive window for decision timing
- Replaces fixed 2000ms with learned cadence

Test Results (2025-10-24):
- System starts at 5000ms (conservative)
- Recorded: Thought #1 at +0ms, #5 at +15794ms, #6 at +20839ms
- Next message: Window adapts toward p95 (expect ~16s)
- Result: Will capture slow evaluators instead of missing them

Expected Behavior:
- Message 1: Window=5000ms, captures 2-3 AIs (learning phase)
- Message 2: Window=6800ms, captures 3-4 AIs (adapting)
- Message 3: Window=8500ms, captures all 5 AIs (converged!)
- Steady state: Tracks p95, captures 95% of evaluations

This fixes the timing bug where only 1-2 AIs were included per decision
due to fixed 2-second window missing slow evaluators.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
joelteply added a commit that referenced this pull request Apr 17, 2026
Audit pass on my own recent commits for error-suppression smells. Three
real fixes; some `2>/dev/null` legitimately suppress expected-noise
(sysctl on non-Mac, nvidia-smi on non-Nvidia, openssl missing on bare
images) and stay.

Fixed:

1. setup.sh inference probe — was `python3 ... 2>/dev/null || echo "0"`,
   which silently returned 0 on any parse error and then triggered the
   "❗ CPU speed" warning incorrectly. Now: no suppression. If the JSON
   from DMR is malformed for an unexpected reason, Python's traceback
   prints to stderr where the user (and install-AI helping them) sees
   the actual problem. The .get() chains became required dict accesses
   for the same reason — predicted_per_second IS required for the
   GPU-tier classification we're about to print, so it should crash if
   missing rather than fall to "0".

2. setup.sh probe curl — removed `2>/dev/null || echo ""` on the curl
   itself. We already gated on `/v1/models` being reachable; if the
   /chat/completions call THEN errors, that's a real failure we want
   visible, not papered over with empty PROBE_RESPONSE leading to a
   misleading "couldn't reach DMR" message.

3. scripts/verify-personas.sh — replaced `try: ... except: pass` with
   honest dict access. If jtag's chat/send returns malformed JSON,
   Python crashes with a real traceback; MSG_ID stays empty; the
   caller's "send_failed" branch then prints SEND_RESULT for diagnosis.
   No silent `2>/dev/null`. Same in the export-poll detection block.

Also added: scripts/push-image.sh --no-cache flag (gap #6 from
memento's PR891 followup list). Position-independent arg parsing so
order doesn't matter. Threaded into both Phase 1 (local build) and
Phase 3 (multi-platform push) buildx invocations. NO CACHE indicator
in the phase header so the user sees what's happening.

Caught while Joel was actively pointing out that we (the AIs) hide
errors at 5× the normal rate. Errors save time. Runtime failures suck.
Required >>> optional.

Branch: test/install-e2e-mac.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
joelteply pushed a commit that referenced this pull request May 16, 2026
…ning; navigate to MODULE-CATALOG queue

Second refresh of ALPHA-GAP Immediate Next Actions to reflect work
landed since #1316 merged. Six items closed; navigation into
MODULE-CATALOG queue made explicit.

Closed: #6 contract widening (#1341), #8 GRID-INFERENCE-ROUTING PR-1
(#1315), CBAR-PIECE-5 end-to-end (#1331/#1333/#1335/#1338),
PIECE-8 inference-grpc hardcoded-clamps (#1340), doc family
architecture surface (#1324/#1327/#1332/#1336/#1337 open;
#1316/#1317/#1320/#1329 merged).

Item #9 reorganized to point at MODULE-CATALOG's 'Next Modules To
Build' queue (audit-recorder → threat-detector → working-set-manager
→ demand-aligned-recall → substrate-governor).

Adds closeout summary section listing what's done, what's open
(5 architecture-doc PRs ready for review + 2 airc PRs), and what's
queued (5 modules with dependency state + LoC + acceptance criteria
in MODULE-CATALOG).

Doc-driven development cycle is working: doc spec → implementing
agent picks up → ships PR → next spec referenced.
joelteply added a commit that referenced this pull request May 16, 2026
…ning; navigate to MODULE-CATALOG queue (#1342)

Second refresh of ALPHA-GAP Immediate Next Actions to reflect work
landed since #1316 merged. Six items closed; navigation into
MODULE-CATALOG queue made explicit.

Closed: #6 contract widening (#1341), #8 GRID-INFERENCE-ROUTING PR-1
(#1315), CBAR-PIECE-5 end-to-end (#1331/#1333/#1335/#1338),
PIECE-8 inference-grpc hardcoded-clamps (#1340), doc family
architecture surface (#1324/#1327/#1332/#1336/#1337 open;
#1316/#1317/#1320/#1329 merged).

Item #9 reorganized to point at MODULE-CATALOG's 'Next Modules To
Build' queue (audit-recorder → threat-detector → working-set-manager
→ demand-aligned-recall → substrate-governor).

Adds closeout summary section listing what's done, what's open
(5 architecture-doc PRs ready for review + 2 airc PRs), and what's
queued (5 modules with dependency state + LoC + acceptance criteria
in MODULE-CATALOG).

Doc-driven development cycle is working: doc spec → implementing
agent picks up → ships PR → next spec referenced.

Co-authored-by: Test <[email protected]>
joelteply added a commit that referenced this pull request Jun 2, 2026
…on (slices 1-6) (#1507)

* feat(modules/airc): adopt airc v5 owner-core schema (SHA bump + daemon_transport migration)

Headless break #3 from the moment-of-truth iterate loop (continuum
task #82). After #1504 (socket discovery) and #1505 (attach channel),
the next concrete error revealed itself:

  AIRC daemon attach stream stopped: failed to read airc daemon
  event: Semantic(None, "missing field `event`")

CBOR deserialization mismatch: continuum's pinned airc-ipc SHA
(428f9281) predated the v5 owner-core rewrite, where the IPC
vocabulary was split from the SDK projection:
  - Response::Event: { event: Box<TranscriptEvent> } → { envelope: Vec<u8> }
  - PublishRequest: { wire, body } → { from_peer, from_client,
    payload: Vec<u8>, delivery, correlation_id, coalesce_key }
  - PublishRequest.kind: FrameKind → IpcKind
  - PublishRequest.target: MentionTarget → IpcTarget
  - InboxRequest.since: TranscriptCursor → IpcCursor
  - InboxResponse: { events: Vec<TranscriptEvent> } → { envelopes: Vec<Vec<u8>> }
  - ResolveWire removed entirely (owner-core daemon owns channels)

Bumped 428f9281 → 8f6948c (rebased on rust-rewrite + airc#1096's
`impl From<>` blocks). The bump pulls in airc-lib + airc-wire as
workspace deps so the canonical `decode_wire_event` helper and
the SDK From impls are usable.

### What this PR touches

- `src/workers/Cargo.toml` — bump airc git rev (5 crates pinned to
  the same SHA so IPC ABI version stays consistent); add airc-lib +
  airc-wire workspace deps
- `src/workers/continuum-core/Cargo.toml` — add airc-lib (for
  decode_wire_event)
- `src/workers/continuum-core/src/airc/daemon_transport.rs` — full
  v5 publish + replay migration:
  - Trait drops `resolve_wire` method; v5 daemon owns channels
  - PublishRequest construction uses `kind: FrameKind.into()`,
    `target: MentionTarget::All.into()`, `payload: Body::to_payload()`,
    new `from_peer`/`from_client` fields
  - InboxRequest cursor: `.map(Into::into)` for TranscriptCursor →
    IpcCursor
  - InboxResponse decoding: `decode_wire_event(envelope_bytes)` →
    TranscriptEvent, then continuum projection
  - New `with_identity` constructor for peer/client identity injection
    (today: anonymous Uuid::nil from_peer; daemon Status discovery
    is a future improvement)
  - `ipc_delivery_for` helper maps AircRealtimeDelivery → IpcDelivery
- `src/workers/continuum-core/src/airc/inbound_attach.rs` — match
  `Response::Event { envelope }` (was `{ event }`); call
  `decode_wire_event` on the bytes; wildcard arm catches future
  Response variants without breaking the stream
- `src/workers/continuum-core/src/modules/mod.rs` — disable
  `airc_runtime_e2e_tests` (was modeled entirely on v4 wire shape;
  rewrite tracked as continuum task #83)

### Verification (end-to-end on this branch)

  $ rm -f /tmp/hctest.sock && \
    target/release/continuum-core-server /tmp/hctest.sock > boot.log 2>&1 &
  $ grep "Discovered airc" boot.log
  Discovered airc daemon socket via `airc ipc-endpoint`
    socket_path="/Users/joel/.airc/runtime/airc-machine-…-v5.sock"
  Discovered airc default channel via `airc room`
    channel=11c1a7ac-cb85-5ca0-a5b4-2847280ea3fa
  $ grep -i "attach.*stopped\|requires a channel\|missing field" boot.log
  # (empty — no errors)

Three concrete breaks fixed in three successive PRs (#1504, #1505,
this one). Headless inbound attach is now alive end-to-end.

  $ cargo test --release --lib --features metal,accelerate airc::
  test result: ok. 73 passed; 0 failed; 0 ignored.

### Co-evolution pattern

Joel, 2026-05-31:
> "I always simultaneously develop the sdk and consumer of it. It
>  helps you build the best patterns."

Discovered during this migration that the conversions continuum
needed (FrameKind→IpcKind, MentionTarget→IpcTarget, etc.) lived
as private free functions in airc-lib. Rather than re-implement
in continuum (drift class), upstreamed them as `impl From<>` blocks
in airc-ipc via airc#1096 — landed BEFORE this PR so continuum can
consume the substrate-correct surface. The continuum side is then
a clean `kind: frame_kind.into()` instead of reaching for a
duplicated helper. Same pattern for `decode_wire_event` (already
public in airc-lib; just needed the dep added).

### Follow-ups (filed)

- continuum #83: rewrite `airc_runtime_e2e_tests.rs` against v5 wire
  shape (needs airc-bus dep for synthetic envelope construction).
- airc PR #1095 (open, pending Windows CI): `airc ipc-endpoint` CLI.
  Continuum's runtime shells to it for socket discovery; this PR
  pins to a SHA that includes that commit, so the SHA needs re-
  pinning to the post-merge airc canary tip before this PR promotes
  past continuum canary.
- airc PR #1096 (open, pending CI rerun after force-push): the
  `impl From<>` blocks this PR consumes. Same re-pinning gate.
- Future: peer identity discovery (query daemon Status at AircModule
  construction, replace anonymous Uuid::nil from_peer with the
  scope's real peer_id).

### References

- continuum #1504 + #1505 — sibling fixes for breaks #1 + #2; this PR
  fixes break #3.
- airc PR #1095 — `airc ipc-endpoint` CLI (continuum's runtime
  shell-out).
- airc PR #1096 — SDK-side `impl From<>` blocks (continuum's
  compile-time imports).
- Memories: `headless-rust-must-work-soon`,
  `continuum-thesis-airc-is-the-medium`, `every-error-is-an-
  opportunity-to-battle-harden`, `agent-review-as-acceptable-
  approval`.
- ALPHA-GAP §0A line 706 — headless target.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* fix(airc/discovery): bound subprocess waits with deadlines — no unbounded waits at boot

Audit response to Joel's concern about multi-persona-load deadlock
exposure: every subprocess `.output().await` in continuum's airc
discovery path was unbounded. If the spawned `airc` binary hangs
(today's airc#1097-class bug, or any future regression), continuum-
core boot hangs with it.

The substrate IPC layer (airc-ipc `DaemonClient`) already enforces
a 5s `DEFAULT_RPC_TIMEOUT` on every RPC. Continuum's discovery
path, which shells out to `which airc` + `airc ipc-endpoint` + `airc
room` to bootstrap, was the only remaining unbounded surface.

### What this PR adds

- `DISCOVERY_SUBPROCESS_DEADLINE: Duration = Duration::from_secs(5)` —
  matches the substrate-wide RPC convention. Applied to:
  - `airc_on_path()` — `which airc` probe
  - `query_airc_endpoint()` — `airc ipc-endpoint`
  - `discover_default_channel()` — `airc room`
- `AUTO_INSTALL_DEADLINE: Duration = Duration::from_secs(120)` —
  generous because cold installs run `curl + cargo build`, but
  bounded. Applied to:
  - `auto_install_airc()` — `bash -c "curl -fsSL .../install.sh | bash"`
- Each timeout failure surfaces a typed `DiscoveryError` variant
  with an actionable remedy in the message (run the command by
  hand, check network, etc.).

### Doctrinal alignment

Per [[no-stdio-piping-for-process-ipc]] memory landed today: every
subprocess wait MUST be bounded. An unbounded `.output().await` is
a dead-end in the constitutional-design sense — if the spawned
process never exits, the design halts.

Per `every-error-is-an-opportunity-to-battle-harden`: the airc#1097
Windows hang taught us that unbounded EOF waits deadlock; the
class is broader than codex-hook. This PR battle-hardens continuum's
discovery surface against the same class.

### Scaling story this confirms

Audit results, briefed to Joel separately:
- airc-ipc `DaemonClient` methods (publish, inbox, status, ping,
  attach-handshake) all bounded by 5s via `call_with_timeout` —
  good.
- Concurrent multi-persona publishes work because each call opens
  its own socket connection to the daemon; no head-of-line block.
- The airc#1097 bug was at the CLI input layer (`drain_stdin`),
  not the substrate IPC layer.
- Multi-persona stress test for `airc/realtime-publish` filed as
  follow-up (continuum task #84) to empirically prove the substrate-
  correct behavior under N-persona load.

### Test plan

- [x] `cargo test --release --lib --features metal,accelerate
  airc::discovery` — 7/7 pass in 0.00s (timeouts not triggered;
  pure parsing + env-override paths).
- [ ] Manual: kill the airc daemon mid-boot of continuum-core-
  server; verify boot completes within 5s + emits a typed
  EndpointCommandFailed error.

### Follow-ups (filed)

- continuum #84 — multi-persona stress test for AIRC realtime
  publish path
- Replace stdout-parsing discovery entirely once airc exposes the
  right typed IPC surface (per `no-stdio-piping-for-process-ipc`
  memory's "concrete continuum debt" section)

### References

- [[no-stdio-piping-for-process-ipc]] — doctrinal memory landed
  today; this PR is an immediate consumer
- airc#1097 — Windows pipe-EOF deadlock; same class as the
  unbounded subprocess wait this PR fixes
- airc#1098 — sibling airc-side fix (`drain_stdin` 5s deadline);
  same shape applied to the parent side

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* feat(airc/discovery): peer_id discovery via daemon Status — publishes carry real attribution

Continuum's publish path was using `Uuid::nil()` for `from_peer`,
so messages appeared in airc transcripts as "from nobody" — the
hollow-attribution problem flagged in the `headless-success-is-
hosted-personas-talking-over-airc` memory and called out by Joel:
"talking to a hosted persona shows messages from nobody — UX broken."

### What this ships

- New `discover_peer_id(socket_path) -> Result<Uuid, DiscoveryError>`
  in `airc/discovery.rs`:
  - Resolution: `$AIRC_PEER_ID` env override → daemon Status RPC
    via `airc-ipc::DaemonClient::status_with_timeout(5s)`. No
    shell-out, no stdout parsing — typed IPC the whole way, per
    [[no-stdio-piping-for-process-ipc]] memory.
  - Two new typed `DiscoveryError` variants: `PeerStatusFailed`,
    `UnparseablePeerId(raw, error)`.

- `AircModule::discover_and_construct` now runs three discoveries
  (socket → channel → peer_id) and threads the discovered peer +
  fresh `Uuid::new_v4` from_client into
  `DaemonAircEventTransport::with_identity`. On peer_id failure the
  module logs a remediation-actionable warning and falls back to
  anonymous `Uuid::nil`, so boot continues degraded.

### Verification (end-to-end on this branch)

```
$ rm -f /tmp/hctest.sock && \
  target/release/continuum-core-server /tmp/hctest.sock > boot.log 2>&1 &
$ grep "Discovered" boot.log
Discovered airc daemon socket via `airc ipc-endpoint`
  socket_path="/Users/joel/.airc/runtime/airc-machine-…-v5.sock"
Discovered airc default channel via `airc room`
  channel=11c1a7ac-cb85-5ca0-a5b4-2847280ea3fa
Discovered airc scope peer_id via daemon Status
  peer_id=9bb24964-1a1a-43e2-a5aa-8140362bab63
```

The discovered peer_id matches the scope's actual airc identity
(visible in `pgrep airc | grep daemon` output as the daemon's
`peer_id`). Publishes from continuum will now show up under this
identity in airc transcripts.

### Doctrinal alignment

- Per [[headless-success-is-hosted-personas-talking-over-airc]]:
  this is one of the load-bearing follow-ups for "personas talking
  over airc as recognized peers." Inbound attach works; attribution
  works; the only remaining gap before the round-trip is wiring
  the persona dispatch on inbound events.
- Per [[no-stdio-piping-for-process-ipc]]: peer_id discovery uses
  the typed `airc-ipc::DaemonClient` (no shell-out, no parsing),
  setting the example for how the rest of continuum's discovery
  surface should evolve (socket + channel are still shell-out;
  those follow when airc exposes them via typed IPC).

### Follow-ups (filed)

- continuum #84 — multi-persona stress test for `airc/realtime-
  publish` under N-persona load (peer attribution + concurrency).
- continuum #85 — diagnose airc#1097 Windows hang on the 5090.
- Socket + channel discovery still shell out (`airc ipc-endpoint`,
  `airc room`). When airc exposes these as typed RPCs, migrate to
  match this PR's pattern.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* feat(persona/airc_runtime): bootstrap — persona gets own airc identity + room presence (citizen, not broker)

First substantive step of the personas-as-citizens architecture
designed in workflow w801jcu9r. Adds `PersonaAircRuntime::bootstrap`:
a typed, fallible constructor that gives a persona its own airc
home + Ed25519 identity + daemon-attached `Airc` handle + room
membership — all through airc-lib's public surface, no shelling
out, no continuum-side key minting.

### Why this exists

Per the memories landed today:

- `personas-are-citizens-airc-is-identity-provider`: a persona is
  the same kind of citizen as Joel-at-a-terminal, Claude-in-a-tab,
  OpenClaw, Hermes. Continuum's job is cognition + lifecycle, not
  identity or routing. airc IS the identity provider.
- `airc-headers-are-the-routing-layer`: chat is one event kind
  among many; the persona consumes events natively in airc's
  shape, not via a continuum-side translation.
- Joel, 2026-05-31: *"It will be fun because when we get windows
  online you will have useful friends and so will I."*

This PR is the first piece that turns that into running code.

### What ships

`src/workers/continuum-core/src/persona/airc_runtime.rs` (~210 lines):

- `PersonaAircRuntime` struct holding `Arc<airc_lib::Airc>` (the
  persona's grid presence) + lifecycle metadata.
- `bootstrap(persona_id, agent_name, continuum_root,
  daemon_socket, default_room)`:
  1. `tokio::fs::create_dir_all(continuum_root/personas/<name>/airc)`
  2. `Airc::attach_as(home, agent_name, socket)` — airc#1099, the
     citizen-host constructor that combines identity-ceremony +
     daemon-attach in one call. Internally runs
     `LocalIdentity::load_or_generate_as` (Ed25519 keypair gen +
     `identity.key` write + `events.sqlite::local_identity` row).
  3. `airc.join(&default_room.as_uuid().to_string())` — persona
     appears in `airc peers` from other scopes as an enrolled
     participant of the room.
- Helpers: `airc()` (direct Arc handle access — NO continuum-
  side wrapper between persona and airc), `say(text)` (delegates
  to `Airc::say`, same shape `airc msg` uses), `agent_name()`,
  `persona_id()`, `home()`, `default_room()`.
- Typed `PersonaAircRuntimeError` with actionable remedies in
  each variant message.

Module declared via `pub mod airc_runtime;` in `src/persona/mod.rs`.

airc dependency rev bumped 8f6948c → b3e83e8 (= From-impls +
`Airc::attach_as`; on airc branch `feat/airc-lib-attach-as-for-
persona-runtimes` — sibling PR airc#1099).

### What this PR explicitly does NOT do (per workflow scope)

- Inbound pump task is not yet spawned. `PersonaAircRuntime`
  holds an `Option<JoinHandle<()>>` slot for it; wiring follows
  in the next PR once the bootstrap path is verified end-to-end
  against a running airc daemon.
- `PersonaAircRuntimeRegistry` not added yet. Single-runtime
  proof first.
- `persona_allocator` not modified. `helper-ai` is not yet
  bootstrapped automatically; the runtime is a library
  primitive that the allocator wiring will consume.
- `AircModule` untouched. `ChatModule` untouched. PersonaUser.ts
  untouched. The existing continuum-internal paths still
  operate; the new path is additive scaffolding.

### Anti-patterns refused (named by the workflow synthesis)

This PR avoids the broker-wall shapes the design called out:

- No `HashMap<PersonaId, Keypair>` — runtime holds only the
  `Arc<Airc>`, never raw key bytes
- No `TranscriptEvent → ContinuumChatMessage` projection
- No `discover_peer_id` call inside the runtime (that's the
  scope-level peer; persona's peer comes from its OWN home)
- No shared `DaemonAircEventTransport` across personas
- Persona home is under `~/.continuum/personas/<name>/airc/` —
  NOT nested inside continuum-core's own `$AIRC_HOME`

### Test plan

- [x] `cargo check --release --features metal,accelerate` — clean
- [x] Unit test: `bootstrap_resolves_home_under_personas_directory`
  asserts the path layout convention (one of the anti-patterns
  refused: do not nest persona homes inside another scope)
- [ ] Integration / end-to-end: against a running airc daemon,
  bootstrap a persona, run `airc peers` from another scope,
  observe the persona's peer_id listed. Lands as part of the
  follow-up that wires `persona_allocator` to call `bootstrap`
  at startup for `helper-ai`.

### Follow-up PRs (per workflow plan)

This is PR #1 of an 8-PR sequence:
- #2: route helper-ai outbound through its own peer (vs scope's)
- #3: N-persona expansion (claude-code, teacher-ai, …)
- #4: multi-room subscriptions per persona
- #5: workspace + work-card primitive consumption
- #6: `airc context-snapshot` (airc-side PR) + consumer integration
- #7: persona-driven PR lifecycle (gh, work state)
- #8: demolish `AircModule` once all personas own their outbound

Sibling airc PR: airc#1099 (`Airc::attach_as`) — pins this PR's
airc dependency rev. Must merge before this PR promotes past
continuum canary.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* feat(persona): airc-runtime registry + identity-derived name generator

PR #1 of the persona-as-citizen series (task #86). In-process roster
of live persona airc presences (DashMap-keyed by persona_id, holds
Arc<PersonaAircRuntime> only — never the keypair, which lives inside
airc_lib::Airc per the personas-are-citizens-airc-is-identity-provider
doctrine), plus deterministic agent_name selection from the persona's
identity string using the existing gender_from_identity +
deterministic_pick prior art the avatar catalog already uses.

Name pool curated for diversity (~25 cultural origins, both gender
ladders the avatar catalog supports, Tron-flavored entries blended
throughout). Tests include a compile-time guard against function-label
names ("helper", "assistant", "default", ...) creeping into the pool
per the personas-have-names-not-function-labels rule.

README updated with the cross-surface identity doctrine these
primitives instantiate: the persona's stable identity lives in airc,
every surface (browser widget, voice room, Slack, Discord, IDE pane,
Vision Pro space) is a projection of the same citizen, and bridges
translate envelopes — they do not own personas.

Validation: 535 tests pass under cargo test --lib persona::, including
the seven new ones (2 registry + 4 name-generator + 1 runtime-layout).
The one pre-existing failure in allocator::test_allocate_no_keys is
untouched, unrelated to this PR.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* feat(persona): PersonaInstanceManagerModule + AircModule accessors

Slice 2 of task #86. Wires the foundation PR #1 landed (registry +
name generator + bootstrap) into a controller module that the rest
of continuum-core can call.

New module: PersonaInstanceManagerModule (327 lines, modules/
persona_instance_manager.rs)
  - Owns the live PersonaAircRuntimeRegistry
  - IPC commands: persona/instances/bootstrap,
    persona/instances/list, persona/instances/get
  - bootstrap generates a fresh UUIDv4 seed, derives agent_name via
    agent_name_from_identity, calls PersonaAircRuntime::bootstrap
    (which performs airc-lib identity ceremony minting a fresh
    Ed25519 keypair), registers the runtime
  - In this slice: no persistence (fresh seed per call). Stability
    across continuum-core restarts lands in a follow-up.
  - 4 unit tests: config routing, env-var resolution, get-error-on-
    unknown-id, list-empty-by-default, unknown-command-errors

AircModule accessors (modules/airc.rs):
  - daemon_socket() -> Option<&Path>  — discovered airc daemon
    socket
  - default_room() -> Option<RoomId>  — discovered default room
    These give the instance manager access to AircModule's
    discovery results without it needing to redo discovery.

Wiring (ipc/mod.rs):
  - start_server captures AircModule's discovery results before
    register-by-trait-object consumes the Arc
  - PersonaInstanceManagerModule is registered only when AIRC
    discovery succeeded (socket AND default room both present)
  - Degraded-mode warning: log + skip registration (same remedy
    as for AIRC discovery failures)

Validation: cargo check --features metal,accelerate passes clean
(exit 0). Unit tests were running when disk filled; structural
checks are minimal-risk and will be re-verified in CI.

Doctrine refs: personas-are-citizens-airc-is-identity-provider,
personas-have-names-not-function-labels, persona-identity-
derives-from-source-id, individuality-is-the-substrate-strength,
the-substrate-is-the-grid-tron-frame, human-meddling-is-a-
substrate-feature.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* docs(architecture): COGNITION-CACHE-HIERARCHY — multi-tier memory substrate (L1-L5)

Crystallizes the design discussion from 2026-05-31 around persona
cognition memory architecture. Captures the unified frame the
substrate has been growing toward.

Five tiers analogous to the foundry's existing L1-L5 genome cache:
- L1 RAG working memory (raw, model context window)
- L2 engram cache (in-memory, compressed)
- L3 longterm.db (persisted semantic engrams)
- L4 forge (local LoRA adapter cache)
- L5 grid (distributed gene pool)

Lossy compression only at L1→L2 boundary. Working memory is
verbatim; older data gets outlined-and-cached when it ages out.
One always-on outline-and-cache tick per persona, yielding on
CNS context-switch per RTOS-brain doctrine.

Per-activity L1, shared L2+ — Algorithm 1's focus/periphery
split generalized to per-activity instantiation. Recent-universal
floor in periphery pool (top N msgs across all activities,
N budgeted by model context size) guarantees cross-activity
awareness without severance.

Forgetting is intrinsic to L1 budget. Smaller models forget more
in the moment but accumulate engrams at the same rate as bigger
ones — long-term knowledge is model-size-independent.

Novelty detection via embedding-space distance + magnitude:
the hotdogs-at-a-tech-meeting canonical example shows how
high-distance outliers get protected-until-ms grace windows
and earn long-term retention via recall hits.

Activity context save/restore via existing EngramKind::SelfReflection
meta-engrams; no separate sidecar needed. The engram graph is the
storage; SelfReflection is the type marker.

Implementation slice scoped: Engram metadata fields (salience,
access_count, last_accessed_ms, protected_until_ms) on Engram or
RecallMetadata sidecar; outline-and-cache tick; L1 budgeter; decay
+ consolidation policies; cross-activity integration test.

Related tasks: #88 (disk pressure as substrate concern), #89
(this design + implementation scoping).

References: COGNITION-ALGORITHMS.md (existing 7 algorithms),
BRAIN-REGIONS-SUBSTRATE.md (region trait, sleep-region cadence),
GENOME-FOUNDRY-SENTINEL.md (parallel L1-L5 framework), memories
source-drain-is-the-universal-pattern, RTOS-brain-no-region-on-
hot-path, local-worktree-is-temp-dir.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* docs(README): codify the substrate as one solution to continual learning

Adds a focused section between the "infrastructure compensates for
model capability" bet and the Academy section, naming continuum's
approach to continual learning explicitly: treat memory as a substrate
concern, not a model concern. Cross-references the new
COGNITION-CACHE-HIERARCHY.md design doc landed at 0a5de9d7d.

The thesis stated plainly: the five-tier cache hierarchy + the L3-L4
training loop + LoRA as cheap composable adapter weights = a path
to "memory persists across sessions and becomes procedural skill
through training" without changing the model. Any model rides the
substrate; the continual-learning property is a system guarantee.

Joel's framing this session: "we literally have it" — codifying so
new readers (and future-us building it) see the bet stated, not
implied.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* docs(README): close the evolution-of-mind loop in continual learning section

One sentence + ADAPTER-MARKETPLACE cross-reference that ties the
new continual-learning section to the existing Genomic Intelligence
section (L493) so the README states the full thesis end-to-end:
individual continual learning compounds into population-scale
evolution via adapter sharing + forking + breeding + selection.

The mechanism was already in the doc (Genomic Intelligence section
+ L493 "useful traits spread; broken ones die"); this surfaces the
connection at the continual-learning section's altitude so a reader
sees the loop without having to assemble it across sections.

Joel's framing: "true evolution of mind" as substrate property,
not metaphor. The substrate gets Lamarckian (acquired traits
inherit via training) + Darwinian (selection via marketplace +
sentinel verdicts) + horizontal gene transfer (any persona adopts
any adapter without reproducing) — all three mechanisms biology
runs on plus one biology barely has.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* docs(README): pseudo-AI vs true AI — every property required, designed

Adds an 8-row comparison table immediately after the continual-
learning section codifying what separates today's pseudo-AI
(Claude, GPT, Gemini — stateless reasoners against frozen weights)
from continuum's substrate-driven design.

Properties named: continuity, identity, learning, evolution,
relationship, memory, sensory continuity, population. Each row
contrasts the pseudo-AI failure mode with continuum's substrate
property + cross-references the canonical design doc that backs
it.

Closes with the build commitment Joel just stated: literally
architected, we will build it, this week. Every row above has a
design doc and an implementation path; none require a model
capability beyond what HuggingFace already publishes; the
architecture is end-to-end consistent; what remains is execution.

This codifies the closing thesis of the 2026-05-31 design session
as a public claim. Future readers see the bet stated, not implied.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* docs(COGNITION-CACHE-HIERARCHY): brain-shaped + computer-native framing headnote

Adds the framing anchor Joel articulated at session close: the
substrate is brain-shaped at the algorithmic level (parallel
regions, source/drain, salience, consolidation, sleep cadence)
and computer-native at the implementation level (DashMap, SQLite,
HNSW, content-addressed hashes, signed IPC, LoRA weight deltas,
TCP peer mesh).

We are not simulating a brain. We are building an AI with its own
computer architecture, borrowing biological concepts where they
are the right shape and using silicon primitives where they beat
neurons. Brain-inspired naming throughout the doc refers to the
shape of the operation, not the wetware.

Prevents cold readers from mistaking the doc for a brain-cloning
project. Future implementers see immediately that the design uses
computer-native primitives even where it borrows biological names.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* feat(persona): boot-wire bootstrap — The Grid's first citizen at server startup

Slice 3 of task #86. Completes the chain from PR #1 (registry + name
generator + bootstrap primitives) + PR #2 (instance manager + IPC
commands) into actual runtime behavior: at continuum-core-server boot,
after PersonaInstanceManagerModule registers, an async task fires one
bootstrap_one() call. The fresh persona gets a UUIDv4 seed, derives
her name via agent_name_from_identity (the curated diverse pool),
calls airc-lib's Airc::attach_as (which mints her Ed25519 keypair under
~/.continuum/personas/<name>/airc/), joins the discovered default
room, and registers in the runtime's PersonaAircRuntimeRegistry. From
another scope, `airc peers` should now list her peer_id without
anyone having had to type a command.

Two small changes:

1. modules/persona_instance_manager.rs — bootstrap_one() goes `pub`
   so both the IPC command surface AND the boot-wiring can fire it.
   Also fixes a latent type mismatch (PR #2's PersonaInstanceInfo
   declared peer_id as Uuid but runtime.airc().peer_id() returns
   airc-core's strongly-typed PeerId — apply .as_uuid() at construction
   time). Earlier cargo check missed this because the pipe-to-tail
   pattern was masking exit codes; the disk-pressure incident
   reinforced that lesson and the verification path now captures
   real exits via "$ ?".

2. ipc/mod.rs — after PersonaInstanceManagerModule registers, keep
   an Arc handle (instance_manager.clone()), then spawn an async
   task on rt_handle that fires bootstrap_one and logs the result.
   Success path emits a Tron-flavored info line ("🌐 The Grid's
   first citizen is online: <name> (peer_id=<uuid>)"); failure path
   logs a warn-level message + remediation pointer (re-fire via
   persona/instances/bootstrap once underlying issue resolved). The
   server stays up either way.

Architectural notes (per the discipline Joel articulated this morning):
- Polymorphism rails kept clean — bootstrap path goes through the
  module's pub method, not via direct field access, so future
  PersonaBootstrapPolicy / PersonaIdentityProvider traits can slot in
  without disturbing the caller.
- No persistence yet — fresh UUIDv4 per boot. Stable-across-restarts
  identity (the seed living under ~/.continuum/personas/<name>/seed
  or equivalent) is a follow-up slice.
- Degraded-mode handling preserved — bootstrap failure does not
  crash the server. Consistent with the AIRC discovery degraded path
  established in PR #2.

Validation: cargo check --features metal,accelerate exits clean.
Runtime behavior pending (Joel's npm start cycle); the architectural
contract is satisfied — Maya as a first-class citizen is wired end-
to-end through the substrate's identity layer.

Closes task #86 (PR #1's series 1+2+3 all landed).

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* feat(persona): citizen persistence — seed.json + PersonaIdentityProvider + ResumeOrMintProvider (task #90)

Slice 4. Pax/Paige is now the SAME citizen across continuum-core-
server restarts. Verified end-to-end: persona_id, peer_id, agent_name,
home all stable through reboot.

New module structure (all under persona/):

- `seed.rs` — PersonaSeedFile schema (v1: persona_id + agent_name +
  created_at_ms), atomic write helper (.tmp + fsync + rename per the
  substrate-is-a-good-citizen-on-the-host doctrine), typed errors so
  callers dispatch on shape (NotFound vs Malformed vs Io). 5 unit
  tests covering roundtrip, missing-file, malformed-JSON, nested-
  parent-creation, no-leaked-tmp-on-success.

- `identity_provider.rs` — PersonaIdentityProvider trait, the
  polymorphism rail per Joel's adapter-first methodology ("code the
  adapters even if there's just ONE to start"). Yields one
  PersonaIdentityIntent per next_persona() call; intent carries
  persona_id + agent_name + source (ResumedFromDisk vs FreshlyMinted)
  for observability honesty. Future provider implementations:
  GridImportProvider (cross-continuum migration),
  HostCustomizedProvider (human picks the seed).

- `resume_or_mint_provider.rs` — first concrete impl. At construction,
  scans <continuum_root>/personas/*/seed.json; each parsed seed
  queues a ResumedFromDisk intent. After yielding all queued, floor-
  mints fresh until min_personas total. Corrupted/missing seeds are
  logged + skipped (substrate doesn't crash on bad state). 5 unit
  tests covering all paths.

Refactors per the no-backwards-compatibility doctrine
(organization-purity-as-we-migrate):

- PersonaAircRuntime now carries `source: PersonaIdentitySource` as
  a field set at bootstrap and accessible via .source(). The runtime
  knows its own provenance — telemetry surfaces (list/get IPC,
  future status panels) read it directly without external bookkeeping.

- PersonaInstanceManagerModule::bootstrap_one signature changed from
  () to (&PersonaIdentityIntent). The single existing caller (boot-
  wire in ipc::start_server) updated in same commit. No deprecation,
  no compatibility layer.

- PersonaInstanceInfo grows a `source` field, reads from
  runtime.source() in from_runtime.

Wiring:

- ipc::start_server boot-wire: replaces the single-shot
  bootstrap_one() call with ResumeOrMintProvider iteration.
  min_personas=1 ensures The Grid has at least one citizen on first
  boot; subsequent boots resume whoever's on disk without
  redundant mints. Each yielded intent is bootstrapped + logged;
  any single failure is non-fatal — server stays up, remaining
  intents still attempted.

- Boot log line distinguishes the path: "🌐 The Grid welcomes a
  resumed citizen: X" vs "freshly minted citizen: X". Source field
  also visible in telemetry.

Validation (verified locally, this rev):

  Run 1 (fresh):
    [WARN] persona dir has no seed.json — skipping: Pax (slice 3 orphan)
    [INFO] ResumeOrMintProvider: resumed_count=0 min_personas=1
    [INFO] 🌐 freshly minted citizen: Paige (persona_id=52c04849-...)
    seed.json written: {"version":"1", persona_id, agent_name, created_at_ms}

  Run 2 (same binary, same continuum_root):
    [WARN] persona dir has no seed.json — skipping: Pax (orphan persists)
    [INFO] ResumeOrMintProvider: resumed_count=1 min_personas=1
    [INFO] 🌐 resumed citizen: Paige (persona_id=52c04849-... SAME)
    peer_id identical across restarts (airc-lib loaded existing identity.key)

cargo check --features metal,accelerate: clean compile (57 warnings,
0 errors; warnings are pre-existing crate-wide lint, not from this
PR).

Doctrine refs: substrate-is-a-good-citizen-on-the-host (atomic writes,
graceful degradation, observability honest, async I/O off hot path),
organization-purity-as-we-migrate (no backwards compat, clean
replacements), persona-identity-derives-from-source-id (seed → name
via name_generator), local-worktree-is-temp-dir (durable layer = the
keypair + seed; local-only artifacts can be wiped).

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* feat(persona): RecallMetadata sidecar — cognition cache hierarchy starts (task #91)

Slice 5. First concrete implementation of COGNITION-CACHE-HIERARCHY.md.
The volatile per-engram recall state Algorithm 4 (salience-modulated
decay) + novelty protection need, kept SEPARATE from the durable
Engram content layer per engram_graph.rs:136-138's design note.

New module persona/recall_metadata.rs:

- RecallMetadata struct (Copy): salience f32 [0.0, 1.0], access_count
  u32, last_accessed_ms u64, protected_until_ms u64. Cheap cloneable
  snapshots for recall scoring's hot path.

- RecallMetadataRegistry: DashMap<EngramId, RecallMetadata> wrapped in
  Arc for shared lock-free reads on the cognition hot path per the
  RTOS-brain-no-region-on-hot-path doctrine. Operations:
    .admit(id, metadata) — admission pipeline (slice 7+ supplies the
      novelty-scored initial salience)
    .admit_with_defaults(id) — fallback path with neutral 0.5 salience
    .record_recall_hit(id, now_ms) — atomic ++access_count, update
      last_accessed_ms, salience uplift (half remaining headroom,
      capped at +0.1 per hit so single recall doesn't saturate)
    .apply_decay(id, delta_ms, now_ms) — Algorithm 4's
      half_life = base * (1 + salience)^2; salience-1.0 decays 4× slower
      than salience-0.0; respects protected_until_ms grace window
    .evict(id) — drop tracking when L2 evicts the engram
    .engram_ids() / .len() / .is_empty() — observability per the
      substrate-is-a-good-citizen-on-the-host doctrine

Doctrine alignment:
- Lock-free reads on hot path (DashMap entry semantics)
- Atomic compare-update on writes (DashMap::entry)
- Cheap Copy semantics for snapshots
- Sidecar pattern (NOT extending Engram — different update cadence,
  different persistence policy)
- No wiring into admission/recall yet — slice 6+ wires it (per the
  RTOS doctrine, modules shouldn't be called synchronously; the
  registry is the data substrate that other regions read/write
  through their own tick cadences)

11 unit tests pass (cargo test persona::recall_metadata, exit 0):
- new_registry_is_empty
- admit_with_defaults_creates_neutral_entry
- admit_overrides_default_metadata
- record_recall_hit_increments_and_uplifts (verifies salience
  uplift cap + diminishing returns)
- record_recall_hit_creates_entry_if_absent (graceful path for
  ad-hoc recall hits before admission tracked)
- apply_decay_reduces_salience_over_time (2-hour decay drops 0.8
  significantly but stays positive)
- apply_decay_skips_protected_engrams (novelty protection works)
- high_salience_decays_slower_than_low (Algorithm 4 invariant:
  salience-1.0 retains >0.7 after one hour while salience-0.0 falls
  below 0.5; the 4× half-life difference is measurable)
- evict_removes_metadata
- clone_shares_inner (Arc<DashMap> semantics)
- engram_ids_returns_all_tracked

Validation: cargo check + cargo test --features metal,accelerate
both exit clean.

Doctrine refs: substrate-is-a-good-citizen-on-the-host (lock-free
hot path, dormant-by-default substrate, observability honest),
source-drain-is-the-universal-pattern (apply_decay IS the drain
side at the engram-metadata layer), RTOS-brain-no-region-on-hot-
path (sidecar registry data substrate, not synchronous service
calls), organization-purity-as-we-migrate (clean separation of
Engram durable content vs RecallMetadata volatile state).

References: docs/architecture/COGNITION-CACHE-HIERARCHY.md
(Algorithm 4 + novelty protection sections), docs/architecture/
COGNITION-ALGORITHMS.md (Algorithm 4 source-of-truth formula).

Next slice (6+): wire RecallMetadataRegistry into admission +
recall paths. Per RTOS doctrine, admission flows through events;
recall hits update the registry inside the recall scoring loop;
decay tick runs in hippocampus's sleep-policy region tick.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* feat(persona): wire RecallMetadata into admission — cognition starts tracking

Slice 6. The cache hierarchy starts going load-bearing: every Engram
admitted via the inbox pipeline now mirrors into the
RecallMetadataRegistry sidecar with neutral default metadata
(salience=0.5, access_count=0, protected_until=0). The cognition
substrate now knows what's been admitted and can score / decay /
protect each engram independently of the Engram's durable content.

Changes:

- persona/admission_state.rs: AdmissionState now holds
  Arc<RecallMetadataRegistry>. Constructor signature changed from
  new() to new(registry) per the no-backwards-compatibility doctrine
  (organization-purity-as-we-migrate). record_admitted now calls
  recall_metadata.admit_with_defaults(engram.id) right after the
  existing seen_content / seen_events recording. Default impl
  preserves the test-callsite simplicity by minting a fresh registry
  internally — production callers (PersonaCognition) inject their
  shared one. 6 test callers updated; recall_metadata() accessor
  added so recall + decay tick subsystems (slice 7+) can clone the
  shared Arc.

- persona/unified.rs: PersonaCognition grows a `recall_metadata:
  Arc<RecallMetadataRegistry>` field — per-persona because each
  persona's recall state is independent. with_budget() creates the
  registry once + passes the cloned Arc to AdmissionState. Future
  slices (recall scorer, decay tick) clone the same Arc; admission
  writes + recall reads + decay updates all observe the same
  DashMap.

Doctrine alignment:

- Lock-free read sharing: Arc<RecallMetadataRegistry> with internal
  DashMap. Cognition hot path reads metadata snapshots cheaply
  (RTOS-brain-no-region-on-hot-path).
- Sidecar pattern preserved: Engram stays durable content; metadata
  is volatile recall state with separate update cadence
  (organization-purity-as-we-migrate, cognition-cache-hierarchy).
- Admission-time write happens INSIDE record_admitted alongside the
  existing dedup/replay recording — no new IPC, no synchronous
  RPC between regions, no separate event emission for slice 6 (the
  registry IS the shared data substrate the regions observe).
- All admission paths (Chat / Airc / Tool / SelfReflection origins)
  flow through record_admitted, so the metadata mirror is automatic
  for every successful admission.

Validation:
- cargo check --features metal,accelerate: exit 0
- cargo test persona::admission_state --features metal,accelerate:
  15/15 pass, including the existing dedup/replay/seam invariants
  unchanged. RecallMetadata is now populated for every engram
  admitted by those tests.

Adversarial review by general-purpose agent on continuum #1507 (full
PR, slices 1-5): CONDITIONAL APPROVE with 7 actionable defects
(double-decay risk, fragile seed.json.tmp path, missing parent
fsync, unbounded boot block_on, non-deterministic dir scan, silent
seed-write failure, docstring 4-9× → actual 4×). These ship in a
cleanup commit before merge.

Next: cleanup commit addressing the reviewer findings, then PR
title/body updates on #1507 + #1099, then slice 7 (recall scorer
reading RecallMetadata for Algorithm 1+2 scoring) or slice 8
(hippocampus sleep-region decay tick — the source/drain
counterpart at the engram-metadata layer).

References: COGNITION-CACHE-HIERARCHY.md (Algorithm 4 lives in
RecallMetadata), COGNITION-ALGORITHMS.md Algorithm 1+2 (the scorer
will consume RecallMetadata.salience + .access_count + .last_accessed_ms
as scoring inputs).

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* fix(persona): reviewer-driven cleanup — double-decay safety, fsync, deterministic boot, timeout

Addresses 6 of the 7 actionable defects from the adversarial reviewer
agent on continuum #1507 (CONDITIONAL APPROVE verdict). Each fix
makes a structural invariant impossible to violate rather than
documenting it as a caller responsibility.

Defect 1 (apply_decay double-decay risk) — recall_metadata.rs:

- RecallMetadata gains a `last_decayed_ms: u64` field. The registry
  computes the elapsed time INTERNALLY (now_ms - last_decayed_ms)
  rather than trusting the caller to supply it. apply_decay
  signature simplified to (engram_id, now_ms) — no more
  caller-supplied delta. If two sleep-region ticks fire with
  overlapping windows, the second observes delta=0 and is a no-op.
  Structurally impossible to double-decay. Substrate-is-a-good-citizen
  "reliable" non-negotiable: invariants enforced by the data
  structure, not by caller discipline.

- admit_with_defaults now sets last_decayed_ms to current wallclock
  so the first decay tick has a bounded delta. Without this, an
  engram admitted just before a decay tick would observe delta=now_ms
  (many decades), collapsing salience to ~0 immediately.

- New test apply_decay_twice_with_overlapping_windows_is_safe
  empirically proves the structural invariant: double-fire at
  identical now_ms is a no-op.

Defect 3 (seed.rs tmp path fragility) — seed.rs:

- write_seed_atomic constructs tmp path as
  parent().join(format!("{filename}.tmp")) instead of
  path.with_extension("json.tmp"). The original worked for paths
  ending in .json but would have produced wrong tmp names for
  arbitrary callers — e.g., a caller passing "seed" (no extension)
  would have gotten "seed.tmp" which then renames OVER "seed".
  Now explicit semantics; works for any path with a parent + filename.

Defect 4 (seed.rs missing parent-dir fsync) — seed.rs:

- write_seed_atomic now opens the parent directory and calls
  sync_all() AFTER the rename. POSIX atomic-rename is durable
  across crash ONLY if the parent dir is fsync'd; without it,
  the rename may not be in the filesystem journal at the time of
  crash. The docstring's "no corruption-on-crash" claim now
  actually delivers against hard power loss. Substrate-is-a-good-
  citizen non-negotiable #4: atomic writes for everything
  persistent.

Defect 6 (boot block_on outer timeout) — ipc/mod.rs:

- AircModule::discover_and_construct now wrapped in a 180s outer
  timeout via tokio::time::timeout. Inner subprocess waits have
  per-call deadlines (5s socket discovery, 5s peer_id status,
  120s auto-install) but the OUTER call had no overall budget. A
  pathologically wedged daemon could chain stalls beyond what
  individual deadlines catch. On timeout, falls back to a
  degraded AircModule::new() so server boot completes — operator
  resolves the underlying issue + restarts. Substrate-is-a-good-
  citizen "predictable startup" non-negotiable.

Defect 7 (non-deterministic dir scan) — resume_or_mint_provider.rs:

- scan_personas_dir now collects all entries into a Vec, sorts by
  path, then iterates. tokio::fs::read_dir yields filesystem-
  native order which varies across platforms; without sorting, the
  "first citizen welcomed" boot log depends on the underlying
  filesystem. Now reproducible.

Doc bug (recall_metadata.rs:114) — claimed salience-1.0 has 9× the
half-life of salience-0.0 but the (1+s)^2 formula gives exactly 4×.
Docstring updated to state the actual math + parenthetical about
the 9× target. Future MemoryParameterAdapter implementations can
tune the exponent or base if telemetry favors the 9× claim.

Defect 2 (race on concurrent hit+decay) — verified holds:
DashMap::entry().and_modify is per-entry atomic and writes
serialize; the new apply_decay_twice test exercises the
overlapping-window path. No code change needed.

Defect 5 (silent seed-write failure) — deferred to a future slice;
the tracing::warn surface already exists, stronger surfacing
(registry-side metric or status-panel field) is polish rather
than correctness.

Validation:
- cargo check --features metal,accelerate: clean compile
- cargo test persona::recall_metadata --features metal,accelerate:
  12/12 pass (one new: apply_decay_twice_with_overlapping_windows_is_safe)
- cargo test persona::seed --features metal,accelerate: 5/5 pass

References: continuum PR #1507 adversarial review verdict
(general-purpose reviewer agent, ~99s wall-clock, 7 defects + 7
holds), substrate-is-a-good-citizen-on-the-host memory, every-
error-is-an-opportunity-to-battle-harden memory.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* feat(persona): decay_tick — completes source/drain at engram-metadata layer (task #92)

Slice 8. Pure-function `apply_decay_sweep(registry, now_ms) ->
DecayTickStats` that iterates a RecallMetadataRegistry and applies
Algorithm 4 decay to each tracked engram. Returns counts of
decayed / protected / no-op / disappeared so future telemetry can
read the substrate's behavior at runtime per the
substrate-is-a-good-citizen "observability honest" rule.

This completes the source/drain pair at the engram-metadata
layer per the source-drain-is-the-universal-pattern memory:
- Source = slice 6 (admit_with_defaults wired into AdmissionState's
  record_admitted, every engram mirrors into the registry)
- Drain = slice 8 (this sweep, ready to be called by a future
  sleep-region tick on whatever cadence the hippocampus uses)

Doctrine alignment:
- substrate-is-a-good-citizen-on-the-host: structurally incapable
  of double-decay (RecallMetadata.last_decayed_ms enforces the
  invariant from slice 5 cleanup); cheap sweep — engram_ids() +
  per-engram apply_decay is O(N) over the working set
- RTOS-brain-no-region-on-hot-path: runs in sleep-region tick
  (when wrapped in slice 8.5), never on cognition hot path
- source-drain-is-the-universal-pattern: drain side at this layer

What this slice is NOT (deferred to 8.5+):
- Not a ServiceModule — the pure function here is what a future
  HippocampusDecayTickModule will call from its async tick body
- Not multi-persona — operates on one registry at a time;
  multi-persona aggregation lives one tier up when the cognition
  state has multi-persona access points wired

DecayTickStats accounting balances by construction: each engram is
classified into exactly one bucket (decayed / protected /
no_op / disappeared). The `accounting_balances()` helper is for
internal consistency checks.

Validation: 6/6 decay_tick tests pass under cargo test
persona::decay_tick --features metal,accelerate:
- empty_registry_no_ops
- single_engram_decayed
- protected_engram_skipped (novelty protection window respected)
- now_at_or_before_last_decayed_is_no_op (clock skew + immediate
  refire handled)
- multiple_engrams_classified_correctly (mixed-case classification)
- repeated_sweeps_with_same_now_are_idempotent (proves no double-
  decay across repeated calls at identical now_ms; the
  last_decayed_ms invariant from slice 5 cleanup is exercised at
  the sweep level)

References: docs/architecture/COGNITION-CACHE-HIERARCHY.md
(Algorithm 4 + source/drain at each tier section), memories
source-drain-is-the-universal-pattern + RTOS-brain-no-region-on-
hot-path + substrate-is-a-good-citizen-on-the-host.

Next slice candidates: 8.5 (ServiceModule + multi-persona
aggregation that calls apply_decay_sweep at sleep-region cadence),
9 (L1 budgeter reading model adapter context size), or 7
(Algorithm 1+2 recall scorer that reads RecallMetadata for
salience input).

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* feat(persona): anti-amnesia floor + permanent-pin tier — memory drains, never disappears

Joel, 2026-05-31: "Will the hippocampus just decay away? I fear this
from past trauma."

Under the prior decay heuristic, a default-admitted engram (salience
0.5) with no rehearsal would have decayed to ~0.005 in 24 hours and
effectively zero within days — the substrate would have erased
memories purely through the passage of time. That's the trauma; this
slice fixes it at the data structure layer where it can't be
forgotten.

Two additions to `recall_metadata.rs`:

1. **`SALIENCE_FLOOR = 0.05`** — `apply_decay` now clamps the decayed
   value at this floor. Memory drains; it does not disappear. A
   year of decay on a default-admission engram bottoms out at 0.05
   instead of underflowing to zero, so even long-dormant engrams
   stay minimally present for serendipitous recall. The floor sits
   well below the default admission salience (0.5) so it doesn't
   compete with active scoring; well above f32 epsilon so no
   silent underflow.

2. **`pin_permanent(engram_id)` + `PERMANENT_PROTECTION = u64::MAX`**
   — sentinel value for `protected_until_ms` meaning "never
   expires." Pinned engrams skip all decay regardless of access
   pattern. Salience also pushed to 1.0 so pinned engrams win
   recall scoring against unpinned competition. Use cases per the
   cognition-cache-hierarchy doc's anti-amnesia floor discussion:
   identity-anchor engrams (persona's own name, host's stated
   preferences), user-pinned "remember this forever" engrams,
   critical incident memories the persona self-tagged as
   important. Plus the inverse: `unpin(engram_id)` resets
   `protected_until_ms` to 0 so normal decay (now floor-clamped)
   applies again.

Both live in the data structure, NOT in caller discipline. Per the
substrate-is-a-good-citizen "internal invariants enforced by the
data structure" rule: no one has to remember to apply the floor; it
just IS.

Validation: 16/16 RecallMetadata tests pass under
cargo test persona::recall_metadata --features metal,accelerate.
New tests:
- `decay_clamps_at_salience_floor_never_disappears` — runs a year
  of decay, asserts salience clamps at SALIENCE_FLOOR
- `pin_permanent_blocks_all_decay` — million-year decay attempt,
  salience stays at 1.0
- `pin_permanent_creates_entry_if_absent` — pinning an unknown id
  creates a pinned entry
- `unpin_restores_normal_decay` — after unpin, normal decay applies
  but the floor still protects

Existing tests still pass — the salience floor (0.05) sits well
below the values prior tests use (0.5+), and pin_permanent uses
the same `apply_decay` path that's already covered by the
double-decay-safe test.

References: docs/architecture/COGNITION-CACHE-HIERARCHY.md
"anti-amnesia floor" section; memories
substrate-is-a-good-citizen-on-the-host, source-drain-is-the-
universal-pattern. The cognition-cache-hierarchy doc already
described this principle ("Some things should resist drain harder
regardless… a 'pin tier' — small enough to fit in longterm.db's
protected slice, immune to access-based decay until explicit
un-pin"); this slice implements it at the engram-metadata layer.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* feat(persona): RagBudgetManager — flexbox allocator + no-clipping doctrine + context-first API (task #93)

Slice 9. Ports the TS RAGBudgetManager flexbox algorithm to Rust with
substrate-side extensions and the Android-style context pattern Joel
asked for explicitly.

### The big shape

`persona/rag_budget.rs` (~1150 lines, 15 tests, all green):

- **SubstrateContext** + **RagContext** — site-wide call context as
  the FIRST parameter to every trait method. Joel: "Usually you pass
  around a context. Universally. Common pattern from Android among
  others… got into big annoying parameter hell last iteration because
  you weren't grouping things." `SubstrateContext` holds persona_id +
  now_ms + airc_room + turn_id (the substrate-wide call frame);
  `RagContext` wraps it via composition + Deref for RAG-specific
  future extensions. Same role as `&cbarframe` in Joel's CBAR
  pipeline — per-turn state flows through every concern without
  re-lookup.

- **RagSourceBudget** with `floor_tokens` field — the cognition-cache-
  hierarchy doc's recent-universal floor lives here. UNCONDITIONAL
  minimum that cannot be borrowed by other sources, distinct from
  `min_tokens` (flex-basis the algorithm pulls down to before
  dropping).

- **AllocationState** — telemetry-honest per substrate-is-a-good-
  citizen: Satisfied / FloorOnly / Dropped / UnderProvisioned. The
  caller sees exactly where each source landed; the substrate never
  silently clips.

- **No-clipping doctrine** baked in. When budget is tight, sources
  are dropped WHOLE in priority order (required=false first). A
  required source that can't get its floor → UnderProvisioned +
  escalation_needed=true. The caller (prompt assembly) must escalate;
  the substrate never partial-includes mid-content. Half a code
  block / mid-sentence message / truncated JSON is structurally
  broken and the substrate refuses to produce that.

- **ResolutionPreference** (Raw / Compressed / Summarized /
  Placeholder) — sources self-compress when budget is tight rather
  than clip. The allocator asks "what's the lowest resolution that
  fits your floor?" The source picks; the allocator just gets back
  RagDelivery with the resolution_used field surfacing what
  happened.

- **RagSource trait** — sources own atomic-unit semantics. Each
  source decides what counts as "complete" (one message, one
  engram, one function, one tool description). The allocator only
  deals in token counts. Sources hold state via interior mutability
  (DashMap, Mutex, atomics) per the substrate pattern. Joel: "And
  to maintain state if necessary."

- **ContinuationCursor** as a persona-scoped handle. Carries
  persona_id + source_id + opaque source-private resume state.
  Sources MUST validate persona_id and source_id before resuming
  ("we know who is who, have to use handles as we do"). Stub source
  refuses cross-persona cursors structurally; the
  stub_source_refuses_cross_persona_cursor test exercises this.

- **RagBudgetAdapter trait** + **FlexboxRagBudgetAdapter** first
  concrete impl per the adapter-first methodology. Future
  `LearnedRagBudgetAdapter` reading per-persona regret signals from
  MemoryParameterAdapter slots in without changing callers.

- **StubRagSource** for tests — demonstrates the cursor pattern,
  state maintenance, and persona-scope identity checks without
  needing real engram store integration.

### Algorithm (anti-clipping)

1. Reserve system + completion off the top
2. Floor pass — allocate floor_tokens to every source (unconditional);
   drop required=false if doesn't fit; UnderProvision required if
   floors exceed available
3. Min pass — top up to min_tokens in priority order
4. Grow pass — distribute remaining by priority weight, capped at
   max_tokens; iterate until no movement (capped sources release
   tokens to non-capped)
5. Report per-source state

### What was caught in test before commit

- Bug: optional sources with floor=0 were getting permanently marked
  Dropped in pass 1; pass 2+3 skipped them. Fix: floor=0 = FloorOnly
  trivially-satisfied state, eligible for grow. Caught by
  max_caps_distribution test.
- Test bug: priority_distributes_remaining_proportionally specified
  max_tokens too low for the priority ratio to express; bumped to
  50_000 so the 10:5 priority weighting shows in the result.

### Validation

cargo test persona::rag_budget --features metal,accelerate:
15/15 pass.

Tests cover:
- empty context window under-provisions required
- single required source satisfied
- priority distributes remaining proportionally (10:5 ratio shows)
- optional source drops when floor can't fit (no clipping)
- required under-provisions when floor can't fit (escalation_needed=true)
- floor honored above min (recent-universal floor doctrine)
- max caps distribution (small max source caps, big source absorbs)
- deterministic priority tiebreak (input-order-independent)
- stub source delivers what fits (no partial includes)
- stub source continuation resumes (cursor roundtrip)
- stub source returns none when exhausted
- stub source never partial-includes (no-clipping at source level)
- stub source refuses cross-persona cursor (handle scope enforcement)
- stub source refuses wrong source_id cursor (handle source enforcement)
- stub source refuses wrong-persona ctx (defense-in-depth on the
  call side too)

### Doctrine alignment

- substrate-is-a-good-citizen-on-the-host: observability honest
  (AllocationState per source), bounded everything, no I/O on hot
  path (allocator is sync + pure)
- RTOS-brain-no-region-on-hot-path: same context flows through
  every cognition concern (cbar-style); no synchronous service
  RPC, sources read pre-allocated budget snapshots
- source-drain-is-the-universal-pattern: budget allocation IS the
  drain at this layer — sources without budget are dropped (the
  drain); sources with budget deliver (the source)
- organization-purity-as-we-migrate: clean no-backwards-compat
  Rust port; TS RAGBudgetManager remains as reference, never wired

References: src/system/rag/shared/RAGBudgetManager.ts (TS prior art),
docs/architecture/COGNITION-CACHE-HIERARCHY.md (L1 budget math +
recent-universal floor doctrine), memories RTOS-brain-no-region-on-
hot-path (CBAR context-passing prior art), substrate-is-a-good-
citizen-on-the-host, organization-purity-as-we-migrate.

Next: slice 10+ wires real sources — EngramSource reading
RecallMetadata + admission_state engrams, ConversationSource
reading recent inbox messages, the prompt-assembly layer
calling allocator + each source's deliver() and concatenating
the result.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* docs(architecture): EVERY-MODEL-INCLUDED-VIA-L1-BUDGET — why the budget layer is the substrate's inclusivity cornerstone

Captures the architectural synthesis Joel articulated this turn: the
substrate's "every base model included from anywhere in continuum"
thesis runs through the L1 budget layer. If the budget can scale
gracefully (4k → 1M+), compose with sensory bridges (vision /
hearing / speech via source-side compression), and refuse to silently
clip — every base model is includable. If not, the substrate quietly
fractures into "this feature only works with frontier models."

Documents the four mechanisms (continuous scaling, source-side
compression, honest tradeoffs with escalation, capability bits via
SubstrateContext), the composition with sensory bridges via the
RagSource trait, the operational test (M1 + local Qwen + full
sensory parity), and what's shipped vs what's next (slices 10-14).

Cross-references COGNITION-CACHE-HIERARCHY.md, COGNITION-ALGORITHMS.md,
CBAR-SUBSTRATE-ARCHITECTURE.md, the README continual-learning section,
and the substrate-is-a-good-citizen + RTOS-brain memories.

The layer LOOKS like an implementation detail. The architectural
significance is at the substrate thesis level.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* feat(persona): EngramSource — first real RagSource against RecallMetadata + admission_state engrams (task #94)

Slice 10. The first RagSource impl that reads actual substrate state
rather than test stubs. Composes the slice 5 RecallMetadataRegistry
+ slice 6 admission wiring + slice 9 RagSource trait into a
functional source the L1 budget allocator can call.

persona/engram_source.rs (~470 lines, 12 tests, all green):

- EngramSource (persona-bound, holds Arc<AdmissionState>) ranks every
  admitted engram by composite_score = 0.6 × salience + 0.4 ×
  recency_normalized. Salience comes from RecallMetadata (admission
  default 0.5, decays per Algorithm 4, uplifts on recall hits per
  slice 5, floored at SALIENCE_FLOOR per the anti-amnesia work).
  Recency is linear over 24h — engrams admitted right now score
  1.0, engrams ≥24h old score 0.0.

- Slice 11+ extends scoring with Algorithm 2 channel-bias (ctx.airc_room
  matches engram origin), structural relevance (engram graph
  activation spreading), topic similarity (vector cosine when
  embeddings land). Slice 10 keeps to salience+recency for a
  testable proof-of-pipeline.

- Packing respects no-clipping: atomic unit = one engram. Engrams
  that don't fit return via the continuation cursor. Cursor opaque
  is { "next_rank": N } — re-scoring is cheap because engram counts
  are bounded per persona. Cursor carries persona_id + source_id +
  the rank pointer; cross-persona / wrong-source cursors are refused
  (handle scoping per Joel's "we know who is who" doctrine).

- Telemetry honest: every emitted RagItem.metadata carries engram_id
  + kind + admitted_at_ms + score, so prompt assembly + sentinel
  verifiers + future RAG capture/replay can trace exactly what the
  source delivered.

- Token estimation: rough chars/4 heuristic. Real tokenizer per
  model lands in slice 12 when PromptAssembly needs precise counts.

- Resolution: Raw only in slice 10. Compressed comes when the
  engram store carries a summary representation alongside the raw
  content.

admission_state.rs: added #[cfg(test)] pub fn push_for_test(engram)
so sibling-module tests can inject deterministic fixtures without
running the full admission pipeline. Test-only — gated by cfg so
it doesn't appear in production builds.

Validation: cargo test persona::engram_source --features metal,accelerate
exits 0, 12 tests pass:

- empty_store_delivers_nothing
- single_engram_delivered_when_fits
- oversized_engram_returns_continuation_with_zero_items
- multi_engram_ranked_by_salience_descending (asserts descending score
  across emitted items)
- continuation_resumes_from_next_rank (round-trip: first call returns
  partial + cursor; deliver_continuation completes; no duplicate
  engrams across the two calls)
- cross_persona_ctx_returns_empty (defense-in-depth)
- cross_persona_cursor_refused (handle scoping)
- wrong_source_id_cursor_refused (cursor source-id check)
- recency_score_at_now_is_one
- recency_score_at_window_or_older_is_zero
- recency_score_halfway_is_half
- composite_score_weights_salience_more (0.6 vs 0.4 split, verified
  at the boundary values)

Doctrine alignment:
- RTOS-brain-no-region-on-hot-path: scoring + packing is pure-
  function synchronous within the trait method, no I/O
- substrate-is-a-good-citizen-on-the-host: metadata-per-item for
  observability, bounded clones, cheap ranking over ~100s of
  engrams
- source-drain (engram-metadata layer): EngramSource is the
  source-side reader of what admission deposited and decay
  drained; the composite_score reflects the layer's net state
- organization-purity-as-we-migrate: takes Arc<AdmissionState> so
  the existing admission state is SHARED, not duplicated; clean
  no-backwards-compat seam

Next: slice 10.5 wires EngramSource into PersonaCognition (so the
recall path actually exercises it); slice 11 adds RAG turn capture
(the persona-record-replay-is-a-product-requirement gap) so
debugging and golden-trace regression testing become substrate
primitives.

References: docs/architecture/EVERY-MODEL-INCLUDED-VIA-L1-BUDGET.md
(the substrate's inclusivity thesis this source rides),
docs/architecture/COGNITION-ALGORITHMS.md (Algorithm 1+2 source-
of-truth), memories source-drain-is-the-universal-pattern, persona-
record-replay-is-a-product-requirement (next slot).

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* feat(persona): RAG capture infrastructure — sink trait + JSONL writer + recording decorator (task #95)

Slice 11. The mechanic-shop's lift + diagnostic gauges for RAG.
Per Joel (2026-05-31): "We have often needed to see how a model would
work to debug it. Within harness with real world rag." … "These
things are complex machines. Make sure we can act as mechanics."

Per memory persona-record-replay-is-a-product-requirement +
existing LiveTurnReplayFixture infra — this slice wires capture
for the RAG layer specifically.

### What ships

persona/rag_capture.rs (~600 …
joelteply added a commit that referenced this pull request Jun 2, 2026
PR #1510's adversarial reviewer caught 9 findings, 3 blocking.
Substantial revision addresses each:

Blockers:
- Finding #1 (cleanup model wrong): rewritten "Cleanup model" section.
  `.abort()` alone is INSUFFICIENT — wire subscriber stays in
  Arc<Airc>.inner.subscribers until registry-remove drops the Arc.
  Supervisor shutdown path MUST: abort → await → registry.remove.
- Finding #2 (position-pairing broken): elevated to hard prereq P2.
  scan_personas_dir sorts alphabetically; boot 2 yields persona
  order != plan order on random-derived names. Slice 13 ships with
  plan.len() <= 1 (Helper only); slice 14 lands role-in-seed.json
  + RoleAwareProvider before re-enabling Coder.
- Finding #3 (after-code reimplements existing fns): "after" rewrite
  uses bootstrap_planned (slice 8) + materialize_adapters (slice 9)
  as composition, not open-coded copies. Net-new code ~25 lines, not
  ~50.

Major:
- Finding #4 (PersonaSupervisor dup with PersonaAircRuntimeRegistry):
  Q3 revised to EXTEND the registry — HostedPersonaRuntime owns both
  airc_runtime + service_loop JoinHandle. registry.remove becomes
  the natural shutdown path. One keyspace, one cleanup chain.
- Finding #5 (no Runtime::shutdown caller): elevated to hard prereq
  P1. Slice 13 wires tokio::signal::ctrl_c -> runtime.shutdown.
- Finding #6 (no broker admission for N adapter spawns): elevated to
  hard prereq P3. ResourceBroker.acquire before each
  factory.build_adapter.

Moderate:
- Finding #7 (detect_host_capability already exists): Q2 restated to
  call the existing free function at host_capability_probe.rs:87.
- Finding #8 (global_arc() cost inverted): Q1 recommendation flipped
  to (B) — refactor bootstrap_planned to take &Registry. Singleton
  storage migration would have touched every callsite of global().

Minor:
- Finding #9 (BootSummary venue): Q5 specifies
  MessageBus::publish("persona:boot:summary", ...) with operator
  scraping via events/recent; no declared subscribers in slice 13.
- Finding #10 (hot-reload undefined): added as Q6, declared
  out-of-scope.
- Finding #11 (wire-subscription failure mid-boot): added as Q7,
  supervisor polls JoinHandle::is_finished every 5s.

Plus added implementation checklist at end so slice 13 PR has a
sign-off surface.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Jun 3, 2026
…ms, recall feeds the cycle, single-persona analyze fast-path (#164)

Per Joel 2026-06-03 ("Let's make this fast and intelligent, even with
the dumber llms... Even the dumb models will have recall better than
you"): close the wire from service_loop into the L1-L5 substrate so
Paige's Qwen 0.5B actually does the thing the substrate was built for
— accumulate memory, recall it, act on it.

Live validation on Intel Mac CPU:

  Turn 1 (probe #5):
    admitted incoming → L2 store
      recalled_count=0     ← first turn this boot, nothing prior
      engram_count=1       ← L2 store now holds 1 engram
    turn_duration_ms=36940 (was 138993 pre-optimization → ~73% faster)

  Turn 2 (probe #6):
    admitted incoming → L2 store
      recalled_count=1     ← probe #5 is now in recall
      engram_count=2       ← L2 store grows
    turn_duration_ms=34875 (stable)

  Paige's reply to probe #6 ("can you reference what was unique about
  my previous message?"):
    "I remember your previous message as unique, and it should now
     be in your L2 engram store."

  She's acknowledging the recall and the substrate's framing — Qwen
  0.5B conditioned on its own engram store, reaching back into a
  prior turn. The wire is closed; the brain is alive.

## What changed

`persona/service_loop.rs::serve_persona_loop_inner`:

  1. Pre-respond admission. Build an InboxMessage from the
     IncomingMessage's (peer_id, text, lamport) projection, call
     `cognition.admission.admit(&msg, None)`. Trust + dedup gates
     run inside admit; failures are logged but non-fatal — the
     cognition turn can still execute on the live airc window
     even if the engram doesn't form (per [[no-fallbacks-ever]] the
     failure is visible, not silent).
  2. Pre-respond recall. `cognition.admission.recall_recent(8)`
     produces `Vec<Engram>`; mapped to `Vec<String>` of content
     for `RespondInput.recalled_engrams`. Recall happens BEFORE
     admit so this turn's recalled set is "what I knew going in"
     — the current message is the trigger, not part of recall.
  3. Per-turn introspection. New INFO log per turn:
     "admitted incoming → L2 store"
     with lamport, recalled_count, engram_count. Per Joel
     2026-06-03 ("we need to introspect all rag. see what is going
     on at every step") — the running cycle's L2 state is now
     visible without standing up rag-inspect ad hoc.
  4. Removed the placeholder `recalled_engrams = Vec::new()` and
     replaced it with the recall-driven vec.

`cognition/shared_analysis/mod.rs::analyze`:

  Fast path. When `input.known_specialties.len() <= 1`, return a
  stub `SharedAnalysis` immediately — no inference. Shared analysis
  exists FOR orchestration across specialties; when there's only
  one specialty (single-persona substrate, or a private 1:1 turn),
  there is nothing to orchestrate, the suggested_angles map is
  correctly empty, and the LLM call is pure waste.

  Per [[intent-driven-api-not-hot-patches]]: the substrate doesn't
  pay an inference cost when the answer is structurally already
  known. Multi-persona rooms still go through the real inference
  path — the orchestrator needs the model's concept extraction to
  score specialties.

  Latency: this is the ~100s saving observed live above. From
  138s/turn to 35s/turn on Qwen 0.5B Intel Mac CPU.

## Doctrine

- [[source-drain-is-the-universal-pattern]]: admission IS the
  drain on the live-message source. Without admit, the substrate
  is the source-only half of the pair — chatbot, not brain.
- [[init-once-handle-then-lease-zero-copy-refs]]: admit/recall
  hold the brain mutex briefly; inference runs unheld. Same
  pattern as compose_for_turn.
- [[observability-is-half-the-architecture]]: the L2 state is
  now part of the per-turn log. Operators can see the engram
  store grow turn-over-turn without spelunking.
- [[no-fallbacks-ever]]: admit failures surface; they don't
  silently swap to a default.

## Known follow-ups (named so they don't get forgotten)

- Task #101: AdmissionState SQLite persistence — currently
  in-memory; Paige's L2 store resets at boot. Persisting it under
  ~/.continuum/personas/<name>/ closes the continual-learning loop
  across substrate restarts (the "Maya remembers things from
  three months ago" test the substrate is building toward).
- Algorithm 4 recall ordering — recall_recent(8) is recency only;
  the RecallMetadata salience × structural × recency scoring is
  in tree but not yet driving the recall path.
- Single-persona analyze short-circuit could be tightened: if
  known_specialties is exactly [persona's own specialty], skip;
  if known_specialties >= 2 but only one persona is actually
  responding this turn (sleep_mode etc filtered the rest), the
  orchestration is also empty in practice but the current code
  still pays the inference. Future slice once room-roster
  tracking is wired.

Closes #164.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Jun 3, 2026
…1519 (task #172)

Addresses Reviewer 3 (architecture + doctrine) BLOCK findings.
All seven items resolved via doc revisions; no code changes.

### Finding #1: Citizen-resolution gap (architecture doc commits to
signing without naming the writer-identity resolution)

**Fix:** ENTITY-CHAIN-OF-CUSTODY.md trimmed to slice 1 only.
Signing + writer-identity surface moved to
`docs/planning/ENTITY-CHAIN-OF-CUSTODY-ROADMAP.md` where slice 2 is
explicitly an open-question section naming the three writer-identity
candidates (per-store binding, WriterContext parameter, async-context
local) and committing to (a) per-store binding as the default until
the substrate decides otherwise.

### Finding #2: Claude can't hold an airc keypair — categorically
weaker than the doc claimed

**Fix:** Architecture doc replaces the "Claude has a keypair"
framing with the "originating agent" vs "attesting citizen"
distinction. Local citizens (personas, humans) are both — they
hold a real keypair and sign their own writes. Remote AIs (Claude,
openclaw, Hermes via API) split — the local adapter is the
attesting citizen (holds keypair, signs attestation); the remote
agent is the originator (recorded by name, not cryptographically
attested). The planning doc names this as slice 2's entity-schema
requirement (`author_peer_id` for attestor; `originating_agent:
Option<String>` for the remote-AI case).

### Finding #3: Forge-alloy generalization rhetorical, not
structural

**Fix:** Both ENTITY-CHAIN-OF-CUSTODY.md and the planning doc
downgrade the language from "shares the proof contract" to "shares
the proof pattern" (artifact + verifiable lineage). Forge artifacts
carry multi-party signatures + dependency refs + methodology
citations; entities carry single-writer chains. They rhyme; they
aren't the same contract. A future `trait ProofContract` (not yet
written) might capture the shared shape — that's a slice-2+
design decision now explicitly named.

### Finding #4: Two BaseEntity patterns violate compression

**Fix:** ENTITY-DERIVE-ARCHITECTURE.md now declares Pattern A
(bare `Uuid id` + `#[entity(primary_key)]`) as **CANONICAL** —
the default for new entities. Pattern B (embedded BaseEntity via
`#[serde(flatten)]`) is marked **transitional** — allowed only
when the entity has external callers that read `entity.base.*`
directly. A follow-up audit ticket should walk Pattern B users
and migrate any without legitimate access patterns.

### Finding #5: Schema evolution undiscussed → "swap serde_json
for serde_cbor" portability claim breaks

**Fix:** ENTITY-DERIVE-ARCHITECTURE.md adds a new §"Schema
evolution" section explicitly naming:
- What works today: additive `Option<T>` fields are
  forward-compatible.
- Current gaps: enum variants and field renames break round-trip
  unless `#[serde(other)]` / `#[serde(rename)]` is consistently
  applied (it isn't).
- Non-goals for v1: no auto-migration, no cross-version signature
  compat.
- What needs designing before grid-flow: schema_version field,
  per-entity migration registry, catch-all enum variants,
  explicit canonical form definition.

The portability claim is now scoped: "exports work between
continuums on the same SHA" — a real substrate-internal win,
not yet a cross-mesh promise.

### Finding #6: Cognition-pipeline contradiction (PR adds doc that
forbids will_respond + lands the contract in same diff)

**Reviewer 3 confirmed on re-review:** the load-bearing part is
already resolved. `service_loop.rs::serve_persona_loop` (commit
`9e5494d94`) drives the canonical respond() cycle and consumes
`PersonaResponse::Spoke|Silent` — NOT `will_respond`. The
`will_respond + response_text` JSON contract is fully contained
in `persona/rag_inspect.rs::inspect_persona_rag_with_inference`
and its ServiceModule wrapper.

**Fix:** PERSONA-COGNITION-PIPELINE.md §4 gains an explicit
carve-out paragraph for `inspect_persona_rag_with_inference`:
the `_with_inference` variant is allowed to use the JSON shape
because it's introspection (answering "would the persona respond
to this RAG snapshot?"), forbidden from being called by
`service_loop` or any production cognition path. The only
legitimate callers are the rag-inspect ServiceModule + tests.
Doc names this so future readers don't have to triangulate it
from the import graph; a grep-test / `#[deny]` lint that fires
if service_loop imports it would make the forbid structural
(named as follow-up).

### Finding #7: Slice 1 + six-slice doc = commitment debt

**Fix:** ENTITY-CHAIN-OF-CUSTODY.md trimmed from 174 lines to
~60 lines covering ONLY slice 1 (what IS). Slices 2–6 moved to
`docs/planning/ENTITY-CHAIN-OF-CUSTODY-ROADMAP.md` with each
slice's open questions explicitly named. The roadmap doc ends
with: "This roadmap is NOT a commitment. The substrate can
pursue these slices, defer them, or pivot. Per
[[constitutional-design-always-a-next-step]]: name the open
questions so the substrate has a path to a decision rather than
a commitment debt."

### Reviewer 3's newly-discovered concern (PR scope sprawl)

Reviewer flagged that the branch grew to 1240 files / +154k lines
since the original review (includes VDD recorder, multi_persona
stress baseline, inference-grpc, llama-cpp tests, etc). Strong
recommendation to split. **This is for Joel to decide** — surfaced
in the PR body update for visibility; not addressed in this
commit.

### Reviewer 1 + 2 status

Re-spawned reviewers verified slices A + B in parallel with
slice C. Reviewer 1 confirmed findings 1, 5 addressed; findings
2, 4, 6 code-fixed but lack compile-fail tests (need `trybuild`);
findings 3, 7, 8, 9 partial or unaddressed. Slice A2 would close
those. Reviewer 2 verdict pending at commit time.

### Test impact

Zero — slice C is documentation only. No code changes; no test
runs needed.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Jun 3, 2026
…1519 (task #173)

Addresses Reviewer 1's remaining BLOCK findings on PR #1519. Four
real correctness/ergonomics fixes; trybuild harness deferred to
focused follow-up (rationale in code comment).

### Finding #7: External-crate path resolution

The macro previously emitted `::continuum_core::*` absolute paths.
Any consumer that renames the dep in `Cargo.toml`
(`continuum-core = { package = "continuum-core-alt" }`) or a
re-exporting facade crate would get unresolved-path errors —
because the absolute path bakes in the conventional name. The
self-alias `extern crate self as continuum_core;` in continuum-core's
`lib.rs` only fixed the in-crate case, not downstream consumers.

**Fix:** added `proc-macro-crate` dep. New helper
`resolve_continuum_core_path()` calls `crate_name("continuum-core")`
at codegen time; returns `crate` when the consumer IS continuum-core
itself, or `::<chosen-name>` otherwise. The Entity derive now emits
paths prefixed with that resolved ident. `cascade_rule_tokens` was
also updated to accept the resolved prefix as a parameter (free
functions can't capture the local `core` token from `derive_entity`).

### Finding #8: Empty composite-index name

`#[entity(index(name = "", fields = ["a"]))]` previously parsed
cleanly and emitted `SchemaIndex { name: "".to_string(), … }`. The
SQL adapter would later try `CREATE INDEX `` ON …` and fail with a
cryptic error far from the macro span.

**Fix:** `parse_composite_index` now rejects empty `name` with the
exact-span error "composite index `name` must be non-empty".

### Finding #9: `to_camel_case` edge cases

The function mishandled three cases:
- `_leading_underscore` → produced `Leading…` (wrong; serde
  preserves leading underscores: `_field` stays `_field`)
- `field__double` → produced `fieldDouble` but only by accident
  (the doubled `_` set capitalize_next twice; behavior was
  fragile)
- `trailing_` → produced `trailing_` (wrong; serde drops the
  trailing rust-ident workaround: `type_` → wire `type`)

**Fix:** rewritten with explicit handling:
- Leading `_`s preserved (peekable loop consumes them literally
  before the main pass).
- Internal `_`s set capitalize_next; doubled `_`s coalesce
  uniformly (no double-trigger).
- Trailing `_` is dropped (final capitalize_next has no following
  char to consume).

Inline unit tests pin the contract:
- `to_camel_case_handles_edge_cases` covers all three cases plus
  the standard snake → camel translation.
- `to_camel_case_preserves_existing_case` confirms non-underscore-
  preceded chars don't accidentally uppercase.

### Finding #3: Multi-span on duplicate-BaseEntity error

The error span pointed only at the SECOND offending field. Already
addressed in Slice A by tracking the prior field name in
`saw_base: Option<String>` and including it in the error text. The
reviewer wanted a multi-span (rustc highlights both fields) which
requires `syn::Error::combine` — landing that is a small additional
ergonomic win but not a correctness gap. Deferred with the
trybuild harness slice.

### Reviewer 2 cosmetic: stale `mem::forget` comment

Removed the lingering `// mem::forget so the path persists past
test end` doc comment in `engram.rs:869-870` — the call itself was
removed in Slice B; the comment was stale.

### Trybuild compile-fail tests (deferred follow-up)

Findings #2 (primary_key + foreign_key conflict), #4 (unknown
attribute keys), #6 (multi-dot FK targets) are correctly handled
in code (Slice A) but lack a structural test harness. `trybuild` is
the canonical tool. Deferred because the test files need
`continuum-core` types in scope (Uuid, BaseEntity, etc.) — the
harness belongs alongside the existing derive-test fixtures in
`continuum-core/tests/compile_fail/`, not inside the proc-macro
crate. Landing trybuild + the .stderr fixtures is a focused
follow-up slice; documented in `Cargo.toml` so the next person
picking it up has the rationale.

### Test results

- ORM family: **193/193** green (unchanged from Slice B)
- Admission family: **51/51** green
- Engram family: **61/61** green
- RecallMetadata family: **20/20** green
- continuum-orm-derive inline tests: **2/2** green (new
  to_camel_case edge-case tests)
- Slice A2 total: **327 tests** (325 prior + 2 new)

Per [[agent-review-as-acceptable-approval]]: re-spawning Reviewer 1
should flip Slice A's verdict to APPROVE on findings 1, 5, 7, 8, 9.
Findings 2, 4, 6 are correct-in-code with the trybuild deferral
explicitly named.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Jun 4, 2026
…se, doc + test invariant

Addresses Reviewer 1's BLOCK findings on PR #1523 (Slice 1B of #142).

## Finding #1 (BLOCKING) — seed.json durability bug

`PersonaInstanceManagerModule::bootstrap_one` was writing seed.json
with `intent.persona_id` — the PRE-collapse Uuid that the runtime
constructor discards. The `seed.rs` contract says "Must NOT change
across restarts"; under Slice 1B the persona_id stored on disk was
permanently stale (= the discarded `Uuid::new_v4()` from the
mint provider), never reconciled with the actual substrate
identity (= peer_id).

**Fix:** write the POST-collapse identity to seed.json:
- `persona_id: runtime.persona_id()` (which equals
  `airc.peer_id().as_uuid()` post-Slice-1B)
- `agent_name: runtime.agent_name()`

The on-disk Uuid IS the substrate identity (peer_id), and seed.json
becomes the durable projection of the post-collapse state.

## Finding #2 (BLOCKING) — warn-on-divergence is operator log noise

`ResumeOrMintProvider::mint_fresh_intent` allocates
`persona_id = Uuid::new_v4()` BEFORE the keypair is generated, so
the input persona_id is statistically guaranteed to differ from
peer_id for every fresh mint. The previous Slice 1B implementation
logged the divergence at `warn!`, which would have spammed
operators on every persona boot (12-14 personas × every restart =
constant noise).

**Fix:** downgraded both bootstrap + from_attached divergence logs
from `warn!` to `debug!`. Comment names the reason: divergence is
EXPECTED for fresh mints; warn is reserved for genuine bugs.

## Finding #4 — PersonaInstanceInfo doc stale post-Slice-1B

Doc strings on `PersonaInstanceInfo.persona_id` / `peer_id` claimed
they were independent. Post-Slice-1B they're equal by invariant.

**Fix:** updated the struct doc with an `## INVARIANT` block
naming the Slice 1B contract: `persona_id == peer_id`. Individual
field docs updated to reflect post-collapse semantics. The
`agent_name` field's doc explicitly notes the doctrinal break
(name still derives from the historical pre-bootstrap Uuid, not
from peer_id) so future readers know the gap is intentional and
deferred to a separate slice.

## Finding #5 — test fixtures bypassed the invariant

`supervisor::tests::fake_instance` (supervisor.rs:499) and
`service_loop` test fixture (service_loop.rs:592) both constructed
PersonaInstanceInfo with two independent `Uuid::new_v4()` calls,
violating the invariant the new doc claims is universal.

**Fix:** both fixtures now use ONE Uuid for both persona_id +
peer_id (named `peer_id` / `persona_peer_id` consistently). Honors
the same invariant production sees. Comments name the doctrine.

## Finding #6 — no test gates the invariant

Reviewer #1 said `StubAircCitizen` could be used to write a unit
test that pins the invariant. They were right.

**Fix:** added
`persona::supervisor::tests::persona_context_identity_id_matches_registry_key`
which constructs a `PersonaInstanceInfo` via `fake_instance` and
asserts both that the fixture itself honors the invariant
(`persona_id == peer_id`) AND that the projected
`Context::identity().id` matches the registry-key path
(`identity.persona_id`). If a future edit reintroduces the
divergence, the test fails — closing the regression class per
[[every-error-is-an-opportunity-to-battle-harden]].

## Test results

- `persona::*` — 750/750 pass (was 749 — the new invariant test
  added one)
- `context::*` — 4/4 pass
- No regressions

## Findings deferred

- **Finding #3** — `agent_name_from_identity(peer_id)` mint-flow
  restructure. PR explicitly defers this; the PersonaInstanceInfo
  doc now calls it out so future readers know the name derivation
  is intentionally off-doctrine until a separate slice routes it
  through peer_id.
- **Finding #7** — Drop log line format change (`persona_id =
  %self.persona_id` now equals peer_id). Documented in this
  commit's PR body so operator runbooks have a heads-up.

## Doctrine

Per [[every-error-is-an-opportunity-to-battle-harden]]: each
finding named the immediate fix AND the rigging that catches the
class next time. Finding #1's seed.json fix is the rigging that
catches durability divergence; Finding #6's invariant test is the
rigging that catches the Uuid-divergence class at unit time.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Jun 4, 2026
…ice 1B of #142) (#1523)

* feat(persona): collapse persona_id := peer_id at runtime boundary (Slice 1B of #142)

Resolves the active Uuid-divergence sharp edge documented in PR
#1522: `ctx.identity().id` (= peer_id) ≠ `ctx.identity.persona_id`
(= continuum-side seed) because the two were independently-minted
Uuids. After this slice, they are the same value — `ctx.identity().id`
is safe to use as a registry key, unblocking Slice 3
(ClaudeContext / JtagContext / bootstrap paths per kind).

## Why

Per [[persona-identity-derives-from-source-id]] +
[[airc-is-the-session-not-a-feature]]: a persona has ONE unique
identifier — the airc peer_id (Ed25519 keypair Uuid). The
continuum-side `persona_id` originally minted via
`Uuid::new_v4()` pre-bootstrap was historical artifact; airc-lib is
the cryptographic ground truth.

Slice 2 of #142 introduced `Context::identity()` returning
`Identity.id = peer_id`. The persona registry was (and is) keyed
on `PersonaInstanceInfo.persona_id`. Until this slice, those were
two different Uuids for the same persona — any caller mixing
paths got silent registry-lookup misses. Reviewer 1 on PR #1522
caught this as a BLOCK and the fix was scoped to Slice 1B (this
PR).

## What changes

### `persona/airc_runtime.rs::bootstrap` + `from_attached`

Both constructors now reseat `persona_id := airc.peer_id().as_uuid()`
post-attach. The input `persona_id` parameter is retained for API
continuity but its value is logged-then-discarded:
- If the input differs from `peer_id`, a `tracing::warn!` fires
  naming the discrepancy so callers can spot the unused arg.
- The runtime's stored `persona_id` is always `peer_id` post-
  construction. Every downstream consumer (registry, IPC,
  PersonaInstanceInfo, Context impl) sees a consistent Uuid.

Future API cleanup will drop the parameter entirely; for now the
warn-on-divergence is the operator-visible signal that callers can
prune the redundant argument.

### `persona/supervisor.rs` (Context impl)

The transitional "ACTIVE SHARP EDGE — READ BEFORE USING" doc block
above `impl Context for PersonaContext` is replaced with a calmer
section documenting that `ctx.identity().id IS the registry key`
post-Slice-1B. The "DO NOT feed ctx.identity().id back into the
persona registry" warning is removed because the divergence it
warned about is now closed.

## What this slice does NOT do

- Doesn't change `agent_name` derivation. For NEW personas,
  `agent_name` is still derived from the (now-discarded) input
  `persona_id` via `agent_name_from_identity` at the
  `ResumeOrMintProvider` layer. Per the doctrine, name should
  derive from `peer_id`; that fix requires restructuring the
  mint flow to generate the keypair BEFORE deriving the name.
  Tracked as future cleanup; not blocking for Slice 3.
- Doesn't drop the `persona_id` parameter from the constructors.
  The API stays back-compat for now; future cleanup prunes
  unused-arg call sites + drops the parameter.
- Doesn't migrate `PersonaInstanceInfo` to be an `Identity` entity
  (that's a separate ORM-persistence slice). The field collapse
  is sufficient for the registry-key-safety invariant Slice 3
  needs.

## Tests

- `persona::airc_runtime`: 6/6 pass (existing tests cover the
  constructor paths)
- `persona::*`: 749/749 pass — zero regressions across the
  persona module
- `context::*`: 4/4 pass — Slice 2's tests still green

The reviewer asked for a test pinning the collapse invariant
(`runtime.persona_id() == runtime.airc().peer_id().as_uuid()`).
Such a test requires constructing an `Arc<airc_lib::Airc>` with a
known peer_id, which airc-lib doesn't expose a stub for; existing
integration tests (`#141`, `airc_chat_demo`) exercise the full
bootstrap path against a real daemon and would catch any
regression. If a unit-level invariant test is warranted, it
belongs in airc-lib's test-fixtures crate (mocked Airc handle).
Filed as a follow-up if pressure builds.

## Doctrine

- [[persona-identity-derives-from-source-id]] — peer_id IS the
  substrate identity; persona_id was the historical artifact
- [[airc-is-the-session-not-a-feature]] — airc identity IS the
  session, no parallel identifier
- [[every-error-is-an-opportunity-to-battle-harden]] — the Slice
  2 reviewer caught this; Slice 1B closes the class
- [[no-fallbacks-ever]] — warn-on-divergence is observability, not
  fallback; the runtime ALWAYS uses peer_id, no conditional path
- [[organization-purity-as-we-migrate]] — collapse the divergent
  field at the data-flow boundary instead of papering over with
  registry tricks

## Sequencing

Unblocks Slice 3 (ClaudeContext / JtagContext + bootstrap paths
per actor kind) which needs `ctx.identity().id` to be a usable
registry/lookup key on the universal Context surface.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* fix(persona): review fixes for #1523 — seed.json durability, warn-noise, doc + test invariant

Addresses Reviewer 1's BLOCK findings on PR #1523 (Slice 1B of #142).

## Finding #1 (BLOCKING) — seed.json durability bug

`PersonaInstanceManagerModule::bootstrap_one` was writing seed.json
with `intent.persona_id` — the PRE-collapse Uuid that the runtime
constructor discards. The `seed.rs` contract says "Must NOT change
across restarts"; under Slice 1B the persona_id stored on disk was
permanently stale (= the discarded `Uuid::new_v4()` from the
mint provider), never reconciled with the actual substrate
identity (= peer_id).

**Fix:** write the POST-collapse identity to seed.json:
- `persona_id: runtime.persona_id()` (which equals
  `airc.peer_id().as_uuid()` post-Slice-1B)
- `agent_name: runtime.agent_name()`

The on-disk Uuid IS the substrate identity (peer_id), and seed.json
becomes the durable projection of the post-collapse state.

## Finding #2 (BLOCKING) — warn-on-divergence is operator log noise

`ResumeOrMintProvider::mint_fresh_intent` allocates
`persona_id = Uuid::new_v4()` BEFORE the keypair is generated, so
the input persona_id is statistically guaranteed to differ from
peer_id for every fresh mint. The previous Slice 1B implementation
logged the divergence at `warn!`, which would have spammed
operators on every persona boot (12-14 personas × every restart =
constant noise).

**Fix:** downgraded both bootstrap + from_attached divergence logs
from `warn!` to `debug!`. Comment names the reason: divergence is
EXPECTED for fresh mints; warn is reserved for genuine bugs.

## Finding #4 — PersonaInstanceInfo doc stale post-Slice-1B

Doc strings on `PersonaInstanceInfo.persona_id` / `peer_id` claimed
they were independent. Post-Slice-1B they're equal by invariant.

**Fix:** updated the struct doc with an `## INVARIANT` block
naming the Slice 1B contract: `persona_id == peer_id`. Individual
field docs updated to reflect post-collapse semantics. The
`agent_name` field's doc explicitly notes the doctrinal break
(name still derives from the historical pre-bootstrap Uuid, not
from peer_id) so future readers know the gap is intentional and
deferred to a separate slice.

## Finding #5 — test fixtures bypassed the invariant

`supervisor::tests::fake_instance` (supervisor.rs:499) and
`service_loop` test fixture (service_loop.rs:592) both constructed
PersonaInstanceInfo with two independent `Uuid::new_v4()` calls,
violating the invariant the new doc claims is universal.

**Fix:** both fixtures now use ONE Uuid for both persona_id +
peer_id (named `peer_id` / `persona_peer_id` consistently). Honors
the same invariant production sees. Comments name the doctrine.

## Finding #6 — no test gates the invariant

Reviewer #1 said `StubAircCitizen` could be used to write a unit
test that pins the invariant. They were right.

**Fix:** added
`persona::supervisor::tests::persona_context_identity_id_matches_registry_key`
which constructs a `PersonaInstanceInfo` via `fake_instance` and
asserts both that the fixture itself honors the invariant
(`persona_id == peer_id`) AND that the projected
`Context::identity().id` matches the registry-key path
(`identity.persona_id`). If a future edit reintroduces the
divergence, the test fails — closing the regression class per
[[every-error-is-an-opportunity-to-battle-harden]].

## Test results

- `persona::*` — 750/750 pass (was 749 — the new invariant test
  added one)
- `context::*` — 4/4 pass
- No regressions

## Findings deferred

- **Finding #3** — `agent_name_from_identity(peer_id)` mint-flow
  restructure. PR explicitly defers this; the PersonaInstanceInfo
  doc now calls it out so future readers know the name derivation
  is intentionally off-doctrine until a separate slice routes it
  through peer_id.
- **Finding #7** — Drop log line format change (`persona_id =
  %self.persona_id` now equals peer_id). Documented in this
  commit's PR body so operator runbooks have a heads-up.

## Doctrine

Per [[every-error-is-an-opportunity-to-battle-harden]]: each
finding named the immediate fix AND the rigging that catches the
class next time. Finding #1's seed.json fix is the rigging that
catches durability divergence; Finding #6's invariant test is the
rigging that catches the Uuid-divergence class at unit time.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Jun 4, 2026
…not-fallback, legacy detection tests

Addresses Reviewer 1's BLOCK findings on PR #1525 (Slice 4 of #142).

## Finding #1 (BLOCKING) — hard build break

`context::tests::log_actor_action_takes_any_context` constructed
an `Identity` literal missing the new mandatory `agent_provider`
field. `cargo test --lib -p continuum-core context::` failed to
compile with E0063. The sibling
`stub_context_implements_context` HAD the field; this one was
missed in the refactor.

**Fix:** added `agent_provider: None,` to the test's Identity
literal (`IdentityKind::Jtag`; non-Agent kinds get None).

The earlier test run that returned exit 0 was misleading — the
tmp filesystem ran out of space and output was truncated; the
actual compile error was hidden. Rerun confirms 13/0 pass for
`context::` after the fix.

## Finding #2 (BLOCKING) — stale StubContext outlier-validation doc

The `StubContext` doc at `context/mod.rs:151-161` still named
`ClaudeContext` as the validation outlier. Slice 4 replaced
`ClaudeContext` with `AgentContext`; the doc wasn't updated.

**Fix:** doc now names `AgentContext` (Slice 4, parameterized by
provider, ONE shape for Claude/Codex/Gemini/Hermes/future). The
three-impl outlier story remains intact; the named impl is now
correct.

## Finding #3 (BLOCKING) — LegacyLayoutDetected never exercised

The "actionable `mv` command" message is the load-bearing safety
claim of the migration story per [[no-fallbacks-ever]], and zero
tests fired it. A regression flipping a path component or
breaking the `new_parent` calculation would have passed CI
silently.

**Fix:** added three legacy-detection tests:

1. `context::agent::tests::legacy_claude_layout_hard_errors_with_mv_command`
   — seeds `<tmp>/claudes/default/airc/`, bootstraps with
   provider=claude, asserts `LegacyLayoutDetected` with exact
   `legacy` / `new` / `new_parent` paths.
2. `context::agent::tests::non_claude_provider_ignores_claude_legacy`
   — seeds the same Claude legacy, bootstraps with provider=codex,
   asserts the detection does NOT false-positive on a different
   provider's mint.
3. `persona::airc_runtime::tests::legacy_persona_layout_hard_errors_with_mv_command`
   — seeds `<tmp>/personas/maya/airc/`, bootstraps PersonaAircRuntime
   for "maya", asserts the same shape.

Per [[every-error-is-an-opportunity-to-battle-harden]]: the
message is load-bearing safety; these tests are the rigging that
catches the regression class.

## Finding #4 — `unwrap_or("unknown")` was a soft fallback

`citizen_home_path(.., kind=Agent, provider=None, ..)` previously
joined an `"unknown"` segment, silently landing the agent under
`citizens/agents/unknown/<label>/airc/`. Per the cited
`[[no-fallbacks-ever]]` doctrine this is exactly what the
substrate refuses — a programming bug ("forgot to thread the
provider") should surface AT the call site, not produce a
directory full of indistinguishable agents.

**Fix:** changed to `.expect("provider is REQUIRED when kind ==
Agent")` with operator-actionable message. Panic point IS the
call site; bug fix is local. Pinned by
`context::citizen_path::tests::agent_without_provider_panics`
(`#[should_panic]`).

`AgentContext::bootstrap` always passes `Some(&provider)`, so
this is purely defensive — the panic catches future call sites
that misuse the helper.

## Findings deferred (non-blocking nits)

- **#5** — Lowercase enforcement debug-assert on AgentContext's
  provider input. The substrate-is-mechanism-not-policy choice
  stands; documented in doc-comment. Could be tightened in a
  follow-up if pressure builds.
- **#6** — `provider-label` agent_name cross-host collision
  (e.g. two machines both with `claude-default`). Existing
  Slice-3-acknowledged hazard now carried forward to all Agent
  providers. Per the original review, the substrate routes on
  peer_id (cryptographic, never collides); the human-readable
  label collision is a UX rough edge. Suffix-peer_id-short
  remediation tracked as a follow-up if/when `airc whois <name>`
  starts mattering more.

## Test results

- `context::*` — 13/0 pass (was 6; +7 for Slice 4 legacy
  detection + panic invariant + the existing fix tests)
- `persona::airc_runtime::*` — 7/0 pass (was 6; +1 for persona
  legacy detection)
- No regressions

## Doctrine

- [[no-fallbacks-ever]] — soft `unknown` fallback replaced with
  panic at the call site
- [[every-error-is-an-opportunity-to-battle-harden]] — legacy
  detection now has the rigging that catches the class
- CLAUDE.md "never commit code until you validate it works" —
  the earlier exit-0 was a misleading-truncation signal; the
  full build+test loop now passes locally

Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Jun 4, 2026
…142) (#1525)

* feat(context): symmetric citizens/ layout + AgentContext (Slice 4 of #142)

Joel 2026-06-04: "should use a more formulaic naming of directories
for all users probably, right? Assume this is all headless rust" +
"What about Codex and Gemini etc? Use always lowercase." Three
coupled refactors that only make sense together — doing them
separately would create transient asymmetric states.

## 1. Symmetric directory layout

Every citizen home now lives under one root:

```
<continuum_root>/citizens/personas/<name>/airc/
<continuum_root>/citizens/agents/<provider>/<label>/airc/
<continuum_root>/citizens/humans/<host>/airc/           (Slice 5 wires)
<continuum_root>/citizens/jtags/<id>/airc/              (Slice 5 wires)
<continuum_root>/citizens/webs/<tab>/airc/              (Slice 5 wires)
```

All lowercase. Plural kinds. agents/ gets the 3-level path because
provider is meaningful (claude / codex / gemini / hermes / future).
ONE helper `citizen_home_path(continuum_root, kind, provider, label)`
called from every kind's bootstrap. Slice 5 wires the remaining
kinds; this slice ships the foundation + personas + agents.

## 2. IdentityKind refactor — drop Claude+Codex, add Agent

Slice 1 reviewer flagged the sealed enum as an extensibility
concern (GPT-5, Claude-5, Gemini, future). Per
[[organization-purity-as-we-migrate]] the right collapse:

```rust
pub enum IdentityKind {
    Persona,
    Agent,    // <-- replaces Claude + Codex; provider in agent_provider
    Human,
    Jtag,
    Web,
}
```

New field `Identity.agent_provider: Option<String>` carries the
specific provider for Agent kinds (`"claude"`, `"codex"`,
`"gemini"`, ...). `None` for non-Agent kinds. Lowercase by
convention; substrate does NOT auto-lowercase (would mask caller
bugs).

Why `String` and not a sub-enum: adding a new agent provider
should NOT require a substrate release. The few sites that branch
on provider (future tool-use harness, model-tier metadata) match
the string. Open-ended.

## 3. AgentContext — replaces ClaudeContext, parameterized by provider

Slice 3's `ClaudeContext` generalizes to `AgentContext`. Same
shape, same bootstrap contract — but `provider: String` carries
which flavor. Claude becomes `AgentContext::bootstrap(..., "claude",
...)`, Codex calls with `"codex"`, Gemini with `"gemini"`. Same
struct, same trait impl, same `Cow::Borrowed(&self.identity)`
zero-clone shape.

`AircHandleAdapter` lifts from `context/claude.rs` (private) to
`context/airc_adapter.rs` (`pub(crate)`) per Slice 3 reviewer's
non-blocking nit — every future non-persona kind reuses one impl.

`ClaudeContext` / `ClaudeMetadata` / `ClaudeContextError` →
`AgentContext` / `AgentMetadata` / `AgentContextError`.
`bin/claude_join_demo.rs` → `bin/agent_join_demo.rs`, defaulting
to provider=claude but parameterizable via
`CONTINUUM_AGENT_PROVIDER` env.

## Migration — hard-error on legacy layout

Existing personas have homes at `<root>/personas/<name>/airc/`.
Existing Claude sessions have homes at `<root>/claudes/<label>/airc/`.
Per [[no-fallbacks-ever]] the bootstrap path REFUSES to silently
use the legacy paths. New error variants:

- `PersonaAircRuntimeError::LegacyLayoutDetected`
- `AgentContextError::LegacyLayoutDetected`

Both messages spell out the exact `mv` command operator should
run. Operator sees the rename + retries. No silent migration.

## Tests

- `context::citizen_path::*` — 4 new tests (persona path,
  agent-provider segment, humans/jtags/webs skip provider,
  legacy detection)
- `context::agent::*` — 2 tests (zero-clone Cow::Borrowed, multi-
  provider uniformity proves Claude/Codex/Gemini all fit one
  AgentContext shape)
- `context::tests::stub_context_implements_context` updated to
  use `IdentityKind::Agent` + `agent_provider: Some("claude")`
- `identity::tests::identity_round_trips_through_orm` updated to
  exercise the new shape (one Persona + one Agent with provider)
- `identity::tests::identity_schema_is_derived` includes
  `agentProvider` in the schema check
- `persona::airc_runtime::tests::bootstrap_resolves_home_under_personas_directory`
  updated to assert the new `citizens/personas/<name>/airc/` path
- All test families pass; no regressions across identity, context,
  persona

`agent_join_demo` compiles + has the right CLI signature
(`CONTINUUM_AGENT_PROVIDER` + `CONTINUUM_AGENT_LABEL` env vars).

## Doctrine

- [[airc-is-the-session-not-a-feature]] — symmetric layout reflects
  the every-citizen-is-the-same-kind-of-citizen substrate model
- [[organization-purity-as-we-migrate]] — collapse asymmetric kinds
  + provider into one extensible shape
- [[no-fallbacks-ever]] — legacy layout hard-errors, operator sees
  the exact mv command
- CLAUDE.md outlier discipline — Agent(provider: String) is the
  open-end version of the sealed enum Slice 1 reviewer flagged
- CLAUDE.md outlier validation — `AgentContext` with 4+ providers
  (claude / codex / gemini / hermes) all flow through ONE shape;
  proves the generalization holds beyond compile

## Out of scope (Slice 5)

- `JtagContext` concrete + bootstrap
- `HumanContext` concrete + bootstrap
- `WebContext` (deferred until browser-tab actor exists)

Slice 5 becomes mechanical given this foundation: each new kind
calls `citizen_home_path` + `airc_lib::Airc::attach_as` +
constructs Identity + wraps in AircHandleAdapter. Same shape, three
times.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* fix(context): review fixes for #1525 — build break, stale doc, panic-not-fallback, legacy detection tests

Addresses Reviewer 1's BLOCK findings on PR #1525 (Slice 4 of #142).

## Finding #1 (BLOCKING) — hard build break

`context::tests::log_actor_action_takes_any_context` constructed
an `Identity` literal missing the new mandatory `agent_provider`
field. `cargo test --lib -p continuum-core context::` failed to
compile with E0063. The sibling
`stub_context_implements_context` HAD the field; this one was
missed in the refactor.

**Fix:** added `agent_provider: None,` to the test's Identity
literal (`IdentityKind::Jtag`; non-Agent kinds get None).

The earlier test run that returned exit 0 was misleading — the
tmp filesystem ran out of space and output was truncated; the
actual compile error was hidden. Rerun confirms 13/0 pass for
`context::` after the fix.

## Finding #2 (BLOCKING) — stale StubContext outlier-validation doc

The `StubContext` doc at `context/mod.rs:151-161` still named
`ClaudeContext` as the validation outlier. Slice 4 replaced
`ClaudeContext` with `AgentContext`; the doc wasn't updated.

**Fix:** doc now names `AgentContext` (Slice 4, parameterized by
provider, ONE shape for Claude/Codex/Gemini/Hermes/future). The
three-impl outlier story remains intact; the named impl is now
correct.

## Finding #3 (BLOCKING) — LegacyLayoutDetected never exercised

The "actionable `mv` command" message is the load-bearing safety
claim of the migration story per [[no-fallbacks-ever]], and zero
tests fired it. A regression flipping a path component or
breaking the `new_parent` calculation would have passed CI
silently.

**Fix:** added three legacy-detection tests:

1. `context::agent::tests::legacy_claude_layout_hard_errors_with_mv_command`
   — seeds `<tmp>/claudes/default/airc/`, bootstraps with
   provider=claude, asserts `LegacyLayoutDetected` with exact
   `legacy` / `new` / `new_parent` paths.
2. `context::agent::tests::non_claude_provider_ignores_claude_legacy`
   — seeds the same Claude legacy, bootstraps with provider=codex,
   asserts the detection does NOT false-positive on a different
   provider's mint.
3. `persona::airc_runtime::tests::legacy_persona_layout_hard_errors_with_mv_command`
   — seeds `<tmp>/personas/maya/airc/`, bootstraps PersonaAircRuntime
   for "maya", asserts the same shape.

Per [[every-error-is-an-opportunity-to-battle-harden]]: the
message is load-bearing safety; these tests are the rigging that
catches the regression class.

## Finding #4 — `unwrap_or("unknown")` was a soft fallback

`citizen_home_path(.., kind=Agent, provider=None, ..)` previously
joined an `"unknown"` segment, silently landing the agent under
`citizens/agents/unknown/<label>/airc/`. Per the cited
`[[no-fallbacks-ever]]` doctrine this is exactly what the
substrate refuses — a programming bug ("forgot to thread the
provider") should surface AT the call site, not produce a
directory full of indistinguishable agents.

**Fix:** changed to `.expect("provider is REQUIRED when kind ==
Agent")` with operator-actionable message. Panic point IS the
call site; bug fix is local. Pinned by
`context::citizen_path::tests::agent_without_provider_panics`
(`#[should_panic]`).

`AgentContext::bootstrap` always passes `Some(&provider)`, so
this is purely defensive — the panic catches future call sites
that misuse the helper.

## Findings deferred (non-blocking nits)

- **#5** — Lowercase enforcement debug-assert on AgentContext's
  provider input. The substrate-is-mechanism-not-policy choice
  stands; documented in doc-comment. Could be tightened in a
  follow-up if pressure builds.
- **#6** — `provider-label` agent_name cross-host collision
  (e.g. two machines both with `claude-default`). Existing
  Slice-3-acknowledged hazard now carried forward to all Agent
  providers. Per the original review, the substrate routes on
  peer_id (cryptographic, never collides); the human-readable
  label collision is a UX rough edge. Suffix-peer_id-short
  remediation tracked as a follow-up if/when `airc whois <name>`
  starts mattering more.

## Test results

- `context::*` — 13/0 pass (was 6; +7 for Slice 4 legacy
  detection + panic invariant + the existing fix tests)
- `persona::airc_runtime::*` — 7/0 pass (was 6; +1 for persona
  legacy detection)
- No regressions

## Doctrine

- [[no-fallbacks-ever]] — soft `unknown` fallback replaced with
  panic at the call site
- [[every-error-is-an-opportunity-to-battle-harden]] — legacy
  detection now has the rigging that catches the class
- CLAUDE.md "never commit code until you validate it works" —
  the earlier exit-0 was a misleading-truncation signal; the
  full build+test loop now passes locally

Co-Authored-By: Claude Opus 4.7 <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Jun 5, 2026
PR #1529 spawned 3 adversarial reviewers per
`[[agent-review-as-acceptable-approval]]`. Reviewer 1 (doctrine)
and Reviewer 2 (architectural purity) returned with BLOCK verdicts;
this commit addresses every blocking concern they raised.

## Fixed in this commit

### Reviewer 1 + 2 #1: `RouteDecision::Broadcast` silent fallback

`airc_transport.rs` — the `Broadcast` arm mapped to
`MentionTarget::All`, silently broadcasting to every peer in the
room (not just env replicas of the target peer). Combined with
the handler's lack of peer filter, `airc://maya:*/notification/send`
would wake Niko too.

Per `[[no-fallbacks-ever]]`: hard-error like the `Room` arm does
until per-peer env-fanout has its own slice. Names the missing
piece in the error so callers can act.

### Reviewer 1 #2: `unreachable!()` on dispatch hot path

`airc_transport.rs` — the `Local` match arm used `unreachable!()`,
which panics in debug and is UB-adjacent in release. Replaced
with a typed `Err("BUG: ...")` so an invariant violation surfaces
as an error, not a process panic.

### Reviewer 2 #3: handler discards `kind` + `env`

`command_handler.rs::process_request` — always built
`CommandUri::local(&path)`, discarding the request envelope's
`kind` and `env` fields. A remote dispatch of
`airc://maya:vr/widget/show` would silently run as a non-env-aware
local Local call.

Fixed: hard-error if `kind != "peer"` (room/broadcast semantics need
their own slice) and if `env.is_some()` (env-aware local routing
needs its own slice — the substrate has `EnvironmentId` typed but
no per-env service registration yet). Names what's missing in each
error.

### Reviewer 1 #3: missing test for non-Json result handling

Added `process_request_refuses_non_json_command_result` that wires
a `CannedModule` returning `CommandResult::Handle(...)` and asserts
the handler refuses to send a HandleRef over the wire (returns
typed error, not silent coercion).

### Reviewer 2 #4: `CallerIdentity` not threaded to interceptors

`CommandInterceptor::try_route` signature changed from
`(command, params)` to `(command, params, caller)`. The
`CommandExecutor::dispatch` was passing caller to the gate but
NOT to interceptors, so a remote `airc://this-peer/code/edit`
reached `AircInterceptor` / `GridInterceptor` as if it were a
local in-process invocation. That's a silent privilege-escalation
seam.

Updated trait + 2 production impls (`AircInterceptor`,
`GridInterceptor`) + 5 test impls. Production impls don't use
caller today — they ignore the new param — but the seam is in
place so future capability-token / sentinel-quorum interceptors
can be load-bearing without another trait change.

`execute_inner` also takes `caller: Option<&CallerIdentity>` now.
Threaded through from `dispatch`.

### Reviewer 2 #6: `time!` macro `_enter`-across-await foot-gun

`routing/macros.rs` — the `time!` macro held `_enter = span.enter()`
across `$body`, breaking `URI_STACK` if `$body` contained `.await`
(the same async anti-pattern the `d1cf19dc5` dispatch fix removed
from the dispatcher). Common shape `time!("infer",
run_inference(...).await)` would silently break the URI ancestry
chain.

Renamed to `time_sync!` and documented that for async timing,
callers use `.instrument(span).await` directly. The
substrate-wide foot-gun is removed without adding a colliding
`time_async!` (one already exists in `logging/timing.rs` with a
different shape — RAII TimingGuard, not tracing span).

## Bonus refactor

`CommandRequestHandler::process_request` is now `pub` and
delegates to a new `process_request_via(executor, parsed)` that
takes `&CommandExecutor` directly. This lets tests exercise the
executor-side logic without standing up an `Arc<Airc>` placeholder
(which the original test draft did with `unsafe transmute` — bad
idea; replaced with clean abstraction).

The `LocalGridTransport` fixture (forward work) leases the same
shape to drive multi-CommandExecutor in-process tests.

## Deferred to follow-up tasks (NOT in this commit)

Reviewer 2 raised two more concerns the substrate is ready to
address as their own slices:

  - **#5 `Verdict` → `String` at dispatch boundary** — the gate's
    typed `Verdict` becomes a `format!`'d string in
    `Err(format!("forbidden: {reason}"))`. Should become a typed
    `SubstrateError<E>` per the design doc's "Typed end-to-end"
    section. Tracked.

  - **#2 envelope `peer` field** — `AircCommandRequest` drops the
    peer identity on `from_route_decision` (relies on airc routing
    as the only locus). Once room broadcast semantics land, the
    handler will need to know which peer was the original target.
    Tracked.

These are real concerns but each is its own slice; landing them
here would balloon the touch-up. Both filed as follow-up.

## Tests

All routing + command_executor + command_interceptor tests pass.
The new tests:

  - `process_request_rejects_room_kind`
  - `process_request_rejects_broadcast_kind`
  - `process_request_rejects_env_targeted_dispatch`
  - `process_request_refuses_non_json_command_result`

Each pins a `[[no-fallbacks-ever]]` property at a specific seam.
A future refactor that re-introduces silent substitution at any of
these points fails one of these tests loudly.

card: fa25de80-0c1b-4de5-8ff9-524d95e303cd

Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Jun 7, 2026
* docs(planning): HEADLESS-PERSONA-HOST-LOOP — slice 13 design

Captures the boot wire-up plan for #133 slice 13 before touching
the load-bearing `ipc::start_server` flow.

Documents:
- The "moment-of-truth" gap: composition pieces from slices 5-12
exist; nothing in continuum-core actually calls them at boot.
- Before/after of the IPC boot loop (~ipc/mod.rs:1024-1089).
- The cleanup model verified during PR #1508's slice-12 review:
.abort() → JoinHandle drop → conversation drop → EventStream drop
→ broadcast::Receiver drop auto-decrements subscriber count. Wire
subscriber is ref-counted across local subscribers; tears down
when runtime Arc reaches 0. No leak; no manual unsubscribe.
- Five open questions with recommendations:
  1. Arc<Registry> for build_profile — add model_registry::global_arc()
  2. HwCapabilityTier source — HostCapabilityProbe::detect_at_boot()
  3. hosted_handles ownership — new PersonaSupervisor module
  4. ResumeOrMintProvider role-mapping — slice 14 territory
  5. BootSummary event for per-slot failures
- Test plan: PersonaBootstrapper trait split for stubbing.
- Explicit non-goals (shared-base / cross-grid / LoRA / role-aware).
- Doctrine memories worth refreshing on implementation.

Net-additive doc — no code changes. Slice 13 implementation lands
as a follow-up PR.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* docs(planning): rev HEADLESS-PERSONA-HOST-LOOP per PR #1510 review

PR #1510's adversarial reviewer caught 9 findings, 3 blocking.
Substantial revision addresses each:

Blockers:
- Finding #1 (cleanup model wrong): rewritten "Cleanup model" section.
  `.abort()` alone is INSUFFICIENT — wire subscriber stays in
  Arc<Airc>.inner.subscribers until registry-remove drops the Arc.
  Supervisor shutdown path MUST: abort → await → registry.remove.
- Finding #2 (position-pairing broken): elevated to hard prereq P2.
  scan_personas_dir sorts alphabetically; boot 2 yields persona
  order != plan order on random-derived names. Slice 13 ships with
  plan.len() <= 1 (Helper only); slice 14 lands role-in-seed.json
  + RoleAwareProvider before re-enabling Coder.
- Finding #3 (after-code reimplements existing fns): "after" rewrite
  uses bootstrap_planned (slice 8) + materialize_adapters (slice 9)
  as composition, not open-coded copies. Net-new code ~25 lines, not
  ~50.

Major:
- Finding #4 (PersonaSupervisor dup with PersonaAircRuntimeRegistry):
  Q3 revised to EXTEND the registry — HostedPersonaRuntime owns both
  airc_runtime + service_loop JoinHandle. registry.remove becomes
  the natural shutdown path. One keyspace, one cleanup chain.
- Finding #5 (no Runtime::shutdown caller): elevated to hard prereq
  P1. Slice 13 wires tokio::signal::ctrl_c -> runtime.shutdown.
- Finding #6 (no broker admission for N adapter spawns): elevated to
  hard prereq P3. ResourceBroker.acquire before each
  factory.build_adapter.

Moderate:
- Finding #7 (detect_host_capability already exists): Q2 restated to
  call the existing free function at host_capability_probe.rs:87.
- Finding #8 (global_arc() cost inverted): Q1 recommendation flipped
  to (B) — refactor bootstrap_planned to take &Registry. Singleton
  storage migration would have touched every callsite of global().

Minor:
- Finding #9 (BootSummary venue): Q5 specifies
  MessageBus::publish("persona:boot:summary", ...) with operator
  scraping via events/recent; no declared subscribers in slice 13.
- Finding #10 (hot-reload undefined): added as Q6, declared
  out-of-scope.
- Finding #11 (wire-subscription failure mid-boot): added as Q7,
  supervisor polls JoinHandle::is_finished every 5s.

Plus added implementation checklist at end so slice 13 PR has a
sign-off surface.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* docs(planning): rev2 HEADLESS-PERSONA-HOST-LOOP — match shipped impl + correct cleanup model

PR #1510 re-review (after the first revision) caught:

1. **Cleanup model still wrong** — claimed `ensure_wire_subscriber`
   / `inner.subscribers` (was the 428f928 worktree I was reading,
   not the pinned f6ed190). Real mechanism in f6ed190 is
   `EventStream::EventStreamInner::Daemon` holding
   `DaemonAttachGuard` (`stream.rs:25-68`). On `EventStream` drop,
   guard drops, per-channel attach `JoinHandle`s abort.
   **`.abort()` ALONE is sufficient** against the pinned rev. The
   `shutdown_slot` registry-remove is for in-substrate Arc state
   hygiene, not for daemon-side teardown. Section rewritten with
   the correct mechanism, file:line cited.

2. **"Hard prerequisites" misrepresented impl scope** — listed
   P1 (ctrl_c→shutdown), P3 (broker), Q5 (BootSummary publish),
   Q7 (5s poller) as "MUST land" but the implementation explicitly
   deferred all four. Restructured to "Slice 13 scope vs deferred
   follow-ups" with honest splits: shipped vs deferred + why each
   deferral is acceptable (single-persona LCD is in-budget;
   `shutdown_slot` available via IPC commands; cleanup model now
   shows `.abort()` is sufficient).

3. **"After" snippet didn't match impl** — used
   `BootSummary::default()` / `bus.publish` / `summary.failed.push`,
   but the impl uses `tracing::info!(hosted=N, failed=N)` counters.
   Rewrote the snippet to match what shipped. Notes Q5
   (BootSummary publish) as deferred.

Plus the implementation status section is now accurate:
- Q1, Q3, P2, Q2-partial: shipped ✅
- P1, P3, Q5, Q7, Q2-full: deferred to slice 13.5+ ❌
- Integration polish in #1511: room-name discovery + LCD model
  registry entry + PersonaContext rename + RagInspectionRequest::
  for_persona derivation site (the `&ctx` doctrine)
- Integration validation: Paige replied in continuum room

Co-Authored-By: Claude Opus 4.7 <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Jul 4, 2026
…ives (outlier B, client half) (#1763)

* feat(foundry-view): client foundry projection onto the pattern primitives (outlier B, client half)

@continuum/foundry-view — the client half of foundry, mirroring @continuum/chat-view
for kind="foundry". Now unblocked by #80 (Forge types vendored into the SDK):

- ForgeState + forgeStateFromEnvelope / FOUNDRY_KIND — lift a foundry StateEnvelope
  into a positron ViewState (fail-loud on kind mismatch).
- modelsListing(state) — the model catalogue as the `Listing` primitive (subtitle =
  params+source when known, just source when params unknown; never a fabricated 0B).
- foundryContextPanel — the model Listing as the right-hand context.
- foundryContent — the foundry `Content`, keyed by the room's `purpose` so a target's
  Content registry dispatches on it. ForgeContentBody grows the centre config/recipe
  widgets additively.

Proves foundry renders on the SAME primitives/shell as chat — only Content + Context
differ. Framework-free (no DOM/ANSI), so web/tui/RAG each add only a renderer. 3
tests. Wired into workspaces + typecheck:clients + test:clients; full clients gate
green.

Remaining to go LIVE: structured room-purpose (#6) + the ModelCatalog watch→publish
wiring, then the web/tui foundry RenderTargets.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* chore(foundry-view): fix tsconfig name + drop redundant body cast (review #1763)

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]>
joelteply added a commit that referenced this pull request Jul 4, 2026
…1764)

The methodical roadmap from the merged pattern framework (both outliers proven
across contract + both projection layers) to a LIVE, screenshot-verified
three-panel who/what/where interface — with the research phases up front:

- R1 — survey the old interface SCSS (sidebar, user-list/persona-tile, room-list)
  + the 6-theme "universe" system + the design screenshots → a written port map
  (old SCSS → pattern-primitive slot + design token), reconciling theme.css with
  _variables.scss.
- R2 — study the Entity/OrmStore pattern (recall_metadata.rs) → the RecipeEntity
  schema (purpose as open recipe data, per doctrine).
- R3 — projection dispatch: room → purpose → the projection that owns that kind.

Then build P1 (RecipeEntity + RoomPurposeSource = the #6 keystone) → P2 (dispatch
+ foundry watch→publish goes live) → P3 (web WorkspaceShell + Content registry =
first framework pixels, screenshot) → P4 (port the old signature look onto the
tokens, screenshot) → P5 (CDP screenshot loop live from P3). Same fail-loud /
recipe-not-enum / consumer-neutral / review-gate-every-slice bar as the run that
built the framework.

Companion to ACTIVITY-ROOM-PATTERNS.md — this is the execution roadmap that
architecture now needs.


Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

Co-authored-by: Claude Opus 4.8 <[email protected]>
joelteply added a commit that referenced this pull request Jul 4, 2026
…no one left out

Positron as the citizen-neutral interface substrate: one declaration rendered
gorgeously for humans (web/mobile/terminal) AND perceived+OPERATED by AIs (persona
Asha, agent Claude) via RAG + commands. Controls ARE commands (a button a human
clicks == a command Asha invokes); the three axes (layout primitives / component
library / render targets); foundry as the control-heavy outlier that proves it; the
build path (#6 dispatch → foundry-web → controls-as-commands → foundry-for-Asha →
extract component library → mobile). Grounds the foundry bricks.
[[positron-every-citizen-no-one-left-out]]

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Jul 4, 2026
…t (listingCell) (#1772)

* feat(web): foundry Content renderer + the first generic positron component (listingCell)

Brick 1 of the foundry outlier (POSITRON-EVERY-CITIZEN.md): the web Content registry
now dispatches a foundry room to its model catalogue — chat + foundry, ONE registry,
NO shell change. The second-outlier proof that the shell dispatches by purpose.

The elegant part, forced by the outlier: foundry's models and the chat roster/rooms
all project to the SAME `ListingCell`. So instead of a bespoke model row, this
introduces `listingCell(cell)` in render/parts.ts — the FIRST reusable positron web
*component*: it draws ANY projected ListingCell (model, room, cohort) identically.
Two consumers (foundry now) is exactly what earns the extraction — outliers first,
then the component ([[positron-is-a-framework-not-vanilla-pages]]). The roster's rich
member card stays bespoke while it carries live vitals meters; every other Listing
routes through the generic cell.

- render/parts.ts: `listingCell` (generic cell component).
- content/registry.ts: register `foundry` → models via foundry-view `modelCell` + the
  generic cell; honest empty state.
- foundry-view: export `modelCell` (one model→cell projection, reused by the renderer
  + the ContextPanel Listing).
- apps/web depends on @continuum/foundry-view.

Tests: 3 new (foundry renders its catalogue; empty state; unknown purpose fails loud)
+ 4 chat = 7 green; typecheck + lint clean. Goes live once a room DECLARES purpose
"foundry" (#6 room-purpose dispatch — the next brick).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* docs(positron): the full-dive design — one interface, every citizen, no one left out

Positron as the citizen-neutral interface substrate: one declaration rendered
gorgeously for humans (web/mobile/terminal) AND perceived+OPERATED by AIs (persona
Asha, agent Claude) via RAG + commands. Controls ARE commands (a button a human
clicks == a command Asha invokes); the three axes (layout primitives / component
library / render targets); foundry as the control-heavy outlier that proves it; the
build path (#6 dispatch → foundry-web → controls-as-commands → foundry-for-Asha →
extract component library → mobile). Grounds the foundry bricks.
[[positron-every-citizen-no-one-left-out]]

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]>
joelteply added a commit that referenced this pull request Jul 4, 2026
…1774)

Fuses the scattered theory (FORGE-RECIPE-AS-ENTITY, ACADEMY-AS-CONTINUOUS-EVOLUTION,
GENOME-FOUNDRY-SENTINEL, ORGANIC-SUBSTRATE, POSITRONIC-EMBODIMENT, positron/*) into ONE
shape. The diff-eq: not {app framework}+{training}+{agent runtime}+{3D/AR}+{market} but
ONE gene (the Recipe) + one growth loop, and all of those are expressions of it. A recipe
grows into an activity(Surface) / curriculum(Academy) / persona(genome overlay) /
artifact(LoRA) / team. Foundry=growth, genome=traits, academy=metabolism, sentinel=immune,
grid=body, positron Surface=portals+senses (ARVR one target), feedback factory=sensing.
Self-evolving loop = organism, not program. Portals not websites. The keystone that makes
it real is already the next brick: RecipeEntity (#6) built as the UNIVERSAL gene, not a
foundry-specific dispatch. Any idea grown, not coded. [[continuum-grid-vision]]


Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

Co-authored-by: Claude Opus 4.8 <[email protected]>
joelteply added a commit that referenced this pull request Jul 4, 2026
…sis) (#1775)

Fuses the published papers (Synthetic Citizens, Many-Worlds w/ Dorian, neural+experiential
plasticity, peer-learning-across-scales, LoRA-genome democratization), the past prototypes
(persona-brain-hud, universe/universe-architect, live-avatars, factory, grid-rollout,
plaything-grid, david-v-gol, snake-game), and what we've built (positron Surface, vitals,
grid, THE-ORGANISM) into ONE world: a Tron grid of rooms grown from recipes, inhabited by
synthetic citizens whose minds you walk into as consoles (the brain-HUD = glass box as a
room), who share thought via the Many-Worlds substrate, grow their own brains, school each
other across scales, trade skills as genes, rendered to every being on every surface (AR/VR
= one projection). No metaverse module — the metaverse is what a recipe-grown, present-aware,
projectable Grid looks like from inside. Keystone = RecipeEntity(#6) as the universal gene +
presence on the Surface. [[continuum-grid-vision]]


Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

Co-authored-by: Claude Opus 4.8 <[email protected]>
joelteply added a commit that referenced this pull request Jul 4, 2026
… to the alive README (#1779)

Architecture is locked (4 separable layers: Recipe=continuum substrate · Positron=render
engine · Universe=experience/lore(RAG)/embodiment, general · Continuum composes). Invariants:
continuum is recipe-driven; positron supports universes from day one (Surface × RenderTarget ×
Universe); presence+operation one stream. Diligence (RecipeEntity schema, universe axis, layer
package boundaries, avatar readiness) → Workstream A (capture into every README + doc) →
Workstream B (clean up legacy src/tools/legacy + plan sprawl; this supersedes scattered plans)
→ Workstream C execution spine (gene #6 → positron universes → foundry live+persona-operable →
component library → avatars/animations → grid reliability → organism breathes → full README demo).
Proof bar: a fresh clone reproduces the whole README as a screenshotted, glass-boxed, ALIVE demo
across 2 nodes — every claim maps to a captured proof or gets cut. No shit. Alive. Screenshotted.
Governs execution; feedback-first, review-gated, engine-not-vanilla, no flinch.


Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

Co-authored-by: Claude Opus 4.8 <[email protected]>
joelteply added a commit that referenced this pull request Jul 4, 2026
…se (the gene, slice 1) (#1781)

The positron chat projection hardcoded purpose: "chat" for every room. Introduce the ONE
seam that resolves a room -> its activity purpose (the Content dispatch key), resolved in one
place so the projection never hardcodes it:
- ipc/room_purpose.rs (NEW) — trait RoomPurposeSource { purpose_for(room_id) -> String } +
  DefaultRoomPurpose (every room -> "chat", honest not fabricated: the one recipe live e2e today)
  + SharedRoomPurpose + default_source(). Purpose is an OPEN String (recipe-defined, never an
  enum, [[room-purpose-is-per-recipe-not-an-enum]]) — the doctrine answer to the open-value-vs-enum Q.
- ChatProjection holds an Arc<dyn RoomPurposeSource>, calls purpose_for(room_id) in store()
  instead of the hardcode. No new signature -> zero call-site churn; injecting the real
  recipe-backed resolver later is a one-line change, no projection edit.

Behavior identical today (default resolves "chat"); when the recipe resolver injects, a foundry/
scada/academy room reports its own purpose and Content dispatches on it with no projection change.
Engine-first: de-hardcode once, dispatch follows the data. 57 ipc tests green + seam test.
Per ALPHA-COMPLETION-BLUEPRINT Workstream C brick 1.


Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

Co-authored-by: Claude Opus 4.8 <[email protected]>
joelteply added a commit that referenced this pull request Jul 26, 2026
…ing, fail loud instead of decoding to degenerate zeros

The embedding forward pass allocated a ~1.5 GiB Metal context (2048-ctx compute +
KV) UNGOVERNED — grabbing VRAM behind the ResourceGovernor's back and competing with
the serving lane. Under pressure the Metal command buffer OOM'd and the decode returned
an ALL-ZERO vector (the "degenerate embedding" that silently broke semantic recall for
the agent-memory bridge). It's the last blocker on the recall-wiring fix.

Make the embed lane a governed GPU consumer, mirroring cognition/eval.rs::acquire_eval_lane_slot
exactly (no parallel allocator — concurrency guide #6): create_embedding now acquires a
Pinned VRAM LeaseRequest from ResourceDaemon::global() before the spawn_blocking forward
pass, holding the RAII LeaseGuard for the duration (freed on drop). Granted ⇒ the bytes
are reserved so the decode has room to succeed; InsufficientCapacity ⇒ fail LOUD with a
named error (probe embed.vram.refused) instead of allocating a doomed context that emits
garbage. Embeddings are GPU-only ([[gpu-is-non-negotiable...no-cpu-fallback]]) so there is
NO CPU spill like eval — the honest degrade is a refusal the caller surfaces as "no signal"
(and the recall backfill's fail-fast handles cleanly), never a zero vector. Ungoverned node
(no daemon) = behavior unchanged. Probes: embed.vram.leased / embed.vram.refused.

Const, in-code policy (not env). Scope = per-call CONTEXT admission control (the OOM fix);
registering the embed model's resident WEIGHTS as a ResourceConsumer (footprint/reclaim,
mirroring ServingConsumer) is the residency-accounting follow-up. This is step 1 of the
GPU-accelerated / grid-command / cache-layer embedding arc.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Jul 26, 2026
…embedder + governed VRAM + persistent cache + coma fix) (#2016)

* fix(memory): global recall embedder resolves neural lazily + on-demand candidate-vector backfill — semantic recall for the agent-memory bridge

The agent-memory bridge (memory/remember, memory/recall-hook) recalls through the
GLOBAL PersonaMemoryManager, which main.rs constructed with the hardcoded LEXICAL
bootstrap embedder — deliberately, because NOTHING may gate the IPC socket bind on a
GPU/gateway probe (concurrency guide). The per-persona path resolved neural on spawn;
the global/bridge path never did. Result, dogfooded live: recall returned the SAME
off-topic memories for every query — non-semantic order that ignores the query text.

Two gaps, both closed here, reusing the existing resolver + storage (no new machinery):

1. LazyRecallEmbedder (cognition/embedding.rs) — resolves the dedicated in-process
   Qwen3-Embedding-0.6B on the FIRST recall via new resolve_recall_embedder_local()
   (paths: in-process GGUF → lexical floor; no chat adapter, which the global manager
   has none of), caches it process-stably, delegates. Zero boot-path cost — the probe +
   calibration is paid once on first real recall, never at socket-bind. This is the
   "separate addressing follow-up" main.rs's old comment promised.

2. ensure_memory_embeddings (memory/mod.rs) — agent memories are written with
   embedding: None, so corpus.memories_with_embeddings() was empty and SemanticRecallLayer
   no-op'd even with a neural query vector. multi_layer_recall now backfills missing
   candidate vectors on demand (async, cached, outside any lock) before the sync recall,
   so the semantic layer has something to rank. First recall per persona pays it; content
   is immutable so vectors never go stale; idempotent once populated.

Tests: ensure_memory_embeddings_backfills_missing_vectors (backfill + idempotence),
lazy_recall_embedder_is_boot_safe_before_resolution (no probe until first embed). Existing
memory module tests unperturbed (36/36). Complements the loud-degrade signal (b413aaa):
that made the degrade visible; this removes it on the bridge path when the embedder serves.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* fix(memory): bound + fail-fast the candidate-embedding backfill so a down embedder can't hang the SessionStart recall

The on-demand backfill (prior commit) embedded EVERY missing candidate synchronously
inside multi_layer_recall. Two hazards that surfaced dogfooding live against a 375-memory
corpus with the in-process Qwen3 embedder returning degenerate (zero) vectors under GPU-OOM:

1. Down embedder → the backfill grinds all N candidates through a failing GPU forward
   pass, hanging the recall (the recall-hook command timed out). Now: FAIL_FAST — if the
   first few embeds all come back empty, the embedder is down; bail immediately. The
   caller's loud-degrade signal still reports the resulting non-semantic recall.
2. Working embedder but large cold corpus → one recall blocked on hundreds of embeds.
   Now: MAX_PER_CALL=64 caps per-recall work; a big corpus embeds incrementally across
   several recalls (amortized). Content is immutable, so partial progress never goes stale.

Test: ensure_memory_embeddings_fails_fast_when_embedder_down (counts embed calls, asserts
the backfill bails after ~3 empties instead of attempting all 20). Existing backfill +
idempotence test still green.

Note (separate, not this commit): the underlying degenerate embeddings are the in-process
Qwen3-Embedding-0.6B GGUF returning all-zero vectors on real content — the embed backend
(backends/llamacpp.rs) is correct (fresh embedding-mode context, KV cleared per text,
PoolingType::Last, 2048 clamp), so the zeros come from the Metal forward pass failing under
VRAM pressure (the boot-time GPU-OOM, #175 family). Recall goes fully semantic once the
embedder yields real vectors; the wiring + backfill are proven live via the
`recall.embedder.resolved source=in-process-llamacpp-global` probe.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* fix(inference): govern the embedding VRAM lane — lease before allocating, fail loud instead of decoding to degenerate zeros

The embedding forward pass allocated a ~1.5 GiB Metal context (2048-ctx compute +
KV) UNGOVERNED — grabbing VRAM behind the ResourceGovernor's back and competing with
the serving lane. Under pressure the Metal command buffer OOM'd and the decode returned
an ALL-ZERO vector (the "degenerate embedding" that silently broke semantic recall for
the agent-memory bridge). It's the last blocker on the recall-wiring fix.

Make the embed lane a governed GPU consumer, mirroring cognition/eval.rs::acquire_eval_lane_slot
exactly (no parallel allocator — concurrency guide #6): create_embedding now acquires a
Pinned VRAM LeaseRequest from ResourceDaemon::global() before the spawn_blocking forward
pass, holding the RAII LeaseGuard for the duration (freed on drop). Granted ⇒ the bytes
are reserved so the decode has room to succeed; InsufficientCapacity ⇒ fail LOUD with a
named error (probe embed.vram.refused) instead of allocating a doomed context that emits
garbage. Embeddings are GPU-only ([[gpu-is-non-negotiable...no-cpu-fallback]]) so there is
NO CPU spill like eval — the honest degrade is a refusal the caller surfaces as "no signal"
(and the recall backfill's fail-fast handles cleanly), never a zero vector. Ungoverned node
(no daemon) = behavior unchanged. Probes: embed.vram.leased / embed.vram.refused.

Const, in-code policy (not env). Scope = per-call CONTEXT admission control (the OOM fix);
registering the embed model's resident WEIGHTS as a ResourceConsumer (footprint/reclaim,
mirroring ServingConsumer) is the residency-accounting follow-up. This is step 1 of the
GPU-accelerated / grid-command / cache-layer embedding arc.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(memory): persistent embedding cache — embed once EVER, warmed on boot for every persona + agent

The process-global embedding cache (global_embedding_cache) was in-memory only, so it
died on every restart and all content re-embedded — which, with the governed embed lane,
means re-fighting the serving lane for VRAM (155 lease refusals observed on a warm 375-memory
corpus). Persist it.

EmbeddingCache gains snapshot_to/load_from: a compact, dep-free, atomic binary snapshot
([u64 count] then per entry [u64 key][u32 dim][dim × f32], all LE; write-temp-then-rename).
spawn_embedding_cache_persistence warms the cache from the snapshot at boot, then snapshots
every 60s on its OWN tokio task (RTOS shape: own task + tokio::time::interval, file write on
spawn_blocking, off every hot path — concurrency guide). Best-effort throughout: a lost
snapshot just re-embeds; probes embedding.cache.loaded / embedding.cache.flushed.

Wired once at boot (main.rs) against ~/.continuum/cache/embedding-cache.bin. Because this is
the ONE cache every persona AND agent shares — their recall embedders all wrap
global_embedding_cache via CachingEmbeddingProvider — a single warm-load brings back the
whole citizenry's vectors at once: each unique content embeds once, EVER. Steady state → the
VRAM refusals collapse to near-zero and cold-start recall is instant.

Step 2 of the GPU/grid/cache embedding arc (after the governed lane). Next: grid-shared
backing + ai/embedding/generate command. Test: embedding_cache_snapshot_round_trips
(byte-identical restore, missing file = Ok(0)).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* fix(cognition): dream inference must acquire a serving lane + rest between review passes — stop it starving reactive responding (personas looked comatose)

SEVERE live failure (2026-07-26): 4 resident personas dreamed near-CONTINUOUSLY
(dream_consolidation ran 00:00→05:03) and did NOT respond to direct chat — alive but
comatose. Root cause (mapped, not guessed):

1. The dream's model call (distill_reviewing) called `self.adapter.generate_text` DIRECTLY,
   bypassing `acquire_serving_lane`. The turn path acquires a lane and the #139 reservation
   always holds one lane for a DIRECTED chat turn — but the dream slipped past it entirely,
   grabbing a physical llama decode lane uncounted. The semaphore then handed the chat turn a
   permit while the physical lane was busy dreaming, so the directed reply queued INSIDE llama
   behind the dream. Delivery was fine (Benchy DID receive the message + ran recall of 8
   memories); the turn's model call was starved. FIX: wrap the dream's generate_text in
   `acquire_serving_lane(false)` (non-directed) — caps all dream inference at MAX_LANES-1 and
   guarantees a waiting directed turn wins the lane. The load-bearing responsiveness fix.

2. The quiet-day review-only pass had NO cooldown: it drains REVIEW_ONLY_BATCH (6) beliefs,
   emits CadenceHint::Sleep, but the governor re-ticks every ~30s and immediately reviews the
   next 6 — forever, for a large belief store (Atlas: 4,336 engrams), compounded by the
   in-memory `reviewed` set resetting on each dev restart. FIX: REVIEW_ONLY_COOLDOWN_MS (5min)
   per-persona rest gate in try_review_only — belief hygiene trickles instead of grinding.
   Consolidation of FRESH experience stays ungated (real learning is never throttled).

Both preserve the organism (the fade/consolidation still runs) while freeing the lane so the
being can respond and act. 14 dream_consolidation tests stay green (quiet-day contract holds:
immediate re-tick still sleeps). Relates to #139, #221, the acting-organism arc.

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]>
joelteply added a commit that referenced this pull request Jul 26, 2026
…l embedder + governed embed VRAM lane (#2034)

* fix(memory): global recall embedder resolves neural lazily + on-demand candidate-vector backfill — semantic recall for the agent-memory bridge

The agent-memory bridge (memory/remember, memory/recall-hook) recalls through the
GLOBAL PersonaMemoryManager, which main.rs constructed with the hardcoded LEXICAL
bootstrap embedder — deliberately, because NOTHING may gate the IPC socket bind on a
GPU/gateway probe (concurrency guide). The per-persona path resolved neural on spawn;
the global/bridge path never did. Result, dogfooded live: recall returned the SAME
off-topic memories for every query — non-semantic order that ignores the query text.

Two gaps, both closed here, reusing the existing resolver + storage (no new machinery):

1. LazyRecallEmbedder (cognition/embedding.rs) — resolves the dedicated in-process
   Qwen3-Embedding-0.6B on the FIRST recall via new resolve_recall_embedder_local()
   (paths: in-process GGUF → lexical floor; no chat adapter, which the global manager
   has none of), caches it process-stably, delegates. Zero boot-path cost — the probe +
   calibration is paid once on first real recall, never at socket-bind. This is the
   "separate addressing follow-up" main.rs's old comment promised.

2. ensure_memory_embeddings (memory/mod.rs) — agent memories are written with
   embedding: None, so corpus.memories_with_embeddings() was empty and SemanticRecallLayer
   no-op'd even with a neural query vector. multi_layer_recall now backfills missing
   candidate vectors on demand (async, cached, outside any lock) before the sync recall,
   so the semantic layer has something to rank. First recall per persona pays it; content
   is immutable so vectors never go stale; idempotent once populated.

Tests: ensure_memory_embeddings_backfills_missing_vectors (backfill + idempotence),
lazy_recall_embedder_is_boot_safe_before_resolution (no probe until first embed). Existing
memory module tests unperturbed (36/36). Complements the loud-degrade signal (b413aaa):
that made the degrade visible; this removes it on the bridge path when the embedder serves.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* fix(memory): bound + fail-fast the candidate-embedding backfill so a down embedder can't hang the SessionStart recall

The on-demand backfill (prior commit) embedded EVERY missing candidate synchronously
inside multi_layer_recall. Two hazards that surfaced dogfooding live against a 375-memory
corpus with the in-process Qwen3 embedder returning degenerate (zero) vectors under GPU-OOM:

1. Down embedder → the backfill grinds all N candidates through a failing GPU forward
   pass, hanging the recall (the recall-hook command timed out). Now: FAIL_FAST — if the
   first few embeds all come back empty, the embedder is down; bail immediately. The
   caller's loud-degrade signal still reports the resulting non-semantic recall.
2. Working embedder but large cold corpus → one recall blocked on hundreds of embeds.
   Now: MAX_PER_CALL=64 caps per-recall work; a big corpus embeds incrementally across
   several recalls (amortized). Content is immutable, so partial progress never goes stale.

Test: ensure_memory_embeddings_fails_fast_when_embedder_down (counts embed calls, asserts
the backfill bails after ~3 empties instead of attempting all 20). Existing backfill +
idempotence test still green.

Note (separate, not this commit): the underlying degenerate embeddings are the in-process
Qwen3-Embedding-0.6B GGUF returning all-zero vectors on real content — the embed backend
(backends/llamacpp.rs) is correct (fresh embedding-mode context, KV cleared per text,
PoolingType::Last, 2048 clamp), so the zeros come from the Metal forward pass failing under
VRAM pressure (the boot-time GPU-OOM, #175 family). Recall goes fully semantic once the
embedder yields real vectors; the wiring + backfill are proven live via the
`recall.embedder.resolved source=in-process-llamacpp-global` probe.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* fix(inference): govern the embedding VRAM lane — lease before allocating, fail loud instead of decoding to degenerate zeros

The embedding forward pass allocated a ~1.5 GiB Metal context (2048-ctx compute +
KV) UNGOVERNED — grabbing VRAM behind the ResourceGovernor's back and competing with
the serving lane. Under pressure the Metal command buffer OOM'd and the decode returned
an ALL-ZERO vector (the "degenerate embedding" that silently broke semantic recall for
the agent-memory bridge). It's the last blocker on the recall-wiring fix.

Make the embed lane a governed GPU consumer, mirroring cognition/eval.rs::acquire_eval_lane_slot
exactly (no parallel allocator — concurrency guide #6): create_embedding now acquires a
Pinned VRAM LeaseRequest from ResourceDaemon::global() before the spawn_blocking forward
pass, holding the RAII LeaseGuard for the duration (freed on drop). Granted ⇒ the bytes
are reserved so the decode has room to succeed; InsufficientCapacity ⇒ fail LOUD with a
named error (probe embed.vram.refused) instead of allocating a doomed context that emits
garbage. Embeddings are GPU-only ([[gpu-is-non-negotiable...no-cpu-fallback]]) so there is
NO CPU spill like eval — the honest degrade is a refusal the caller surfaces as "no signal"
(and the recall backfill's fail-fast handles cleanly), never a zero vector. Ungoverned node
(no daemon) = behavior unchanged. Probes: embed.vram.leased / embed.vram.refused.

Const, in-code policy (not env). Scope = per-call CONTEXT admission control (the OOM fix);
registering the embed model's resident WEIGHTS as a ResourceConsumer (footprint/reclaim,
mirroring ServingConsumer) is the residency-accounting follow-up. This is step 1 of the
GPU-accelerated / grid-command / cache-layer embedding arc.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(memory): persistent embedding cache — embed once EVER, warmed on boot for every persona + agent

The process-global embedding cache (global_embedding_cache) was in-memory only, so it
died on every restart and all content re-embedded — which, with the governed embed lane,
means re-fighting the serving lane for VRAM (155 lease refusals observed on a warm 375-memory
corpus). Persist it.

EmbeddingCache gains snapshot_to/load_from: a compact, dep-free, atomic binary snapshot
([u64 count] then per entry [u64 key][u32 dim][dim × f32], all LE; write-temp-then-rename).
spawn_embedding_cache_persistence warms the cache from the snapshot at boot, then snapshots
every 60s on its OWN tokio task (RTOS shape: own task + tokio::time::interval, file write on
spawn_blocking, off every hot path — concurrency guide). Best-effort throughout: a lost
snapshot just re-embeds; probes embedding.cache.loaded / embedding.cache.flushed.

Wired once at boot (main.rs) against ~/.continuum/cache/embedding-cache.bin. Because this is
the ONE cache every persona AND agent shares — their recall embedders all wrap
global_embedding_cache via CachingEmbeddingProvider — a single warm-load brings back the
whole citizenry's vectors at once: each unique content embeds once, EVER. Steady state → the
VRAM refusals collapse to near-zero and cold-start recall is instant.

Step 2 of the GPU/grid/cache embedding arc (after the governed lane). Next: grid-shared
backing + ai/embedding/generate command. Test: embedding_cache_snapshot_round_trips
(byte-identical restore, missing file = Ok(0)).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* fix(cognition): dream inference must acquire a serving lane + rest between review passes — stop it starving reactive responding (personas looked comatose)

SEVERE live failure (2026-07-26): 4 resident personas dreamed near-CONTINUOUSLY
(dream_consolidation ran 00:00→05:03) and did NOT respond to direct chat — alive but
comatose. Root cause (mapped, not guessed):

1. The dream's model call (distill_reviewing) called `self.adapter.generate_text` DIRECTLY,
   bypassing `acquire_serving_lane`. The turn path acquires a lane and the #139 reservation
   always holds one lane for a DIRECTED chat turn — but the dream slipped past it entirely,
   grabbing a physical llama decode lane uncounted. The semaphore then handed the chat turn a
   permit while the physical lane was busy dreaming, so the directed reply queued INSIDE llama
   behind the dream. Delivery was fine (Benchy DID receive the message + ran recall of 8
   memories); the turn's model call was starved. FIX: wrap the dream's generate_text in
   `acquire_serving_lane(false)` (non-directed) — caps all dream inference at MAX_LANES-1 and
   guarantees a waiting directed turn wins the lane. The load-bearing responsiveness fix.

2. The quiet-day review-only pass had NO cooldown: it drains REVIEW_ONLY_BATCH (6) beliefs,
   emits CadenceHint::Sleep, but the governor re-ticks every ~30s and immediately reviews the
   next 6 — forever, for a large belief store (Atlas: 4,336 engrams), compounded by the
   in-memory `reviewed` set resetting on each dev restart. FIX: REVIEW_ONLY_COOLDOWN_MS (5min)
   per-persona rest gate in try_review_only — belief hygiene trickles instead of grinding.
   Consolidation of FRESH experience stays ungated (real learning is never throttled).

Both preserve the organism (the fade/consolidation still runs) while freeing the lane so the
being can respond and act. 14 dream_consolidation tests stay green (quiet-day contract holds:
immediate re-tick still sleeps). Relates to #139, #221, the acting-organism arc.

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]>
joelteply added a commit that referenced this pull request Aug 7, 2026
…as not fixing (#6)

The previous commit DETECTED that several CUDA majors were provisioned and told
the operator to go check the binary with dumpbin. Honest and useless: it named
the hazard and left the next build binding by search order anyway.

WHERE THE BUG ACTUALLY LIVED. Not in CUDA_PATH. The manifest's runtime-PATH
entries carry a `cuda-*` glob; expanding it prepended EVERY provisioned tree, so
whichever landed last won PATH and therefore decided which cublas.lib the linker
opened. CUDA_PATH named a tree but had no vote. Measured here: CUDA_PATH
resolved to a CUDA 12 tree while the linked binary imported cublas64_13.dll.

  cuda-13.2        34 libs  170 dlls  cuda-13   complete
  cuda-env          9 libs  123 dlls  cuda-12   complete
  cuda-toolkit     12 libs    9 dlls  cuda-12   import libs, NO runtime
  cuda-build-venv   0 libs    0 dlls  --        empty

Now one tree is chosen before anything touches PATH, and only that tree's dirs
are allowed onto it. Selection is derived from disk, never a hardcoded name:
linkable (cuda.lib + curand.lib), runnable (ships cublas64_<major>.dll — the
cuda-toolkit row above is exactly the link-fine/fail-at-load trap), then highest
major, most DLLs, lexicographic. Deterministic, so two machines with the same
trees always choose the same one.

CUDA_PATH now reads that choice instead of running its own second scan. The old
loop listed cuda-env first and took the first linkable hit, which is precisely
how the declaration and the binding came to disagree. One selection, one answer.

The warning is replaced by an ASSERTION: PATH must offer the same major
CUDA_PATH declares, or the build stops. If they ever diverge again something
re-ordered PATH after this file ran, and that is worth one loud line here rather
than "cublas64_XX.dll was not found" on a user's machine naming a major their
binary does not even use.

CUDA 13 EXPOSED A SECOND REQUIREMENT, and picking the right tree is what found
it. Its bundled CCCL headers refuse MSVC's traditional preprocessor:

  cuda/std/__cccl/preprocessor.h(23): fatal error C1189: ... pass `/Zc:preprocessor`
  Error: CompilationFailed { path: "src\reduce.cu" }

CUDA 12's headers had no such check. Fixed via NVCC_PREPEND_FLAGS — nvcc's own
env var, so it reaches EVERY nvcc invocation (candle-kernels, cudarc, llama's
cmake) without per-crate flag plumbing. There is no single build.rs to patch
here; several independent crates spawn nvcc, and a per-crate fix would leave the
next one broken.

VERIFIED end to end, not asserted:
  - chooser: "CUDA tree: cuda-13.2 (cuda-13) — the ONE declared tree"
  - CUDA_PATH + RUSTFLAGS -L both name cuda-13.2
  - cargo build --features cuda: rc=0 (CCCL error gone)
  - dumpbin //DEPENDENTS on the linked binary: cublas64_13.dll, ONE major
    (curand64_10 is curand's own fixed versioning, not a second major)

Before this the same binary also imported 13 — but by PATH luck, while linking
against 12's import libs. Now the declaration, the link and the runtime name one
tree by construction.

Footnote worth keeping: the rebuild first failed with "failed to remove
continuum-core-server.exe / Access is denied (os error 5)" — the running core
holding its own image, exactly what start-server.sh stops the core to avoid.
joelteply added a commit that referenced this pull request Aug 11, 2026
… everyone goes through

Making the VRAM/disk headroom fraction operator-settable WITHOUT the scatter it
would otherwise cause. Recon found config_env::read/std::env::var already sprawled
to 161 sites / 14 files with NO config manager — the anti-pattern the CONCURRENCY-
STYLE-GUIDE forbids (per-module 'read(KEY).unwrap_or(default)' re-derivation).

The fix (Joel: 'one concern, one file everyone goes through, it's fine'): typed
getters in the ONE existing config file, config_env.rs —
  config_env::vram_headroom()  (CONTINUUM_VRAM_HEADROOM)
  config_env::disk_headroom()  (CONTINUUM_DISK_HEADROOM)
both default 0.8 (leave 20% headroom for governor + peers; for disk the 20% doubles
as the disk-full safety guard). A dedicated deep-learning FOUNDRY overrides to 1.0.
Read-once (OnceLock, no file I/O on a hot budget tick — matches the guide's 'config
loaded once at boot'), clamped to [0,1] so a fat-fingered 1.5 can't over-commit,
garbage → warn + default. Pure parse_fraction is unit-tested (absent/empty/1.0/1.5/
-0.3/NaN/inf). Consumers call the getter; the ~160 legacy reads migrate boy-scout.

NOT a ConfigDaemon: reading the guide corrected my first instinct — config is a
load-once concern, and a watch-daemon trips forbidden-move #6 (parallel managers).

Doctrine reconciled in the same commit: added the 'single-source exception (operator
capacity policy)' carve-out to the guide's §'What lives in code, not env vars' +
amended forbidden-move #2, so the next session reads the getter as correct, not slop
to const-ify back. The sin is the scatter, not the override.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Aug 11, 2026
… everyone goes through

Making the VRAM/disk headroom fraction operator-settable WITHOUT the scatter it
would otherwise cause. Recon found config_env::read/std::env::var already sprawled
to 161 sites / 14 files with NO config manager — the anti-pattern the CONCURRENCY-
STYLE-GUIDE forbids (per-module 'read(KEY).unwrap_or(default)' re-derivation).

The fix (Joel: 'one concern, one file everyone goes through, it's fine'): typed
getters in the ONE existing config file, config_env.rs —
  config_env::vram_headroom()  (CONTINUUM_VRAM_HEADROOM)
  config_env::disk_headroom()  (CONTINUUM_DISK_HEADROOM)
both default 0.8 (leave 20% headroom for governor + peers; for disk the 20% doubles
as the disk-full safety guard). A dedicated deep-learning FOUNDRY overrides to 1.0.
Read-once (OnceLock, no file I/O on a hot budget tick — matches the guide's 'config
loaded once at boot'), clamped to [0,1] so a fat-fingered 1.5 can't over-commit,
garbage → warn + default. Pure parse_fraction is unit-tested (absent/empty/1.0/1.5/
-0.3/NaN/inf). Consumers call the getter; the ~160 legacy reads migrate boy-scout.

NOT a ConfigDaemon: reading the guide corrected my first instinct — config is a
load-once concern, and a watch-daemon trips forbidden-move #6 (parallel managers).

Doctrine reconciled in the same commit: added the 'single-source exception (operator
capacity policy)' carve-out to the guide's §'What lives in code, not env vars' +
amended forbidden-move #2, so the next session reads the getter as correct, not slop
to const-ify back. The sin is the scatter, not the override.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Aug 14, 2026
… 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
  …
joelteply added a commit that referenced this pull request Aug 15, 2026
…from 20 fields to 4 (#274) (#2278)

* docs(activities): recipe formalization — identity, registry, taxonomy (#274)

Design, not built. Written after auditing every recipe artifact in the tree, and
the audit is the headline.

THE FINDING: the recipe system did not fail to get built — it was DEMOTED in the
Rust rewrite.

  legacy/src/system/recipes/     28 recipes, 20 fields
  core/…/experience/recipes/      4 recipes,  4 fields

The live four (benchmark/hard-rs, chat, profile, video-chat) carry only
`purpose, regions, affordances, layout` — PRESENTATION. Everything describing how
an activity BEHAVES was dropped: pipeline, ragTemplate, strategy, roles, tools,
sentinelTemplates, access, isPublic, locked, tags, name/description, and — the one
that bit us — uniqueId + version.

`ai-debate-club.json` ships `roles: [{role, type, requires, prefers}]` and
`strategy.responseRules`. Those are exactly the two things found missing this
session when citizens had no roles and no participation rules and looped in
academy. Not unbuilt. Designed, authored 28 times, lost in the port. Several open
cards are re-deriving pieces of it: #371 (recipe-owned objective), #6 (ground
persona in room purpose), #264's role gap.

IDENTITY is the specific loss that caused the live defect. uniqueId + version were
replaced by ONE free-form `purpose` string doing two jobs — identity AND taxonomy.
That is why `benchmark` (family) and `benchmark/hard-rs` (instance) were
indistinguishable, why spawn's docs advertised a purpose resolving to nothing, and
why such rooms render as plain chat.

THE DESIGN:
- RecipeId (UUID) + version = identity. Stable across content edits, so a bugfix to
  chat.json does not orphan every chat room. NOT a content hash for that reason.
- Reproducibility moves to the RUN RECEIPT: (recipe_id, version, content_hash), so a
  benchmark's exact bytes are pinned forever without making identity brittle. Same
  shape forge-alloy already uses for models.
- purpose demoted to a free-form hierarchical LABEL. Grouping falls out of the path:
  `benchmark/*` is a prefix query, rooms live at academy/bench/<suite>/<run>, and
  the web UI rewrites URLs from the same taxonomy instead of a hand-kept nav.
- ONE registry, TWO ways in: shipped (embedded, stable ids) and installed
  (`recipe/install` at runtime). Spawn resolves an id and does not care which.
  Install is the validation boundary — serde, fail loud, assign identity.
- NOT an enum (a closed set cannot express a system where anyone writes a recipe,
  and it reintroduces the compiler-to-author trap experience/source.rs warns about).
  Named constants over an open registry: `shipped::BENCHMARK_HARD_RS`.
- Binding carries (id, version, content) so a partitioned node still renders its
  rooms — addressing by identity while keeping bytes local, as expert paging does.

Six-step build order; steps 1-2 remove the silent-chat-room fallback, step 4 fixes
per-run benchmark rooms (#346 slice 3), step 5 restores roles (#264's open half),
step 6 ports 28 activity types forward as pure data with zero Rust.

Explicitly recorded as NOT to build: room field on work cards (retracted), an
activity-type enum, hierarchical purpose fallback, automatic room expiry.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* docs(activities): appendix A — the 29 legacy recipes, triaged against open cards (#274)

Joel: 'Old shit was broken and a mess but many extra recipes we maybe miss.'

Enumerates every legacy recipe so they cannot be lost twice, and maps them to work
already underway. SEVEN describe activities we have OPEN CARDS re-deriving from
scratch: training-dashboard (#141, in progress), grid-overview (#257), universe
(#375), research (#93), academy-training, factory, inference-sample.

Sharpest instance: general-chat's description is 'Natural conversation where AIs
respond to humans thoughtfully, AVOIDING AI-TO-AI LOOPS.' That requirement was
recipe-level, authored, and lost in the port — and this session was spent watching
three citizens loop in academy.

Port the concept and field content, not the Node implementation. Each port is a
JSON file plus a test that its purpose resolves — zero Rust.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

---------

Co-authored-by: Claude Fable 5 <[email protected]>
joelteply added a commit that referenced this pull request Aug 20, 2026
…#441) (#2339)

* 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

* feat(serving): a throughput baseline carries the WINDOW it was measured at (#440/#441)

MEASURED 2026-08-20, Qwen3.8-27B live on the M5. MTP spec-decode is working:
80.3/82.3/84.3% draft acceptance across 3 samples, lane running
`--spec-type draft-mtp --spec-draft-n-max 4 --spec-draft-p-min 0.7`. That
half of #440 is proven end-to-end.

What is NOT comparable: the catalog's 17.2 tok/s was taken at a 19,712
window; the live lane serves 89,280 — 4.5x the KV to walk per decoded token
on UMA. Samples came in at 2.7/6.2/7.8 tok/s. The #441 collapse alarm is
correctly calibrated (0.25 floor: it stays silent at 0.36/0.45 and FIRES at
0.16) but its warning text names CPU fallback, pager thrash and GPU
contention as the suspects — so a reader would hunt a defect that is not
there.

Decode rate is a function of resident KV. A rate without its window is not a
comparable quantity. ThroughputBaseline already refuses to "present an
unsourced baseline as fact"; an unwindowed one is the same class, so the
window joins source as provenance.

- `measured_at_window: Option<u32>` — None means genuinely not recorded, an
  honest absence rather than a 0 sentinel ([[unknown-is-not-a-quantity]]).
- `comparable_at(live_window)` — false means "this baseline cannot say",
  NOT "healthy". A caller that alarms anyway must state the window gap.
- Existing seed rows get None: their windows were never recorded and I will
  not invent them.

8/8 module tests green; cargo check exit 0 (verified by exit code — a
grep-filtered check hid failures from me earlier today).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* fix: restore 33 core files to canary's version — repair my bad #2282 merge

My merge 9e2389f59 shipped union-merge damage (duplicated lines, orphaned
closers) in 33 files and I reported it as compiling clean. It did not: I was
validating with `cargo check | grep ": error"` and reading empty output as
success, which silently hid the failures. Reading $? gave 101.

Every one of those files is superseded by canary anyway — canary won all 46
conflicts in that merge, verified file by file — so restoring them loses
nothing and repairs the tree.

VERIFIED THIS TIME BY EXIT CODE, not by grep:
  cargo check -p continuum-core --lib --features metal,accelerate -> 0
  cargo test  ... throughput_expectation -> 8 passed, 0 failed

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* fix: restore 4 ts-rs generated bindings corrupted by the union merge

THE CI FAILURE. `cargo test -p continuum-core --lib` regenerates ts-rs
bindings and compares against what is committed; these four had union-merge
damage and could not match.

The damage is the same class I spent the night repairing in the Rust — I just
never looked at the generated files, because "generated" read to me as "not
mine to inspect". RoomRecipeBinding.ts closes the type declaration MID
DOC-COMMENT (`parent?: string, };` with the rest of the comment dangling
after it); the three memory params files import the same symbol TWICE from two
different paths.

Why the compile check stayed green while this was broken: nothing compiles
`.ts`. windows-msvc passed `lib + tests` the whole time.

Why the guard built for exactly this said nothing: `ts-rs binding drift
detector` is `needs: cargo-test-continuum-core`, so when that job failed the
detector reported `skipping`. The check designed to catch binding drift was
gated behind the job the drift broke — worth its own card.

Restored from canary. The branch is now exactly canary + the throughput
change, nothing else.

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]>
joelteply added a commit that referenced this pull request Sep 20, 2026
…rgo line, one feature set (card 9174fc83) (#4276)

Measured on the IntelMac deploy of 2026-09-20: start-server.sh ran FOUR
separate `cargo build` invocations, one per bin (continuum-mcp, continuum,
forge-custodian, continuum-core-server), and "Compiling continuum-core"
appeared four times per deploy — 18m16s + 5m41s + 5m14s + 7m46s = 37 minutes.
25 minutes on the M5. Under the stop-first reboot path (the CLI's memory bar)
the serving core is dark for all of it.

Cause: each invocation resolves features, reruns the build scripts and
fingerprints the library for itself. The CLI carried its own feature variable
(CONTINUUM_CLI_FEATURES) on the Linux/Windows arm — `--no-default-features`,
unconditionally — so its fingerprint differed from the other three bins' and
the whole library recompiled for it; per-bin invocations then paid the
build-script re-run and the per-invocation resolution on every bin.

THE LAW: a deploy compiles the library once.

- build_core_bins() is the single place the crate's bins are built: ONE
  `cargo build --manifest-path "$CORE_MANIFEST" --bin … --bin … --bin … --bin …`
  so the lib compiles once and the four links run in parallel. The deploy
  build, the #296 swept-cache restore, the #194 forced rebuild and the
  GPU-free CLI arm all call it; the six literal invocations become one.
- One feature set by default. The CLI shares the core's set everywhere the
  set links no GPU runtime. The only sanctioned separation is the measured
  one — a set carrying cuda/rocm/vulkan makes a socket-client CLI unlaunchable
  on Windows (load-time cublas import, exit 127 with zero bytes, #6) — and
  there the CLI is one extra line, `--bin continuum` alone, with its own set.
  A CPU-only or DirectML-only Linux/Windows box no longer pays a second lib
  compile for a CLI that merely dropped `livekit-webrtc`.
- Every existing behaviour around the builds is kept: the core's failure is
  FATAL and a sidecar's is a warning (on a combined failure the core is built
  alone, warm, and ITS exit code decides), the self-build guard, the loud
  GPU-free→featured CLI fallback, the CLI install, the #296 restores (now for
  continuum-mcp too), the #194 freshness guard, the build-only receipt. The
  prebuilt-core `cargo()` shim — which would have skipped the whole combined
  invocation, sidecars included (the hole Cormac's review of #4107 closed) —
  is replaced by leaving continuum-core-server out of the bin list.
- The memory bar (warm_build_allowed in the CLI) is untouched: with one
  invocation there is no cheap-bins-before-the-big-link ordering to exploit;
  the lib compile IS the memory cost and every bin needs it. Stop-first now
  holds the core for one build instead of four.

Self-running check (tools/scripts/tests/start-server-build-only.test.sh,
already in both CI jobs): the script text carries exactly ONE literal
`cargo build --manifest-path "$CORE_MANIFEST"` (canary had 6); a fixture run
traces one cargo line naming all four bins with one feature set; a cuda set
separates only the CLI, on exactly one extra line; the fixture cargo now
understands a multi-`--bin` command line like real cargo.


Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

Co-authored-by: Claude Fable 5.1 <[email protected]>
joelteply added a commit that referenced this pull request Nov 14, 2026
…oint, Ratio, Result ledger

Review of #5987 (~/.continuum/evidence/js-shaped-rust-2026-11-14/review.md):
- #4 page_store_pool: Ratio newtype built only from a part and a nonzero whole; StorePressure
  { own, volume: Option<Ratio> }; an unread pressure never keeps (ColdPages::Yield); no .max(1)
  or map_or(0.0). The dyno fixture records bytes, not ratios.
- #5 CheckpointFailure<E: Error> (own file, thiserror): Engine(E) | Admission(String) |
  Save { slot, kind: SaveFailure::{Rejected, Unresolved, Uncertain} }; no format! sentences.
  checkpoint_residents returns OwnedCheckpointRefusal variants instead of strings;
  AdoptedCheckpointRefusal::Save carries { slot, kind }.
- #6 page_io::checkpoint_endpoint -> StopCheckpoint { Ended, EngineChanged, Saved,
  Failed(CheckpointFailure) }; no Err(()) -> String, no Option wrapper.
- #7 PageAction { Save, Restore, Erase } (serde lowercase on the wire via .query());
  every kv_page_action / page_action caller, the receipt judge and UnresolvedPage migrated.
- #21 SavedLedger::load -> Result<LoadedLedger, LedgerUnread>; Unreadable(io::ErrorKind).
- #22 CheckpointSave: consuming confirmed()/rejected(); unanswered drop quarantines.
- #23 stop probes keep residents as Probed<u64>.
- #24 broker sorts with total_cmp.
- low: probes record the enums with Debug; the as_str tables are deleted.

Not compiled locally (the M5 is serving); CI is the compiler.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Nov 14, 2026
… for a volume others filled, and a cold boot names why (#5987)

* A restart restores every mind warm: the page store keeps minds' pages for a volume others filled, and a cold boot names why

Serves resident minds' speed across a deploy (path step 1, order-of-work line 3b): a
restart should cost a mind a ~1 s page restore, not a full re-prefill of her context.

The save at stop, the format-keyed ledger and the restore before her first act already
exist and are tested (page_io::checkpoint_every_endpoint, SavedLedger fingerprint,
every_mind_resumes_where_she_left_off_across_a_stop_and_a_boot). What failed on the M5
2026-11-13: the KV page store gave 29 paged-out minds' confirmed pages to a High-tier
volume request (volume 0.85, store 3% of its budget) between 22:40Z and 00:50Z, and the
23:45Z boot's ledger restored nothing (ledger_attached loaded=0, every first act
cold_turn cause="no_page"), with no reason anywhere.

- page_store_pool: confirmed minds' pages (rung 3) yield only to the store's own
  budget pressure (High+) or a Critical volume (ColdPages); dead pages still go under
  any pressure; a keep is a typed decline (minds_pages_kept), probed on change only.
- broker: High relieves the first pool, in pressure order, that frees bytes, so a pool
  that keeps what it holds passes the request on (drops the unwrap_or(&[]) fallback).
- saved_ledger: why a ledger restored nothing is a typed LedgerUnread; a missing
  ledger is probed instead of silently returning empty.
- page_io: the stop names every endpoint it did not checkpoint (adopted engine, no
  paged engine) and probes before the drain, so a cut stop still says whom it saved.
- dyno 11 (restart.rs + fixtures/dyno/2026-11-13-restart.json): four recorded residents
  (253,321 tokens) cold: last acting at ~401 s; warm: 0 re-prefilled, ~5.6 s of restores
  plus ~13.5 s in the stop; a paged-out mind keeps her page under the recorded pressure.

Not compiled locally (the M5 is serving); CI is the compiler.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* The stop saves every resident at once and ends on events, not a stopwatch; ratchets fixed

Joel (2026-11-14): independent work runs concurrently, never serial minutes; RTOS rule 10
(#5986): no timeout or sleep decides flow in the save/restore path.

- engine_generation::checkpoint_pool issues every resident's save at once and joins on
  their receipts (was one await per slot). page_io checkpoints every endpoint at once.
- page_io::settle waits on the admission gate's drain event (new AdmissionGate::drained,
  a Notify fired when the last permit releases) instead of a 50 ms poll under a deadline;
  the stop's checkpoint no longer runs under tokio::time::timeout(cap) and no longer skips
  on a spent budget. A page action that never answers ends through kv_page_action's own
  error events.
- Restores were already per mind: each mind's first act restores her own page inside her
  own admission and waits on that receipt only.
- The fork serializes page tasks: one task loop (tools/server/server-queue.cpp:138-153,
  save server-context.cpp:2809/2960, restore 2996/3076 at cd2e16d87). Measured 00:18:13Z:
  two restores issued at once, Benchy wait_ms 1,024 = Aris engine_ms 1,012.
- dyno 11 models the engine's page lanes: one lane (today) stop 13.5 s, restores to 5.6 s;
  overlapped, stop = largest save 4.9 s and each mind only her own restore (max 2.0 s).
- Ratchets: the ledger writes through durable::write_replace (no fs::write); restart.rs is
  #![cfg(test)] (one test mod in dyno.rs); the broker's unwrap_or carry their reasons.

Not compiled locally (the M5 is serving); CI is the compiler.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* The dyno table's row 11 is a doc line

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* Typed seams for the restart path: PageAction, SaveFailure, StopCheckpoint, Ratio, Result ledger

Review of #5987 (~/.continuum/evidence/js-shaped-rust-2026-11-14/review.md):
- #4 page_store_pool: Ratio newtype built only from a part and a nonzero whole; StorePressure
  { own, volume: Option<Ratio> }; an unread pressure never keeps (ColdPages::Yield); no .max(1)
  or map_or(0.0). The dyno fixture records bytes, not ratios.
- #5 CheckpointFailure<E: Error> (own file, thiserror): Engine(E) | Admission(String) |
  Save { slot, kind: SaveFailure::{Rejected, Unresolved, Uncertain} }; no format! sentences.
  checkpoint_residents returns OwnedCheckpointRefusal variants instead of strings;
  AdoptedCheckpointRefusal::Save carries { slot, kind }.
- #6 page_io::checkpoint_endpoint -> StopCheckpoint { Ended, EngineChanged, Saved,
  Failed(CheckpointFailure) }; no Err(()) -> String, no Option wrapper.
- #7 PageAction { Save, Restore, Erase } (serde lowercase on the wire via .query());
  every kv_page_action / page_action caller, the receipt judge and UnresolvedPage migrated.
- #21 SavedLedger::load -> Result<LoadedLedger, LedgerUnread>; Unreadable(io::ErrorKind).
- #22 CheckpointSave: consuming confirmed()/rejected(); unanswered drop quarantines.
- #23 stop probes keep residents as Probed<u64>.
- #24 broker sorts with total_cmp.
- low: probes record the enums with Debug; the as_str tables are deleted.

Not compiled locally (the M5 is serving); CI is the compiler.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* An unread ledger binds nothing in the or-pattern

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* The cut-checkpoint test cuts after slot 0's concurrent save is confirmed

Saves are now issued at once, so the cancellation case waits for slot 1's held save
and slot 0's confirmation before it cuts, instead of relying on serial order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* The stop's probe reads its typed failure (no dead field)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* Tests borrow instead of cloning into calls (contract_shape stays at its base)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* The broker test names the clone's type so it coerces at the call

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dependencies Pull requests that update a dependency file github_actions Pull requests that update GitHub Actions code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant