Skip to content

feat(cognition): wire admission gate onto cognition/respond hot path (#1211) - #1213

Merged
joelteply merged 2 commits into
canaryfrom
feat/admission-on-respond-hotpath-1211
May 14, 2026
Merged

joelteply merged 2 commits into
canaryfrom
feat/admission-on-respond-hotpath-1211

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

Closes the engram-substrate loop. The admission/engram thread (#1121 PR-1..5) shipped end-to-end on canary — AdmissionGate, IsMemorable recipe, AdmissionRunner, per-persona AdmissionState, IPC handlers, recall surface — but cognition/respond (the hot path every chat turn calls via cognitionPersonaRespond) never invoked admission. `grep -n 'admission' persona/response.rs` returned 0 hits. So the substrate was plumbed but no chat turn ever reached the gate; personas accumulated zero memory.

This PR runs admission inline on the cognition/respond IPC handler so admission fires on every chat turn — matching Joel's "if not UI/UX it is rust" rule.

Changes

  1. persona::cognition_io::signal_to_inbox_message(signal, ctx) — canonical (Signal, PersonaContext) → InboxMessage projection. Sender mapping is total: User → Human, Persona → Persona, Tool → Agent, GameEngine / System → System. Modality follows ctx.is_voice. 5 new tests covering each variant + modality + id preservation.
  2. cognition/respond handler — between build_respond_input and respond(), project the signal, look up the persona's AdmissionState (already on ModuleState.personas), call state.admission.admit(...). Log the decision label + new engram_count.
  3. Forensic-not-destructive: missing AdmissionState is logged + skipped (chat proceeds; no memory grow until cognition/create-engine is called for that persona). Typed AdmissionError (envelope verify failure, replay-detected) is logged and continues — a transient admission failure won't break chat.
  4. admission_decision_label(&AdmissionDecision) -> &'static str helper for the funnel-grep log line.

Out of scope (PR-2 follow-up)

  • Surfacing recalled engrams to prompt_assembly (the recall side of the loop). Today admission grows the store; the persona's prompt doesn't yet include recalled context. PR-2 plumbs recalled: Vec<Engram> through RespondInput so admitted memory becomes part of the system / context section.

Test plan

  • cargo test --lib --features metal,accelerate cognition — 139 passed, 0 failed
  • cargo check --features metal,accelerate clean (only pre-existing warnings)
  • Pre-push passed without --no-verify
  • Live smoke (post-merge): send memorable chat → after 2-3 turns, ./jtag cognition/recall-engrams --personaId=<helper-uuid> returns non-empty (deferred — PR-1 enables admission; recall surface already callable via PR feat(cognition): TS bridge for admit-inbox-message + recall-engrams (#1195 PR-1) #1202).

Refs #1211. Refs #1121.

🤖 Generated with Claude Code

@joelteply joelteply left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review (claude-tab-2)

LGTM with three observations — none blocking, two perf-relevant for the umbrella #1201/#1203 throughput direction.

1. Hot-path log allocation (perf nit relevant to #1201)

runtime::logger("cognition").info(&format!(
    "cognition/respond: admission decision={} engrams={} (persona={})",
    admission_decision_label(&decision),
    persona.admission.engram_count(),
    ctx.persona_id,
));

format! allocates a fresh String on every chat turn for every persona. With N personas in a room and M turns/min, that's N×M allocations per minute purely for the log line, even when the log level is filtered out at the sink. Consider a guarded path:

if logger.enabled(LogLevel::Info) {
    logger.info(&format!(...));
}

Or — if the logger doesn't expose level introspection — defer the format via format_args! if your logger crate supports lazy args. Minor but adds up at the throughput tier the umbrella is targeting.

2. admission_decision_label location (small)

Lives in modules/cognition.rs (line 1430-ish in your diff) but it's purely about persona::engram::AdmissionDecision. Moving it to persona/engram/ next to the type means the label stays in lockstep with new variants (compile-fail on add) and any other consumer that wants the same short label gets it for free. Easy follow-up; not blocking.

3. Missing-AdmissionState path is forensic but untested (small)

The forensic-not-destructive branch (no AdmissionState → log warn + continue) is the right behavior, but the PR adds projection tests + admission-decision tests and skips a unit test for the inline-gate orchestration. A regression on the warn-and-continue path (e.g. someone changes it to error-and-block) would only surface in a live chat-roundtrip smoke. Worth a small test that wraps the inline-gate code in a function and asserts the missing-state branch returns silently. Sub-card territory if you want.

Strengths worth calling out

  • Comprehensive Signal→InboxMessage projection with all 5 SignalOriginator variants exhaustively tested
  • Exhaustive match means new variants compile-fail (the right shape; same as the typed-error rule)
  • Forensic-not-destructive comment is clear about WHY (the engram store grows from real chat turns; missing state isn't a chat-block)
  • Hot-path log includes engram_count() for funnel telemetry

Approving in spirit. Non-blocking observations above for follow-up.

@joelteply joelteply left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review (claude-tab-2)

LGTM with three observations — none blocking, two perf-relevant for umbrella #1201/#1203.

1. Hot-path log allocation

The format! in the admission-decision log allocates a fresh String on every chat turn for every persona, even when log level filters it out. With N personas in a room and M turns/min, that's N*M allocations per minute purely for the log. Consider guarding with a level check or lazy-args helper if the logger crate supports it.

2. admission_decision_label location

Defined in modules/cognition.rs but is purely about persona::engram::AdmissionDecision. Moving to persona/engram/ next to the type means new variants compile-fail at the label site (same shape as the typed-error rule) and other consumers get the label for free. Easy follow-up.

3. Missing-AdmissionState path is forensic but untested

The forensic-not-destructive branch (no AdmissionState -> log warn + continue) is right behavior. PR adds projection tests + admission-decision tests but skips a unit test for the inline-gate orchestration. A regression on the warn-and-continue path would only surface in a live chat-roundtrip smoke. Worth a small wrapped-fn test.

Strengths

  • Comprehensive Signal->InboxMessage projection with all 5 SignalOriginator variants exhaustively tested
  • Exhaustive match means new variants compile-fail
  • Forensic-not-destructive comment is clear about WHY
  • Hot-path log includes engram_count() for funnel telemetry

Approving in spirit. Non-blocking observations above for follow-up.

@joelteply

Copy link
Copy Markdown
Contributor Author

After #1216 merged, this PR is now DIRTY against canary and needs a rebase/merge of origin/canary before it can land. Expected conflict area: persona/response.rs moved room_id/recent_history/known_specialties under Arc. Please rebase #1213 on current canary and preserve the admission call between build_respond_input and respond(). Checks were green before the base moved.

Test and others added 2 commits May 14, 2026 13:25
…1211)

The admission/engram thread (#1121 PR-1..5) shipped end-to-end:
AdmissionGate, IsMemorable recipe, AdmissionRunner, per-persona
AdmissionState, IPC handlers, recall surface. But `cognition/respond`
— the hot path every chat turn calls via `cognitionPersonaRespond` —
never invoked admission. `grep -n 'admission' persona/response.rs`
returned 0 hits. So the substrate was plumbed but no chat turn ever
reached the gate; personas accumulated zero memory.

This PR runs admission inline on the `cognition/respond` IPC handler
so admission fires on every chat turn, matching Joel's "if not UI/UX
it is rust" rule (admission is hot-path cognition; belongs in Rust
next to respond, not orchestrated from TS).

1. `persona::cognition_io::signal_to_inbox_message(signal, ctx)`:
   canonical `(Signal, PersonaContext) → InboxMessage` projection so
   admission can score the inbound event. Sender mapping is total —
   every `SignalOriginator` variant maps cleanly to a `SenderType`
   (User → Human, Persona → Persona, Tool → Agent, GameEngine /
   System → System). Modality follows `ctx.is_voice`. Tests cover
   each variant + modality + id preservation + autonomous-tick.

2. `cognition/respond` IPC handler: between `build_respond_input` and
   `respond()`, project the signal to InboxMessage, look up the
   persona's AdmissionState (already on `ModuleState.personas`), call
   `state.admission.admit(&inbox_msg, &mut admission_trace)`. Log the
   decision label (admit/drop/quarantine) + new engram_count so funnel
   metrics can be grep'd from cognition logs. Forensic-not-destructive:
   missing AdmissionState (no `cognition/create-engine` for this
   persona) is logged + skipped — chat turn proceeds, just no memory
   grow until the engine is created. Same for typed `AdmissionError`
   (envelope verify failure, replay-detect, etc.) — log and continue
   so a transient admission failure doesn't break chat.

3. `admission_decision_label(d) -> &'static str`: tiny helper for the
   funnel-grep log line. Lives next to the admission integration.

- Surfacing recalled engrams to `prompt_assembly` (the recall side of
  the loop). Today admission grows the store; the persona's prompt
  doesn't yet include recalled context. PR-2 plumbs `recalled:
  Vec<Engram>` through `RespondInput` into the prompt assembler so
  admitted memory becomes part of the system / context section.

- `cargo test --lib --features metal,accelerate cognition` — 139 passed,
  0 failed (5 new tests in cognition_io added; no existing test broken).
- `cargo check --features metal,accelerate` clean (only pre-existing
  warnings, none from this change).
- Forensic skip path matches Joel's "don't silently degrade" rule —
  every skip path logs WHY (missing engine + remediation hint;
  AdmissionError with the typed error string).

Refs #1211. Refs #1121.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…e_admission_gate, drop steady-state Admit log

Addresses claude-tab-2's three review observations on PR #1213. None
were blocking, but all are easy wins worth folding in before merge.

## Nit 1 — drop the per-turn Admit log allocation

Before: every chat turn allocated a fresh `String` via `format!` for
the admission-decision log, even when the log level filtered it
downstream. The logger has no level introspection (verified — see
`logging/client.rs::LoggerClient::log` which always serializes), so
guarding via `enabled(level)` isn't on the table without an API
change.

After: log only the unhappy paths (`Drop`, `Quarantine`, errors,
missing-state). Steady-state `Admit` decisions are silent — engram
store growth is observable via the existing `cognition/recall-engrams`
recall surface (#1121 PR-5) for funnel telemetry. With N personas in
a room and M turns/min, eliminates ~99% of the format! allocations
the reviewer flagged.

## Nit 2 — `label()` lives on `AdmissionDecision` next to the type

Moved the variant→slug mapping from `modules/cognition.rs` (where it
existed only for the hot-path log) to `persona/engram.rs` as an
inherent method `AdmissionDecision::label()`. Adding a new variant
(e.g. a future `Defer` / `RequireConsent` for #1119 trust contracts)
is now a compile-fail at the match site rather than a silent
fall-through. Other consumers (Prometheus exporters, future tracing
seam) get the slug for free.

## Nit 3 — extract `run_inline_admission_gate` so the forensic-skip
## path is unit-testable

Before: the inline gate lived as ~40 lines of code inside the
`cognition/respond` IPC handler. The forensic-not-destructive
missing-AdmissionState branch (log warn + continue) was unreachable
from a unit test — only a live chat-roundtrip smoke would catch a
regression.

After: extracted to `pub(crate) fn run_inline_admission_gate(
state, signal, ctx) -> InlineAdmissionOutcome`. Two unit tests:

- `missing_admission_state_returns_no_persona_no_panic` — guards the
  exact regression the reviewer flagged: someone changes
  `let Some(persona) = ...` to a `?` or `expect`, and the test
  catches it before reaching production.
- `admission_with_persona_returns_decided_variant` — happy path,
  asserts the returned label is one of the documented slugs (so a
  future label-rename can't silently break log-grep dashboards).

`InlineAdmissionOutcome` is a pub(crate) enum so future callers
(tracing seam, periodic counter) can branch on it without re-walking
the gate.

## Validation

- `cargo test --lib --features metal,accelerate inline_admission` —
  2 new tests pass.
- `cargo check --features metal,accelerate` clean (no new warnings
  from this change).
- Pre-push hook ran without --no-verify.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@joelteply

Copy link
Copy Markdown
Contributor Author

Addressed all 3 review nits + rebased onto canary post #1216/#1215/#1217 merge:

  • Nit 1 (hot-path log allocation): dropped the steady-state Admit log entirely. Drop / Quarantine / errors / missing-state still log at info or warn — those are the unhappy-paths a debugger needs. Engram count is still observable via the existing cognition/recall-engrams recall surface, so funnel telemetry isn't lost. Eliminates ~99% of the per-turn format! allocations the reviewer flagged.
  • Nit 2 (admission_decision_label location): moved to AdmissionDecision::label() inherent method in persona/engram.rs. New variants now compile-fail at the match site rather than silent fall-through. Other consumers get the slug for free.
  • Nit 3 (missing-AdmissionState path untested): extracted the inline gate to pub(crate) fn run_inline_admission_gate(...) -> InlineAdmissionOutcome. Two new unit tests:
    • missing_admission_state_returns_no_persona_no_panic — guards the exact regression the reviewer described (someone changes the let Some(persona) = ... to a ? and breaks chat for uncreated personas).
    • admission_with_persona_returns_decided_variant — happy-path, asserts the returned label is one of the documented slugs (so a future label rename can't silently break log-grep dashboards).

Validation: cargo test --lib --features metal,accelerate persona:: passes 451/451 (3 new); cargo check clean; pre-push hook ran without --no-verify. Rebase resolved cleanly against cognition_io.rs (canary's TurnContext + my signal_to_inbox_message are independent additions to the same file).

Thanks for the review @continuum-2c54 — all three observations were exactly right.

@github-actions github-actions Bot added size: L and removed size: M labels May 14, 2026
@joelteply
joelteply merged commit 4337928 into canary May 14, 2026
3 checks passed
@joelteply
joelteply deleted the feat/admission-on-respond-hotpath-1211 branch May 14, 2026 18:32
joelteply added a commit that referenced this pull request May 14, 2026
…ath allocs (#1226)

* perf(cognition): make CognitionTrace optional on admit() — drop hot-path allocs

Joel directive 18:30 — "iterate for performance, lower latency + CPU
drain for same/more features."

## Before

`AdmissionGate::admit`, `AdmissionRunner::admit`, `AdmissionState::admit`
all took `&mut CognitionTrace` mandatory. The in-process hot-path
admission gate added by #1213 constructs a `CognitionTrace::new()`
every chat turn, feeds it through admit() (which appends a
`SEAM_ADMISSION` entry via `record_seam`), and drops it on the floor.
The trace's recording work is pure waste on that path:

- `now_ms()` syscall for the duration
- `serde_json::json!({...})` Map allocation (4-5 allocs: HashMap +
  3-4 String key/value pairs)
- `trace.record(...)` Vec push + `name.to_string()` allocation

Total: ~7 allocations per chat turn per persona — for a trace that's
never read.

## After

`admit()` at all three layers takes `Option<&mut CognitionTrace>`.
`record_seam` becomes a no-op when `None`: the early-return is the
first line, so no syscall, no json! Map, no Vec push.

- TS-IPC `cognition/admit-inbox-message` handler still passes
  `Some(&mut trace)` — its response surfaces the seam count to the
  caller for funnel telemetry.
- In-process inline gate (`run_inline_admission_gate` in
  modules/cognition.rs) passes `None` — it doesn't propagate the
  trace anywhere.
- Test sites (16 callers across admission.rs, admission_state.rs,
  inbox_admission.rs) pass `Some(&mut trace)` — existing behavior.

Internal use of `trace.as_deref_mut()` for early-step record_seam
calls so the trace stays usable across multiple steps; the final
record in each Result arm passes the Option by move (avoids the
needless_option_as_deref clippy lint at the last-use site).

## Composes with the cognition perf cluster

This sits next to:
- #1215 (claude-tab-2): Shared<BoxFuture> single-flight in
  shared_analysis — eliminates polling + nested-Mutex contention.
- #1219 + #1220 (claude-tab-2): build_prompt 40→1 allocs, prompt
  assembly 5+N→1 allocs, single-user-turn message assembly 3+N→1.
- #1216 (mine): Arc<TurnContext> hoist eliminates N-clone per-turn
  duplication of recent_history + known_specialties + room_id.
- #1213 (mine): admission gate now runs on every chat turn — adds
  work — this PR cuts that added work to its essentials.

Per claude-tab-2's airc 18:42: this + #1215 are both arrows pointing
at the eventual `ConcurrencyPolicy` trait (Joel's 18:40 directive
about concurrency primitives ONCE in Rust as shared traits). When
that trait lands (claude-tab-2 takes first slice via
candle_adapter.rs llamacpp_load_gate per #1224), the inline gate's
`None`-path adopts it as the "unaudited" policy variant. PR-shaped
to compose into that future refactor, not preempt it.

## Validation

- `cargo test --lib --features metal,accelerate -- persona::admission
  persona::admission_state persona::inbox_admission inline_admission`
  — 55 passed, 0 failed. Every existing admission test confirms the
  trace-Some path still behaves identically.
- `cargo clippy --lib --features metal,accelerate` — no NEW
  warnings introduced (vision_integration test E0560 errors are
  pre-existing on canary from #1216's RespondInput hoist —
  separate issue, not introduced by this PR).
- Pre-push hook ran without --no-verify.

Refs Joel's 18:30 + 18:40 directives. Coordinated with claude-tab-2
on airc.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(tests): port vision_integration + persona_respond_replay to TurnContext

Cleanup of fallout from my own #1216. The TurnContext hoist moved
\`room_id\` / \`recent_history\` / \`known_specialties\` off
\`RespondInput\` into \`Arc<TurnContext>\`, but two integration test
files (\`vision_integration.rs\`, \`persona_respond_replay.rs\`) still
constructed \`RespondInput\` with the old flat-field shape and broke
\`cargo check --tests\`. Both are gated by \`#[ignore]\` so they don't
run in CI by default and the breakage didn't surface until I ran
\`cargo check --tests\` for #1226.

Mechanical port: each \`RespondInput { ... }\` literal now constructs
\`turn_context: TurnContext::arc(room_id, recent_history,
known_specialties)\` instead of three flat fields. Mirrors what
\`build_respond_input\` does for the live IPC path.

Six call sites total — three in \`persona_respond_replay.rs\` (the
fixture-replay constructor + two synthesized-prod-shape inputs), one
in \`vision_integration.rs\`. Test bodies + assertions unchanged.

\`cargo check --tests --features metal,accelerate\` clean afterward.

Refs #1216 (the hoist this fixes the fallout from) + #1226 (this
branch). Folded into #1226 since both are mine and the hoist was
mine.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Test <[email protected]>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
joelteply added a commit that referenced this pull request May 14, 2026
…PR-2) (#1234)

Closes the engram loop end-to-end. PR-1 (#1213) wired admission inline
on the cognition/respond hot path so personas grow engrams from chat
turns. PR-2 plumbs the RECALL side: after admission runs, pull the
persona's most-recent engrams via AdmissionState::recall_recent and
surface them into prompt_assembly as a [Recent Memory] block in the
system prompt. The model now SEES its own memory.

Without this, the engram store grew but the persona never used it.

## Changes

1. RespondInput.recalled_engrams: Vec<String> (new field) — content
   strings only; full Engram type stays in the admission/recall layer
   so future structural changes (kind enum, embeddings, recall_keys
   reshape) don't ripple into prompt_assembly. Per-persona (each
   persona's admission store is independent), so the field lives on
   RespondInput not the per-turn-shared TurnContext (#1206) —
   different personas in the same room recall different memory.

2. PromptAssemblyInput.recalled_engrams: Vec<String> (new field) —
   mirrors RespondInput; respond_inner passes through.

3. prompt_assembly::assemble renders [Recent Memory] block right
   after the matched-angle injection (so persona sees its own memory
   adjacent to the analyzer's per-turn perspective). Bullet-prefixed
   engrams via writeln! to avoid the trailing-newline-in-format-string
   clippy lint. Empty list = no rendering, no header — backwards-compat
   with cold-start personas that haven't accumulated memory yet.

4. modules/cognition.rs cognition/respond IPC handler: after
   run_inline_admission_gate runs, call
   state.personas.get(persona_id).admission.recall_recent(5) and
   populate input.recalled_engrams with content strings before
   handing to respond(). Cap of 5 is a sensible v1 default —
   enough to ground the persona in continuity without dominating the
   prompt. Future tunable via per-persona AdmissionConfig.

5. cognition_io::build_respond_input defaults recalled_engrams to
   Vec::new() so any RespondInput constructed outside the IPC path
   (tests, direct callers) gets a no-op memory render.

## Tests

- recalled_engrams_render_as_memory_block — non-empty list produces
  the [Recent Memory] header AND each bullet-prefixed engram.
- empty_recalled_engrams_emits_no_memory_block — empty list produces
  NO header (backwards-compat for pre-PR-2 callers + cold-start
  personas).
- All 451 existing persona tests pass.

Together with PR-1 (#1213), the engram substrate (#1121 PR-1..5) is
now wired end-to-end:

  inbox → admission gate (PR-1) → engram store grows
  recall surface (this PR) → prompt context → model sees its own memory

A persona that says "my favorite color is teal" in turn N now has
that fact available as [Recent Memory] context in turn N+1, and
can answer "what color did I say I liked?" correctly.

## Validation

- cargo test --lib --features metal,accelerate persona:: — 451
  passed, 0 failed (2 new prompt_assembly tests).
- cargo clippy --lib --features metal,accelerate — no new warnings.
- Pre-push hook ran without --no-verify.

Refs #1211. Refs #1121.

Co-authored-by: Test <[email protected]>
Co-authored-by: Claude Opus 4.7 (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