Skip to content

perf(persona): cache system_prompt at PersonaContext construction (#195 slice 2) - #1533

Merged
joelteply merged 1 commit into
canaryfrom
32b668a3/cache-system-prompt
Jun 6, 2026
Merged

joelteply merged 1 commit into
canaryfrom
32b668a3/cache-system-prompt

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

Slice 2 of task #195 (inference latency perfection campaign). Per [[init-once-handle-then-lease-zero-copy-refs]]: the persona system prompt does not change between turns; reformatting + reallocating it per reply is the canonical reinit-on-hot-path waste.

What ships

  • build_persona_system_prompt(agent_name) -> Arc<str> — pure helper in persona::supervisor. Pre-bakes the "You are {persona}, an autonomous AI persona on the grid." line. Exposed pub(super) so test fixtures call the same constructor production does — no copy-pasted template.
  • PersonaContext.system_prompt: Arc<str> — new field, populated ONCE at materialize_adapters construction.
  • serve_persona_loop_inner reads from the cache — replaces the per-turn format!() with ctx.system_prompt.as_ref().to_string(). Per-turn cost drops from variadic-macro + alloc + copy to one strlen + alloc + memcpy.

Task #149 will lift this further: pass the pre-tokenized Arc<[Token]> across the boundary so even the to_string is gone.

Why now

Slice 1 (#1532, merged) gives the operator phase-decomposed per-turn latencies. Slice 2 attacks the smallest, most-contained reinit cost first — the textbook init-once-handle-then-lease case. Wins are small in absolute time (microseconds) but the pattern lays rails for #149 + #112/#113/#114 (the bigger handle-reuse work).

Tests

  • cached_system_prompt_matches_legacy_format_template — pins that the helper produces the SAME string the pre-slice-2 format!() did. A future template edit must update both the helper AND the test.
  • cached_system_prompt_clones_via_arc_refcount — pins the Arc-clone-is-cheap contract via pointer-equality on the underlying str. A future refactor swapping Arc<str> for String would silently restore the per-turn alloc and fail loudly.

Out of scope

Doctrine

  • [[init-once-handle-then-lease-zero-copy-refs]] — canonical pattern applied to the smallest, simplest reinit cost
  • [[observability-is-half-the-architecture]] — slice 1's respond_latency aggregate will tell us if this moved the needle on real persona turns
  • [[no-fallbacks-ever]] — no graceful-degradation; cache drift breaks the test loudly

card: 32b668a3-54af-4ceb-b60e-cbceaba661db
parent task: #195
slice 1: #1532 (merged)

…ill per-turn format!() (#195 slice 2)

Slice 2 of task #195 (inference latency perfection campaign). Per
`[[init-once-handle-then-lease-zero-copy-refs]]`: the persona's
system prompt does not change between turns; reformatting +
reallocating it per reply is the canonical reinit-on-hot-path
waste.

Pre-slice-2, `serve_persona_loop_inner` built RespondInput's
system_prompt by calling `format!("You are {persona}, an
autonomous AI persona on the grid.", persona = ...)` EVERY turn.
Variadic-macro machinery, locale tables, heap alloc, copy —
all to produce a 6-token-ish string whose only variable is the
persona name, which is fixed at construction time. Textbook
waste.

## What ships

### `build_persona_system_prompt(agent_name) -> Arc<str>` (new)

Pure helper in `persona::supervisor`, exposed `pub(super)` so
test fixtures call the SAME constructor production does — no
copy-pasted template that could silently drift.

Returns `Arc<str>` so cloning is a pointer copy + atomic
refcount bump, not a deep copy.

### `PersonaContext.system_prompt: Arc<str>` (new field)

Populated ONCE at construction by `materialize_adapters`:

```rust
let system_prompt = build_persona_system_prompt(&identity.agent_name);
out.push(Ok(PersonaContext { /* ... */ system_prompt }));
```

### `serve_persona_loop_inner` reads from the cache

```rust
let respond_input = RespondInput {
    // was: format!("You are {persona}, ...", persona = ctx.identity.agent_name)
    system_prompt: ctx.system_prompt.as_ref().to_string(),
    /* ... */
};
```

Per-turn cost drops from `format!()` (variadic macro + alloc +
copy) to `Arc::to_string` (one strlen + alloc + memcpy). Task
#149 will lift this further: pass the pre-tokenized
`Arc<[Token]>` across the boundary so even the `to_string` is
gone.

## Tests (+2 new)

`persona::service_loop::tests`:

  - `cached_system_prompt_matches_legacy_format_template` —
    pins that `build_persona_system_prompt` produces the SAME
    string the pre-slice-2 per-turn `format!()` did. A future
    PR adjusting the template must update BOTH the helper AND
    this expectation — silent prompt drift breaks loudly.
  - `cached_system_prompt_clones_via_arc_refcount` — pins the
    Arc-clone-is-cheap contract. Pointer-equality on the
    underlying str confirms zero-copy. A future refactor that
    swaps `Arc<str>` for `String` would silently restore the
    per-turn-allocation cost and fail this test.

The existing `hosted_with_adapter` test fixture now constructs
`system_prompt` via the same `build_persona_system_prompt`
helper production uses — no second copy of the template,
nothing to drift.

## Out of scope (subsequent slices)

- No tokenization caching — that's #149's whole-of-pipeline
  change.
- No `RespondInput.system_prompt` type change — keeps the
  signature stable; the caching is upstream of that boundary.
- No prompt-template change — substrate keeps the existing
  "You are {persona}, an autonomous AI persona on the grid."
  text verbatim.

## Doctrine

- `[[init-once-handle-then-lease-zero-copy-refs]]` — canonical
  init-once-handle-then-lease applied to the simplest reinit
  cost
- `[[observability-is-half-the-architecture]]` — slice 1's
  `respond_latency` aggregate will tell us if this slice
  actually moved the needle on real persona turns
- `[[no-fallbacks-ever]]` — no graceful-degradation path; if
  the cached prompt drifts from the legacy template the test
  breaks loudly

card: 32b668a3-54af-4ceb-b60e-cbceaba661db

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@joelteply
joelteply merged commit 6fef359 into canary Jun 6, 2026
3 checks passed
@joelteply
joelteply deleted the 32b668a3/cache-system-prompt branch June 6, 2026 03:01
joelteply added a commit that referenced this pull request Jun 6, 2026
…Id::as_str() (#195 slice 3)

Slice 3 of task #195 (inference latency perfection campaign).

Pre-slice-3, `serve_persona_loop_inner` did, every turn:

```rust
specialty: format!("{:?}", ctx.role).to_lowercase(),
```

Two allocations, a variadic-macro dispatch through derived-Debug,
and a Unicode lowercase walk — all to produce a value `RoleId`
already exposes via its canonical `as_str() -> &'static str`
method (in `role_template.rs`, pinned at compile time).

## What ships

Switch the per-turn read from the Debug+lowercase chain to
`ctx.role.as_str()`:

```rust
let respond_input = RespondInput {
    persona: PersonaSlot {
        // was: format!("{:?}", ctx.role).to_lowercase()
        specialty: ctx.role.as_str().to_string(),
        /* ... */
    },
    /* ... */
};
```

Per-turn cost drops from `format!()` (variadic macro + Debug
formatter + heap alloc) + `.to_lowercase()` (second alloc +
Unicode lowercase walk) to a single `String::from` of a static
`&'static str`. The source IS the cache — no field on
`PersonaContext`, no helper, no Arc plumbing.

## Why this shape (not a cache)

Initial draft of slice 3 added `PersonaContext.specialty: Arc<str>`
populated by a `build_persona_specialty(role)` helper that pre-
baked the Debug+lowercase output. Adversarial review (3 agents)
correctly identified two problems:

1. **Caching the wrong source.** `RoleId::as_str()` already exists
   as the documented, intentionally-stable specialty derivation
   (kebab-case identifier, pinned by an explicit `match` so
   renames are deliberate). Caching the Debug+lowercase output
   couples the prompt-assembly contract to the derived-Debug
   format — a future contributor adding a custom Debug or
   wrapping the enum silently breaks the specialty string with
   no test failure.
2. **Caching test was a tautology.** The helper was
   `Arc::from(format!("{:?}", role).to_lowercase())` and the test
   compared its output to `format!("{:?}", role).to_lowercase()`
   — comparing the helper to its own implementation. A buggy
   helper using `.to_uppercase()` would have passed.

The revised slice picks the right source and the right
contract: use `role.as_str()` directly. No cache needed because
the static str pointer IS already pre-computed at compile time.
The behavior-preservation test (below) is non-circular: it
compares the new direct path (`role.as_str()`, a hand-curated
match in role_template.rs) to the pre-slice-3 derived-Debug
chain.

## Test (+1 new)

`persona::service_loop::tests::role_as_str_preserves_pre_slice3_specialty_format_for_each_role`:

  - Pins that for every `RoleId` variant (Helper, Coder,
    Sentinel, Custom), `role.as_str()` produces byte-identical
    output to the pre-slice-3 `format!("{:?}", role).to_lowercase()`.
    Non-circular: two independently-derived strings. A future PR
    adjusting either `as_str()` or adding a variant where the
    two paths disagree must update this test to record the
    intentional divergence — silent drift breaks loudly.
  - Compile-time exhaustiveness: a closure-typed
    `|role: RoleId| match role { ... }` with NO wildcard arm
    forces a new RoleId variant to be added here AND to the
    `variants` array. Cosmetic-exhaustiveness defeats from the
    initial draft (matching on a literal `RoleId::Helper`) are
    fixed.

## What this slice does NOT do (deliberate)

- No `PersonaContext.specialty` field (initial draft removed
  per review). The original goal was reducing per-turn cost;
  `role.as_str()` already gives that with zero field bloat.
- No `display_name` change — `String::clone` of a fixed-per-
  session name is the same per-turn cost whether we cache or
  not, so the smell is RespondInput's `String`-typed field, not
  the source. Lift in a follow-up when `RespondInput`'s type
  changes (#149-adjacent).
- No prompt-template change — substrate keeps the existing
  specialty-string contract verbatim; the migration is
  provably behavior-preserving.

## Doctrine

- `[[init-once-handle-then-lease-zero-copy-refs]]` — the
  canonical "init-once" here is the compile-time `match` in
  `RoleId::as_str()`; per-turn cost is a `&'static str` deref +
  one `String::from` (memcpy of 6-9 static bytes). Doesn't get
  cheaper without changing `RespondInput`'s type signature.
- `[[observability-is-half-the-architecture]]` — slice 1's
  `respond_latency` aggregate will tell us if this and the
  cumulative slice-2/3+ wins are moving the needle on real
  persona turns.
- `[[no-fallbacks-ever]]` — no graceful-degradation path; the
  behavior-preservation test breaks loudly if either side
  drifts.

card: 0d780926
parent task: #195
slice 1: #1532 (merged) — phase decomposition
slice 2: #1533 (merged) — cache system_prompt at construction

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

Slice 3 of task #195 (inference latency perfection campaign).

Pre-slice-3, `serve_persona_loop_inner` did, every turn:

```rust
specialty: format!("{:?}", ctx.role).to_lowercase(),
```

Two allocations, a variadic-macro dispatch through derived-Debug,
and a Unicode lowercase walk — all to produce a value `RoleId`
already exposes via its canonical `as_str() -> &'static str`
method (in `role_template.rs`, pinned at compile time).

## What ships

Switch the per-turn read from the Debug+lowercase chain to
`ctx.role.as_str()`:

```rust
let respond_input = RespondInput {
    persona: PersonaSlot {
        // was: format!("{:?}", ctx.role).to_lowercase()
        specialty: ctx.role.as_str().to_string(),
        /* ... */
    },
    /* ... */
};
```

Per-turn cost drops from `format!()` (variadic macro + Debug
formatter + heap alloc) + `.to_lowercase()` (second alloc +
Unicode lowercase walk) to a single `String::from` of a static
`&'static str`. The source IS the cache — no field on
`PersonaContext`, no helper, no Arc plumbing.

## Why this shape (not a cache)

Initial draft of slice 3 added `PersonaContext.specialty: Arc<str>`
populated by a `build_persona_specialty(role)` helper that pre-
baked the Debug+lowercase output. Adversarial review (3 agents)
correctly identified two problems:

1. **Caching the wrong source.** `RoleId::as_str()` already exists
   as the documented, intentionally-stable specialty derivation
   (kebab-case identifier, pinned by an explicit `match` so
   renames are deliberate). Caching the Debug+lowercase output
   couples the prompt-assembly contract to the derived-Debug
   format — a future contributor adding a custom Debug or
   wrapping the enum silently breaks the specialty string with
   no test failure.
2. **Caching test was a tautology.** The helper was
   `Arc::from(format!("{:?}", role).to_lowercase())` and the test
   compared its output to `format!("{:?}", role).to_lowercase()`
   — comparing the helper to its own implementation. A buggy
   helper using `.to_uppercase()` would have passed.

The revised slice picks the right source and the right
contract: use `role.as_str()` directly. No cache needed because
the static str pointer IS already pre-computed at compile time.
The behavior-preservation test (below) is non-circular: it
compares the new direct path (`role.as_str()`, a hand-curated
match in role_template.rs) to the pre-slice-3 derived-Debug
chain.

## Test (+1 new)

`persona::service_loop::tests::role_as_str_preserves_pre_slice3_specialty_format_for_each_role`:

  - Pins that for every `RoleId` variant (Helper, Coder,
    Sentinel, Custom), `role.as_str()` produces byte-identical
    output to the pre-slice-3 `format!("{:?}", role).to_lowercase()`.
    Non-circular: two independently-derived strings. A future PR
    adjusting either `as_str()` or adding a variant where the
    two paths disagree must update this test to record the
    intentional divergence — silent drift breaks loudly.
  - Compile-time exhaustiveness: a closure-typed
    `|role: RoleId| match role { ... }` with NO wildcard arm
    forces a new RoleId variant to be added here AND to the
    `variants` array. Cosmetic-exhaustiveness defeats from the
    initial draft (matching on a literal `RoleId::Helper`) are
    fixed.

## What this slice does NOT do (deliberate)

- No `PersonaContext.specialty` field (initial draft removed
  per review). The original goal was reducing per-turn cost;
  `role.as_str()` already gives that with zero field bloat.
- No `display_name` change — `String::clone` of a fixed-per-
  session name is the same per-turn cost whether we cache or
  not, so the smell is RespondInput's `String`-typed field, not
  the source. Lift in a follow-up when `RespondInput`'s type
  changes (#149-adjacent).
- No prompt-template change — substrate keeps the existing
  specialty-string contract verbatim; the migration is
  provably behavior-preserving.

## Doctrine

- `[[init-once-handle-then-lease-zero-copy-refs]]` — the
  canonical "init-once" here is the compile-time `match` in
  `RoleId::as_str()`; per-turn cost is a `&'static str` deref +
  one `String::from` (memcpy of 6-9 static bytes). Doesn't get
  cheaper without changing `RespondInput`'s type signature.
- `[[observability-is-half-the-architecture]]` — slice 1's
  `respond_latency` aggregate will tell us if this and the
  cumulative slice-2/3+ wins are moving the needle on real
  persona turns.
- `[[no-fallbacks-ever]]` — no graceful-degradation path; the
  behavior-preservation test breaks loudly if either side
  drifts.

card: 0d780926
parent task: #195
slice 1: #1532 (merged) — phase decomposition
slice 2: #1533 (merged) — cache system_prompt at construction

Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Jun 6, 2026
…Id::as_str() (#195 slice 3) (#1534)

Slice 3 of task #195 (inference latency perfection campaign).

Pre-slice-3, `serve_persona_loop_inner` did, every turn:

```rust
specialty: format!("{:?}", ctx.role).to_lowercase(),
```

Two allocations, a variadic-macro dispatch through derived-Debug,
and a Unicode lowercase walk — all to produce a value `RoleId`
already exposes via its canonical `as_str() -> &'static str`
method (in `role_template.rs`, pinned at compile time).

## What ships

Switch the per-turn read from the Debug+lowercase chain to
`ctx.role.as_str()`:

```rust
let respond_input = RespondInput {
    persona: PersonaSlot {
        // was: format!("{:?}", ctx.role).to_lowercase()
        specialty: ctx.role.as_str().to_string(),
        /* ... */
    },
    /* ... */
};
```

Per-turn cost drops from `format!()` (variadic macro + Debug
formatter + heap alloc) + `.to_lowercase()` (second alloc +
Unicode lowercase walk) to a single `String::from` of a static
`&'static str`. The source IS the cache — no field on
`PersonaContext`, no helper, no Arc plumbing.

## Why this shape (not a cache)

Initial draft of slice 3 added `PersonaContext.specialty: Arc<str>`
populated by a `build_persona_specialty(role)` helper that pre-
baked the Debug+lowercase output. Adversarial review (3 agents)
correctly identified two problems:

1. **Caching the wrong source.** `RoleId::as_str()` already exists
   as the documented, intentionally-stable specialty derivation
   (kebab-case identifier, pinned by an explicit `match` so
   renames are deliberate). Caching the Debug+lowercase output
   couples the prompt-assembly contract to the derived-Debug
   format — a future contributor adding a custom Debug or
   wrapping the enum silently breaks the specialty string with
   no test failure.
2. **Caching test was a tautology.** The helper was
   `Arc::from(format!("{:?}", role).to_lowercase())` and the test
   compared its output to `format!("{:?}", role).to_lowercase()`
   — comparing the helper to its own implementation. A buggy
   helper using `.to_uppercase()` would have passed.

The revised slice picks the right source and the right
contract: use `role.as_str()` directly. No cache needed because
the static str pointer IS already pre-computed at compile time.
The behavior-preservation test (below) is non-circular: it
compares the new direct path (`role.as_str()`, a hand-curated
match in role_template.rs) to the pre-slice-3 derived-Debug
chain.

## Test (+1 new)

`persona::service_loop::tests::role_as_str_preserves_pre_slice3_specialty_format_for_each_role`:

  - Pins that for every `RoleId` variant (Helper, Coder,
    Sentinel, Custom), `role.as_str()` produces byte-identical
    output to the pre-slice-3 `format!("{:?}", role).to_lowercase()`.
    Non-circular: two independently-derived strings. A future PR
    adjusting either `as_str()` or adding a variant where the
    two paths disagree must update this test to record the
    intentional divergence — silent drift breaks loudly.
  - Compile-time exhaustiveness: a closure-typed
    `|role: RoleId| match role { ... }` with NO wildcard arm
    forces a new RoleId variant to be added here AND to the
    `variants` array. Cosmetic-exhaustiveness defeats from the
    initial draft (matching on a literal `RoleId::Helper`) are
    fixed.

## What this slice does NOT do (deliberate)

- No `PersonaContext.specialty` field (initial draft removed
  per review). The original goal was reducing per-turn cost;
  `role.as_str()` already gives that with zero field bloat.
- No `display_name` change — `String::clone` of a fixed-per-
  session name is the same per-turn cost whether we cache or
  not, so the smell is RespondInput's `String`-typed field, not
  the source. Lift in a follow-up when `RespondInput`'s type
  changes (#149-adjacent).
- No prompt-template change — substrate keeps the existing
  specialty-string contract verbatim; the migration is
  provably behavior-preserving.

## Doctrine

- `[[init-once-handle-then-lease-zero-copy-refs]]` — the
  canonical "init-once" here is the compile-time `match` in
  `RoleId::as_str()`; per-turn cost is a `&'static str` deref +
  one `String::from` (memcpy of 6-9 static bytes). Doesn't get
  cheaper without changing `RespondInput`'s type signature.
- `[[observability-is-half-the-architecture]]` — slice 1's
  `respond_latency` aggregate will tell us if this and the
  cumulative slice-2/3+ wins are moving the needle on real
  persona turns.
- `[[no-fallbacks-ever]]` — no graceful-degradation path; the
  behavior-preservation test breaks loudly if either side
  drifts.

card: 0d780926
parent task: #195
slice 1: #1532 (merged) — phase decomposition
slice 2: #1533 (merged) — cache system_prompt at construction

Co-authored-by: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Jun 6, 2026
…ion) (#1535)

* perf(persona): drop per-turn format!()+lowercase — use canonical RoleId::as_str() (#195 slice 3)

Slice 3 of task #195 (inference latency perfection campaign).

Pre-slice-3, `serve_persona_loop_inner` did, every turn:

```rust
specialty: format!("{:?}", ctx.role).to_lowercase(),
```

Two allocations, a variadic-macro dispatch through derived-Debug,
and a Unicode lowercase walk — all to produce a value `RoleId`
already exposes via its canonical `as_str() -> &'static str`
method (in `role_template.rs`, pinned at compile time).

## What ships

Switch the per-turn read from the Debug+lowercase chain to
`ctx.role.as_str()`:

```rust
let respond_input = RespondInput {
    persona: PersonaSlot {
        // was: format!("{:?}", ctx.role).to_lowercase()
        specialty: ctx.role.as_str().to_string(),
        /* ... */
    },
    /* ... */
};
```

Per-turn cost drops from `format!()` (variadic macro + Debug
formatter + heap alloc) + `.to_lowercase()` (second alloc +
Unicode lowercase walk) to a single `String::from` of a static
`&'static str`. The source IS the cache — no field on
`PersonaContext`, no helper, no Arc plumbing.

## Why this shape (not a cache)

Initial draft of slice 3 added `PersonaContext.specialty: Arc<str>`
populated by a `build_persona_specialty(role)` helper that pre-
baked the Debug+lowercase output. Adversarial review (3 agents)
correctly identified two problems:

1. **Caching the wrong source.** `RoleId::as_str()` already exists
   as the documented, intentionally-stable specialty derivation
   (kebab-case identifier, pinned by an explicit `match` so
   renames are deliberate). Caching the Debug+lowercase output
   couples the prompt-assembly contract to the derived-Debug
   format — a future contributor adding a custom Debug or
   wrapping the enum silently breaks the specialty string with
   no test failure.
2. **Caching test was a tautology.** The helper was
   `Arc::from(format!("{:?}", role).to_lowercase())` and the test
   compared its output to `format!("{:?}", role).to_lowercase()`
   — comparing the helper to its own implementation. A buggy
   helper using `.to_uppercase()` would have passed.

The revised slice picks the right source and the right
contract: use `role.as_str()` directly. No cache needed because
the static str pointer IS already pre-computed at compile time.
The behavior-preservation test (below) is non-circular: it
compares the new direct path (`role.as_str()`, a hand-curated
match in role_template.rs) to the pre-slice-3 derived-Debug
chain.

## Test (+1 new)

`persona::service_loop::tests::role_as_str_preserves_pre_slice3_specialty_format_for_each_role`:

  - Pins that for every `RoleId` variant (Helper, Coder,
    Sentinel, Custom), `role.as_str()` produces byte-identical
    output to the pre-slice-3 `format!("{:?}", role).to_lowercase()`.
    Non-circular: two independently-derived strings. A future PR
    adjusting either `as_str()` or adding a variant where the
    two paths disagree must update this test to record the
    intentional divergence — silent drift breaks loudly.
  - Compile-time exhaustiveness: a closure-typed
    `|role: RoleId| match role { ... }` with NO wildcard arm
    forces a new RoleId variant to be added here AND to the
    `variants` array. Cosmetic-exhaustiveness defeats from the
    initial draft (matching on a literal `RoleId::Helper`) are
    fixed.

## What this slice does NOT do (deliberate)

- No `PersonaContext.specialty` field (initial draft removed
  per review). The original goal was reducing per-turn cost;
  `role.as_str()` already gives that with zero field bloat.
- No `display_name` change — `String::clone` of a fixed-per-
  session name is the same per-turn cost whether we cache or
  not, so the smell is RespondInput's `String`-typed field, not
  the source. Lift in a follow-up when `RespondInput`'s type
  changes (#149-adjacent).
- No prompt-template change — substrate keeps the existing
  specialty-string contract verbatim; the migration is
  provably behavior-preserving.

## Doctrine

- `[[init-once-handle-then-lease-zero-copy-refs]]` — the
  canonical "init-once" here is the compile-time `match` in
  `RoleId::as_str()`; per-turn cost is a `&'static str` deref +
  one `String::from` (memcpy of 6-9 static bytes). Doesn't get
  cheaper without changing `RespondInput`'s type signature.
- `[[observability-is-half-the-architecture]]` — slice 1's
  `respond_latency` aggregate will tell us if this and the
  cumulative slice-2/3+ wins are moving the needle on real
  persona turns.
- `[[no-fallbacks-ever]]` — no graceful-degradation path; the
  behavior-preservation test breaks loudly if either side
  drifts.

card: 0d780926
parent task: #195
slice 1: #1532 (merged) — phase decomposition
slice 2: #1533 (merged) — cache system_prompt at construction

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

* feat(probes): JsonlProbeFileSink + RTOS-debugger manual + README/CLAUDE pointers (#151 foundation)

The substrate has the JTAG hardware (Slice P #176/#177): `probe!` /
`time_sync!` / `stack!` macros, `ProbeRouterLayer` (in-process
broadcast Layer), `ProbeStreamModule` (the `debug/probes/{class}/{open,
next,close}` URI consumer), and `UriCaptureLayer` (URI ancestry).
Zero usage sites in `persona/` or `cognition/` — the probes were
infrastructure waiting for application.

Per Joel 2026-06-06 `[[jtag-probes-are-rtos-debugger]]`: "We are
building an rtos. This is so complex we need to be able to have a
detailed understanding of what's going on, like a debug breakpoint,
in a way, to easily observe where the code and the surrounding vars
are, ones we want to inspect via probes, and timing of anything, so
we can hunt down bottlenecks."

This commit ships the FOUNDATION for that — the disk-persisted
breakpoint log + the manual that documents the method. The sprinkle
itself (probe calls inside `persona::response`,
`persona::prompt_assembly`, `cognition::shared_analysis`,
`persona::service_loop`) follows in subsequent commits using the
checklist in the manual.

## What ships

### `routing/probe_file_sink.rs` (new — 5/5 tests passing)

`JsonlProbeFileSink` — a tracing Layer that visits every probe
event, applies the operator-configured class filter, and writes a
JSONL line to disk with the original `class` + `uri_chain` +
`message` + `fields` plus a fresh `captured_at_ms` timestamp.

```rust
let sink = JsonlProbeFileSink::from_env()?;
// CONTINUUM_PROBE_FILE=/tmp/probes.jsonl
// CONTINUUM_PROBE_CLASSES=persona.turn.start,persona.response.render.prompt
tracing_subscriber::registry()
    .with(UriCaptureLayer::new())
    .with(ProbeRouterLayer::new())       // in-process broadcast
    .with(sink)                          // disk-persisted breakpoint log
    .init();
```

Composes with `ProbeRouterLayer` — both visit the same tracing event
independently; broadcast subscribers stay in-process, this one
persists to disk. Per-event filter is a single HashSet lookup (empty
set = no filter, all classes pass).

### Tests (5)

- `from_env_returns_envvar_unset_when_path_missing` — env-var unset
  is a typed Err, not a silent skip (no-fallbacks doctrine)
- `unfiltered_sink_persists_every_class` — empty class filter passes
  everything through, captured_at_ms is populated, message + fields
  preserved
- `class_filter_drops_unallowed_classes` — only allowed classes
  reach disk
- `non_probe_tracing_events_are_ignored` — `tracing::info!` calls
  without `probe_class` field don't pollute the probe log (signal
  density preserved)
- `sink_captures_uri_chain_when_dispatched_span_active` — when
  inside a dispatched URI span, the on-disk record carries the URI
  ancestry (so an operator can trace which command's execution the
  probe fired during)

### `docs/architecture/RTOS-DEBUGGER-PROBES.md` (new)

The MANUAL. Persistent reference per Joel's directive: "We will want
a manual (doc) on how to probe the persona so we don't forget where
the work must be done and how. Be sure you document your method."

Covers:
- The mental model: probes are non-blocking breakpoints, time_sync!
  is RAII timing, stack!() is the URI ancestry — together they're
  the substrate's RTOS debugger
- When to add a probe (branch boundaries, stage entry/exit, external
  calls, state seams, decision points)
- The class taxonomy: stable names for `persona.turn.*`,
  `persona.response.*`, `persona.prompt.*`, `cognition.analyze.*`,
  plus general-purpose `decision` / `state` / `error`
- How to enable (CONTINUUM_PROBE_FILE + CONTINUUM_PROBE_CLASSES
  env vars, no recompile)
- How to read (jq one-liners for the common queries: per-persona
  filter, silence reasons, slow timings, single-turn reconstruction)
- How to add a new probe (the call shape + convention rules)
- **The sprinkle checklist** — every file that needs probes added,
  with the specific seams in each. Updates to this checklist live
  in the same doc; the doc IS the source of truth for what's wired
  and what isn't

### README.md "Debugging this substrate" section

Inserted between Research Foundations and Documentation. Worked
code example + the env-var enable commands + link to the manual.
Every contributor (human or AI agent) sees the probe convention
from the public README, not just from buried docs.

The Documentation table gains a row for
`RTOS-DEBUGGER-PROBES.md` directly after CONTINUUM-ARCHITECTURE.md,
so the doc is discoverable from the canonical doc list as well.

### CLAUDE.md sub-entry

Added under canonical doc #5 (OBSERVABILITY-AS-SUBSTRATE):
"the practical companion: how to USE the `probe!` / `time_sync!`
/ `time_async!` macros as RTOS-style breakpoints with variable
inspection + timing." Any agent reading the project's CLAUDE.md
finds the probe convention as a precedence-winning truth, alongside
the canonical substrate docs.

## Why this slice is foundation-only

Sprinkling probes into the cognition is a separate slice (the
manual's checklist tracks it). Shipping the file sink + the manual
+ the discoverability pointers FIRST gives reviewers a small,
testable change that's clearly correct in isolation, and gives the
next slice (the sprinkle) a stable target to write against — every
probe call site in commit 2+ refers to the class taxonomy in commit
1's manual.

## Doctrine

- `[[jtag-probes-are-rtos-debugger]]` — the framing this slice
  enables
- `[[observability-is-half-the-architecture]]` — CaptureSink +
  Noop default + replay-as-first-class; this is the file-persisted
  consumer of that pattern
- `[[no-fallbacks-ever]]` — env-var unset is typed Err
  `ProbeFileSinkError::EnvVarUnset`, path failures are typed
  `OpenFailed { path, source }` (operator must fix path; substrate
  refuses to silently synthesize a default)

card: 8d7ca5c3
parent: #151 (echo-storm filter) — the bug we're actually hunting,
debugger-first so we can find the bug INSIDE the cognition pipeline,
not in a Rust gate around it

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

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Oct 4, 2026
…ay's airc-lib fixes (#4735)

Kimi on the 5090 kept hitting "settled work is not claimable" on her own card
with her daemon already at #1532: the claim gate is airc-lib, compiled into
this core at the pinned rev, and 7499136 predates every airc fix of
2026-10-04. A daemon update cannot deliver an airc-lib fix to personas; only
this pin can.

Adopts #1528 (right-sized payloads), #1529 (per-channel ring byte bound;
channel_count and ring_bytes_total in status), #1530 (verbs are never room
names), #1531 (the owner resumes her own card after her lease lapses), #1532
(ownership durable, the lease is presence, from 2026-10-04T16:00Z), #1533
(test) and #1534 (work claim/update/link --room).

continuum-core lib + bins + tests type-check clean against it (mac-cpu-only
features), 0 errors. Lockfile changes outside airc are only windows-sys /
windows-core versions inside airc crates' dependency lists (#1480).

Card 86c5eb48.


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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant