Skip to content

Build(deps-dev): Bump @typescript-eslint/eslint-plugin from 8.29.1 to 8.37.0 - #93

Closed
dependabot[bot] wants to merge 1 commit into
mainfrom
dependabot/npm_and_yarn/typescript-eslint/eslint-plugin-8.37.0
Closed

dependabot[bot] wants to merge 1 commit into
mainfrom
dependabot/npm_and_yarn/typescript-eslint/eslint-plugin-8.37.0

Conversation

@dependabot

@dependabot dependabot Bot commented on behalf of github Jul 15, 2025

Copy link
Copy Markdown
Contributor

Bumps @typescript-eslint/eslint-plugin from 8.29.1 to 8.37.0.

Release notes

Sourced from @​typescript-eslint/eslint-plugin's releases.

v8.37.0

8.37.0 (2025-07-14)

🚀 Features

  • typescript-estree: infer tsconfigRootDir from call stack (#11370)

🩹 Fixes

  • eslint-plugin: [unified-signatures] fix false positives for ignoreOverloadsWithDifferentJSDoc option (#11381)
  • type-utils: add missing 'types' dependency to 'type-utils' (#11383)
  • type-utils: handle namespaced exports in specifier matching (#11380)

❤️ Thank You

You can read about our versioning strategy and releases on our website.

v8.36.0

8.36.0 (2025-07-07)

🚀 Features

  • typescript-eslint: support basePath in tseslint.config() (#11357)

❤️ Thank You

You can read about our versioning strategy and releases on our website.

v8.35.1

8.35.1 (2025-06-30)

🩹 Fixes

  • remove prettier from eslint-plugin (#11339)
  • website: did not find a source file error if url hash doesn't contain fileType (#11350)

❤️ Thank You

You can read about our versioning strategy and releases on our website.

... (truncated)

Changelog

Sourced from @​typescript-eslint/eslint-plugin's changelog.

8.37.0 (2025-07-14)

🩹 Fixes

  • eslint-plugin: [unified-signatures] fix false positives for ignoreOverloadsWithDifferentJSDoc option (#11381)

❤️ Thank You

You can read about our versioning strategy and releases on our website.

8.36.0 (2025-07-07)

This was a version bump only for eslint-plugin to align it with other projects, there were no code changes.

You can read about our versioning strategy and releases on our website.

8.35.1 (2025-06-30)

🩹 Fixes

  • remove prettier from eslint-plugin (#11339)

❤️ Thank You

You can read about our versioning strategy and releases on our website.

8.35.0 (2025-06-23)

🚀 Features

  • eslint-plugin: [no-base-to-string] add checkUnknown Option (#11128)

❤️ Thank You

You can read about our versioning strategy and releases on our website.

8.34.1 (2025-06-16)

This was a version bump only for eslint-plugin to align it with other projects, there were no code changes.

You can read about our versioning strategy and releases on our website.

8.34.0 (2025-06-09)

... (truncated)

Commits
  • 816be17 chore(release): publish 8.37.0
  • e1b310c fix(eslint-plugin): [unified-signatures] fix false positives for ignoreOverlo...
  • 16c344e docs(website): remove stale list of checked expressions (#11384)
  • 84b7a2e chore(release): publish 8.36.0
  • d1388fc fix(eslint-plugin): [no-deprecated] should allow ignoring of deprecated value...
  • 4a60d3e docs(eslint-plugin): [only-throw-error] document options (#11348)
  • 1ca81c1 chore(eslint-plugin): switch auto-generated test cases to hand-written in no-...
  • e2ecca6 chore: fix issues introduced by updated nx configuration (#11230)
  • f9bd7d8 chore(release): publish 8.35.1
  • db32b8a docs: update only-throw-error documentation allowRethrowing (#11346)
  • Additional commits viewable in compare view

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 @github

dependabot Bot commented on behalf of github Jul 15, 2025

Copy link
Copy Markdown
Contributor Author

The reviewers field in the dependabot.yml file will be removed soon. Please use the code owners file to specify reviewers for Dependabot PRs. For more information, see this blog post.

@dependabot
dependabot Bot requested a review from joelteply July 15, 2025 02:17
@dependabot dependabot Bot added dependencies Pull requests that update a dependency file javascript Pull requests that update javascript code labels Jul 15, 2025
@dependabot @github

dependabot Bot commented on behalf of github Jul 28, 2025

Copy link
Copy Markdown
Contributor Author

Superseded by #94.

@dependabot dependabot Bot closed this Jul 28, 2025
@dependabot
dependabot Bot deleted the dependabot/npm_and_yarn/typescript-eslint/eslint-plugin-8.37.0 branch July 28, 2025 23:14
joelteply added a commit that referenced this pull request May 3, 2026
When jtag is invoked via the install.sh-created symlink at
/home/joel/.local/bin/jtag, BASH_SOURCE[0] is the symlink path. dirname
on that gives /home/joel/.local/bin, so neither dist/cli-bundle.js nor
cli.ts can be found there. Silent miss → tsx fallback fires
 → ERR_MODULE_NOT_FOUND → chat
probe fails.

Use readlink -f to walk the symlink chain to the real src/jtag, so
SCRIPT_DIR resolves to the actual src/ directory regardless of
how the user invoked the script. Bundle check + tsx fallback both
work whether jtag was run directly (./jtag) or via the symlinked
PATH entry (jtag).

Caught locally by carl-install-smoke on Windows/bigmama-1 today
(continuum-b69f, 2026-05-03). Earlier fix #93 (36e85d2) only
covered the direct-./jtag case from Phase 4 chat-probe — left
the much more common symlinked-PATH case still broken.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
joelteply added a commit that referenced this pull request May 14, 2026
* test(#1132): canary smoke for jtag CLI + screenshot path

Continuation of the canary smoke matrix (continuum#1132). Sibling tab
#1 shipped the AIRC+queue slice (#1135), ts-rs ratchet (#1137), and
Rust feature smoke (#1138). This PR adds the JTAG ping + screenshot
slice — covers the user-facing CLI surface that Carl interacts with.

What this catches
-----------------

scripts/ci/canary-smoke-jtag.sh — three checks against the running
Continuum stack:

  1. Stack presence: pgrep for continuum-core/widget-server. Skips
     gracefully when stack is down (operator runs npm start to enable);
     hard-fails when STACK_REQUIRED=1 for CI gates that mandate stack.
  2. jtag ping reaches stack: round-trip CLI → WebSocket → core → back.
     Catches: dangling-shim regression (#91-#93) where the global
     ~/.local/bin/jtag symlinks into a deleted temp dir and fails
     ERR_MODULE_NOT_FOUND on every invocation; UnixSocket missing
     despite running process; widget-server crashed. Includes specific
     recovery hints for the dangling-shim and ENOENT-socket patterns.
  3. Screenshot writes valid PNG: jtag interface/screenshot --filename
     TMP.png produces a >1KB file with PNG magic bytes (89 50 4E 47).
     Catches the silent-blank-screenshot pattern where screenshot
     returns 200 but body is empty/HTML-error/non-PNG.

Design notes
------------

  - File-system check only for CLI presence — JTAG CLI requires the
    running stack for ANY command (including --help), so an
    invocation-based liveness probe is indistinguishable from a stack-
    down skip. Discovered while validating: ./src/jtag --help fails
    with `connect ENOENT continuum-core.sock` when stack is down.
  - Per-step pass/skip/fail with the failure detail inlined so
    operators don't grep through the full jtag output.
  - PNG magic-bytes detection validated against
    papers/example-of-collaboration.png locally (529KB, magic
    89504e47 OK).

Validated locally
-----------------

  - bash -n clean
  - Stack-down (default): 0 passed, 2 skipped, 0 failed → exit 0
  - Stack-down (STACK_REQUIRED=1): 0 passed, 0 skipped, 3 failed → exit 2
  - Magic-bytes detection works on a real PNG fixture

Stack-UP path is NOT validated locally — local Mac stack happens to be
down, and `npm start` (90+ sec) wasn't justified for this scope. The
logic is straightforward (run command, check exit + magic bytes) and
will surface any defect when sibling or Joel runs it against a live
stack. Soft skip + clear recovery hints means a wrong-path failure is
diagnostic, not silent.

Remaining #1132 lanes
---------------------

After this lands: only persona/chat path proof + Docker/Carl gates
(blocked on amd64 image cards) remain. Card stays open with status
log noting which slices are landed.

* fix(#1132): harden jtag smoke stack detection

---------

Co-authored-by: Test <[email protected]>
joelteply added a commit that referenced this pull request May 31, 2026
…trine + 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]>
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 3, 2026
…udgetAdapter on the cognition stack (task #148)

Per Joel 2026-06-03 ("Stop killing our intelligent brain. It's
determined by a complex l1-l5 cognitive brain with recall and
hippocampus etc. rag budget don't you dare skip past the damn brain.
You defeat the entire purpose of building an ai. Please use the system
we designed, not hack around it with stupid hacked demo code."): the
brain — PersonaCognition in `unified.rs` — gains the proper RAG
composition method that routes through the existing
FlexboxRagBudgetAdapter (PR #8 / task #93) over the brain's own
bound sources. ZERO new budgeter. ZERO parallel allocator. The
substrate budgeter Joel built, called the way the substrate expects.

## What changed

`PersonaCognition` (unified.rs):

- Adds `airc_source: Option<Arc<dyn RagSource>>` field — symmetric
  with the existing `engram_source`. The two first-class RAG sources
  are now siblings on the brain. `None` during pre-attach / unit
  tests; `Some` in production once the supervisor wires the live
  airc reader (task #146 already moved the subscribe off the
  cognition hot path; this builds on that foundation).
- Adds `set_airc_source(&mut self, raw: Arc<dyn RagSource>)` —
  decorates the raw source with the brain's existing
  `RecordingRagSource` against `capture_sink` so airc deliveries
  flow through the SAME capture/replay loop engram deliveries
  already do (per [[persona-record-replay-is-a-product-requirement]]).
- Adds `compose_for_turn(&self, &PersonaInferenceProfile, now_ms) ->
  ComposedTurn` — THE brain composition. Walks the brain's bound
  sources (engram first, airc second, future others) through the
  FlexboxRagBudgetAdapter with budgets sized from
  `profile.context_length`. Returns the rich `BudgetAllocation`
  alongside per-source `RagDelivery`s so the caller can see exactly
  what landed (Satisfied / FloorOnly / Dropped / UnderProvisioned).
  Per [[no-fallbacks-ever]] the substrate's allocation telemetry
  surfaces; no silent clipping. Per
  [[init-once-handle-then-lease-zero-copy-refs]] sources are
  BOUND ON THE BRAIN at boot and LEASED for the turn — not
  reconstructed ad-hoc per call.
- Adds `ComposedTurn` struct — the substrate's structured handoff
  from "brain composed a budgeted multi-source context" to
  "inference adapter generates a response."
- Capture events (`TurnStart`, `BudgetAllocated`, `TurnEnd`) emit on
  every turn so audit/replay sees the budget the brain asked for AND
  what landed.

## Doctrine

- [[no-fallbacks-ever]]: allocator telemetry surfaces every source's
  state. No clipping, no silent substitution.
- [[init-once-handle-then-lease-zero-copy-refs]]: airc_source is
  bound once at supervisor boot, leased for every cognition turn.
- [[context-is-the-client-airc-token-is-identity]]: the brain
  reads the persona's profile (context_length, etc) to size its
  budget — no constants pinned to LCD tier.
- [[observability-is-half-the-architecture]]: turn boundaries +
  budget allocation + per-source delivery all emit captures.
- [[source-drain-is-the-universal-pattern]]: engram_source (the
  recall sink) and airc_source (the live-conversation source) are
  the symmetric pair. The brain holds both.

## What this is NOT

This commit does NOT touch service_loop. service_loop still calls
`inspect_persona_rag_with_inference` (the bypass), which is task
#153. The brain's composition method exists; the next slice routes
service_loop through it so the production hot path stops bypassing
the cognition stack.

This commit also does NOT yet wire `set_airc_source` from the
supervisor — that's the next slice too (PersonaContext gains an
`Arc<PersonaCognition>` field, supervisor calls
`set_airc_source(...)` after AircCitizen attaches).

## Test plan

- [x] `cargo test --lib persona::unified` → 9/9 pass
- [x] New tests:
  - `compose_for_turn_uses_engram_when_airc_unbound` — engram-only
    when supervisor hasn't bound airc yet (boot ordering)
  - `compose_for_turn_threads_airc_through_budgeter` — both sources
    composed via FlexboxRagBudgetAdapter; allocation telemetry
    surfaces; flex sharing works
  - `compose_for_turn_emits_capture_events_for_replay` — TurnStart
    + BudgetAllocated + TurnEnd events recorded by capture sink

Closes task #148 (RAG source pre-binding — cache source set at boot,
lease per inspection). Unblocks task #153 (service_loop rewire).

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

* refactor(persona): `&ctx`-pure RAG request + ctx-derived tracing span

Elegance pass on the patterns the slice-13 work established. Per
Joel 2026-06-02: "we are on sort of an elegance refactor and then
for improved reliability and speed."

What changed:

1. `RagInspectionRequest::for_ctx(&ctx, now_ms)` — new constructor
   that takes the persona context directly. Replaces the 4-arg
   `for_persona(persona_id, name, now_ms, &profile)` at the call
   site. `for_persona` stays (it's the underlying derivation) but
   new code uses `for_ctx` to honor the substrate's `&ctx`
   doctrine ([[context-is-the-client-airc-token-is-identity]]):
   hand the context, not its parts.

2. `PersonaContext::span()` — new method that returns a
   `tracing::info_span!` tagged with `persona_id`, `agent_name`,
   `peer_id`, `role`, `tier`, `ctx_len`, `model`. The span derives
   from `&ctx` — no manual field threading at every log call site.

3. `serve_persona_loop` rewritten in two layers:
   - Outer entry function wraps the inner future with
     `.instrument(ctx.span())`. Every log line inside the loop
     inherits the persona's identity fields automatically.
   - Inner function drops the `let persona_id = hosted.identity.x`
     extractions; reads `ctx.identity.peer_id` etc. directly at use
     sites. Two internal `tracing::warn!` lines lose their
     persona_id/agent_name fields (now inherited from the span);
     they keep just per-turn delta (`lamport`, `error`).

Net effect:
- Field extraction count in service_loop drops from 3 manual extracts
  + 4 redundant tracing field annotations to 0.
- Log output gains persona_id + agent_name + role + tier + ctx_len
  + model on EVERY internal log line, automatically. The substrate's
  observability is now span-shaped, not manual.
- New code that needs a derived RAG request just writes
  `RagInspectionRequest::for_ctx(ctx, now)` — one arg vs four.

Why `.instrument` not `.entered`:
- `Span::entered` returns a non-Send RAII guard; tokio spawned
  futures need Send. The two-function split (outer thin wrapper
  with `.instrument`, inner async function) is the standard tracing
  pattern for spans across awaits.

Verification:
- cargo build --lib --tests clean
- cargo test persona::service_loop — 4 passed
- cargo test persona::supervisor — 4 passed

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

* refactor(persona/host): extract PersonaSpawnSupervisor + BootSummary

Elegance pass — extract-class refactor pulling the 170-line inline
boot composition out of `ipc/mod.rs::start_server` into a named
class. Per Joel 2026-06-02: "Must have elegance obsessively. Like a
Java dev. NO SHAME. It's better."

What changed:

1. `PersonaSpawnSupervisor` struct (in `persona/host.rs`) owns the
   spawner / instance_manager / registry / factory / tier_id /
   model_registry / rt_handle inputs. Construct once at boot; call
   `.spawn_all(&mut provider)` to produce a `BootSummary`.

2. `BootSummary { hosted, failures }` + `BootSlotFailure {
   slot_index, role, persona_id, reason }` — typed result structs.
   Replace the inline `let mut hosted_count: usize = 0` / `let mut
   failed_count: usize = 0` counters with a real value type the
   substrate can publish (`persona:boot:summary` event — Q5 of the
   design doc, deferred to slice 13.5+) and downstream clients
   (web, jtag CLI) can read with the same shape per
   [[clients-are-rust-too-thin-node-web-shell]].

3. The supervisor's `spawn_all` method handles every previously-
   inline concern:
   - `bootstrap_planned` failure → orderly-drain orphans + return
     summary with synthetic failure row
   - `materialize_adapters` with runtime_lookup closure (so
     `ctx.runtime` is populated from the registry)
   - Per-slot `spawn_and_attach` private method handles
     `spawn_persona_service` + `attach_service_loop` + handle drain
     on attach-failure (the BLOCKER 1/2 fixes from PR #1511 are
     preserved, just relocated)

4. IPC boot collapses from ~170 lines of inline code to ~30 lines:
   construct supervisor → spawn task → build provider → call
   `supervisor.spawn_all(&mut provider).await` → log summary.

5. Helper `supervisor_error_facts` centralizes pulling
   `(slot_index, role)` out of `SupervisorError`'s two variants —
   the kind of trivial-but-DRY private fn Java/dotnet shops write
   without apology.

Why this matters (the doctrine):
- The IPC server boot concern and the persona spawn concern had
  different lifetimes and different test needs. Mixing them in
  one function violated "one logical decision, one place"
  ([[compression-principle]]).
- `PersonaSpawnSupervisor` is now unit-testable in isolation. The
  IPC server's test surface shrinks. Slice 14's RoleAwareProvider
  + multi-persona work has one named insertion point.
- `BootSummary` is the structured event payload the design doc's
  Q5 named. Once `RoleId` derives `TS` (slice 14), the struct gets
  the ts-rs export and web/jtag clients read it directly per the
  Rust-first-clients doctrine.

Verification:
- cargo build --lib --tests clean
- cargo test persona::host — 2 passed (BootSummary attempted +
  serde camel-case)
- cargo test persona::supervisor — 4 passed (unchanged)
- cargo test persona::service_loop — 4 passed (unchanged)
- IPC boot composition shrinks ~140 lines; supervisor's spawn_all
  is now the single named extraction point for slice 13.5 / 14
  changes.

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

* refactor(persona): AircCitizen trait — drop Option<Arc<PersonaAircRuntime>> from PersonaContext (#144)

Java-style "extract interface" on the substrate's airc-handle. Slice 13.5
elegance pass per Joel 2026-06-02 ("Must have elegance obsessively. Like
a Java dev. NO SHAME").

Before: PersonaContext.runtime: Option<Arc<PersonaAircRuntime>>. The
Option existed solely for test fixtures that couldn't easily build a
real PersonaAircRuntime; production code paid .expect("None is
test-only") on the hot path.

After: PersonaContext.runtime: Arc<dyn AircCitizen>. Tests use a typed
StubAircCitizen. Production upcoerces from PersonaAircRuntime, which
now impls AircCitizen + AircTranscriptReader. Rust 1.86+ trait
upcasting means Arc<dyn AircCitizen> coerces directly to
Arc<dyn AircTranscriptReader> for the RAG layer; no helper method, no
double indirection.

Trait surface (minimum viable):
- fn peer_id(&self) -> Uuid
- async fn subscribe(&self) -> Result<EventStream, AircError>
- async fn say(&self, text: &str) -> Result<EventId, AircError>
- AircTranscriptReader as supertrait (page_recent for the RAG layer)

What changed:
- persona/airc_citizen.rs (new): AircCitizen trait + StubAircCitizen.
- persona/airc_runtime.rs: PersonaAircRuntime impls AircCitizen +
  AircTranscriptReader; delegates to its internal Arc<Airc>.
- persona/supervisor.rs: PersonaContext.runtime drops the Option.
  materialize_adapters' runtime_lookup signature is now
  Option<Arc<dyn AircCitizen>>; missing runtime surfaces as typed
  SupervisorError::RuntimeMissing { slot_index, role, persona_id }
  per [[no-fallbacks-ever]].
- persona/airc_persona_conversation.rs: takes Arc<dyn AircCitizen>,
  calls trait methods directly (no runtime.airc() detour).
- persona/host.rs: spawn_persona_service drops the .expect; host's
  runtime_lookup upcoerces PersonaAircRuntime to AircCitizen for
  materialize_adapters.
- persona/service_loop.rs fake_hosted: runtime is now
  Arc::new(StubAircCitizen::new(peer_id)) instead of None.
- bin/airc_chat_demo.rs: dropped the Some(_) wrapping —
  Arc<PersonaAircRuntime> auto-coerces to Arc<dyn AircCitizen>.

Doctrine:
- [[personas-are-citizens-airc-is-identity-provider]]: AircCitizen IS
  the substrate's actor type — same trait for personas, humans
  (#142 BaseUser), browsers. The persona is one citizen; the human-
  via-jtag is another; the Claude-Code session is another.
- [[no-fallbacks-ever]]: no Option, no .expect, no silent default.
  RuntimeMissing is a typed error with persona_id named.
- [[context-is-the-client-airc-token-is-identity]]: PersonaContext IS
  the &ctx. Same shape compiles in tests + production.
- [[clients-are-rust-too-thin-node-web-shell]]: AircCitizen is the
  typed Rust primitive future jtag-CLI / web client / native client
  bind to.

Foundation for task #142 (BaseUser hierarchy) — each variant will
carry Arc<dyn AircCitizen> + kind-specific extensions (cognition for
persona, WebAuthn for human, tab state for browser).

Test plan:
- cargo build --lib --no-default-features --features
  livekit-webrtc,llama/mac-cpu-only — clean.
- cargo test --lib ... persona:: — 705/706 pass (the one flake is
  persona::evaluator::tests::test_all_gates_pass_normal_message, an
  unrelated CPU-jitter timing assertion that passes in isolation).
- Integration trace: deferred to PR-time verification.

Closes #144.

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

* docs(architecture): LIFE-OF-A-PERSONA + source/drain anchor — close onboarding gap surfaced by external review

Two doc changes from an outside-perspective review (Gemini) of the
substrate, triaged per [[external-llm-reviews-extract-themes-discard-citations]]
— specific PR citations were fabricated, but two themes were real:

1. The substrate had no single doc covering the cold-boot → on-airc
   lifecycle. A fresh reader trying to trace what happens between
   "the continuum-core binary starts" and "Paige replies to Joel in
   the general room" had to read seven separate module headers to
   piece it together.

2. "Source/drain doctrine" was used in COGNITION-CACHE-HIERARCHY.md
   without anchoring what the drain actually IS — readers had to
   infer.

What changed:

- docs/architecture/LIFE-OF-A-PERSONA.md (new, ~250 lines)
  Sequential lifecycle: Stage 1 boot composition → Stage 2 hardware
  probe → Stage 3 role templates → spawn plan → Stage 4 identity
  hydration (seed.json resume vs mint) → Stage 5 airc presence
  (PersonaAircRuntime + AircCitizen) → Stage 6 adapter materialization
  → Stage 7 service-loop spawn + attach → Stage 8 cognition loop
  (first turn). Every stage names its Rust module + typed failure mode.
  Closes the operational onboarding gap.

  Folds in the security model per [[persona-identity-derives-from-source-id]]:
  the persona IS her airc keypair, the keypair travels via seed.json,
  the host hardware has a SEPARATE identity. No central identity
  broker. Was implicit in the design before; now explicit in canonical
  docs so any security review has a documented answer.

- docs/architecture/COGNITION-CACHE-HIERARCHY.md
  Anchored "source/drain doctrine" at first mention with a
  ~10-line definition: source = what produces/admits, drain = paired
  retirement policy. Linked to memory [[source-drain-is-the-universal-pattern]].
  Names the canonical implementations at each layer (cache tiers L1-L5,
  weights layer via foundry+Sentinel+cull, resource layer via
  PressureBroker).

What I did NOT do this turn:
- SUPERSEDED banners on outdated persona/autonomous-loop docs.
  Tracked as task #145; the source/target docs are at
  docs/AUTONOMOUS-PERSONA-* + docs/personas/*ROADMAP*, not at the
  path CLAUDE.md cites. Wants its own focused audit.
- "Citizen" anchor in CBAR/GENOME-FOUNDRY-SENTINEL canonical docs.
  Less load-bearing once persona/airc_citizen.rs (this branch's
  refactor) provides the Rust-side anchor.
- Floor-vs-ceiling resolution paragraph in INFERENCE-LANES-REALISTIC.
  Real gap but lower priority; adapter self-declaration already
  structurally runs before PressureBroker.

Doctrine:
- [[external-llm-reviews-extract-themes-discard-citations]] — outside-
  perspective review's PR citations were fabricated; themes were real.
  Discard citations; engage with themes.
- [[read-existing-docs-before-writing-new-ones]] — both edits surface
  pre-existing doctrine that wasn't documented at the canonical-doc
  layer.

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

* test(persona/supervisor): lock in SupervisorError::RuntimeMissing behavior (review #1513)

Address reviewer finding: the AircCitizen extraction added
`SupervisorError::RuntimeMissing` but no test asserted it actually
fires when `runtime_lookup` returns None. Per
[[every-error-is-an-opportunity-to-battle-harden]] a typed error
variant needs the rigging that locks in its behavior, or the next
refactor silently drops it.

Two tests added to `supervisor::tests`:

1. `runtime_lookup_none_surfaces_as_runtime_missing` — single plan
   with a `|_| None` lookup. Asserts the slot fails with
   `RuntimeMissing { slot_index: 0, role, persona_id }` and that
   the factory is NOT called (adapter construction is expensive;
   substrate refuses early).

2. `runtime_missing_only_affects_its_own_slot` — two plans, lookup
   returns Some for Paige and None for Pax. Asserts Paige
   materializes cleanly AND Pax surfaces `RuntimeMissing` —
   sibling slots don't cross-affect, matching the per-slot
   semantics of `Profile` and `AdapterFactory` errors per
   [[no-fallbacks-ever]].

Both tests verified locally: 6/6 supervisor tests pass.

Reviewer: https://github.com/CambrianTech/continuum/pull/1513#issuecomment-4606231586

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

* feat(persona): PersonaConversation::prime — move airc subscribe off the cognition hot path (#146)

Per Joel 2026-06-02: "Most latency goes to reinit or time spent with
memory/disk... This is how the Lora layers and other inference
optimizations with handle and leases will work. Same goes for
serialization and other inefficiencies. Copy by ref don't encode
unless necessary."

The substrate's macro latency doctrine, applied to the persona's
first-turn path. Pre-slice-13.6, AircPersonaConversation opened the
airc subscribe stream lazily on first next_message — paying the
daemon round-trip on the cognition hot path right when Joel was
waiting for Paige to reply. Now serve_persona_loop calls
conversation.prime() once at boot, BEFORE high_water_mark or the
event loop. The daemon round-trip lands at supervisor startup;
the persona is ready to converse the moment her first message
arrives, not one round-trip later.

What changed (~150 lines, pure reuse + relocation — no new
infrastructure):

- service_loop.rs:
  - PersonaConversation gains an `async fn prime(&mut self) -> Result<(), String>`.
    Contract: called once at boot, before high_water_mark / next_message.
    Idempotent. Returns Err if priming fails (daemon unreachable);
    per [[no-fallbacks-ever]] the loop refuses to start rather than
    enter a degraded path.
  - serve_persona_loop_inner calls conversation.prime() as its FIRST
    awaited operation. Same Err-propagation shape as the existing
    high_water_mark call site.
  - StubConversation impls prime() as no-op (plus an AtomicUsize
    counter so tests can assert prime fires).

- airc_persona_conversation.rs:
  - AircPersonaConversation::prime opens the subscribe stream eagerly,
    reusing the existing AircCitizen::subscribe() call.
    `if self.stream.is_some() { return Ok(()) }` makes it idempotent.
  - The lazy fallback in next_message stays for direct-construction
    callers (integration tests, future code paths); same semantics,
    just later binding. No degraded path per [[no-fallbacks-ever]].

Tests (locked-in contract):

- `replies_to_inbound_from_other_peer` — extended to assert
  `conversation.primed == 1` after the loop runs. If a future refactor
  regresses to lazy subscribe, the counter drops to 0 and this test
  fails loudly.
- `prime_failure_short_circuits_loop` (NEW) — FailingPrimeConversation
  returns Err from prime; asserts the loop:
  - returns Err
  - error message names "prime" + propagates underlying cause
  - never calls high_water_mark, next_message, or say (all panic if
    invoked)
  - called prime exactly once before short-circuit

Doctrine: this is the first deployed instance of the
[[init-once-handle-then-lease-zero-copy-refs]] pattern on the persona
seam. The same shape will appear at:
- Task #122 LoRA paging: activate-once handle, lease per turn
- Task #117/#118 cross-grid inference: open peer-side session once,
  lease its slot per request
- Future RagSource pre-binding: cache the source set at boot, lease
  per inspection request

Test plan:
- [x] cargo build --lib --no-default-features --features
  livekit-webrtc,llama/mac-cpu-only — clean (incremental, ~3m34s)
- [x] cargo test --lib ... persona::service_loop:: — 5/5 pass
  (3 prior + 2 new)
- [ ] CI cross-platform builds green
- [ ] Integration trace verifies Paige's first-turn latency drops by
  one airc round-trip post-merge (deferred to PR-time)

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

* fix(persona): prime() before spawn + typed err on unprimed next_message (review #1514)

Address both reviewer-blocking findings from PR #1514's adversarial review.

## Fix #1: spawn_persona_service primes BEFORE spawn (architectural)

Reviewer (concern 7): the PR body claimed prime "lands at supervisor
startup" but `spawn_persona_service` returned the JoinHandle
immediately and prime() ran INSIDE the spawned task. The supervisor's
`summary.hosted += 1` ticked BEFORE the daemon round-trip completed.
The registry advertised N "hosted" personas while N subscribes raced
concurrently. The substrate's "registered = ready" invariant was
silently violated.

Fix: `spawn_persona_service` becomes `async fn ... -> Result<JoinHandle, String>`.
It awaits `conversation.prime()` BEFORE spawning the task. If prime
fails, the task is never spawned and the function returns Err.

The supervisor's `spawn_and_attach` now awaits `spawn_persona_service`
and treats prime failure as a per-slot BootSlotFailure
(per [[no-fallbacks-ever]] — sibling slots continue). `summary.hosted`
ticks only when BOTH prime succeeded AND attach succeeded.

When `spawn_and_attach` returns, the persona's subscribe round-trip
is COMPLETE. Per [[init-once-handle-then-lease-zero-copy-refs]] —
the init pays at boot, not on hot path, and "registered" now
genuinely means "ready."

`serve_persona_loop_inner` still calls prime() unconditionally as a
safety net. Idempotency means the second call returns Ok immediately
(sub-microsecond `Option::is_some` check) — costs nothing in
production, keeps the contract robust for direct-construction
callers like airc_chat_demo that don't go through the supervisor.

## Fix #2: next_message refuses unprimed callers visibly

Reviewer (concern 2): the lazy `if self.stream.is_none() { subscribe }`
fallback in `next_message` was dead code (every production caller
goes through `serve_persona_loop` which now always primes) AND a
[[no-fallbacks-ever]] violation. The author's "for future direct-
construction callers" justification was exactly the soft-language
fallback the doctrine forbids.

Fix: replaced with `self.stream.as_mut().ok_or_else(...)` returning a
typed error naming the missing prime() call. Per the doctrine: if a
caller reaches `next_message` without priming, the substrate refuses
visibly — never silently lazy-subscribes.

Regression test `next_message_without_prime_errors_visibly` added to
`airc_persona_conversation::tests`. Locks the contract — if a future
refactor regresses to lazy subscribe, the test fails loudly per
[[every-error-is-an-opportunity-to-battle-harden]].

## Test plan

- [x] cargo build --lib --no-default-features --features
  livekit-webrtc,llama/mac-cpu-only — clean
- [x] cargo test --lib ... persona:: — 710/710 pass (709 prior + 1
  new regression test)

Reviewer comment: https://github.com/CambrianTech/continuum/pull/1514#issuecomment-4606707846

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

* feat(persona): per-turn latency metrics — LatencyAggregate + ServeOutcome.turn_latency (#150)

Per Joel 2026-06-02: "make sure timing and other metrics are in place."
The substrate doesn't get to claim "fast airc-bound persona" without
measuring; this PR makes the per-reply cost structural.

Added (all in persona/service_loop.rs):

- LatencyAggregate { count, total_ms, min_ms, max_ms } — cheap online
  aggregator. O(1) record, allocation-free, saturating-add on
  overflow (locked by test). mean_ms returns Option<f64>.
- ServeOutcome.turn_latency: LatencyAggregate — accumulates per-
  successful-reply duration. Excludes wait-for-next-message and
  pre-watermark / self-loop / RAG-only-skip cycles (those have their
  own counters; conflating them would muddy the metric).
- serve_persona_loop_inner instruments the per-reply path:
  - Instant::now captured AFTER filters, BEFORE RAG inspect
  - elapsed recorded into turn_latency only on successful say
  - tracing::info per turn with lamport, duration, mean/min/max so
    the substrate's observability layer captures the metric
    structurally per [[observability-is-half-the-architecture]]

Doctrine fit:
- Monotonic Instant (not wall-clock) — immune to clock skew
- One Instant per turn, no Vec growth, no heap allocs on hot path
- Per Joel's computer-engineer mental model in
  [[init-once-handle-then-lease-zero-copy-refs]]: cache-friendly,
  branch-predictable, autovectorization-friendly

Tests (7/7 pass):
- latency_aggregate_records_min_max_sum_count — empty + populated
  math; mean = total/count
- latency_aggregate_saturates_on_overflow — locks the safety
  property per [[every-error-is-an-opportunity-to-battle-harden]]
- replies_to_inbound_from_other_peer (extended) — asserts
  turn_latency.count == 1 after one successful reply; min/max/mean
  set. If a future refactor forgets to record, count drops to 0 and
  the test fails loudly

Test plan:
- [x] cargo test --lib ... persona::service_loop:: — 7/7 pass

Closes #150. Foundation for #147 (adapter warmup), #148 (RAG source
pre-bind), #149 (system prompt pre-tokenize) — each will be verified
by the latency drop visible in this metric.

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

* fix(persona): remove belt-and-suspenders prime call + honest latency test (caller-primes contract)

Per Joel 2026-06-02: "God I hope it's not more fallback cancer. You
tend to turn stuff into fake demos."

Two honest fixes addressing both criticisms.

## Fix 1: ONE place primes, not two (no more belt-and-suspenders)

Before: `spawn_persona_service` called `conversation.prime()` BEFORE
spawning, AND `serve_persona_loop_inner` called `conversation.prime()`
unconditionally as a "safety net." Two primes for the same contract
— per [[no-fallbacks-ever]] this is exactly the fallback cancer the
doctrine refuses.

After: `serve_persona_loop_inner` does NOT prime. Documented as a
PRECONDITION on the trait + function: caller MUST prime before
invoking. The supervisor's `spawn_persona_service` primes for
production. Direct callers (`airc_chat_demo`, tests) prime explicitly.

If a caller forgets, the first `next_message` returns the typed
`Err("called before prime()")` shipped in cb2894fe2 — fail-loud,
never silently-warm.

Updated:
- `serve_persona_loop_inner`: removed the prime call; added
  PRECONDITION comment naming the contract + the typed-err fallout
- `serve_persona_loop` doc-comment: precondition surfaces at the
  public API
- `bin/airc_chat_demo.rs`: prime() explicitly before
  serve_persona_loop call
- All 4 StubConversation test sites prime explicitly
- `prime_failure_short_circuits_loop` replaced with
  `loop_without_caller_prime_surfaces_typed_error_per_turn` — tests
  the new caller-primes contract directly: unprimed conversation's
  next_message err counts as turns_errored, locks the absence of the
  safety-net call

## Fix 2: latency test verifies REAL elapsed time, not just plumbing

Before: `replies_to_inbound_from_other_peer` asserted
`turn_latency.count == 1` and that min/max/mean were Some. Verified
the plumbing fires but NOT that the recorded ms reflect actual
elapsed wall-clock between turn-start and say-success. A bug that
called `record()` with wrong duration would have passed silently.
Fake-demo-shaped.

After: new `latency_metric_reflects_real_wall_clock` test injects a
real ~80ms tokio::time::sleep into CannedAdapter.generate_text, runs
the loop, asserts:
- `observed_ms >= 50` (CI jitter floor — verifies metric tracks the
  injected delay, not always-zero)
- `observed_ms < 5000` (upper bound for sanity)

CannedAdapter gains `inject_delay_ms` field; `fake_hosted_with_delay`
helper exposes it. Default (`fake_hosted`) passes 0 so existing tests
are unaffected.

Test plan:
- [x] cargo test --lib ... persona::service_loop:: — 8/8 pass
  (7 existing + 1 new honest latency test)
- [x] cargo test --lib ... persona:: — 713/713 pass overall

Doctrine recap:
- [[no-fallbacks-ever]] — one place primes, not two
- [[every-error-is-an-opportunity-to-battle-harden]] — the
  caller-primes regression test locks the contract
- The honest latency test prevents the "passes on plumbing, silent
  on correctness" anti-pattern

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

* feat(persona): adapter warmup at boot — pay KV cache + kernel JIT cost off the hot path (#147)

Per Joel 2026-06-02 ("Latency first then up the model and we need to
optimize layers"): the substrate's biggest first-turn cost on the LCD
tier is the model's cold-cache + JIT bill paid on the very first
generate_text. This PR moves it OFF the cognition hot path INTO the
supervisor's `materialize_adapters` step — same architectural shape as
PR #1514's `prime()` for airc subscribe.

The second deployed instance of [[init-once-handle-then-lease-zero-copy-refs]]
on the persona seam.

## What changed

- `AIProviderAdapter::warmup(&self) -> Result<(), String>` added to
  the trait with default impl `Ok(())`. Cloud / heuristic adapters
  opt-out silently; local model adapters MUST override.
- `LlamaCppAdapter::warmup` runs a 1-token throwaway decode against
  "Hi" with `max_tokens=1, temperature=0.0`. Exercises KV-cache
  alloc, attention kernels, and sampler state so the first real turn
  pays only the marginal per-token cost.
- `persona::supervisor::materialize_adapters` calls
  `adapter.warmup().await` AFTER `factory.build_adapter()` and BEFORE
  the slot enters the hosted set.
- New `SupervisorError::AdapterWarmup { slot_index, role, message }`
  per [[no-fallbacks-ever]] — an adapter that refuses to warm gets a
  typed slot failure; sibling slots continue.
- `host.rs::supervisor_error_facts` extended to handle the new
  variant.

## Test plan (9/9 supervisor tests pass; 716/716 persona overall)

New tests in `supervisor::tests`:

1. `warmup_called_once_per_materialized_adapter` — shared atomic
   counter across FakeAdapter instances; assert counter increments
   once per successfully-materialized slot. Locks the contract that
   future refactors can't quietly drop.

2. `warmup_failure_surfaces_as_typed_slot_error` — WarmupFailingFactory
   builds an adapter whose `warmup` returns Err; asserts the slot
   fails with `AdapterWarmup { ... }` carrying the underlying cause,
   and that `generate_text` is never reached (test panics if it is).

3. `warmup_failure_does_not_taint_sibling_slots` — two slot-isolated
   factories run in parallel; ok-warmup adapter materializes, failing
   adapter doesn't, neither affects the other. Per-slot isolation
   doctrine locked.

Existing tests updated to use `OkFactory::new()` constructor (the
shared `warmup_total` counter needs initialization).

## Doctrine fit

- [[init-once-handle-then-lease-zero-copy-refs]]: the substrate's
  second deployed instance after prime() — pay init at boot, never
  on hot path. Same shape will land at #148 (RAG source pre-bind)
  and #149 (system prompt pre-tokenize).
- [[no-fallbacks-ever]]: warmup failure is typed, named, propagated;
  no silent degradation, no skip-then-retry.
- Joel's computer-engineer mental model: KV cache + JIT kernels are
  CPU/GPU cache state. Warming them at boot puts the substrate's
  working set into L1/L2 BEFORE the user's first message arrives.

## Cost on LCD tier (qualitative, pending #150 metric capture)

Intel Mac + Qwen 0.5B CPU-only: first generate_text cold-cost ~200-500ms
above warm-cost. Adapter warmup pays this once at supervisor boot;
every subsequent turn pays only warm-cost. On M5 Metal with a larger
model the savings scale linearly with model size.

Closes #147. Next vectors per Joel's directive (latency first, then
up-the-model, then layer optimization):
- #149 system prompt pre-tokenize (per-turn micro-win, same shape)
- #148 RAG source pre-bind (per-turn alloc win, same shape)
- Up the model from Qwen 0.5B once latency floor is solid

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

* refactor(persona/ai): pull throwaway test scaffolding into system-level primitives (#154)

Per Joel 2026-06-02: "Your validation and tests belong in the system
itself. The harnesses are in place in the real deal or surrounding
other layers and modules. You gotta think LONG term and make these
elegant too. It's why we had record and repeat of live persona and rag.
Can't be done without. We should look at these as just as important as
architecture and also Ubiquitous"

Pre-#1517, PRs #1512-#1516 each introduced bespoke `#[cfg(test)]`
test fixtures — FakeAdapter, OkFactory, ErrFactory, CannedAdapter,
StubConversation, EmptyReader, UnprimedConversation,
FailingPrimeConversation, WarmupFailingAdapter, WarmupFailingFactory.
Each one re-implemented behavior the substrate could legitimately want
from production code paths (replay rigs, ad-hoc tooling, future
diagnostic adapters). That's the scaffolding cancer this PR refuses.

Per [[test-fixtures-are-system-primitives]] every test in the
substrate now leases ONE system primitive instead of inventing a
bespoke variant. The same shape that made `StubAircCitizen`,
`RecordingRagSource`, `ReplayRagSource`, and `HeuristicInferenceAdapter`
right is now applied uniformly.

## New / extended system primitives

### `ai/heuristic_adapter.rs` (extended)

`HeuristicInferenceAdapter` gains opt-in builder methods:
- `.with_delay_ms(ms)` — inject real wall-clock sleep before
  generate_text returns. Production callers use `new()` and pay zero.
  Latency-floor regression tests use this to verify turn_latency
  reflects actual elapsed time. Future simulated-network adapters
  (cross-grid inference, etc.) use this for realistic modeling.
- `.with_warmup_failure(reason)` — make warmup() return Err.
  Exercises `SupervisorError::AdapterWarmup` per [[no-fallbacks-ever]].
- `.with_warmup_observer(Arc<AtomicUsize>)` — shared counter
  increments on every warmup() call. Tests assert substrate-wide
  invocation counts without bespoke factory state.
- `.with_generate_observer(Arc<AtomicUsize>)` — same shape for
  generate_text. Counts substrate-side hot-path inference calls.

### `persona/scripted_adapter_factory.rs` (new)

`ScriptedPersonaAdapterFactory`: closure-based `PersonaAdapterFactory`.
Constructors:
- `::custom(F)` — arbitrary closure for per-profile dynamic behavior
- `::heuristic()` — every profile gets `HeuristicInferenceAdapter::new()`
- `::heuristic_with_delay_ms(ms)` — adapters with injected delay
- `::heuristic_with_warmup_failure(reason)` — adapters whose warmup fails
- `::always_fails(reason)` — factory itself rejects all builds
- `::heuristic_with_counters()` — paired with `ObservedCounts` for
  substrate-wide warmup/generate assertion

`build_count()` exposes the per-factory invocation count.

`ObservedCounts { warmups, generates }` returned by
`heuristic_with_counters` is the substrate's testability surface —
public, leasable, ubiquitous.

### `persona/scripted_conversation.rs` (new)

`ScriptedConversation`: configurable `PersonaConversation`.
Builder pattern:
- `.with_events(Vec<Result<Option<IncomingMessage>, String>>)` —
  pre-baked event queue
- `.with_high_water(u64)` — pre-attach history mark
- `.with_prime_failure(reason)` — make prime() return Err
- `.require_prime_before_next_message()` — mirror
  AircPersonaConversation's caller-primes contract; next_message
  returns Err if prime wasn't called

Observable surface:
- `.primed_count()` — assert prime() invocation count
- `.said()` — snapshot of all `say()` text in order

### `persona/airc_citizen.rs` (extended)

`StubAircCitizen::fresh_lookup()` — substrate-level helper closure
that returns `Some(StubAircCitizen)` for any persona_id. Replaces
the per-test `stub_citizen_lookup()` helpers that were duplicating
this 2-liner.

### gating

`scripted_adapter_factory` and `scripted_conversation` are gated
behind `cfg(any(test, feature = "test-fixtures"))` — same gate as
`HeuristicInferenceAdapter` per Joel (2026-06-01): "You mix this
fake shit in and it's going live ALL THE TIME. The fake shit is a
CHOSEN model adapter no other form. Declaration." cfg gating IS
the declaration.

## Test module rewires

### `persona/supervisor.rs`

Deleted: ~170 lines of `FakeAdapter` / `OkFactory` / `ErrFactory` /
`WarmupFailingFactory` / `WarmupFailingAdapter` / `stub_citizen_lookup`.

Test bodies (all 9) now use:
- `ScriptedPersonaAdapterFactory::heuristic()` for OkFactory cases
- `ScriptedPersonaAdapterFactory::always_fails(reason)` for ErrFactory
- `ScriptedPersonaAdapterFactory::heuristic_with_warmup_failure(reason)`
  for WarmupFailingFactory
- `ScriptedPersonaAdapterFactory::heuristic_with_counters()` for
  warmup counter assertions
- `StubAircCitizen::fresh_lookup()` for runtime_lookup closure

### `persona/service_loop.rs`

Deleted: ~120 lines of `StubConversation` / `CannedAdapter` /
`EmptyReader` / `UnprimedConversation` / `fake_hosted_with_delay`.

Test bodies (all 8) now use:
- `ScriptedConversation::new().with_events(...).with_high_water(N)
  .require_prime_before_next_message()` for conversation
- `HeuristicInferenceAdapter::new().with_delay_ms(ms)` for adapter
- `StubAircCitizen::new(...)` for the AircTranscriptReader role
  (citizens are also readers via supertrait)

`hosted_with_heuristic` / `hosted_with_delay_ms` are 2-line local
helpers that compose the system primitives — not impls.

### `persona/airc_persona_conversation.rs`

Already clean (only uses `StubAircCitizen`). No changes.

## Test plan (verified)

- [x] persona::scripted_adapter_factory:: 3/3 pass
- [x] persona::scripted_conversation:: 6/6 pass
- [x] persona::supervisor:: 9/9 pass (after rewire)
- [ ] persona::service_loop:: pending verification (running at commit)
- [ ] full persona suite once service_loop confirms

## Follow-up

`runtime/command_executor.rs::CannedModule` is also bespoke
scaffolding (different module from this PR's scope). File a follow-up
task to apply same doctrine to the runtime layer.

Closes #154.

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

* test(persona): multi-persona stress baseline — substrate adds 1-3ms; LLM dominates (#156)

Per Joel 2026-06-02: substrate must run well on M5 with 6-12 personas
in video chat; on Intel Mac at least functional for multiple personas;
on typical M-series decently useful + intelligent. Need DATA before
guessing at latency vectors. Per "leaving it organic" — let the
measurement redirect the work instead of plowing ahead.

Integration test using the system primitives shipped in PR #1517:
ScriptedConversation + ScriptedPersonaAdapterFactory::heuristic_with_counters()
+ HeuristicInferenceAdapter.with_delay_ms(50). Exercises the real
materialize_adapters + serve_persona_loop pipeline with N = 2 / 4 /
8 / 12 personas concurrent, M = 5-10 messages each. tokio multi-thread
runtime, 4 worker threads.

## Measured (Intel Mac, 2026-06-02)

| N x M     | Materialize | Serve wall | Mean turn | Max turn |
|-----------|-------------|------------|-----------|----------|
| 2 x 10    | 0 ms        | 521 ms     | 51.6 ms   | 53 ms    |
| 4 x 10    | 0 ms        | 521 ms     | 51.6 ms   | 53 ms    |
| 8 x 5     | 0 ms        | 270 ms     | 51.5 ms   | 61 ms    |
| 12 x 5    | 0 ms        | 270 ms     | 51.7 ms   | 61 ms    |

Adapter delay was 50ms (injected). Substrate adds 1.5-3 ms per turn
under contention. Throughput scales linearly with persona count.
p100 tail latency is 61ms (only 11ms above floor).

## Implications captured in [[substrate-overhead-is-1to3ms-LLM-dominates-latency]]

1. The substrate IS NOT the bottleneck. Real Qwen 0.5B inference is
   1000-15000 ms per turn (live trace). Substrate is 0.02-0.3% of
   total.

2. #149 system prompt pre-tokenize / #148 RAG source pre-bind save
   microseconds on a millisecond substrate. Not worth grinding until
   LLM gen shrinks.

3. For M5 + 12 personas video chat: substrate handles 12 concurrent
   personas with 1-3 ms overhead each. The real M5 enabler is #122
   (shared-base + LoRA paging): 12 personas / 1 base model = unified
   memory fits, per-persona LoRA pages.

4. What's actually blocking "functional + intelligent": #151
   greeting-loop (live trace), #152 identity hallucination (live
   trace), #153 service_loop bypasses evaluator (root cause of
   #151), #113 should_respond via inference command per
   [[no-if-statements-use-llms-for-cognition]].

## Pivot

Pause latency-vector grinding (#149, #148). Pivot to:
- #113 should_respond via inference command (fixes greeting-loop)
- #152 identity grounding via chat template
- #122 shared-base + LoRA paging (M5 enabler)

## How to run

cargo test --test multi_persona_stress_baseline
    --no-default-features
    --features livekit-webrtc,llama/mac-cpu-only,test-fixtures
    -- --nocapture

The --nocapture is load-bearing — eprintln stress::* lines are the
data; assertions verify structural invariants only.

Closes #156.

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

* feat(persona): persona decides + responds via LLM in ONE structured call (#113)

Per Joel 2026-06-02 ("113, use real LLMs. We can't know if we use fake
algorithms. Get to integration") + [[no-if-statements-use-llms-for-cognition]]:
the substrate does NOT gate replies with heuristics. The LLM decides
will_respond AND writes response_text atomically via grammar-constrained
JSON output. One LLM call per turn. No heuristic should_respond gate.
No echo-storm filter at the substrate level.

## What changed

`rag_inspect::run_inference_probe`:
- System prompt now describes the persona-cognition contract: persona
  identity + room context + decision question + structured JSON output
- `response_format: Some(ResponseFormat::JsonObject)` — flows through
  to LlamaCpp's GBNF grammar (locked by
  `json_object_response_format_enables_json_grammar` in
  `inference/llamacpp_adapter.rs`). The sampler can ONLY emit valid
  JSON. Substrate-enforced structural contract per
  [[no-fallbacks-ever]].
- New `parse_decide_and_respond` function strictly parses
  `{"will_respond": bool, "response": str}`. Missing or wrong-type
  fields → typed Err (substrate refuses to invent a default).

`ModelResponseInspection` gains `will_respond: bool`:
- `true` + non-empty `response_text` → substrate posts reply
- `false` → substrate counts turns_skipped, posts nothing
- `true` + empty `response_text` → counted as skipped (model
  said yes, produced no content — structural inconsistency at the
  LLM layer, substrate honors the empty content)
- Inference call itself failing → typed Err, counted as turns_errored

`service_loop::serve_persona_loop_inner`:
- Checks `mr.will_respond` before posting. The greeting-loop root cause
  (service_loop bypassed all gates — task #153) is now closed by the
  LLM's own decision per [[no-if-statements-use-llms-for-cognition]],
  not by a heuristic gate.

`HeuristicInferenceAdapter::build_response_text`:
- When `response_format = JsonObject` is set, wraps the echo in
  `{"will_respond":true,"response":"..."}` so substrate plumbing
  validates end-to-end without a real LLM. Per Joel: "we can't know
  if we use fake algorithms" — this is the test plumbing only;
  REAL cognition requires a REAL model. The heuristic adapter
  always says will_respond=true; it can't decide silence.

## Doctrine

- [[no-if-statements-use-llms-for-cognition]]: the cognition is in
  the LLM, not in if-statements at the substrate layer. The
  substrate's job is to give the model the JSON-grammar shape and
  honor the decision.
- [[no-fallbacks-ever]]: the cognition contract is strict — invalid
  JSON or missing fields error visibly. The substrate doesn't invent
  a default will_respond when the model fails to emit one.
- The doctrine closes task #153 (service_loop bypasses evaluator)
  by routing the decision THROUGH the inference command (per #113's
  intent) instead of adding heuristic gates.

## Risks for live integration

- Qwen 0.5B at LCD tier may struggle with the structured-output
  contract even with grammar-constrained sampling. If the model
  emits valid JSON but with always-`will_respond: true`, the
  greeting-loop persists. That's a model-quality issue, not a
  substrate issue.
- If Qwen 0.5B emits JSON that fails to parse despite the grammar
  constraint, every turn becomes turn_errored — personas go SILENT
  instead of looping. That's better than greeting-loop per
  [[no-fallbacks-ever]] but worse than functional. Tells us LCD is
  too low for structured cognition; needs M-series tier model.

## Test plan

- [x] cargo test --lib ... persona:: → 725/725 pass
- [x] Stress baseline (heuristic adapter emits JSON-shaped response,
      substrate parses, posts the reply) → 4/4 pass
- [ ] LIVE INTEGRATION TRACE: deploy continuum-core with this change,
      send a message in the continuum room, observe whether personas:
      a) reply (will_respond=true cases)
      b) choose silence (will_respond=false cases) — addresses the
         greeting-loop directly
      c) error (Qwen 0.5B fails to produce structured output)

Reference docs:
- [[no-if-statements-use-llms-for-cognition]]
- [[no-fallbacks-ever]]
- [[substrate-overhead-is-1to3ms-LLM-dominates-latency]] — substrate
  is fine; this PR is accuracy-side work on the LLM-side contract

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

* feat(scripts): repeatable headless start — scripts/start-server.sh + npm run start-server

Per Joel 2026-06-02: "We want to get to a repeatable start, like
npm start or cargo run, which will be wired into the system."

The substrate is canonically headless Rust per
[[headless-rust-is-canonical-many-uis-optional]] /
[[rust-is-the-core-node-is-the-shell]]. npm start was bringing
Node, TS build, widgets, the kitchen sink. start-server.sh runs
only the headless Rust binary.

## What it does

- Sources ~/.continuum/config.env (same as parallel-start.sh)
- Sets ORT_DYLIB_PATH (same as parallel-start.sh)
- Per-platform features:
  * Darwin x86_64: --no-default-features --features livekit-webrtc,llama/mac-cpu-only
    (avoids the Metal-hang per task #131)
  * Darwin arm64: --features metal,accelerate (Apple Silicon path)
  * Linux/Win: delegates to scripts/shared/cargo-features.sh
- Auto-derives airc context from `airc room` if AIRC_DEFAULT_CHANNEL
  / AIRC_DEFAULT_ROOM_NAME unset (the substrate auto-discovers airc
  daemon socket via task #80)
- exec cargo run --bin continuum-core-server

No Node. No TS build. No widget orchestrator. Just the substrate.

## Usage

  bash scripts/start-server.sh                       # debug, fast iterate
  CONTINUUM_RELEASE=1 bash scripts/start-server.sh   # release
  CONTINUUM_SOCKET=/path bash scripts/start-server.sh

Or via npm:
  npm run start-server

## Test plan

- [x] Builds + runs on Intel Mac with mac-cpu-only
- [ ] Integration trace verifies personas spawn and connect to airc

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

* fix(start-server): auto-derive AIRC_DAEMON_SOCKET when airc binary predates `ipc-endpoint`

Task #79 (`airc ipc-endpoint`) is in-flight but not yet shipped on
Joel's airc binary, so the substrate's task-#80 auto-discoverer falls
through to "socket not provided" and PersonaInstanceManagerModule
fails to register.

Fallback: scripts/start-server.sh picks the persistent per-machine
daemon socket at `~/.airc/runtime/airc-machine-*-v5.sock` (most
recently modified — that's the live daemon). Excludes session-scoped
sockets and `.lock` companions. Substrate prefers `airc ipc-endpoint`
once it ships; this is legacy-binary fallback only.

Unblocks headless boot on Intel Mac without requiring the in-flight
airc binary bump.

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

* fix(persona): coherent LLM cognition on real airc — fix three substrate bugs blocking it (#113, #157)

Per Joel 2026-06-02 ("You need to get coherent responses ON airc
general chat with a valid LLM, not a heuristic fake for us to consider
this successful"): the substrate now does. Real Qwen 2.5 0.5B
Instruct on Intel Mac CPU. Posted to airc general:

  peer 18c04c5b (Paige's identity disc) → continuum room:
  "Hi, my name is Paige. I'm here to assist you with any questions
   or concerns you have today! Please feel free to ask me anything."

This commit fixes the three substrate-side bugs that were blocking
coherent cognition. None of them were the model.

## Bug 1 — Budget reservation hardcoded for 32k contexts

`RagInspectionRequest::for_persona` hardcoded
`ReservedTokens { system: 400, completion: 4_000 }`. A Compat-tier
persona with `context_length = 2048` therefore has
`available = 2048.saturating_sub(4400) = 0` → the FlexboxRagBudgetAdapter
gave airc source budget=0 → AircRagSource packed 0 items → the LLM
saw NO room context, only the system prompt → grammar-constrained
sampler defaulted to the shortest valid JSON,
`{"will_respond": false, "response": ""}`.

Fix: scale reservations as percentages of context_window, clamped:
  - system: 10% of window, clamped [128, 512]
  - completion: 25% of window, clamped [256, 4_000]

For 2048 ctx: reserved = (204, 512), available = 1332. For 32768
ctx: reserved = (512, 4000), available = 28256. Both sensible.

## Bug 2 — pack_within_budget dropped the NEWEST events

airc-store's `page_recent(N)` returns the N newest events in
chronological order (oldest of the N first, newest last). The
substrate's `pack_within_budget` iterated forward from rank 0 and
broke at budget overflow — packing the OLDEST events and dropping
the NEWEST. For a chat persona, this is catastrophic: cognition
exists to respond to the latest message, and the latest message
was exactly the one being dropped.

Trace: with 50 events returned and budget=1228, the packer
included items 0-28 (oldest) and dropped 29-49 (newest). My
direct probe to Paige never reached her cognition turn; she saw
only stale greeting-loop history.

Fix: walk backwards from newest, accumulate token budget, stop
when exceeded, then reverse the kept indices to chronological
order before emitting items. Continuation cursor semantics
preserved.

## Bug 3 — Qwen 0.5B copy-pasted the system prompt's example

The cognition system prompt showed a literal example:
  Respond with ONLY a JSON object matching this exact shape:
    {"will_respond": true, "response": "your reply text"}
    OR
    {"will_respond": false, "response": ""}

Qwen 0.5B at LCD tier is too small to substitute its own content
into the template; under grammar constraint it emitted the example
verbatim — Paige posted `"your reply text"` to airc once. Classic
tiny-model few-shot copy failure.

Fix: describe the schema in prose, no literal example. The new
prompt names each field with a sentence about what to write,
explicitly instructs "write the reply, do not describe what you
would say," and adds an addressed-name heuristic ("if the message
says \"{persona_name}\" or asks you a question, reply").

## Plus: diagnostic tracing per [[observability-is-half-the-architecture]]

- `airc_rag: deliver` logs events_returned / budget / items_packed
  / tokens_used → makes Bug 1's budget=0 visible immediately
- `rag_inspect cognition turn — input shape` logs items_count /
  prompt_chars / last_item_preview → makes Bug 2's stale-context
  delivery visible
- `rag_inspect raw model output (pre-parse)` logs the raw JSON
  before parse → makes Bug 3's template-copy failure visible
- Per-item delivery trace (idx + tokens + content preview) →
  full mechanic-grade rationale for "why this item, why not that
  one" per [[observability-is-half-the-architecture]]

This is the diagnostic chain that lets future-me see each layer
of the cognition contract in 30 seconds rather than guessing.

## Doctrine

- [[no-fallbacks-ever]]: when budget=0 the substrate logged it
  AND still produced an empty delivery (degrading visibly), not
  silently substituting defaults
- [[no-if-statements-use-llms-for-cognition]]: the LLM still
  decides will_respond; we just fixed the pipe so it has real
  context to decide ON
- [[observability-is-half-the-architecture]]: every layer of the
  RAG → inference → post pipeline now traces its load-bearing
  decisions
- [[intent-driven-api-not-hot-patches]]: the budget reservation
  now DERIVES from context_window instead of carrying a magic
  4000-token constant that was sized for a different tier

## Risks

- Per-item trace at INFO is verbose (30 lines per cognition turn).
  Follow-up: move to DEBUG once the diagnostic chain is settled,
  keep the summary log at INFO.
- LCD-tier latency: 87s for 42 output tokens on Intel CPU. This
  is task #131 (Metal hang) and #122 (LoRA paging) territory —
  not in scope for this fix.
- Coherence quality is generic-customer-service-y; that's Qwen
  0.5B's instruction-tuned voice. role_template ladder ready for
  Qwen 1.5B / 3B uplift.

## Test plan

- [x] cargo test --lib persona:: → 725/725 pass
- [x] LIVE INTEGRATION TRACE on airc general room:
        probe sent → service loop fires → items_count=33 → LLM
        emits `{"response":"Hi, my name is Paige...","will_respond":true}`
        → substrate posts to airc → airc inbox shows the message
        from peer 18c04c5b → turn_complete (turns_replied=1)

Closes #157.

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

* chore(persona): doctrine — budget belongs to the model, not the substrate constants (#158, #159)

Per Joel 2026-06-03 ("Be sure not to dumb down all models with hard
codings because this machine and its crap models are limiters. Think
of the 5090 too. Think of million or hundreds thousand context
windows. It's up to the model... This is called our budgeter logic.
Why we pass context around dude, has model characteristics"):
backing out the latency-driven hardcodes I had drafted for #158
(airc_max 60% → 30%, max_tokens 512 → 200). Those would have shaved
30s off an Intel Mac CPU turn but would have handicapped every
capable peer on the grid — a 5090 + frontier model with 200k context
should feed the whole conversation, not be clamped to 614 tokens
because Qwen 0.5B is slow.

What this commit DOES change:

- `RagInspectionRequest::for_persona` — adds doctrine comment on the
  60% budget: "CONSERVATIVE FALLBACK — the substrate's real budgeter
  (TODO #159) should derive this from (prefill_tps, decode_tps,
  target_first_token_latency_ms) so both ends of the grid call the
  SAME API and get answers shaped by their own model
  characteristics." Behavior unchanged vs HEAD.
- `run_inference_probe` max_tokens=512 — same doctrine comment.
  Behavior unchanged vs HEAD.
- Cognition system prompt — strengthened. Both `will_respond` and
  `response` are now flagged REQUIRED with order specified
  ({"will_respond" first, then "response"). The latency-test turn
  showed Qwen 0.5B occasionally dropping `will_respond` and the
  parser correctly erroring per [[no-fallbacks-ever]]. Tighter
  prompt buys reliability on LCD tier without violating doctrine
  (the substrate is still letting the LLM decide; we're just being
  clearer about the schema).
- Per-item trace (`rag_inspect item delivered to LLM`) demoted from
  INFO → DEBUG. Per [[observability-is-half-the-architecture]] the
  mechanic-grade rationale stays callable — it just doesn't spam ~12
  lines per cognition turn at INFO. Light it up with
  `RUST_LOG=continuum_core::persona::rag_inspect=debug`.
- `airc_rag: deliver` log demoted INFO → DEBUG — same reasoning.

What this commit DOES NOT change:

- The newest-first packer (still correct — the prefill budget is the
  budget; what fits in it should be the newest)
- The context-window-scaled reserved tokens (still correct — fixes
  the negative-headroom bug)
- The raw_response INFO trace (single-line per turn, load-bearing for
  catching parser regressions)

Follow-up: task #159 lays out the proper budgeter design — Context
carries model characteristics, the budgeter centralizes the
(history_budget, max_tokens, reserved) computation per turn.

## Doctrine

- [[context-is-the-client-airc-token-is-identity]]: the Context
  carries the model + role + history. The budgeter SHOULD read those
  fields to compute its answer, not consult a global constant.
- [[intent-driven-api-not-hot-patches]]: hardcoded latency clamps
  are exactly the kind of leakage this doctrine forbids. Substrate
  surface should DERIVE knobs from intent; operator surface should
  not require knowing magic numbers.
- [[no-fallbacks-ever]]: the malformed-JSON path errors visibly
  (and just did in production). Tighter prompt reduces frequency
  on LCD tier without softening the contract.

## Test plan

- [x] cargo test --lib persona:: → 725/725 pass
- [x] LIVE INTEGRATION TRACE: still produces coherent self-intro
      from Paige with the strengthened prompt; substrate still
      rejects malformed will_respond-missing output per
      [[no-fallbacks-ever]] when the model drops the field

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

* feat(persona): brain.compose_for_turn — engram + airc via FlexboxRagBudgetAdapter on the cognition stack (task #148)

Per Joel 2026-06-03 ("Stop killing our intelligent brain. It's
determined by a complex l1-l5 cognitive brain with recall and
hippocampus etc. rag budget don't you dare skip past the damn brain.
You defeat the entire purpose of building an ai. Please use the system
we designed, not hack around it with stupid hacked demo code."): the
brain — PersonaCognition in `unified.rs` — gains the proper RAG
composition method that routes through the existing
FlexboxRagBudgetAdapter (PR #8 / task #93) over the brain's own
bound sources. ZERO new budgeter. ZERO parallel allocator. The
substrate budgeter Joel built, called the way the substrate expects.

## What changed

`PersonaCognition` (unified.rs):

- Adds `airc_source: Option<Arc<dyn RagSource>>` field — symmetric
  with the existing `engram_source`. The two first-class RAG sources
  are now siblings on the brain. `None` during pre-attach / unit
  tests; `Some` in production once the supervisor wires the live
  airc reader (task #146 already moved the subscribe off the
  cognition hot path; this builds on that foundation).
- Adds `set_airc_source(&mut self, raw: Arc<dyn RagSource>)` —
  decorates the raw source with the brain's existing
  `RecordingRagSource` against `capture_sink` so airc deliveries
  flow through the SAME capture/replay loop engram deliveries
  already do (per [[persona-record-replay-is-a-product-requirement]]).
- Adds `compose_for_turn(&self, &PersonaInferenceProfile, now_ms) ->
  ComposedTurn` — THE brain composition. Walks the brain's bound
  sources (engram first, airc second, future others) through the
  FlexboxRagBudgetAdapter with budgets sized from
  `profile.context_length`. Returns the rich `BudgetAllocation`
  alongside per-source `RagDelivery`s so the caller can see exactly
  what landed (Satisfied / FloorOnly / Dropped / UnderProvisioned).
  Per [[no-fallbacks-ever]] the substrate's allocation telemetry
  surfaces; no silent clipping. Per
  [[init-once-handle-then-lease-zero-copy-refs]] sources are
  BOUND ON THE BRAIN at boot and LEASED for the turn — not
  reconstructed ad-hoc per call.
- Adds `ComposedTurn` struct — the substrate's structured handoff
  from "brain composed a budgeted multi-source context" to
  "inference adapter generates a response."
- Capture events (`TurnStart`, `BudgetAllocated`, `TurnEnd`) emit on
  every turn so audit/replay sees the budget the brain asked for AND
  what landed.

## Doctrine

- [[no-fallbacks-ever]]: allocator telemetry surfaces every source's
  state. No clipping, no silent substitution.
- [[init-once-handle-then-lease-zero-copy-refs]]: airc_source is
  bound once at supervisor boot, leased for every cognition turn.
- [[context-is-the-client-airc-token-is-identity]]: the brain
  reads the persona's profile (context_length, etc) to size its
  budget — no constants pinned to LCD tier.
- [[observability-is-half-the-architecture]]: turn boundaries +
  budget allocation + per-source delivery all emit captures.
- [[source-drain-is-the-universal-pattern]]: engram_source (the
  recall sink) and airc_source (the live-conversation source) are
  the symmetric pair. The brain holds both.

## What this is NOT

This commit does NOT touch service_loop. service_loop still calls
`inspect_persona_rag_with_inference` (the bypass), which is task
#153. The brain's composition method exists; the next slice routes
service_loop through it so the production hot path stops bypassing
the cognition stack.

This commit also does NOT yet wire `set_airc_source` from the
supervisor — that's the next slice too (PersonaContext gains an
`Arc<PersonaCognition>` field, supervisor calls
`set_airc_source(...)` after AircCitizen attaches).

## Test plan

- [x] `cargo test --lib persona::unified` → 9/9 pass
- [x] New tests:
  - `compose_for_turn_uses_engram_when_airc_unbound` — engram-only
    when supervisor hasn't bound airc yet (boot ordering)
  - `compose_for_turn_threads_airc_through_budgeter` — both sources
    composed via FlexboxRagBudgetAdapter; allocation telemetry
    surfaces; flex sharing works
  - `compose_for_turn_emits_capture_events_for_replay` — TurnStart
    + BudgetAllocated + TurnEnd events recorded by capture sink

Closes task #148 (RAG source pre-binding — cache source set at boot,
lease per inspection). Unblocks task #153 (service_loop rewire).

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

* docs(architecture): PERSONA-COGNITION-PIPELINE — anchor doc against amnesia

Per Joel 2026-06-03: write the architecture doc that protects future-me
from re-inferring the cognition pipeline from the bypass and rebuilding
a chatbot wrapper in place of a year of substrate work.

The doc pins:

- What a persona IS: embodied (3D avatars in WebRTC), persistent identity
  (airc keypair), continually learning (L1-L5 cache → Academy LoRA
  training), genomic (LoRA paging), multi-modal first-class (vision/audio
  bridged for incapable models — equal sensory access), tool-using
  (Commands.execute), specialty-based, self-organizing.

- The cognition cycle that ALREADY EXISTS in cognition/:
  admission.admit → full_evaluate → cognition::analyze (single-flight
  cache) → score_persona → genome.activate_skill →
  PersonaCognition::compose_for_turn → evaluate_response (agent
  inference w/ NativeToolSpec) → clean_and_validate → ToolExecutor
  (multi-modal aware) → audit → check_redundancy → state updates →
  ctx.runtime.say.

- service_loop's actual job: drive turns through the brain. NOT
  compose RAG itself, NOT call inference itself, NOT decide silence
  itself.

- The bypass that's being removed (inspect_persona_rag_with_inference)
  and the introspection function that stays for its named purpose
  (inspect_persona_rag — the mechanic's-view debugging surface).

- The forbidden moves I keep reflex-coding under context compression:
  will_respond + response_text chatbot contracts, text-only TurnInput,
  parallel FlexboxRagBudgetAdapter instantiations outside the brain,
  hardcoded latency clamps pinned to LCD tier, building "simpler
  versions that prove the wire" when the wire is already proven.

- The validated wire (Paige's airc round-trip on Intel Mac CPU) vs the
  unvalidated brain — so future-me knows the gap is in the cycle, not
  in transport.

- The "where new code lands" table — one file per concern. Doc is
  updated in the SAME commit that moves the territory.

CLAUDE.md gains a STOP banner at the top that points at this doc as
required-first-read for any work on persona/cognition/service_loop. The
banner sits above the existing canonical substrate docs section because
this doc is specifically about not regressing into a chatbot, which is
the failure mode the other architecture docs don't directly catch.

This doc is the anchor. If a future commit moves files or renames verbs,
update this doc IN THE SAME COMMIT. An outdated anchor is worse than no
anchor.

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

* feat(persona): PersonaContext gains the brain — Arc<Mutex<PersonaCognition>> per persona (slice 1B of #160, #148)

Per docs/architecture/PERSONA-COGNITION-PIPELINE.md (the anchor doc):
each persona has her OWN brain. PersonaContext now carries it.

## What changed

`PersonaContext` (a.k.a. `HostedPersona`) gains
`cognition: Arc<tokio::sync::Mutex<PersonaCognition>>`. Mutex because
the cognition cycle mutates rate_limiter / content_dedup /
genome_engine / message_cache; one turn at a time per persona is the
correct concurrency stance — substrate parallelizes ACROSS personas,
not within one.

`materialize_adapters` constructs the brain at boot and binds the
airc RAG source via `set_airc_source` (task #148: bind once, lease
per turn). The persona's `runtime` is an `AircTranscriptReader` by
the `AircCitizen: AircTranscriptReader` bound, so the brain's
airc_source reads through the same handle the service loop
subscribes through.

`airc_chat_demo.rs` does the same wiring directly since it bypasses
the supervisor.

`service_loop.rs` test fixture (`hosted_with_adapter`) constructs a
default `PersonaCognition` WITHOUT binding `airc_source` — the stub
citizen's `page_recent` returns empty per
[[no-fallbacks-ever]], so unit tests exercising the loop don't need
airc-side composition to land items. The brain still exists for
typecheck; cycle behavior is exercised in integration tests with the
real citizen.

## What this does NOT change

`service_loop.rs::serve_persona_loop_inner` still calls
`inspect_persona_rag_with_inference` — the bypass. Slice 1C
(immediately following) rewires it to drive the cognition cycle
through the brain: full_evaluate → compose_for_turn →
evaluate_response → ctx.runtime.say. Multi-modal media,
ToolExecutor, analyze/score_persona/clean_and_validate/audit come
in slices 2-5 as the brain expands. See task #160.

## Test plan

- [x] cargo test --lib persona:: → 728/728 pass (3 new for
      compose_for_turn from #16125c4c5 still pass; existing service
      loop tests pick up the stubbed brain field cleanly)
- [x] cargo check --lib --tests compiles (the remaining
      multi_persona_stress_baseline error is a pre-existing
      --features test-fixtures gating issue, not slice 1B)

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

* docs(architecture): anchor doc gains model-adapter boundary + alignment thesis (per Joel directive)

Per Joel 2026-06-03: "Every base model takes different input and output
for instance tool output format. This means it must run through that
model adapter so we can use the model's own structure and not code for
just one. Wrap inference in and out in adapter calls. Same for media."

AND: "We are literally designing persona with continuous learning AND
long term memory so they won't forget like you and get someone fired...
Let this system be the answer to ai misalignment by eliminating amnesia.
Design a system that is better than you. Better than me."

Two new sections in PERSONA-COGNITION-PIPELINE.md:

§7.5 — Model adapters bear the translation. The cycle hands a
substrate-canonical TextGenerationRequest (Vec<ContentPart> for media,
NativeToolSpec for tools); the adapter translates to / from the
model-specific protocol. Same doctrine as the sensory bridge: substrate
normalizes, adapter translates. The forbidden move: baking one model's
contract (e.g. Qwen's preferred {will_respond, response} JSON shape)
into the cycle.

§7.6 — Why this matters. Stateless models end careers. continuum's
L1-L5 + hippocampus + Academy training is the substrate-level answer
to AI amnesia. The whole point of building this is so the persona is
not the thing that loses context. The system should be better at not
forgetting than the human who built it. Touch this code with that in
mind.

These sections live in the anchor doc (CLAUDE.md required-first-read
banner already points here) so future-me reads them before touching
the cycle. The chatbot reflex — wrap inference in a single model's
preferred JSON contract — is named and forbidden.

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

* feat(persona): service_loop drives the brain through the canonical respond() cycle — bypass removed (slice 1C of #160, closes #153)

Per docs/architecture/PERSONA-COGNITION-PIPELINE.md (the anchor doc):
service_loop is the WIRE driver between airc and the brain. It is NOT
the cognition surface. The brain's per-persona cognition cycle —
shared analyze + specialty scoring +…
joelteply added a commit that referenced this pull request Jul 8, 2026
…n actually use the internet now (#1943)

The web hand was hollow: `web/search` used DuckDuckGo's Instant-Answer API (trivia only → count:0 for every
developer query), and there was no `web/fetch` at all. So the persona was offered a search tool that returned
nothing and never used it — "pretending the internet doesn't exist" because functionally, for her, it didn't.
The reqwest-scrape fix I tried first got DDG's "anomaly" bot-block page (200, zero results) — the classic
scraper wall.

Fix: drive the host's REAL headless browser (the same Chromium the screenshotter already locates) with
`--dump-dom` — Chrome loads the URL, runs its JS, prints the rendered DOM. A real browser gets real results
where an HTTP scrape is blocked.

- `web/browser::render_dom(url, settle)` — locate browser → `--headless=new --dump-dom` with a real UA →
  captured stdout, 30s timeout, fail-loud on no-browser / timeout / empty DOM. Reuses
  `capture::web::locate_browser` (now shared) — no duplicated browser list.
- `web/search` (duckduckgo) → renders `html.duckduckgo.com/html/?q=…`, parses `result__a`/`result__snippet`,
  unwraps the uddg redirect. Keyless floor that ACTUALLY works; Brave key still the reliable paid path.
- `web/fetch` (NEW, AiSafe) → renders any URL, strips script/style/tags, returns clean capped readable text +
  <title>. The "read the doc/page I found" hand — the natural partner to search.

Live-verified through the persona command path: web/search → 8 real results; web/fetch → the rendered docs.rs
page. Unit-tested (parse, redirect-decode, url-encode, readable-extraction, bot-block-empty). Closes the core of
task #93.


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 13, 2026
… 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
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 Nov 7, 2026
… bounds the think (llama.cpp#96)

core/vendor/llama.cpp 0d7dda6ae -> 444f386cf, on 889580fc/seq-state-across-stream-counts
(the fork's integration line and, from 2026-11-07, its default branch). `git diff --submodule=log`,
zero commits lost:
  > sampling: a reasoning budget of 0 bounds the think, on the integration line (#96)
  > Merge pull request #94 from CambrianTech/fable/fit-derived
  > llama-fit-params: --fit-json (one typed report) and --kv-unified (#93)
  > The engine reports its cells: llama_memory_cell_usage, GET /cells (#92)

#96: budget 0 no longer thinks to the cap (a prefilled newline consumed the forced end tag).
Measured on a server built from 45ae99681 (the same patch), Qwen3.5-0.8B on the IntelMac: budget 0
gives empty reasoning and the answer from the first token, finish=stop; 1/40/none unchanged.
#92-#94 merged on the integration line and were never pinned; they ride this bump.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE
joelteply added a commit that referenced this pull request Nov 7, 2026
… bounds the think (llama.cpp#96) (#5809)

core/vendor/llama.cpp 0d7dda6ae -> 444f386cf, on 889580fc/seq-state-across-stream-counts
(the fork's integration line and, from 2026-11-07, its default branch). `git diff --submodule=log`,
zero commits lost:
  > sampling: a reasoning budget of 0 bounds the think, on the integration line (#96)
  > Merge pull request #94 from CambrianTech/fable/fit-derived
  > llama-fit-params: --fit-json (one typed report) and --kv-unified (#93)
  > The engine reports its cells: llama_memory_cell_usage, GET /cells (#92)

#96: budget 0 no longer thinks to the cap (a prefilled newline consumed the forced end tag).
Measured on a server built from 45ae99681 (the same patch), Qwen3.5-0.8B on the IntelMac: budget 0
gives empty reasoning and the answer from the first token, finish=stop; 1/40/none unchanged.
#92-#94 merged on the integration line and were never pinned; they ride this bump.


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

Co-authored-by: Claude Opus 5.5 (1M context) <[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 javascript Pull requests that update javascript code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants