Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript

feat(brain): add context continuity and receipts suite (#56)

Sol Aitken0162d13071ef
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index bad31890..44078698 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.28.0",
+ "version": "0.29.0",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index ff59f6d9..510b6bbf 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.28.0",
+ "version": "0.29.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"skills": "./skills",
"hooks": "./hooks/hooks.json",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 72825ece..924492c3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,29 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [0.29.0] - 2026-05-31
+
+Context continuity and receipt surfaces. Agent-facing context can now leave redacted receipts and telemetry behind, operators can inspect budget presets before applying them, and session transcripts can be imported into a continuity-backed recall DAG.
+
+### Added
+
+- Append-only continuity records under `Brain/log/continuity/` with redaction-safe payloads, stable IDs, source references, pagination, and source invalidation markers.
+- Opt-in prompt context receipts for `brain_context_pack` and `brain_pre_compress_pack`, with CLI/MCP list/show surfaces that expose item IDs, budgets, source hashes, safety/redaction metadata, and final text hashes without storing raw private content.
+- Opt-in recall telemetry for search, context-pack, and pre-compress calls, including duration, status, result counts, top artifacts, budget/cache metadata, coverage gaps, and CLI/MCP summaries.
+- Opt-in context-pack transforms for cache-stable ordering and repeated-context deduplication. Transform annotations report original/stable ranks and reference hints while leaving default ordering unchanged.
+- Read-only context budget presets (`tight-context`, `long-context`) with CLI/MCP `show`, `suggest`, and `diff` diagnostics, confidence/reason reporting, explicit override preservation, and invalid override detection.
+- Pre-compaction extraction through CLI/MCP and core APIs. Bounded text segments emit typed decision, commitment, outcome, rule, and open-question continuity records with deterministic base64/media sanitization and idempotent deduplication.
+- Session recall DAG foundation. `import-session --recall` stores normalized turns as raw continuity records, deterministic two-depth summary nodes preserve source lineage, and CLI/MCP `session-grep`, `session-describe`, and `session-expand` inspect bounded hits and paginated raw turn content.
+
+### Changed
+
+- MCP full-server tool count is now 65 after adding context receipt, telemetry, preset, pre-compaction, and session recall tools.
+- `o2b brain import-session --json` includes recall import counters; they remain zero unless `--recall` is explicitly enabled.
+
+### Notes
+
+- All new context receipt, telemetry, transform, preset, pre-compaction, and session recall behavior is opt-in or read-only by default.
+
## [0.28.0] - 2026-05-31
Brain safety and governance foundations. Automatically surfaced Brain context now has a deterministic guardrail against prompt-injection-like note content, config can point at local secrets without exposing values to agents, and larger governance workflows get preview-first core manifests.
@@ -2287,7 +2310,7 @@ with `source_type: inline`, the source-file wikilink in `source`,
and a `dedup_hash`over the normalised payload. After capture
the source line is annotated`@osb✓ [[sig-...]]`(inline form)
or the info-string flips to`osb-checked`with a`<!-- @osb✓
- [[sig-...]] -->`comment line (block form), making re-runs
+ [[sig-...]] -->`comment line (block form), making re-runs
idempotent. Default ignore set covers`Brain/`, `.git`,
`node_modules`, `.obsidian`, `.trash`, `.stversions`,
`.open-second-brain`; additional excludes via `--exclude`,
@@ -3633,6 +3656,7 @@ plugin config (vault field)`, and exits with a clear
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[0.29.0]: https://github.com/itechmeat/open-second-brain/compare/v0.28.0...v0.29.0
[0.28.0]: https://github.com/itechmeat/open-second-brain/compare/v0.27.0...v0.28.0
[0.27.0]: https://github.com/itechmeat/open-second-brain/compare/v0.26.0...v0.27.0
[0.26.0]: https://github.com/itechmeat/open-second-brain/compare/v0.25.0...v0.26.0
diff --git a/README.md b/README.md
index 5787ac1d..9d27f662 100644
--- a/README.md
+++ b/README.md
@@ -114,7 +114,7 @@ The capabilities you actually feel day to day:
These are the headline capabilities. The full surface also includes: importing Claude Code memory directories, daily logging-discipline cron with a complexity-to-thinking warning, cross-project pointers for shared vaults, transient pinned session context through `brain_pinned_context` / `Brain/pinned.md`, source-agent query and comparison (`brain_agent_query`, `brain_agent_diff`, `o2b brain agent-query`, `o2b brain agent-diff`), the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, an operator dashboard, configurable Markdown-link presentation output, MCP output-contract checks for core agent-facing tools, private-region stripping with `<private>...</private>`, the v0.12.0 Brain Integrity Suite (content-hash drift detection, durable workrun checkpoints, destructive-from-confirmed retire gate, and the `brain_review_candidates` MCP tool that previews what the next dream pass would do without writing anything), the v0.13.0 Hybrid Search and Recall Quality suite (explainable recall, MMR diversity, link-graph traversal, entity-boosted retrieval, header-anchored chunking), the v0.14.0 Semantic Brain Health and Self-Maintenance suite (cross-preference contradiction detection, concept-gap and stale-claim surfacing, per-preference edit-history, a clean/watch/investigate reconciliation verdict via `brain_health`, and dependency-ordered `doctor --remediate`), the v0.17.0 Brain Lifecycle Review Suite (`intent-review`, `retention`, `monthly`, lifecycle schemas, and discipline complexity ratio), and the v0.18.0 MCP context economy (a per-tool preview budget that returns a bounded inline preview and parks the full payload in a vault-local artifact the agent fetches on demand with `brain_artifact_get`, plus a `recall_hint` one-liner on search results), and the v0.19.0 typed graph semantics (typed frontmatter relationships - `related` / `extends` / `contradicts` / `superseded_by` - that surface inline on search results, a `visibility:` scoping axis for `brain_search`, and a `brain_mcp_landscape` view of the Model Context Protocol servers configured across the vault), and the v0.20.0 Recall and Ranking Quality suite (a configurable Weibull recency-decay curve, structural query-intent classification that re-weights ranking by query shape, language-agnostic synonym expansion via local co-occurrence, per-memory and total recall character budgets for `brain_context_pack`, a persistent query cache that self-invalidates on a corpus-generation change, and a `brain_pre_compress_pack` tool that returns a budgeted top-preferences addendum for a host runtime to inject before context compression), and the v0.21.0 Brain Lifecycle Suite (a per-preference mutation audit trail keyed by preference id - create / promote / update / retire / merge with revision + content-hash before/after, via `o2b brain audit` and `brain_audit`; a multi-phase `dream` pipeline that names its close / reconcile / synthesize / heal / log seams and reports a structured per-phase summary without rewriting the proven internals; deterministic reconcile-phase domain classification that buckets contradictions into claims / entity / decisions / source-freshness, auto-resolves only the decisive source-freshness case, and surfaces the rest as open questions instead of forcing a merge; a budgeted `o2b brain morning-brief` / `brain_morning_brief` session-start summary of top preferences, recent open questions, and recent notes; language-agnostic ISO-8601 temporal extraction that fills preference validity windows from signal text; and opt-in heal-phase vault enrichment that links exact title mentions across user pages), and the v0.22.0 Vault portability + session economy suite (a deterministic lossless session codec - `expand(compress(x)) === x` for all input, opt-in on the signal store and exposed as `o2b brain codec`; an `o2b brain sources` / `brain_sources` read-only dashboard of signals by agent and source type; vault-map `{{role}}` tokens resolved via an optional `Brain/_vault-map.yaml` and wired into scan-inline read paths and graph import; named multi-vault profiles with `o2b vault profile` + a `brain_switch_vault` tool, activated by a pointer in config; and `o2b brain graph-export` / `graph-import` for moving a vault's knowledge graph between layouts with skip/overwrite/merge conflict modes). Browse [`docs/cli-reference.md`](docs/cli-reference.md) for every verb and [`docs/how-it-works.md`](docs/how-it-works.md) for the mental model.
-The v0.26.0 surface adds audited schema mutation/admin tools, real-time lifecycle capture hooks for prompt markers and `brain_feedback` tool calls, CJK-aware FTS recall, and `brain_watchdog` / `o2b brain watchdog` recovery probes. The v0.27.0 surface adds recall-control and trust tools: structured search query documents, session focus, MCP `brain_recall_gate`, polarity-aware context lanes, and opt-in evidence packs for CLI/MCP search. The v0.28.0 surface adds a deterministic prompt-injection guard for automatically surfaced Brain context, agent-blind `$secret:NAME` references, and preview foundations for source-scoped forget, privacy-scanned knowledge packs, and oversized payload externalization.
+The v0.26.0 surface adds audited schema mutation/admin tools, real-time lifecycle capture hooks for prompt markers and `brain_feedback` tool calls, CJK-aware FTS recall, and `brain_watchdog` / `o2b brain watchdog` recovery probes. The v0.27.0 surface adds recall-control and trust tools: structured search query documents, session focus, MCP `brain_recall_gate`, polarity-aware context lanes, and opt-in evidence packs for CLI/MCP search. The v0.28.0 surface adds a deterministic prompt-injection guard for automatically surfaced Brain context, agent-blind `$secret:NAME` references, and preview foundations for source-scoped forget, privacy-scanned knowledge packs, and oversized payload externalization. The v0.29.0 surface adds opt-in context receipts and recall telemetry, read-only context budget presets, pre-compaction extraction, and a continuity-backed session recall DAG.
## CLI
@@ -134,6 +134,11 @@ o2b brain schema lint --json # Runtime schema vocabulary + usage/admin
o2b brain watchdog --json # Brain probes + safe recovery recommendations
o2b brain graph-export --out graph.json # Export the vault knowledge graph
o2b brain semantics-backfill --json # Dry-run typed preference-edge repair proposals
+o2b brain context-receipts list --json # Inspect opt-in prompt context receipts
+o2b brain recall-telemetry summary --json # Aggregate opt-in recall/context telemetry
+o2b brain context-presets suggest --model claude-sonnet-4 --context-window 200000 --json
+o2b brain import-session session.jsonl --recall --json # Populate the session recall DAG
+o2b brain session-grep --query "decision" --json # Search raw/session summary recall nodes
o2b vault profile switch work # Activate a named multi-vault profile
o2b brain agent-query --agent claude --json # Source-agent provenance query
o2b brain agent-diff --mode diff --agent claude --agent codex
@@ -156,6 +161,7 @@ Full list (~50 verbs across `o2b`, `o2b brain`, `o2b vault`, `o2b discipline`, P
- Secrets are not supposed to live in the vault. Daily logs and config exports go through a best-effort redactor for common secret-name patterns.
- `$secret:NAME` config references store only the reference and resolve from the local process environment; `o2b secrets list|status` reports availability without printing values.
- Automatically surfaced Brain snippets from `brain_context_pack` and `brain_pre_compress_pack` pass through a deterministic prompt-injection guard. Filtered outputs return a placeholder plus machine-readable reason codes; source Markdown is not rewritten.
+- Context receipts and recall telemetry are opt-in and store redacted metadata, hashes, source refs, counters, and gap diagnostics rather than raw private prompt text.
- Brain mutations (`dream`, `merge`, `upgrade`) take a pre-run snapshot with a SHA-256 sidecar; `o2b brain rollback` aborts on drift unless `--force-rollback`.
- Lifecycle review commands (`intent-review`, `retention`, `monthly`) are read-only. Retention emits recommendations only; it never deletes, moves, or edits Brain artifacts.
- Hooks (Claude Code, Codex) inject active context and capture explicit prompt markers / `brain_feedback` tool calls through the same signal dedup boundary; lifecycle observations are audited/logged and never block the runtime.
diff --git a/docs/brainstorm/context-continuity-receipts-suite/cli-output/claude.md b/docs/brainstorm/context-continuity-receipts-suite/cli-output/claude.md
new file mode 100644
index 00000000..d7e35366
--- /dev/null
+++ b/docs/brainstorm/context-continuity-receipts-suite/cli-output/claude.md
@@ -0,0 +1,39 @@
+### Variant 1: Shared continuity substrate with feature modules on top
+
+- **Approach**: Extract one small, append-only, rebuildable record substrate (stable source IDs, content/text hashing, redaction + private-flag policy, bounded pagination, stable JSON envelope, purge/invalidate-by-source) and build all four log-shaped features - injection receipts, recall telemetry, pre-compaction decision capture, and session-DAG nodes - as typed record kinds on it. The three context-pipeline features (budget presets diagnostic, cache-stable ordering, repeated-context dedup) attach as opt-in transforms/readers over `context-pack.ts` and `pre-compress-pack.ts` without owning their own persistence. Each feature stays a separate module with its own flag and CLI/MCP surface; only the substrate is shared.
+- **Trade-offs**:
+ - Pro: maximal DRY - hashing, redaction, pagination, JSON contract, and forget/purge integration are written and tested once, then reused by receipts/telemetry/decisions/DAG.
+ - Pro: SOLID - substrate is a single responsibility with a stable interface; features depend on the abstraction, satisfying the "rebuildable/auditable derived index" constraint uniformly.
+ - Pro: redaction/private-content safety and `forget`/source-purge are enforced centrally, lowering the risk of a leak slipping through one feature.
+ - Con: the substrate must be designed before most vertical value lands, so the first atomic commits produce infrastructure rather than user-visible features.
+ - Con: over-generalizing the record schema (forcing DAG lineage and a receipt into one shape) risks a leaky abstraction if kinds diverge more than expected.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 2: Independent vertical slices, minimal sharing
+
+- **Approach**: Implement each of the seven tasks as a fully self-contained module with its own store/files, flag, contract, and tests, sharing only small leaf utilities (hash, ISO time, redaction helper) pulled in ad hoc. No common substrate; receipts, telemetry, decisions, and the DAG each define and persist their own record format. Context-pipeline features patch `context-pack.ts`/`pre-compress-pack.ts` independently behind their own opt-in switches.
+- **Trade-offs**:
+ - Pro: maximally KISS per feature and ideal for atomic TDD commits - each task ships and is reviewable in isolation with no cross-feature coupling.
+ - Pro: lowest blast radius; a bug or rollback in one feature cannot touch the others, and defaults stay untouched per task.
+ - Con: DRY violation across the four log-shaped surfaces - pagination, redaction, JSON envelopes, and purge-by-source get re-implemented 3-4 times, inviting drift and inconsistent privacy guarantees.
+ - Con: cross-cutting requirements (forget/source-purge finding references, consistent privacy redaction across receipts + telemetry) must be wired feature-by-feature, easy to miss in one.
+ - Con: seven slightly different JSON contracts increase doc/test surface and long-term maintenance.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Variant 3: Central injection-boundary pipeline orchestrator
+
+- **Approach**: Model context assembly as one staged pipeline (retrieve -> dedup -> cache-stable order -> budget/preset -> emit receipt -> record telemetry), and a parallel compaction pipeline (ingest turns -> DAG compaction -> pre-compaction decision capture), both wired through a central orchestrator with a stage/emitter bus. The seven features become registered stages or subscribers rather than standalone modules, with shared context flowing through the pipeline.
+- **Trade-offs**:
+ - Pro: cleanest conceptual flow - ordering, dedup, budgeting, receipts, and telemetry compose naturally as sequential stages over one context object.
+ - Pro: adding future context paths (the spec's "future context paths") is a matter of registering a stage, maximizing extensibility.
+ - Con: high coupling - every feature now depends on the orchestrator's lifecycle and shared context shape, the opposite of opt-in/isolated; turning one stage off is harder than an independent flag.
+ - Con: drifts toward the explicitly prohibited "general LLM orchestration platform," and risks changing default `brain_context_pack`/search behavior by routing them through new central machinery.
+ - Con: largest up-front build and the hardest to deliver as small atomic TDD commits, since the pipeline scaffold must exist before any stage is meaningful.
+- **Complexity**: large
+- **Risk**: high
+
+### Recommended: Variant 1
+
+**Rationale**: Four of the seven tasks are fundamentally the same shape - a bounded, opt-in, rebuildable, redaction-aware local record log with stable source IDs and purge integration - so a single small substrate satisfies DRY and SOLID and lets the privacy/forget guarantees be enforced and tested once instead of four divergent times. It avoids the prohibited orchestrator coupling of Variant 3 and the cross-surface drift of Variant 2, while still allowing each feature its own flag, CLI/MCP surface, and atomic TDD commits on top. The context-pipeline trio remains lightweight opt-in transforms over existing packs, keeping defaults unchanged as the constraints require.
diff --git a/docs/brainstorm/context-continuity-receipts-suite/cli-output/prompt.md b/docs/brainstorm/context-continuity-receipts-suite/cli-output/prompt.md
new file mode 100644
index 00000000..fc552ae7
--- /dev/null
+++ b/docs/brainstorm/context-continuity-receipts-suite/cli-output/prompt.md
@@ -0,0 +1,94 @@
+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation.
+
+# Task
+
+Implement a Context Continuity & Injection Receipts Suite for Open Second Brain using the following local Hermes triage snapshot tasks. Treat the tasks as one cohesive multi-task PR, but propose variants that keep the implementation professional, SOLID, KISS, and DRY.
+
+## Selected tasks
+
+### t_772706ee P3 - Session summary DAG with lossless drill-down recall
+
+Hermes-LCM persists raw conversation messages, compacts older context into a depth-aware summary DAG, and exposes bounded recovery tools (`lcm_grep`, `lcm_describe`, `lcm_expand`, `lcm_expand_query`, `lcm_load_session`). OSB already has session import adapters, deterministic session codec, conversation fact extraction, context packs, and pre-compress preference packs, but does not have a session-local hierarchy where compacted conversation ranges can be searched, described, and expanded back to exact source turns. Acceptance: ingest long imported Hermes/Claude/Codex session into raw turns and at least two DAG depths without losing source IDs; search returns raw-turn and summary-node hits with bounded snippets; expanding a summary node returns immediate sources with pagination and exact raw turn follow-up; opt-in and no default behavior change; tests cover lineage, pagination, oversized turns, rebuildability, and idempotency.
+
+### t_192d9c8c P3 - Model-aware context budget presets with dry-run diagnostics
+
+Hermes-LCM has inspectable model-family context presets. OSB has many independent knobs (`brain_context_pack` limits, `brain_pre_compress_pack`, MCP preview budget, search limits), but no read-only diagnostic that maps runtime/model context characteristics to recommended OSB budget settings while preserving overrides. Acceptance: `context-preset suggest` returns recommendation with reason/confidence/no mutation; `context-preset diff` reports exact proposed changes while preserving explicit overrides; at least tight-context and long-context presets; token-footprint or doctor can reference diagnostics; tests cover selection, override preservation, invalid override reporting, JSON output.
+
+### t_57eedc53 P3 - Pre-compaction decision and commitment capture
+
+Hermes-LCM optionally scans the soon-to-be-compacted conversation segment and writes durable decisions, commitments, outcomes, rules, and open questions. OSB has `brain_pre_compress_pack`, import-session, timeline, and fact extraction, but not a compression-boundary capture path. Acceptance: bounded compression-boundary payload can produce durable typed records with source turn refs; best-effort and never blocks compression on failure; idempotent by session+turn range+text hash; extracted records appear in timeline/search surfaces; tests cover empty/noisy segments, duplicate extraction, media/base64 sanitization, failure handling.
+
+### t_6e50c711 P3 - Cache-stable Brain context pack ordering with ranking annotations
+
+ContextPilot reorders retrieved context blocks to improve prefix/KV-cache reuse while preserving original ranking metadata. OSB context packs optimize for one request at a time. Acceptance: optional cache-stable order without changing selected blocks; moved blocks retain original rank, score, why_retrieved; plain Markdown and JSON remain understandable; disabled by default; tests cover deterministic ordering, rank preservation, repeated-block grouping, backwards-compatible output.
+
+### t_8c5f1093 P2 - Lossless repeated-context deduplication with reference hints
+
+ContextPilot detects byte-identical or chunk-identical repeated context within an explicit session and replaces later repeats with auditable reference hints only when the original remains accessible. OSB has compression, payload externalization, budgets, and artifacts, but no session-scoped repeated-context dedup pass. Acceptance: detect repeated context across explicit session IDs; replace with reference hints only when original remains accessible; content-defined chunking catches shifted repeated sections; visibility boundaries prevent cross-session/agent contamination; diagnostics report blocks saved; tests cover repeated tool results, shifted blocks, missing-original fallback, isolation, small-input no-op.
+
+### t_92d938e9 P2 - Prompt context receipts for auditable Brain injection
+
+Hermes-agentmemory records which memories were summarized into context. OSB has `why_retrieved`, query cache, context packs, and logs, but no receipt log of the final Brain context that crossed the prompt boundary. Acceptance: context-pack, pre-compress, and future context paths can emit receipts; receipts include stable source identifiers, ranking/budget metadata, redaction/private flags, final injected-text hash; no raw private content by default; CLI/MCP can list/show by session/host/trigger/source/receipt id; forget/source purge can find/invalidate references; tests cover emission, redaction-safe serialization, filters, cache/forget integration.
+
+### t_e3d045d6 P1 - Recall telemetry log with coverage and knowledge-gap summary
+
+ByteRover records recall queries and summarizes coverage/cache/timing/gaps. OSB has `why_retrieved`, query cache, ranking diagnostics, token-footprint, and benchmarks, but no retained recall telemetry log for live recall usage. Acceptance: search/context-pack calls can record bounded local telemetry without changing returned results; telemetry can be disabled/redacted; view supports time/status/detail filters and JSON; summary reports coverage, cache hits, latency, top artifacts, unanswered gaps; interrupted calls visible after timeout; tests cover log write, pruning, corrupt tolerance, aggregation, privacy redaction.
+
+# Project context
+
+Project: Open Second Brain, TypeScript/Bun CLI + MCP server, filesystem-first Obsidian-compatible Brain vault.
+
+Recent main commits:
+
+- 3b7b3a5 feat(brain): add safety governance foundations (#55) / v0.28.0
+- 794ee45 feat(search): ship recall control and trust surfaces (#54) / v0.27.0
+- 40d4e2b feat: cjk schema lifecycle recovery (#53) / v0.26.0
+- f62918c feat: runtime schema packs foundation (#52) / v0.25.0
+- 14d1ee1 feat: brain model semantics foundation (#51) / v0.24.0
+- 3a5d5c3 feat: agent capability CLI integration (#50) / v0.23.0
+- a085bfa feat: vault portability + session economy (#49) / v0.22.0
+- 73e4a28 feat: brain lifecycle suite (#48) / v0.21.0
+- bd49cd5 feat: recall and ranking quality (#47) / v0.20.0
+- 5fa7eb0 feat: MCP context economy (#45) / v0.18.0
+
+Related files and existing surfaces:
+
+- `src/core/brain/context-pack.ts`: builds `brain_context_pack` items with token/char budgets, polarity lanes, and v0.28 safety reports.
+- `src/core/brain/pre-compress-pack.ts`: builds `brain_pre_compress_pack` addendum for host compression boundaries.
+- `src/mcp/brain-tools.ts`: MCP handlers for context pack, pre-compress pack, search, receipts/future tools should fit here.
+- `src/core/brain/sessions/types.ts`, `src/core/brain/sessions/import.ts`: normalize Claude/Codex/Hermes transcripts to `SessionTurn` and import `@osb` markers/tool calls.
+- `src/core/search/*`: existing search ranking, evidence packs, query cache, focus, structured query.
+- `src/mcp/artifact-store.ts`: context economy stores oversized tool output artifacts.
+- `src/core/brain/payload-registry.ts`: v0.28 payload externalization foundation.
+- `docs/cli-reference.md`, `docs/mcp.md`, `README.md`, `CHANGELOG.md`: user-facing docs to update.
+
+Project conventions and constraints:
+
+- Brain source of truth remains plain Markdown/vault files. Derived indexes/caches must be rebuildable or auditable.
+- Prefer deterministic, bounded, opt-in surfaces. Avoid silently mutating live config or injecting raw private content.
+- CLI/MCP outputs need stable JSON contracts and tests. Read-only/preview-first is preferred for governance and context workflows.
+- No new external dependencies unless clearly necessary.
+- Do not replace Hermes-LCM or build a general LLM orchestration platform.
+- Do not change default `brain import-session`, `brain codec`, `brain_context_pack`, or search behavior unless the caller opts in.
+- Version bump must happen before GitHub push, but not during Phase 0.
+- Before every commit, run `bun run fmt` and `bun run lint`.
+- Phase 2 implementation must be TDD and atomic commits.
+
+# Required output format
+
+Produce exactly 3 distinct architectural variants. For each variant:
+
+### Variant N: <short name>
+
+- **Approach**: 2-3 sentences describing the variant.
+- **Trade-offs**: bullet list of pros and cons.
+- **Complexity**: small | medium | large
+- **Risk**: low | medium | high
+
+After the three variants, add exactly one recommendation:
+
+### Recommended: Variant N
+
+**Rationale**: 2-3 sentences explaining why this variant over the others, considering the project context and constraints above.
+
+Output nothing outside of these sections.
diff --git a/docs/brainstorm/context-continuity-receipts-suite/design.md b/docs/brainstorm/context-continuity-receipts-suite/design.md
new file mode 100644
index 00000000..baf52410
--- /dev/null
+++ b/docs/brainstorm/context-continuity-receipts-suite/design.md
@@ -0,0 +1,75 @@
+# Context Continuity & Receipts Suite - OSB-native context audit and recall continuity
+
+**Status:** draft
+**Author:** GitHub Copilot (via feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+Open Second Brain already has strong recall, context-pack, pre-compress, session-import, artifact, and safety surfaces, but the exact context crossing the agent prompt boundary is still hard to audit after the fact. Long sessions also lose navigability once host runtimes compress older turns: derived facts and preferences survive, while the source turn ranges behind decisions, commitments, summaries, and repeated context are not exposed as a bounded drill-down graph. Operators need read-only, local, privacy-aware continuity tools that explain what was injected, what recall queries succeeded or failed, what session material was compacted, and how to recover exact source slices without flooding the model.
+
+## Scope
+
+- Shared append-only continuity record substrate for redaction-safe, source-linked, bounded JSONL records under the Brain vault.
+- Prompt context receipts for `brain_context_pack` and `brain_pre_compress_pack`, with CLI/MCP list/show surfaces.
+- Recall telemetry for search/context-pack/pre-compress calls, with view and summary filters for coverage, cache, latency, top artifacts, and gaps.
+- Pre-compaction extraction API/CLI that records typed decisions, commitments, outcomes, rules, and open questions from a bounded turn segment without blocking host compression.
+- Session recall DAG foundation: raw imported session turns, deterministic summary nodes, search, describe, and expand with source lineage and pagination.
+- Opt-in context transforms: cache-stable ordering, repeated-context deduplication with reference hints, and model-aware budget preset diagnostics.
+- User-facing docs and version metadata for the new release.
+
+## Out of scope
+
+- Replacing Hermes-LCM or implementing a general conversation compression engine.
+- Automatic promotion of extracted rules into confirmed preferences.
+- Persisting raw private content in receipts by default.
+- Automatically mutating `_brain.yaml`, runtime configs, or host MCP settings from context presets.
+- Enabling cache-stable ordering, deduplication, receipts, or telemetry by default for existing callers.
+- Cross-session deduplication or recall contamination across different agents/visibility scopes.
+
+## Chosen approach
+
+Use Variant 1 from the brainstorm: create a small shared continuity substrate and build feature modules on top. The substrate owns stable record IDs, hashes, timestamps, source references, redaction/private flags, JSONL append/read, pagination, filtering, and source invalidation markers. Feature modules remain responsible for their domain payloads: receipts describe injected context; telemetry describes recall operations; pre-compact extraction records durable session knowledge; session recall stores raw turns and summary nodes; context transforms shape emitted context only when explicitly requested.
+
+## Design decisions
+
+- **One substrate, typed payloads.** Use a closed `kind` union with kind-specific payload interfaces instead of separate stores per feature. This avoids duplicating redaction, pagination, and source-reference logic while preserving domain-specific validation.
+- **Append-only JSONL plus derived helpers.** Store records in `Brain/log/continuity/YYYY-MM.jsonl` so they remain vault-local and inspectable. Indexes or summaries can be rebuilt from JSONL records; tests should not rely on hidden state.
+- **Redaction-safe by default.** Receipts and telemetry store hashes, source IDs, snippets, counts, and reason metadata, not raw full prompt text. Any raw debug text requires an explicit local option and must carry `private: true`/redaction flags.
+- **Opt-in integration.** Existing `packContext`, `buildPreCompressPack`, and search behavior remain unchanged unless callers pass receipt/telemetry/transform options or invoke new CLI/MCP verbs.
+- **Deterministic session DAG first.** Initial session recall summaries are deterministic extractive summaries over imported turns and child nodes, not model-generated summaries. This gives source lineage, pagination, search, and tests without adding model dependencies.
+- **Transform metadata is explicit.** Cache-stable ordering and dedup never hide relevance. Moved/deduplicated blocks keep `original_rank`, stable block IDs, previous-reference metadata, and diagnostics.
+- **Preset diagnostics never apply.** Context presets expose `show`, `suggest`, and `diff` only. They return proposed config/env changes and override conflicts but do not write config.
+- **Forget/source-purge is discoverable.** This release adds source-reference lookup/invalidation markers in the substrate. Destructive purge application remains a follow-up; the important contract is that receipts/telemetry/DAG/extractions can be found by source.
+
+## File changes
+
+Expected new files:
+
+- `src/core/brain/continuity/store.ts` - append/read/filter/paginate continuity records.
+- `src/core/brain/continuity/types.ts` - shared record and source-reference contracts.
+- `src/core/brain/continuity/redaction.ts` - private-region stripping, snippet hashing, safe serialization helpers.
+- `src/core/brain/context-receipts.ts` - receipt builders/list/show filters.
+- `src/core/brain/recall-telemetry.ts` - telemetry record builders and summaries.
+- `src/core/brain/pre-compact-extract.ts` - deterministic extraction from bounded turn segments.
+- `src/core/brain/session-recall.ts` - raw turn ingestion, summary-node build, search/describe/expand.
+- `src/core/brain/context-transforms.ts` - cache-stable ordering and repeated-context dedup primitives.
+- `src/core/brain/context-presets.ts` - preset catalog, suggestion, diff diagnostics.
+- Focused tests under `tests/core/brain/` and CLI/MCP tests as surfaces are added.
+
+Expected modified files:
+
+- `src/core/brain/context-pack.ts` - optional receipt/telemetry/ordering/dedup hooks and structured metadata.
+- `src/core/brain/pre-compress-pack.ts` - optional receipt/telemetry hooks.
+- `src/cli/brain/*` / verb registry/help - new read-only verbs.
+- `src/mcp/brain-tools.ts` - read-only MCP tools for receipts, session recall, presets, and telemetry.
+- `src/core/search/*` and/or CLI search wrapper - optional recall telemetry emission without changing results.
+- `docs/cli-reference.md`, `docs/mcp.md`, `README.md`, `CHANGELOG.md`, package/manifests for release.
+
+## Risks and open questions
+
+- **Scope pressure:** a full LCM clone would be too large. Keep session summaries deterministic and bounded; model-assisted summarization can be a future extension.
+- **JSONL growth:** continuity logs need filters and likely pruning later. This release should include bounded reads and summary filters, not a retention policy overhaul.
+- **Privacy:** receipts and telemetry are valuable precisely because they describe prompt boundaries. Tests must assert raw private regions and secret-like content do not persist by default.
+- **Search integration:** telemetry should not change search result contracts or cache keys unless explicitly enabled.
+- **MCP tool count:** adding several read-only tools may affect tool-surface size. Prefer compact schemas and capability-aware docs; avoid duplicating CLI-only diagnostics unless useful to agents.
diff --git a/docs/brainstorm/context-continuity-receipts-suite/plan.md b/docs/brainstorm/context-continuity-receipts-suite/plan.md
new file mode 100644
index 00000000..a691ab80
--- /dev/null
+++ b/docs/brainstorm/context-continuity-receipts-suite/plan.md
@@ -0,0 +1,51 @@
+# Context Continuity & Receipts Suite - implementation plan
+
+## Tasks
+
+### Task 1: Continuity record substrate
+
+- **Files**: `src/core/brain/continuity/types.ts`, `src/core/brain/continuity/store.ts`, `src/core/brain/continuity/redaction.ts`, `tests/core/brain/continuity-store.test.ts`
+- **Acceptance**: append/read/filter/paginate redaction-safe continuity records under `Brain/log/continuity/`; stable IDs and source refs; source invalidation markers; corrupt-line tolerance.
+- **Depends on**: none
+
+### Task 2: Prompt context receipts
+
+- **Files**: `src/core/brain/context-receipts.ts`, `src/core/brain/context-pack.ts`, `src/core/brain/pre-compress-pack.ts`, CLI/MCP receipt surfaces, receipt tests
+- **Acceptance**: context-pack and pre-compress can optionally emit receipts with item IDs, source paths/hashes, budgets, lanes/safety/redaction flags, final text hash; list/show filters work; no raw private content by default.
+- **Depends on**: Task 1
+
+### Task 3: Recall telemetry log and summary
+
+- **Files**: `src/core/brain/recall-telemetry.ts`, search/context-pack/pre-compress call wrappers, CLI/MCP telemetry surfaces, tests
+- **Acceptance**: optional telemetry records recall/context-pack status, duration, mode, result count, top artifacts, cache/budget metadata, and gaps; view and summary filters produce JSON; disabled/redacted modes preserve privacy.
+- **Depends on**: Task 1
+
+### Task 4: Context transforms
+
+- **Files**: `src/core/brain/context-transforms.ts`, `src/core/brain/context-pack.ts`, MCP/CLI context-pack options, tests
+- **Acceptance**: opt-in cache-stable ordering keeps selected blocks but records `original_rank` and movement diagnostics; session-scoped dedup replaces repeated blocks with reference hints only when an accessible original exists; default behavior unchanged.
+- **Depends on**: Task 2
+
+### Task 5: Context budget presets
+
+- **Files**: `src/core/brain/context-presets.ts`, CLI/MCP preset diagnostics, optional token-footprint/doctor warning only when it reuses the existing diagnostic output path without adding remediation behavior, tests
+- **Acceptance**: read-only `show`, `suggest`, and `diff` expose tight-context and long-context presets with match reason/confidence, proposed changes, explicit override preservation, and invalid override reporting.
+- **Depends on**: none
+
+### Task 6: Pre-compaction extraction
+
+- **Files**: `src/core/brain/pre-compact-extract.ts`, CLI/MCP extraction surface, timeline/search integration if bounded, tests
+- **Acceptance**: bounded segment input emits typed decision/commitment/outcome/rule/open-question records with source turn refs; deterministic media/base64 sanitization; idempotent by session+turn range+content hash; failures are non-blocking and reported.
+- **Depends on**: Task 1
+
+### Task 7: Session recall DAG foundation
+
+- **Files**: `src/core/brain/session-recall.ts`, session adapter reuse, CLI/MCP `session-grep`/`session-describe`/`session-expand`, tests
+- **Acceptance**: imported session turns can be stored as raw turn records; deterministic summary nodes at two depths keep source lineage; search returns bounded raw and summary hits; expand returns immediate sources and paginated exact raw content; duplicate import idempotent.
+- **Depends on**: Task 1
+
+### Task 8: Docs, version, self-review, QA, PR
+
+- **Files**: `README.md`, `docs/cli-reference.md`, `docs/mcp.md`, `CHANGELOG.md`, package/manifests, PR body
+- **Acceptance**: user-facing docs describe opt-in behavior and privacy defaults; version bumped before push; self-review checks diff against `main`; full QA passes; pre-push ask_report stop-point completed.
+- **Depends on**: Tasks 1-7
diff --git a/docs/brainstorm/context-continuity-receipts-suite/variants.md b/docs/brainstorm/context-continuity-receipts-suite/variants.md
new file mode 100644
index 00000000..d0ff9c52
--- /dev/null
+++ b/docs/brainstorm/context-continuity-receipts-suite/variants.md
@@ -0,0 +1,47 @@
+# Context Continuity & Receipts Suite - brainstorm variants
+
+## Consultant output
+
+Source: `cli-output/claude.md`
+
+### Variant 1: Shared continuity substrate with feature modules on top
+
+- **Approach**: Extract one small, append-only, rebuildable record substrate (stable source IDs, content/text hashing, redaction + private-flag policy, bounded pagination, stable JSON envelope, purge/invalidate-by-source) and build all four log-shaped features - injection receipts, recall telemetry, pre-compaction decision capture, and session-DAG nodes - as typed record kinds on it. The three context-pipeline features (budget presets diagnostic, cache-stable ordering, repeated-context dedup) attach as opt-in transforms/readers over `context-pack.ts` and `pre-compress-pack.ts` without owning their own persistence. Each feature stays a separate module with its own flag and CLI/MCP surface; only the substrate is shared.
+- **Trade-offs**:
+ - Pro: maximal DRY - hashing, redaction, pagination, JSON contract, and forget/purge integration are written and tested once, then reused by receipts/telemetry/decisions/DAG.
+ - Pro: SOLID - substrate is a single responsibility with a stable interface; features depend on the abstraction, satisfying the rebuildable/auditable derived index constraint uniformly.
+ - Pro: redaction/private-content safety and forget/source-purge are enforced centrally, lowering leak risk.
+ - Con: the substrate must be designed before most vertical value lands.
+ - Con: over-generalizing the record schema risks a leaky abstraction if kinds diverge.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 2: Independent vertical slices, minimal sharing
+
+- **Approach**: Implement each of the seven tasks as a fully self-contained module with its own store/files, flag, contract, and tests, sharing only small leaf utilities ad hoc.
+- **Trade-offs**:
+ - Pro: KISS per feature and straightforward atomic TDD commits.
+ - Pro: lowest rollback blast radius.
+ - Con: repeated redaction, pagination, JSON envelopes, and purge-by-source logic across log-shaped surfaces.
+ - Con: privacy and source-purge behavior can drift between features.
+ - Con: seven different JSON contracts increase maintenance.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Variant 3: Central injection-boundary pipeline orchestrator
+
+- **Approach**: Model context assembly as one staged pipeline and compaction as a second pipeline, with the seven features registered as stages/subscribers.
+- **Trade-offs**:
+ - Pro: conceptually clean context flow.
+ - Pro: extensible stage registration.
+ - Con: high coupling and difficult opt-out behavior.
+ - Con: drifts toward a general LLM orchestration platform.
+ - Con: hardest to deliver as atomic TDD commits.
+- **Complexity**: large
+- **Risk**: high
+
+## Orchestrator decision
+
+Chosen: **Variant 1 - Shared continuity substrate with feature modules on top**.
+
+Rationale: four selected tasks are record-log-shaped and need the same guarantees: stable IDs, bounded pagination, redaction-safe serialization, source linkage, and future invalidation. A small substrate keeps those guarantees centralized without forcing context pack/search/session features through a central orchestration pipeline. Context ordering, deduplication, and budget presets remain opt-in transforms/readers over existing surfaces so default behavior stays stable.
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index 26211b00..7d014e9d 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -64,8 +64,15 @@ o2b brain backlinks List inbound references to a Brain artifact id
o2b brain semantics-backfill Dry-run typed preference-edge backfill preview (since v0.24.0): --json returns missing inverse superseded_by proposals; no writes
o2b brain mcp-landscape List MCP servers configured across the vault (since v0.19.0): name, source file, packages, required env-var names (values never read)
o2b brain scan-inline Capture `@osb` markers from folders listed under `notes.read_paths` in _brain.yaml
-o2b brain import-session Replay signals from a registered agent session .jsonl (or directory)
+o2b brain import-session Replay signals from a registered agent session .jsonl (or directory); --recall also stores turns in the session recall DAG
o2b brain session-hook Internal hook bridge: read one lifecycle payload from stdin, capture prompt markers / brain_feedback, append lifecycle audit/log rows
+o2b brain context-receipts List/show opt-in prompt context receipt continuity records (since v0.29.0)
+o2b brain recall-telemetry List/summarise opt-in recall telemetry continuity records (since v0.29.0)
+o2b brain context-presets Show/suggest/diff read-only context budget presets (since v0.29.0)
+o2b brain pre-compact-extract Extract decision/commitment/outcome/rule/open-question continuity records from bounded text (since v0.29.0)
+o2b brain session-grep Search imported session recall raw turns and summary nodes (since v0.29.0)
+o2b brain session-describe Count raw turns and deterministic summary depths for one session recall DAG (since v0.29.0)
+o2b brain session-expand Expand a session recall node to immediate sources and paginated raw turn content (since v0.29.0)
o2b brain import-claude-memory (CLI-only) Import metadata.type=feedback entries from a Claude Code memory directory into Brain/preferences/. --dry-run / --apply, sidecar manifest for idempotency, UPDATE preserves accumulated evidence
```
@@ -88,12 +95,28 @@ o2b brain summary Operator dashboard - trust verdict (clean | watch
o2b brain page-dedup Page-level duplicate detector (by content hash + frontmatter similarity)
o2b brain lint Self-healing structural drift fixer; --consolidate folds multi-source duplicates
o2b brain token-footprint Token-budget monitor across instruction files and active.md
-o2b brain context-pack Bounded-token vault slice for priming an agent's context window (--max-tokens N, --lanes for directives/constraints/consider)
+o2b brain context-pack Bounded-token vault slice for priming an agent's context window (--max-tokens N, --lanes for directives/constraints/consider; v0.29.0 adds opt-in --receipt, --telemetry, --cache-stable, --dedup-repeated)
o2b brain synthesise Concept-scoped JSON envelope: target node + linkers + optional unlinked mentions
o2b brain moc-audit Per-MOC coverage audit: classify cluster members into well-covered / fragile / candidate-missing
o2b brain unlinked Raw-text mentions outside `[[...]]` (Unicode-aware boundaries)
```
+### Context continuity and receipts (since v0.29.0)
+
+```text
+o2b brain context-pack Existing budgeted context pack; add --receipt to emit a context receipt, --telemetry to emit redacted recall telemetry, --cache-stable for stable ordering diagnostics, and --dedup-repeated for repeated-context reference hints
+o2b brain context-receipts list [--trigger context_pack|pre_compress] [--host <name>] [--session-id <id>] [--limit <n>] [--json]; show <receipt-id> [--json]
+o2b brain recall-telemetry list|summary [--mode search|context_pack|pre_compress] [--status ok|empty|error|timeout] [--host <name>] [--since <iso>] [--until <iso>] [--limit <n>] [--json]
+o2b brain context-presets show [tight-context|long-context] --json; suggest --model <name> --context-window <tokens> --json; diff <preset-id> [current-value flags] [--override <path>...] --json
+o2b brain pre-compact-extract --session-id <id> --turn-start <id> --turn-end <id> --text <bounded-text> [--host <name>] [--max-chars <n>] [--json]
+o2b brain import-session <path> --recall [--recall-session-id <id>] [--recall-summary-group-size <n>] [--json]
+o2b brain session-grep --query <text> [--session-id <id>] [--limit <n>] [--snippet-chars <n>] [--json]
+o2b brain session-describe --session-id <id> [--json]
+o2b brain session-expand <record-id> [--raw-limit <n>] [--cursor <offset>] [--json]
+```
+
+Receipts, telemetry, transforms, and session recall import are opt-in. Receipt and telemetry records store redaction-safe payloads, source references, hashes, counters, and bounded snippets rather than raw private prompt context; session recall stores redacted turn text only when explicitly imported for later expansion.
+
## Vault scope
Single exclusion policy for every vault walker.
diff --git a/docs/mcp.md b/docs/mcp.md
index 3c90efac..a554b6b8 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -18,7 +18,7 @@ in Open Second Brain depends on the MCP server being running.
## Tool Highlights
-The full server currently advertises 58 tools. The table below highlights the
+The full server currently advertises 65 tools. The table below highlights the
operator-facing core, schema, agent-source, health, recovery, and Pay Memory
tools; the full surface also includes Brain writer, review, query, temporal,
link-graph, and search tools. In Claude Code, that full schema can push MCP definitions beyond
@@ -26,41 +26,48 @@ link-graph, and search tools. In Claude Code, that full schema can push MCP defi
writer split below for the always-loaded writer subset, or the runtime
capability flags for a narrower per-process full server.
-| Tool | Purpose | Required arguments |
-| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |
-| `second_brain_capabilities` | Report the tools available to this MCP process and the withheld-tool reasons after runtime capability filtering. | — |
-| `second_brain_status` | Report config and vault status, with secrets redacted. | — |
-| `second_brain_query` | List vault pages with an optional case-insensitive title substring. | — |
-| `vault_health` | Run vault, config, and plugin manifest health checks. | — |
-| `brain_health` | Run semantic Brain Health checks and return the health verdict/domains. | — |
-| `brain_mcp_landscape` | List the MCP servers configured across the vault: name, source config file, packages, and required env-var names. Env values never read. | — |
-| `brain_agent_query` | Read-only source-agent retrieval over Brain provenance. Filters by agents, topic, free-text query, contribution kind, and limit. | — |
-| `brain_agent_diff` | Read-only comparison between source agents using browse/search/diff/map modes over the same provenance foundation. | — |
-| `brain_audit` | Read-only per-preference mutation trail (create / promote / update / retire / merge) with agent, reason, revision + content-hash before/after. | `pref_id` |
-| `brain_morning_brief` | Read-only session-start summary: top confirmed preferences, recent reconcile open questions, recent notes; character-budgeted. | — |
-| `brain_search` | Read-only vault search with optional structured query lanes, explicit focus hints, and evidence-pack diagnostics. | `query` |
-| `brain_recall_gate` | Read-only classifier for whether an automatic recall attempt should run; returns `retrieve` plus a stable reason. | `prompt` |
-| `brain_context_pack` | Budgeted context slice; pass `lanes: true` to return directives, constraints, and consider lanes. Filtered items include `safety.reasons`. | `max_tokens` |
-| `brain_sources` | Read-only dashboard of signals grouped by (agent, source_type) with active/processed and distinct-topic counts. | — |
-| `get_active_schema_pack` | Return the active runtime schema pack resolved from `Brain/_brain.yaml`. | — |
-| `list_schema_packs` | List schema packs available to the vault/runtime. | — |
-| `schema_stats` | Summarise declared schema tokens and observed artifact usage. | — |
-| `schema_lint` | Report unknown, unused, and invalid schema references without writing. | — |
-| `schema_graph` | Return a schema relationship graph for declared types, aliases, prefixes, and link types. | — |
-| `schema_explain_type` | Explain one schema token, including aliases, references, and usage. | `token` |
-| `schema_review_orphans` | Review declared schema tokens that have no observed usage. | — |
-| `schema_apply_mutations` | Apply audited, locked schema mutations to `Brain/_brain.yaml`. | `mutations` |
-| `reload_schema_pack` | Reload and validate the active schema pack after local edits. | — |
-| `brain_watchdog` | Probe Brain config, required dirs, and search-index health; optionally apply safe directory remediation. | — |
-| `brain_switch_vault` | Activate a named vault profile; the change takes effect on the next server launch. | `name` |
-| `payment_memory_init` | Bootstrap `Brain/payments/{policies,assets,drafts,reports}/ (+ dated YYYY-MM-DD receipt subdirs)` and write the spending policy template. | — |
-| `payment_receipt_append` | Save a Markdown receipt for one paid API call. `raw_output` is redacted before persisting. | `service`, `status`, `reason` |
-| `asset_capture` | Save a Markdown note for an asset produced by a paid call, linked to its receipt. | `title`, `service`, `result_url` |
-| `payment_report_generate` | Aggregate a date's receipts into a Markdown report under `Brain/payments/reports/`. | `date` |
-| `payment_policy_check` | Evaluate a prospective paid call against `policies/spending.json` (allowed / approval_required / denied). | `service` |
-| `payment_request_approval` | Create a pending-payment-request the user must approve before the agent runs `pay`. | `service`, `reason` |
-| `payment_request_status` | Look up a pending request by id; agent uses this to poll for approval. | `id` |
-| `payment_request_consume` | Mark an `approved` request as `consumed` and link the resulting receipt. | `id`, `receipt` |
+| Tool | Purpose | Required arguments |
+| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- |
+| `second_brain_capabilities` | Report the tools available to this MCP process and the withheld-tool reasons after runtime capability filtering. | — |
+| `second_brain_status` | Report config and vault status, with secrets redacted. | — |
+| `second_brain_query` | List vault pages with an optional case-insensitive title substring. | — |
+| `vault_health` | Run vault, config, and plugin manifest health checks. | — |
+| `brain_health` | Run semantic Brain Health checks and return the health verdict/domains. | — |
+| `brain_mcp_landscape` | List the MCP servers configured across the vault: name, source config file, packages, and required env-var names. Env values never read. | — |
+| `brain_agent_query` | Read-only source-agent retrieval over Brain provenance. Filters by agents, topic, free-text query, contribution kind, and limit. | — |
+| `brain_agent_diff` | Read-only comparison between source agents using browse/search/diff/map modes over the same provenance foundation. | — |
+| `brain_audit` | Read-only per-preference mutation trail (create / promote / update / retire / merge) with agent, reason, revision + content-hash before/after. | `pref_id` |
+| `brain_morning_brief` | Read-only session-start summary: top confirmed preferences, recent reconcile open questions, recent notes; character-budgeted. | — |
+| `brain_search` | Read-only vault search with optional structured query lanes, explicit focus hints, and evidence-pack diagnostics. | `query` |
+| `brain_recall_gate` | Read-only classifier for whether an automatic recall attempt should run; returns `retrieve` plus a stable reason. | `prompt` |
+| `brain_context_pack` | Budgeted context slice; pass `lanes: true` to return directives, constraints, and consider lanes. Filtered items include `safety.reasons`. | `max_tokens` |
+| `brain_context_receipts` | List or show opt-in prompt context receipt continuity records with budgets, hashes, source refs, safety/redaction metadata, and item IDs. | `operation` |
+| `brain_recall_telemetry` | List or summarise opt-in recall telemetry records for search, context-pack, and pre-compress calls. | `operation` |
+| `brain_context_presets` | Show, suggest, or diff read-only context budget presets (`tight-context`, `long-context`) without writing config. | `operation` |
+| `brain_pre_compact_extract` | Extract decision/commitment/outcome/rule/open-question records from bounded text into continuity storage. | `session_id`, `turn_start`, `turn_end`, `text` |
+| `brain_session_grep` | Search imported session recall raw turns and deterministic summary nodes. | `query` |
+| `brain_session_describe` | Describe raw-turn counts and summary depths for one imported session recall DAG. | `session_id` |
+| `brain_session_expand` | Expand a raw or summary session recall node to immediate sources and paginated raw turn content. | `id` |
+| `brain_sources` | Read-only dashboard of signals grouped by (agent, source_type) with active/processed and distinct-topic counts. | — |
+| `get_active_schema_pack` | Return the active runtime schema pack resolved from `Brain/_brain.yaml`. | — |
+| `list_schema_packs` | List schema packs available to the vault/runtime. | — |
+| `schema_stats` | Summarise declared schema tokens and observed artifact usage. | — |
+| `schema_lint` | Report unknown, unused, and invalid schema references without writing. | — |
+| `schema_graph` | Return a schema relationship graph for declared types, aliases, prefixes, and link types. | — |
+| `schema_explain_type` | Explain one schema token, including aliases, references, and usage. | `token` |
+| `schema_review_orphans` | Review declared schema tokens that have no observed usage. | — |
+| `schema_apply_mutations` | Apply audited, locked schema mutations to `Brain/_brain.yaml`. | `mutations` |
+| `reload_schema_pack` | Reload and validate the active schema pack after local edits. | — |
+| `brain_watchdog` | Probe Brain config, required dirs, and search-index health; optionally apply safe directory remediation. | — |
+| `brain_switch_vault` | Activate a named vault profile; the change takes effect on the next server launch. | `name` |
+| `payment_memory_init` | Bootstrap `Brain/payments/{policies,assets,drafts,reports}/ (+ dated YYYY-MM-DD receipt subdirs)` and write the spending policy template. | — |
+| `payment_receipt_append` | Save a Markdown receipt for one paid API call. `raw_output` is redacted before persisting. | `service`, `status`, `reason` |
+| `asset_capture` | Save a Markdown note for an asset produced by a paid call, linked to its receipt. | `title`, `service`, `result_url` |
+| `payment_report_generate` | Aggregate a date's receipts into a Markdown report under `Brain/payments/reports/`. | `date` |
+| `payment_policy_check` | Evaluate a prospective paid call against `policies/spending.json` (allowed / approval_required / denied). | `service` |
+| `payment_request_approval` | Create a pending-payment-request the user must approve before the agent runs `pay`. | `service`, `reason` |
+| `payment_request_status` | Look up a pending request by id; agent uses this to poll for approval. | `id` |
+| `payment_request_consume` | Mark an `approved` request as `consumed` and link the resulting receipt. | `id`, `receipt` |
`second_brain_query` accepts `pattern` (string) and `limit` (1–500, default 50).
`vault_health` accepts `repo` (string) for plugin manifest validation.
@@ -72,7 +79,17 @@ capability flags for a narrower per-process full server.
`vec:`, and `hyde:` lanes; `focus_query` / `focus_path_prefix` to steer a
single call; and `evidence_pack: true` to return significant/matched/missing
terms, abstention text, terminal-state downrank reasons, and per-result
-`why_retrieved`. `brain_recall_gate` accepts optional `previous_prompt` and
+`why_retrieved`. It can also emit opt-in recall telemetry with `telemetry: true`.
+`brain_context_pack` accepts opt-in `receipt`, `telemetry`, `cache_stable`, and
+`dedup_repeated` diagnostics; `brain_pre_compress_pack` accepts opt-in `receipt`
+and `telemetry`. `brain_context_receipts` supports `operation: "list"|"show"`;
+`brain_recall_telemetry` supports `operation: "list"|"summary"`; and
+`brain_context_presets` supports `operation: "show"|"suggest"|"diff"`.
+`brain_pre_compact_extract` writes idempotent typed continuity records after
+deterministic media/base64 sanitization. `brain_session_grep`,
+`brain_session_describe`, and `brain_session_expand` inspect the opt-in session
+recall DAG populated by CLI `import-session --recall` or the core API.
+`brain_recall_gate` accepts optional `previous_prompt` and
`explicit`; `explicit: true` always returns `retrieve: true`.
`payment_memory_init` accepts `agent` (string) and `overwrite` (boolean — to
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 4ae84057..505f4ec4 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -2,7 +2,7 @@
"id": "open-second-brain",
"name": "Open Second Brain",
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",
- "version": "0.28.0",
+ "version": "0.29.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 4eb865b9..3df09728 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.28.0",
+ "version": "0.29.0",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
"keywords": [
diff --git a/plugin.yaml b/plugin.yaml
index 0f8a3360..5676b85a 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.28.0"
+version: "0.29.0"
description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index 805ca56e..a7768506 100644
--- a/plugins/codex/.codex-plugin/plugin.json
+++ b/plugins/codex/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.28.0",
+ "version": "0.29.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 4c657b8d..47876fd1 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.28.0"
+version: "0.29.0"
description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/pyproject.toml b/pyproject.toml
index c2a4c865..6223197c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"
# CLI entry points (those moved to `package.json` `bin`).
[project]
name = "open-second-brain"
-version = "0.28.0"
+version = "0.29.0"
description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/src/cli/brain.ts b/src/cli/brain.ts
index db4c3f4c..e748ab47 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -54,6 +54,13 @@ import {
cmdBrainPageDedup,
cmdBrainTokenFootprint,
cmdBrainContextPack,
+ cmdBrainContextReceipts,
+ cmdBrainContextPresets,
+ cmdBrainPreCompactExtract,
+ cmdBrainRecallTelemetry,
+ cmdBrainSessionDescribe,
+ cmdBrainSessionExpand,
+ cmdBrainSessionGrep,
cmdBrainLint,
cmdBrainActions,
cmdBrainSummary,
@@ -177,6 +184,20 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promis
return await cmdBrainTokenFootprint(rest);
case "context-pack":
return await cmdBrainContextPack(rest);
+ case "context-receipts":
+ return await cmdBrainContextReceipts(rest);
+ case "context-presets":
+ return await cmdBrainContextPresets(rest);
+ case "pre-compact-extract":
+ return await cmdBrainPreCompactExtract(rest);
+ case "recall-telemetry":
+ return await cmdBrainRecallTelemetry(rest);
+ case "session-grep":
+ return await cmdBrainSessionGrep(rest);
+ case "session-describe":
+ return await cmdBrainSessionDescribe(rest);
+ case "session-expand":
+ return await cmdBrainSessionExpand(rest);
case "lint":
return await cmdBrainLint(rest);
case "actions":
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
index b6d6ec1c..92ee8692 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -56,6 +56,13 @@ Brain verbs (observing memory):
page-dedup Detect (and optionally merge) near-duplicate vault pages
token-footprint Report per-category vault token size with a warn threshold
context-pack Return a tier-then-recency vault slice under a token budget
+ context-receipts List/show prompt context receipt records
+ context-presets Show/suggest/diff read-only context budget presets
+ pre-compact-extract Extract typed continuity records from bounded text
+ recall-telemetry List/summarize opt-in recall telemetry records
+ session-grep Search imported session recall turns and summaries
+ session-describe Describe an imported session recall DAG
+ session-expand Expand a session recall node to source turns
lint Self-healing structural checks (--consolidate); --apply to write
actions Ranked maintenance action list (dedup + lint + footprint)
summary Operator dashboard: trust verdict, doctor/dream counts, actions
@@ -255,11 +262,14 @@ export const VERB_HELP: Record<string, string> = {
"import-session":
"usage: o2b brain import-session <path> [--vault <vault>]\n" +
" [--format auto|<registered-adapter>]\n" +
- " [--since <ISO>] [--dry-run] [--json]\n" +
+ " [--agent <name>] [--since <ISO>] [--dry-run] [--recall]\n" +
+ " [--recall-session-id <id>] [--recall-summary-group-size <n>] [--json]\n" +
"Extract signals from a registered agent session .jsonl file (or\n" +
"directory of .jsonl files). Two extraction paths run in parallel:\n" +
"@osb markers in user/assistant messages, and replay of brain_feedback\n" +
"tool_use calls. Dedup against the inbox by normalised payload hash.\n" +
+ "With --recall, also stores normalized turns in the continuity-backed\n" +
+ "session recall DAG.\n" +
"Autodetect failure exits 2 — pass --format to override.\n",
merge:
"usage: o2b brain merge <keep-pref-id> <drop-pref-id>\n" +
@@ -326,13 +336,40 @@ export const VERB_HELP: Record<string, string> = {
"threshold (default 200000; override via --warn-threshold or the\n" +
"BRAIN_TOKEN_WARN_THRESHOLD env var).\n",
"context-pack":
- "usage: o2b brain context-pack --max-tokens <n> [--query <q>] [--lanes] [--vault <path>] [--json]\n" +
+ "usage: o2b brain context-pack --max-tokens <n> [--query <q>] [--lanes] [--cache-stable] [--dedup-repeated]\n" +
+ " [--receipt] [--receipt-host <name>] [--telemetry] [--telemetry-host <name>]\n" +
+ " [--session-id <id>] [--turn-id <id>] [--vault <path>] [--json]\n" +
"Return the highest-tier, most recent vault slice that fits under\n" +
"<n> tokens. Items ordered core → supporting → peripheral, then\n" +
"newest first. Stops adding pages when the next page would exceed\n" +
"the budget. --query <q> filters by NFKC+casefold substring match\n" +
"on topic + principle. --lanes also returns directives, constraints,\n" +
"and consider lanes alongside the legacy flat items list.\n",
+ "context-receipts":
+ "usage: o2b brain context-receipts list [--trigger context_pack|pre_compress] [--host <name>] [--session-id <id>] [--limit <n>] [--vault <path>] [--json]\n" +
+ " o2b brain context-receipts show <receipt-id> [--vault <path>] [--json]\n" +
+ "Read prompt context receipt continuity records emitted by opt-in callers.\n",
+ "context-presets":
+ "usage: o2b brain context-presets show [preset-id] [--json]\n" +
+ " o2b brain context-presets suggest [--model <name>] [--context-window <tokens>] [--json]\n" +
+ " o2b brain context-presets diff <preset-id> [current-value flags] [--override <path>...] [--json]\n" +
+ "Dry-run model-aware context budget preset diagnostics. Never writes config.\n",
+ "pre-compact-extract":
+ "usage: o2b brain pre-compact-extract --vault <path> --session-id <id> --turn-start <id> --turn-end <id> --text <text> [--host <name>] [--max-chars <n>] [--json]\n" +
+ "Extract Decision/Commitment/Outcome/Rule/Open question lines into idempotent continuity records.\n",
+ "recall-telemetry":
+ "usage: o2b brain recall-telemetry list [--mode search|context_pack|pre_compress] [--status ok|empty|error|timeout] [--host <name>] [--since <iso>] [--until <iso>] [--limit <n>] [--vault <path>] [--json]\n" +
+ " o2b brain recall-telemetry summary [same filters] [--vault <path>] [--json]\n" +
+ "Read opt-in recall telemetry continuity records and aggregate coverage gaps.\n",
+ "session-grep":
+ "usage: o2b brain session-grep --query <text> [--session-id <id>] [--limit <n>] [--snippet-chars <n>] [--vault <path>] [--json]\n" +
+ "Search imported session recall raw turns and summary nodes.\n",
+ "session-describe":
+ "usage: o2b brain session-describe --session-id <id> [--vault <path>] [--json]\n" +
+ "Describe counts and summary depths for an imported session recall DAG.\n",
+ "session-expand":
+ "usage: o2b brain session-expand <record-id> [--raw-limit <n>] [--cursor <offset>] [--vault <path>] [--json]\n" +
+ "Expand a raw or summary session recall node to immediate sources and paginated raw turn content.\n",
lint:
"usage: o2b brain lint --consolidate [--apply] [--yes] [--vault <path>] [--json]\n" +
"Self-healing structural lint. Dry-run by default; --apply writes\n" +
diff --git a/src/cli/brain/verbs/context-pack.ts b/src/cli/brain/verbs/context-pack.ts
index 82ea52b1..ed054d64 100644
--- a/src/cli/brain/verbs/context-pack.ts
+++ b/src/cli/brain/verbs/context-pack.ts
@@ -17,6 +17,14 @@ export async function cmdBrainContextPack(argv: string[]): Promise<number> {
"max-tokens": { type: "string" },
query: { type: "string" },
lanes: { type: "boolean" },
+ receipt: { type: "boolean" },
+ "receipt-host": { type: "string" },
+ telemetry: { type: "boolean" },
+ "telemetry-host": { type: "string" },
+ "session-id": { type: "string" },
+ "turn-id": { type: "string" },
+ "cache-stable": { type: "boolean" },
+ "dedup-repeated": { type: "boolean" },
});
const config = defaultConfigPath();
const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
@@ -36,6 +44,41 @@ export async function cmdBrainContextPack(argv: string[]): Promise<number> {
maxTokens,
...(flags["query"] ? { query: flags["query"] as string } : {}),
...(flags["lanes"] === true ? { includeLanes: true } : {}),
+ ...(flags["receipt"] === true
+ ? {
+ receipt: {
+ host: trimOrDefault(flags["receipt-host"], "cli"),
+ trigger: "context_pack" as const,
+ ...(trimOrUndefined(flags["session-id"]) !== undefined
+ ? { sessionId: trimOrUndefined(flags["session-id"]) }
+ : {}),
+ ...(trimOrUndefined(flags["turn-id"]) !== undefined
+ ? { turnId: trimOrUndefined(flags["turn-id"]) }
+ : {}),
+ },
+ }
+ : {}),
+ ...(flags["cache-stable"] === true || flags["dedup-repeated"] === true
+ ? {
+ transforms: {
+ ...(flags["cache-stable"] === true ? { cacheStableOrdering: true } : {}),
+ ...(flags["dedup-repeated"] === true ? { deduplicateRepeatedContext: true } : {}),
+ },
+ }
+ : {}),
+ ...(flags["telemetry"] === true
+ ? {
+ telemetry: {
+ host: trimOrDefault(flags["telemetry-host"], "cli"),
+ ...(trimOrUndefined(flags["session-id"]) !== undefined
+ ? { sessionId: trimOrUndefined(flags["session-id"]) }
+ : {}),
+ ...(trimOrUndefined(flags["turn-id"]) !== undefined
+ ? { turnId: trimOrUndefined(flags["turn-id"]) }
+ : {}),
+ },
+ }
+ : {}),
});
if (flags["json"]) {
@@ -47,8 +90,14 @@ export async function cmdBrainContextPack(argv: string[]): Promise<number> {
path: i.path,
tier: i.tier,
tokens: i.tokens,
+ ...(i.originalRank !== undefined ? { original_rank: i.originalRank } : {}),
+ ...(i.stableRank !== undefined ? { stable_rank: i.stableRank } : {}),
+ ...(i.dedupedFrom !== undefined ? { deduped_from: i.dedupedFrom } : {}),
+ ...(i.referenceHint !== undefined ? { reference_hint: i.referenceHint } : {}),
})),
skipped: report.skipped,
+ ...(report.receiptId ? { receipt_id: report.receiptId } : {}),
+ ...(report.telemetryId ? { telemetry_id: report.telemetryId } : {}),
...(report.lanes ? { lanes: report.lanes } : {}),
});
return 0;
@@ -57,8 +106,19 @@ export async function cmdBrainContextPack(argv: string[]): Promise<number> {
process.stdout.write(`tokens used: ${report.tokensUsed} / ${report.maxTokens}\n`);
process.stdout.write(`pages included: ${report.items.length}\n`);
process.stdout.write(`pages skipped: ${report.skipped.length}\n\n`);
+ if (report.receiptId) process.stdout.write(`receipt: ${report.receiptId}\n`);
for (const i of report.items) {
process.stdout.write(`[${i.tier}] ${i.id} (${i.tokens} tokens)\n`);
}
return 0;
}
+
+function trimOrDefault(value: string | boolean | string[] | undefined, fallback: string): string {
+ return trimOrUndefined(value) ?? fallback;
+}
+
+function trimOrUndefined(value: string | boolean | string[] | undefined): string | undefined {
+ if (typeof value !== "string") return undefined;
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : undefined;
+}
diff --git a/src/cli/brain/verbs/context-presets.ts b/src/cli/brain/verbs/context-presets.ts
new file mode 100644
index 00000000..e8a9b16b
--- /dev/null
+++ b/src/cli/brain/verbs/context-presets.ts
@@ -0,0 +1,108 @@
+import {
+ diffContextPreset,
+ getContextPreset,
+ listContextPresets,
+ suggestContextPreset,
+ type ContextPresetCurrentConfig,
+} from "../../../core/brain/context-presets.ts";
+import { CliError, parse } from "../helpers.ts";
+
+export async function cmdBrainContextPresets(argv: string[]): Promise<number> {
+ const subcommand = argv[0];
+ const rest = argv.slice(1);
+ if (subcommand === "show") return showPreset(rest);
+ if (subcommand === "suggest") return suggestPreset(rest);
+ if (subcommand === "diff") return diffPreset(rest);
+ throw new CliError("brain context-presets: expected show, suggest, or diff");
+}
+
+function showPreset(argv: string[]): number {
+ const { flags, positional } = parse(argv, { json: { type: "boolean" } });
+ const id = positional[0];
+ const value = id === undefined ? listContextPresets() : getContextPreset(id);
+ if (value === null) throw new CliError(`brain context-presets show: unknown preset ${id}`);
+ writeOutput(value, flags["json"] === true);
+ return 0;
+}
+
+function suggestPreset(argv: string[]): number {
+ const { flags } = parse(argv, {
+ json: { type: "boolean" },
+ model: { type: "string" },
+ "context-window": { type: "string" },
+ });
+ const windowRaw = trimOrUndefined(flags["context-window"]);
+ const suggestion = suggestContextPreset({
+ ...(trimOrUndefined(flags["model"]) !== undefined
+ ? { model: trimOrUndefined(flags["model"]) }
+ : {}),
+ ...(windowRaw !== undefined
+ ? { contextWindowTokens: positiveInteger(windowRaw, "--context-window") }
+ : {}),
+ });
+ writeOutput(suggestion, flags["json"] === true);
+ return 0;
+}
+
+function diffPreset(argv: string[]): number {
+ const { flags, positional } = parse(argv, {
+ json: { type: "boolean" },
+ override: { type: "string-array" },
+ "context-pack-max-tokens": { type: "string" },
+ "context-pack-max-chars-per-memory": { type: "string" },
+ "context-pack-max-total-chars": { type: "string" },
+ "pre-compress-top-k": { type: "string" },
+ "pre-compress-max-chars-per-memory": { type: "string" },
+ "pre-compress-max-total-chars": { type: "string" },
+ });
+ const id = positional[0];
+ if (id === undefined) throw new CliError("brain context-presets diff: preset id is required");
+ const current: ContextPresetCurrentConfig = {
+ context_pack: numericSection(flags, [
+ ["context-pack-max-tokens", "max_tokens"],
+ ["context-pack-max-chars-per-memory", "max_chars_per_memory"],
+ ["context-pack-max-total-chars", "max_total_chars"],
+ ]),
+ pre_compress: numericSection(flags, [
+ ["pre-compress-top-k", "top_k"],
+ ["pre-compress-max-chars-per-memory", "max_chars_per_memory"],
+ ["pre-compress-max-total-chars", "max_total_chars"],
+ ]),
+ overrides: (flags["override"] as string[] | undefined) ?? [],
+ };
+ writeOutput(diffContextPreset(id, current), flags["json"] === true);
+ return 0;
+}
+
+function numericSection(
+ flags: Record<string, string | boolean | string[] | undefined>,
+ pairs: ReadonlyArray<readonly [string, string]>,
+): Record<string, number> {
+ const out: Record<string, number> = {};
+ for (const [flag, key] of pairs) {
+ const value = trimOrUndefined(flags[flag]);
+ if (value !== undefined) out[key] = positiveInteger(value, `--${flag}`);
+ }
+ return out;
+}
+
+function positiveInteger(value: string, label: string): number {
+ if (!/^[0-9]+$/.test(value)) throw new CliError(`${label} must be a positive integer`);
+ const parsed = Number.parseInt(value, 10);
+ if (parsed < 1) throw new CliError(`${label} must be a positive integer`);
+ return parsed;
+}
+
+function trimOrUndefined(value: string | boolean | string[] | undefined): string | undefined {
+ if (typeof value !== "string") return undefined;
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : undefined;
+}
+
+function writeOutput(value: unknown, json: boolean): void {
+ if (json) {
+ process.stdout.write(JSON.stringify(value, null, 2) + "\n");
+ return;
+ }
+ process.stdout.write(JSON.stringify(value, null, 2) + "\n");
+}
diff --git a/src/cli/brain/verbs/context-receipts.ts b/src/cli/brain/verbs/context-receipts.ts
new file mode 100644
index 00000000..9ac29c70
--- /dev/null
+++ b/src/cli/brain/verbs/context-receipts.ts
@@ -0,0 +1,105 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import {
+ getContextReceipt,
+ isContextReceiptTrigger,
+ listContextReceipts,
+ summarizeContextReceipt,
+} from "../../../core/brain/context-receipts.ts";
+import { CliError, parse, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainContextReceipts(argv: string[]): Promise<number> {
+ const subcommand = argv[0];
+ const rest = argv.slice(1);
+ if (subcommand === "list") return listReceipts(rest);
+ if (subcommand === "show") return showReceipt(rest);
+ throw new CliError("brain context-receipts: expected list or show");
+}
+
+function listReceipts(argv: string[]): number {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ trigger: { type: "string" },
+ host: { type: "string" },
+ "session-id": { type: "string" },
+ limit: { type: "string" },
+ });
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const triggerRaw = trimOrUndefined(flags["trigger"]);
+ if (triggerRaw !== undefined && !isContextReceiptTrigger(triggerRaw)) {
+ throw new CliError(`brain context-receipts list: unknown trigger '${triggerRaw}'`);
+ }
+ const limit = parsePositiveInteger(trimOrUndefined(flags["limit"]), "--limit");
+ const receipts = listContextReceipts(vault, {
+ ...(triggerRaw !== undefined ? { trigger: triggerRaw } : {}),
+ ...(trimOrUndefined(flags["host"]) !== undefined
+ ? { host: trimOrUndefined(flags["host"]) }
+ : {}),
+ ...(trimOrUndefined(flags["session-id"]) !== undefined
+ ? { sessionId: trimOrUndefined(flags["session-id"]) }
+ : {}),
+ ...(limit !== undefined ? { limit } : {}),
+ });
+ const summaries = receipts.map(summarizeContextReceipt);
+
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify({ total: summaries.length, receipts: summaries }, null, 2) + "\n",
+ );
+ return 0;
+ }
+
+ process.stdout.write(`${summaries.length} context receipt(s):\n`);
+ for (const receipt of summaries) {
+ process.stdout.write(
+ ` ${receipt.created_at} ${receipt.id} ${receipt.trigger ?? "unknown"} ${receipt.host ?? "-"} items=${receipt.item_count ?? "?"}\n`,
+ );
+ }
+ return 0;
+}
+
+function showReceipt(argv: string[]): number {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const id = trimOrUndefined(positional[0]);
+ if (id === undefined) throw new CliError("brain context-receipts show: receipt id is required");
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const receipt = getContextReceipt(vault, id);
+ if (receipt === null) throw new CliError(`brain context-receipts show: receipt not found: ${id}`);
+
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify(receipt, null, 2) + "\n");
+ return 0;
+ }
+
+ const summary = summarizeContextReceipt(receipt);
+ process.stdout.write(`id: ${summary.id}\n`);
+ process.stdout.write(`created_at: ${summary.created_at}\n`);
+ process.stdout.write(`trigger: ${summary.trigger ?? "unknown"}\n`);
+ process.stdout.write(`host: ${summary.host ?? "-"}\n`);
+ if (summary.session_id) process.stdout.write(`session_id: ${summary.session_id}\n`);
+ if (summary.turn_id) process.stdout.write(`turn_id: ${summary.turn_id}\n`);
+ process.stdout.write(`item_count: ${summary.item_count ?? "?"}\n`);
+ process.stdout.write(`source_count: ${summary.source_count}\n`);
+ return 0;
+}
+
+function parsePositiveInteger(value: string | undefined, label: string): number | undefined {
+ if (value === undefined) return undefined;
+ if (!/^[0-9]+$/.test(value)) {
+ throw new CliError(`brain context-receipts list: ${label} must be a positive integer`);
+ }
+ const parsed = Number.parseInt(value, 10);
+ if (parsed < 1) {
+ throw new CliError(`brain context-receipts list: ${label} must be a positive integer`);
+ }
+ return parsed;
+}
+
+function trimOrUndefined(value: string | boolean | string[] | undefined): string | undefined {
+ if (typeof value !== "string") return undefined;
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : undefined;
+}
diff --git a/src/cli/brain/verbs/import-session.ts b/src/cli/brain/verbs/import-session.ts
index db576b2d..0698c59e 100644
--- a/src/cli/brain/verbs/import-session.ts
+++ b/src/cli/brain/verbs/import-session.ts
@@ -18,6 +18,7 @@ import {
okJson,
resolveBrainVault,
parseOptionalIsoDate,
+ CliError,
} from "../helpers.ts";
export async function cmdBrainImportSession(argv: string[]): Promise<number> {
@@ -27,6 +28,9 @@ export async function cmdBrainImportSession(argv: string[]): Promise<number> {
since: { type: "string" },
"dry-run": { type: "boolean" },
agent: { type: "string" },
+ recall: { type: "boolean" },
+ "recall-session-id": { type: "string" },
+ "recall-summary-group-size": { type: "string" },
json: { type: "boolean" },
});
if (positional.length < 1) return fail("brain import-session requires a <path> argument");
@@ -38,6 +42,14 @@ export async function cmdBrainImportSession(argv: string[]): Promise<number> {
return fail("--agent must be a non-empty string when provided");
}
const agent = explicitAgent ?? resolveAgentName(config);
+ const recallSessionId = normalizeFlagString(flags["recall-session-id"]);
+ if (flags["recall-session-id"] !== undefined && recallSessionId === null) {
+ return fail("--recall-session-id must be a non-empty string when provided");
+ }
+ const recallSummaryGroupSize = parsePositiveIntegerFlag(
+ flags["recall-summary-group-size"],
+ "--recall-summary-group-size",
+ );
const formatRaw = flags["format"] as string | undefined;
let format: SessionAdapterId | undefined;
@@ -64,6 +76,11 @@ export async function cmdBrainImportSession(argv: string[]): Promise<number> {
...(format ? { format } : {}),
...(since ? { since } : {}),
dryRun: Boolean(flags["dry-run"]),
+ recall: Boolean(flags["recall"]),
+ ...(recallSessionId !== null ? { recallSessionId } : {}),
+ ...(recallSummaryGroupSize !== undefined
+ ? { recallSummaryGroupSize: recallSummaryGroupSize }
+ : {}),
})
: {
files: [
@@ -72,6 +89,11 @@ export async function cmdBrainImportSession(argv: string[]): Promise<number> {
...(format ? { format } : {}),
...(since ? { since } : {}),
dryRun: Boolean(flags["dry-run"]),
+ recall: Boolean(flags["recall"]),
+ ...(recallSessionId !== null ? { recallSessionId } : {}),
+ ...(recallSummaryGroupSize !== undefined
+ ? { recallSummaryGroupSize: recallSummaryGroupSize }
+ : {}),
}),
],
warnings: [],
@@ -112,6 +134,8 @@ export async function cmdBrainImportSession(argv: string[]): Promise<number> {
signals_deduped: f.signals_deduped,
tool_replays: f.tool_replays,
malformed: f.malformed,
+ recall_turns_imported: f.recall_turns_imported,
+ recall_summary_nodes: f.recall_summary_nodes,
errors: f.errors,
})),
warnings: result.warnings,
@@ -124,6 +148,10 @@ export async function cmdBrainImportSession(argv: string[]): Promise<number> {
ok(` signals_created: ${f.signals_created}`);
ok(` signals_deduped: ${f.signals_deduped}`);
ok(` tool_replays: ${f.tool_replays}`);
+ if (flags["recall"]) {
+ ok(` recall_turns_imported: ${f.recall_turns_imported}`);
+ ok(` recall_summary_nodes: ${f.recall_summary_nodes}`);
+ }
if (f.malformed > 0) ok(` malformed: ${f.malformed}`);
for (const e of f.errors) info(` error: ${e.path}: ${e.message}`);
}
@@ -139,3 +167,16 @@ export async function cmdBrainImportSession(argv: string[]): Promise<number> {
return fail(`import-session failed: ${(exc as Error).message ?? exc}`);
}
}
+
+function parsePositiveIntegerFlag(
+ value: string | boolean | string[] | undefined,
+ flag: string,
+): number | undefined {
+ if (value === undefined) return undefined;
+ if (typeof value !== "string" || !/^[0-9]+$/.test(value)) {
+ throw new CliError(`${flag} must be a positive integer`);
+ }
+ const parsed = Number.parseInt(value, 10);
+ if (parsed < 1) throw new CliError(`${flag} must be a positive integer`);
+ return parsed;
+}
diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.ts
index 7a4007c6..c1e465f0 100644
--- a/src/cli/brain/verbs/index.ts
+++ b/src/cli/brain/verbs/index.ts
@@ -41,6 +41,15 @@ export { cmdBrainImportClaudeMemory } from "./import-claude-memory.ts";
export { cmdBrainPageDedup } from "./page-dedup.ts";
export { cmdBrainTokenFootprint } from "./token-footprint.ts";
export { cmdBrainContextPack } from "./context-pack.ts";
+export { cmdBrainContextReceipts } from "./context-receipts.ts";
+export { cmdBrainContextPresets } from "./context-presets.ts";
+export { cmdBrainPreCompactExtract } from "./pre-compact-extract.ts";
+export { cmdBrainRecallTelemetry } from "./recall-telemetry.ts";
+export {
+ cmdBrainSessionDescribe,
+ cmdBrainSessionExpand,
+ cmdBrainSessionGrep,
+} from "./session-recall.ts";
export { cmdBrainLint } from "./lint.ts";
export { cmdBrainActions } from "./actions.ts";
export { cmdBrainSummary } from "./summary.ts";
diff --git a/src/cli/brain/verbs/pre-compact-extract.ts b/src/cli/brain/verbs/pre-compact-extract.ts
new file mode 100644
index 00000000..531b438b
--- /dev/null
+++ b/src/cli/brain/verbs/pre-compact-extract.ts
@@ -0,0 +1,75 @@
+import { extractPreCompactRecords } from "../../../core/brain/pre-compact-extract.ts";
+import { CliError, parse } from "../helpers.ts";
+import { inspect } from "node:util";
+
+export async function cmdBrainPreCompactExtract(
+ argv: string[],
+): Promise<number> {
+ const { flags } = parse(argv, {
+ json: { type: "boolean" },
+ vault: { type: "string" },
+ "session-id": { type: "string" },
+ "turn-start": { type: "string" },
+ "turn-end": { type: "string" },
+ text: { type: "string" },
+ host: { type: "string" },
+ "max-chars": { type: "string" },
+ });
+ const vault = stringRequired(flags["vault"], "--vault");
+ const sessionId = stringRequired(flags["session-id"], "--session-id");
+ const turnStart = stringRequired(flags["turn-start"], "--turn-start");
+ const turnEnd = stringRequired(flags["turn-end"], "--turn-end");
+ const text = stringRequired(flags["text"], "--text");
+ const maxChars = stringOptional(flags["max-chars"]);
+ const result = extractPreCompactRecords(vault, {
+ sessionId,
+ turnStart,
+ turnEnd,
+ text,
+ ...(stringOptional(flags["host"]) !== undefined
+ ? { host: stringOptional(flags["host"]) }
+ : {}),
+ ...(maxChars !== undefined
+ ? { maxChars: positiveInteger(maxChars, "--max-chars") }
+ : {}),
+ });
+ writeOutput(
+ { count: result.records.length, ...result },
+ flags["json"] === true,
+ );
+ return 0;
+}
+
+function stringRequired(
+ value: string | boolean | string[] | undefined,
+ label: string,
+): string {
+ const parsed = stringOptional(value);
+ if (parsed === undefined)
+ throw new CliError(`brain pre-compact-extract: ${label} is required`);
+ return parsed;
+}
+
+function stringOptional(
+ value: string | boolean | string[] | undefined,
+): string | undefined {
+ if (typeof value !== "string") return undefined;
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : undefined;
+}
+
+function positiveInteger(value: string, label: string): number {
+ if (!/^[0-9]+$/.test(value))
+ throw new CliError(`${label} must be a positive integer`);
+ const parsed = Number.parseInt(value, 10);
+ if (parsed < 1) throw new CliError(`${label} must be a positive integer`);
+ return parsed;
+}
+
+function writeOutput(value: unknown, json: boolean): void {
+ if (json) {
+ process.stdout.write(JSON.stringify(value) + "\n");
+ return;
+ }
+ process.stdout.write(inspect(value, { colors: false, depth: null }) + "\n");
+}
diff --git a/src/cli/brain/verbs/recall-telemetry.ts b/src/cli/brain/verbs/recall-telemetry.ts
new file mode 100644
index 00000000..f43cfc54
--- /dev/null
+++ b/src/cli/brain/verbs/recall-telemetry.ts
@@ -0,0 +1,146 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import {
+ isRecallTelemetryMode,
+ isRecallTelemetryStatus,
+ listRecallTelemetry,
+ summarizeRecallTelemetry,
+} from "../../../core/brain/recall-telemetry.ts";
+import { CliError, parse, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainRecallTelemetry(argv: string[]): Promise<number> {
+ const subcommand = argv[0];
+ const rest = argv.slice(1);
+ if (subcommand === "list") return listTelemetry(rest);
+ if (subcommand === "summary") return summarizeTelemetry(rest);
+ throw new CliError("brain recall-telemetry: expected list or summary");
+}
+
+function listTelemetry(argv: string[]): number {
+ const { flags } = parseTelemetryFlags(argv);
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const filter = telemetryFilter(flags, "brain recall-telemetry list");
+ const records = listRecallTelemetry(vault, filter);
+
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify({ total: records.length, records }, null, 2) + "\n");
+ return 0;
+ }
+
+ process.stdout.write(`${records.length} recall telemetry record(s):\n`);
+ for (const record of records) {
+ process.stdout.write(
+ ` ${record.createdAt} ${record.id} ${record.payload["mode"] ?? "unknown"} ${record.payload["status"] ?? "unknown"} results=${record.payload["result_count"] ?? "?"}\n`,
+ );
+ }
+ return 0;
+}
+
+function summarizeTelemetry(argv: string[]): number {
+ const { flags } = parseTelemetryFlags(argv);
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const summary = summarizeRecallTelemetry(
+ vault,
+ telemetryFilter(flags, "brain recall-telemetry summary"),
+ );
+
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify(summary, null, 2) + "\n");
+ return 0;
+ }
+
+ process.stdout.write(`records: ${summary.total}\n`);
+ process.stdout.write(`total results: ${summary.total_results}\n`);
+ process.stdout.write(`empty runs: ${summary.empty_runs}\n`);
+ process.stdout.write(`by mode: ${JSON.stringify(summary.by_mode)}\n`);
+ process.stdout.write(`by status: ${JSON.stringify(summary.by_status)}\n`);
+ process.stdout.write(`gaps: ${JSON.stringify(summary.gap_counts)}\n`);
+ return 0;
+}
+
+function parseTelemetryFlags(argv: string[]): {
+ readonly flags: Record<string, string | boolean | string[] | undefined>;
+} {
+ return parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ mode: { type: "string" },
+ status: { type: "string" },
+ host: { type: "string" },
+ since: { type: "string" },
+ until: { type: "string" },
+ limit: { type: "string" },
+ });
+}
+
+function telemetryFilter(
+ flags: Record<string, string | boolean | string[] | undefined>,
+ label: string,
+): {
+ readonly mode?: ReturnType<typeof modeFlag>;
+ readonly status?: ReturnType<typeof statusFlag>;
+ readonly host?: string;
+ readonly since?: string;
+ readonly until?: string;
+ readonly limit?: number;
+} {
+ return {
+ ...(modeFlag(flags["mode"], label) !== undefined
+ ? { mode: modeFlag(flags["mode"], label) }
+ : {}),
+ ...(statusFlag(flags["status"], label) !== undefined
+ ? { status: statusFlag(flags["status"], label) }
+ : {}),
+ ...(trimOrUndefined(flags["host"]) !== undefined
+ ? { host: trimOrUndefined(flags["host"]) }
+ : {}),
+ ...(trimOrUndefined(flags["since"]) !== undefined
+ ? { since: trimOrUndefined(flags["since"]) }
+ : {}),
+ ...(trimOrUndefined(flags["until"]) !== undefined
+ ? { until: trimOrUndefined(flags["until"]) }
+ : {}),
+ ...(parsePositiveInteger(trimOrUndefined(flags["limit"]), label, "--limit") !== undefined
+ ? {
+ limit: parsePositiveInteger(trimOrUndefined(flags["limit"]), label, "--limit"),
+ }
+ : {}),
+ };
+}
+
+function modeFlag(raw: string | boolean | string[] | undefined, label: string) {
+ const value = trimOrUndefined(raw);
+ if (value === undefined) return undefined;
+ if (!isRecallTelemetryMode(value)) {
+ throw new CliError(`${label}: --mode must be search, context_pack, or pre_compress`);
+ }
+ return value;
+}
+
+function statusFlag(raw: string | boolean | string[] | undefined, label: string) {
+ const value = trimOrUndefined(raw);
+ if (value === undefined) return undefined;
+ if (!isRecallTelemetryStatus(value)) {
+ throw new CliError(`${label}: --status must be ok, empty, error, or timeout`);
+ }
+ return value;
+}
+
+function parsePositiveInteger(
+ value: string | undefined,
+ label: string,
+ flag: string,
+): number | undefined {
+ if (value === undefined) return undefined;
+ if (!/^[0-9]+$/.test(value)) {
+ throw new CliError(`${label}: ${flag} must be a positive integer`);
+ }
+ const parsed = Number.parseInt(value, 10);
+ if (parsed < 1) throw new CliError(`${label}: ${flag} must be a positive integer`);
+ return parsed;
+}
+
+function trimOrUndefined(value: string | boolean | string[] | undefined): string | undefined {
+ if (typeof value !== "string") return undefined;
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : undefined;
+}
diff --git a/src/cli/brain/verbs/session-recall.ts b/src/cli/brain/verbs/session-recall.ts
new file mode 100644
index 00000000..f0bb0a4a
--- /dev/null
+++ b/src/cli/brain/verbs/session-recall.ts
@@ -0,0 +1,124 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import {
+ describeSessionRecall,
+ expandSessionRecall,
+ searchSessionRecall,
+} from "../../../core/brain/session-recall.ts";
+import { CliError, parse, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainSessionGrep(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ query: { type: "string" },
+ "session-id": { type: "string" },
+ limit: { type: "string" },
+ "snippet-chars": { type: "string" },
+ });
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const result = searchSessionRecall(vault, {
+ query: requiredString(flags["query"], "brain session-grep", "--query"),
+ ...(stringOptional(flags["session-id"]) !== undefined
+ ? { sessionId: stringOptional(flags["session-id"]) }
+ : {}),
+ ...(positiveIntegerOptional(flags["limit"], "brain session-grep", "--limit") !== undefined
+ ? {
+ limit: positiveIntegerOptional(flags["limit"], "brain session-grep", "--limit"),
+ }
+ : {}),
+ ...(positiveIntegerOptional(flags["snippet-chars"], "brain session-grep", "--snippet-chars") !==
+ undefined
+ ? {
+ snippetChars: positiveIntegerOptional(
+ flags["snippet-chars"],
+ "brain session-grep",
+ "--snippet-chars",
+ ),
+ }
+ : {}),
+ });
+ writeOutput(result, flags["json"] === true);
+ return 0;
+}
+
+export async function cmdBrainSessionDescribe(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ "session-id": { type: "string" },
+ });
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const result = describeSessionRecall(vault, {
+ sessionId: requiredString(flags["session-id"], "brain session-describe", "--session-id"),
+ });
+ writeOutput(result, flags["json"] === true);
+ return 0;
+}
+
+export async function cmdBrainSessionExpand(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ "raw-limit": { type: "string" },
+ cursor: { type: "string" },
+ });
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const id = positional[0];
+ if (id === undefined) throw new CliError("brain session-expand: record id is required");
+ const result = expandSessionRecall(vault, {
+ id,
+ ...(positiveIntegerOptional(flags["raw-limit"], "brain session-expand", "--raw-limit") !==
+ undefined
+ ? {
+ rawLimit: positiveIntegerOptional(
+ flags["raw-limit"],
+ "brain session-expand",
+ "--raw-limit",
+ ),
+ }
+ : {}),
+ ...(stringOptional(flags["cursor"]) !== undefined
+ ? { cursor: stringOptional(flags["cursor"]) }
+ : {}),
+ });
+ writeOutput(result, flags["json"] === true);
+ return 0;
+}
+
+function requiredString(
+ value: string | boolean | string[] | undefined,
+ command: string,
+ flag: string,
+): string {
+ const parsed = stringOptional(value);
+ if (parsed === undefined) throw new CliError(`${command}: ${flag} is required`);
+ return parsed;
+}
+
+function stringOptional(value: string | boolean | string[] | undefined): string | undefined {
+ if (typeof value !== "string") return undefined;
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : undefined;
+}
+
+function positiveIntegerOptional(
+ value: string | boolean | string[] | undefined,
+ command: string,
+ flag: string,
+): number | undefined {
+ const parsed = stringOptional(value);
+ if (parsed === undefined) return undefined;
+ if (!/^[0-9]+$/.test(parsed))
+ throw new CliError(`${command}: ${flag} must be a positive integer`);
+ const number = Number.parseInt(parsed, 10);
+ if (number < 1) throw new CliError(`${command}: ${flag} must be a positive integer`);
+ return number;
+}
+
+function writeOutput(value: unknown, json: boolean): void {
+ if (json) {
+ process.stdout.write(JSON.stringify(value, null, 2) + "\n");
+ return;
+ }
+ process.stdout.write(JSON.stringify(value, null, 2) + "\n");
+}
diff --git a/src/core/brain/context-pack.ts b/src/core/brain/context-pack.ts
index db5299f3..e34c89c4 100644
--- a/src/core/brain/context-pack.ts
+++ b/src/core/brain/context-pack.ts
@@ -27,6 +27,13 @@ import { PAGE_TIER, readTier, type PageTier } from "./page-meta/tier.ts";
import { estimateTokens } from "./text/tokenizer.ts";
import { normalizeForDedup } from "./text/normalize.ts";
import { applyCharBudget } from "./recall-budget.ts";
+import { emitContextReceipt, type ContextReceiptOptions } from "./context-receipts.ts";
+import { emitRecallTelemetry, type RecallTelemetryOptions } from "./recall-telemetry.ts";
+import {
+ applyContextTransforms,
+ type ContextTransformOptions,
+ type ContextTransformAnnotations,
+} from "./context-transforms.ts";
import {
buildContextLanes,
normalizeContextLane,
@@ -40,7 +47,7 @@ const TIER_ORDER: ReadonlyArray<PageTier> = [
PAGE_TIER.peripheral,
];
-export interface ContextPackItem {
+export interface ContextPackItem extends ContextTransformAnnotations {
readonly id: string;
readonly path: string;
readonly tier: PageTier;
@@ -65,6 +72,8 @@ export interface ContextPackReport {
readonly tokensUsed: number;
readonly items: ReadonlyArray<ContextPackItem>;
readonly skipped: ReadonlyArray<ContextPackSkipped>;
+ readonly receiptId?: string;
+ readonly telemetryId?: string;
readonly lanes?: ContextLanesReport;
}
@@ -87,6 +96,12 @@ export interface ContextPackOptions {
readonly maxTotalChars?: number;
/** Opt-in polarity-aware lanes. Omitted preserves the legacy flat output shape. */
readonly includeLanes?: boolean;
+ /** Opt-in audit receipt for the final emitted context. */
+ readonly receipt?: ContextReceiptOptions;
+ /** Opt-in telemetry for recall coverage and gap diagnostics. */
+ readonly telemetry?: RecallTelemetryOptions;
+ /** Opt-in post-selection context transforms. Defaults preserve legacy order and bodies. */
+ readonly transforms?: ContextTransformOptions;
}
interface Candidate {
@@ -182,14 +197,20 @@ function collectCandidates(vault: string): Candidate[] {
}
export function packContext(vault: string, opts: ContextPackOptions): ContextPackReport {
+ const startedAtMs = Date.now();
if (!Number.isFinite(opts.maxTokens) || opts.maxTokens <= 0) {
- return Object.freeze({
- maxTokens: 0,
- tokensUsed: 0,
- items: Object.freeze([]),
- skipped: Object.freeze([]),
- ...withOptionalLanes(opts, []),
- });
+ return finalizeContextPackReport(
+ vault,
+ opts,
+ {
+ maxTokens: 0,
+ tokensUsed: 0,
+ items: Object.freeze([]),
+ skipped: Object.freeze([]),
+ ...withOptionalLanes(opts, []),
+ },
+ startedAtMs,
+ );
}
const query = opts.query ? normalizeForDedup(opts.query) : null;
const candidates = collectCandidates(vault);
@@ -251,7 +272,10 @@ export function packContext(vault: string, opts: ContextPackOptions): ContextPac
{ maxTotalChars: opts.maxTotalChars },
);
if (capped.dropped.length > 0) {
- const keptItems = capped.kept.map((k) => k.item);
+ const keptItems = applyContextTransforms(
+ capped.kept.map((k) => k.item),
+ opts.transforms,
+ );
const droppedSet = new Set(capped.dropped);
let recomputed = 0;
for (const i of keptItems) recomputed += i.tokens;
@@ -264,21 +288,107 @@ export function packContext(vault: string, opts: ContextPackOptions): ContextPac
});
}
}
- return Object.freeze({
- maxTokens: opts.maxTokens,
- tokensUsed: recomputed,
- items: Object.freeze(keptItems),
- skipped: Object.freeze(skipped),
- ...withOptionalLanes(opts, keptItems),
- });
+ return finalizeContextPackReport(
+ vault,
+ opts,
+ {
+ maxTokens: opts.maxTokens,
+ tokensUsed: recomputed,
+ items: Object.freeze(keptItems),
+ skipped: Object.freeze(skipped),
+ ...withOptionalLanes(opts, keptItems),
+ },
+ startedAtMs,
+ );
}
}
- return Object.freeze({
- maxTokens: opts.maxTokens,
- tokensUsed: used,
- items: Object.freeze(items),
- skipped: Object.freeze(skipped),
- ...withOptionalLanes(opts, items),
- });
+ const finalItems = applyContextTransforms(items, opts.transforms);
+ const finalTokensUsed = finalItems.reduce((sum, item) => sum + item.tokens, 0);
+ return finalizeContextPackReport(
+ vault,
+ opts,
+ {
+ maxTokens: opts.maxTokens,
+ tokensUsed: finalTokensUsed,
+ items: Object.freeze(finalItems),
+ skipped: Object.freeze(skipped),
+ ...withOptionalLanes(opts, finalItems),
+ },
+ startedAtMs,
+ );
+}
+
+function finalizeContextPackReport(
+ vault: string,
+ opts: ContextPackOptions,
+ report: ContextPackReport,
+ startedAtMs: number,
+): ContextPackReport {
+ let enriched = report;
+ if (opts.receipt) {
+ const receipt = emitContextReceipt(vault, {
+ options: opts.receipt,
+ items: report.items.map((item) => ({
+ id: item.id,
+ path: item.path,
+ text: item.body,
+ tokens: item.tokens,
+ tier: item.tier,
+ trimmed: item.trimmed,
+ safetyFiltered: item.safety?.filtered,
+ })),
+ finalText: report.items.map((item) => item.body).join("\n\n"),
+ budget: contextPackBudgetMetadata(opts, report),
+ extra: {
+ skipped_count: report.skipped.length,
+ lanes: opts.includeLanes === true,
+ },
+ });
+ enriched = { ...enriched, receiptId: receipt.id };
+ }
+ if (opts.telemetry) {
+ const telemetry = emitRecallTelemetry(vault, {
+ createdAt: opts.telemetry.createdAt,
+ host: opts.telemetry.host,
+ sessionId: opts.telemetry.sessionId,
+ turnId: opts.telemetry.turnId,
+ mode: "context_pack",
+ status: report.items.length > 0 ? "ok" : "empty",
+ durationMs: Date.now() - startedAtMs,
+ resultCount: report.items.length,
+ topArtifacts: report.items.slice(0, 10).map((item) => ({ id: item.id, path: item.path })),
+ gaps: contextPackGaps(report),
+ metadata: {
+ ...(opts.telemetry.metadata ?? {}),
+ ...contextPackBudgetMetadata(opts, report),
+ skipped_count: report.skipped.length,
+ lanes: opts.includeLanes === true,
+ ...(enriched.receiptId ? { receipt_id: enriched.receiptId } : {}),
+ },
+ });
+ enriched = { ...enriched, telemetryId: telemetry.id };
+ }
+ return Object.freeze(enriched);
+}
+
+function contextPackBudgetMetadata(
+ opts: ContextPackOptions,
+ report: ContextPackReport,
+): Record<string, unknown> {
+ return {
+ max_tokens: report.maxTokens,
+ tokens_used: report.tokensUsed,
+ ...(opts.maxCharsPerMemory !== undefined
+ ? { max_chars_per_memory: opts.maxCharsPerMemory }
+ : {}),
+ ...(opts.maxTotalChars !== undefined ? { max_total_chars: opts.maxTotalChars } : {}),
+ };
+}
+
+function contextPackGaps(report: ContextPackReport): ReadonlyArray<string> {
+ const gaps = new Set<string>();
+ if (report.items.length === 0 && report.skipped.length === 0) gaps.add("no_matching_context");
+ for (const skipped of report.skipped) gaps.add(skipped.reason.replace(/-/g, "_"));
+ return [...gaps];
}
diff --git a/src/core/brain/context-presets.ts b/src/core/brain/context-presets.ts
new file mode 100644
index 00000000..a1349f64
--- /dev/null
+++ b/src/core/brain/context-presets.ts
@@ -0,0 +1,188 @@
+export type ContextPresetId = "tight-context" | "long-context";
+export type ContextPresetConfidence = "high" | "medium" | "low";
+
+export interface ContextBudgetPreset {
+ readonly id: ContextPresetId;
+ readonly label: string;
+ readonly model_hints: ReadonlyArray<string>;
+ readonly context_window_tokens: {
+ readonly min: number;
+ readonly max: number | null;
+ };
+ readonly context_pack: {
+ readonly max_tokens: number;
+ readonly max_chars_per_memory: number;
+ readonly max_total_chars: number;
+ };
+ readonly pre_compress: {
+ readonly top_k: number;
+ readonly max_chars_per_memory: number;
+ readonly max_total_chars: number;
+ };
+}
+
+export interface ContextPresetSuggestionInput {
+ readonly model?: string;
+ readonly contextWindowTokens?: number;
+}
+
+export interface ContextPresetSuggestion {
+ readonly preset_id: ContextPresetId;
+ readonly confidence: ContextPresetConfidence;
+ readonly reason: string;
+ readonly preset: ContextBudgetPreset;
+}
+
+export interface ContextPresetCurrentConfig {
+ readonly context_pack?: Partial<ContextBudgetPreset["context_pack"]>;
+ readonly pre_compress?: Partial<ContextBudgetPreset["pre_compress"]>;
+ readonly overrides?: ReadonlyArray<string>;
+}
+
+export interface ContextPresetChange {
+ readonly path: string;
+ readonly current: number | null;
+ readonly preset: number;
+}
+
+export interface ContextPresetDiff {
+ readonly preset_id: ContextPresetId;
+ readonly changes: ReadonlyArray<ContextPresetChange>;
+ readonly preserved_overrides: ReadonlyArray<ContextPresetChange>;
+ readonly unchanged: ReadonlyArray<string>;
+ readonly invalid_overrides: ReadonlyArray<string>;
+}
+
+const PRESETS: ReadonlyArray<ContextBudgetPreset> = Object.freeze([
+ Object.freeze({
+ id: "tight-context",
+ label: "Tight context",
+ model_hints: Object.freeze(["mini", "small", "flash", "haiku"]),
+ context_window_tokens: Object.freeze({ min: 0, max: 32_000 }),
+ context_pack: Object.freeze({
+ max_tokens: 4_000,
+ max_chars_per_memory: 1_200,
+ max_total_chars: 6_000,
+ }),
+ pre_compress: Object.freeze({
+ top_k: 5,
+ max_chars_per_memory: 800,
+ max_total_chars: 4_000,
+ }),
+ }),
+ Object.freeze({
+ id: "long-context",
+ label: "Long context",
+ model_hints: Object.freeze(["sonnet", "opus", "pro", "large"]),
+ context_window_tokens: Object.freeze({ min: 32_001, max: null }),
+ context_pack: Object.freeze({
+ max_tokens: 24_000,
+ max_chars_per_memory: 4_000,
+ max_total_chars: 30_000,
+ }),
+ pre_compress: Object.freeze({
+ top_k: 20,
+ max_chars_per_memory: 2_000,
+ max_total_chars: 16_000,
+ }),
+ }),
+]);
+
+const PRESET_FIELDS = Object.freeze([
+ "context_pack.max_tokens",
+ "context_pack.max_chars_per_memory",
+ "context_pack.max_total_chars",
+ "pre_compress.top_k",
+ "pre_compress.max_chars_per_memory",
+ "pre_compress.max_total_chars",
+]);
+
+export function listContextPresets(): ReadonlyArray<ContextBudgetPreset> {
+ return PRESETS;
+}
+
+export function getContextPreset(id: string): ContextBudgetPreset | null {
+ return PRESETS.find((preset) => preset.id === id) ?? null;
+}
+
+export function suggestContextPreset(input: ContextPresetSuggestionInput): ContextPresetSuggestion {
+ const model = input.model?.toLowerCase() ?? "";
+ const byModel = PRESETS.find((preset) => preset.model_hints.some((hint) => model.includes(hint)));
+ if (byModel) {
+ return {
+ preset_id: byModel.id,
+ confidence: "high",
+ reason: `model hint matched ${byModel.id}`,
+ preset: byModel,
+ };
+ }
+
+ const window = input.contextWindowTokens;
+ if (window !== undefined && Number.isFinite(window)) {
+ const byWindow = PRESETS.find(
+ (preset) =>
+ window >= preset.context_window_tokens.min &&
+ (preset.context_window_tokens.max === null || window <= preset.context_window_tokens.max),
+ );
+ if (byWindow) {
+ return {
+ preset_id: byWindow.id,
+ confidence: "high",
+ reason: `context window ${window} tokens matched ${byWindow.id}`,
+ preset: byWindow,
+ };
+ }
+ }
+
+ const fallback = PRESETS[0]!;
+ return {
+ preset_id: fallback.id,
+ confidence: "low",
+ reason: "no model or context-window hint matched; using conservative default",
+ preset: fallback,
+ };
+}
+
+export function diffContextPreset(
+ id: string,
+ current: ContextPresetCurrentConfig,
+): ContextPresetDiff {
+ const preset = getContextPreset(id);
+ if (preset === null) throw new Error(`unknown context preset: ${id}`);
+
+ const overrides = new Set(current.overrides ?? []);
+ const validFields = new Set(PRESET_FIELDS);
+ const changes: ContextPresetChange[] = [];
+ const preserved: ContextPresetChange[] = [];
+ const unchanged: string[] = [];
+
+ for (const path of PRESET_FIELDS) {
+ const presetValue = valueAt(preset, path)!;
+ const currentValue = valueAt(current, path);
+ if (currentValue === presetValue) {
+ unchanged.push(path);
+ continue;
+ }
+ const change = { path, current: currentValue, preset: presetValue };
+ if (overrides.has(path)) preserved.push(change);
+ else changes.push(change);
+ }
+
+ return Object.freeze({
+ preset_id: preset.id,
+ changes: Object.freeze(changes),
+ preserved_overrides: Object.freeze(preserved),
+ unchanged: Object.freeze(unchanged),
+ invalid_overrides: Object.freeze([...overrides].filter((path) => !validFields.has(path))),
+ });
+}
+
+function valueAt(
+ obj: ContextBudgetPreset | ContextPresetCurrentConfig,
+ path: string,
+): number | null {
+ const [section, key] = path.split(".") as ["context_pack" | "pre_compress", string];
+ const sectionValue = obj[section] as Record<string, number | undefined> | undefined;
+ const value = sectionValue?.[key];
+ return typeof value === "number" ? value : null;
+}
diff --git a/src/core/brain/context-receipts.ts b/src/core/brain/context-receipts.ts
new file mode 100644
index 00000000..8190798b
--- /dev/null
+++ b/src/core/brain/context-receipts.ts
@@ -0,0 +1,187 @@
+import { createHash } from "node:crypto";
+
+import {
+ appendContinuityRecord,
+ listContinuityRecords,
+} from "./continuity/store.ts";
+import type { ContinuityRecord } from "./continuity/types.ts";
+
+export type ContextReceiptTrigger = "context_pack" | "pre_compress";
+
+export interface ContextReceiptOptions {
+ readonly host: string;
+ readonly trigger: ContextReceiptTrigger;
+ readonly createdAt?: string;
+ readonly sessionId?: string;
+ readonly turnId?: string;
+}
+
+export interface ContextReceiptItemInput {
+ readonly id: string;
+ readonly path?: string;
+ readonly text?: string;
+ readonly tokens?: number;
+ readonly tier?: string;
+ readonly trimmed?: boolean;
+ readonly safetyFiltered?: boolean;
+}
+
+export interface EmitContextReceiptInput {
+ readonly options: ContextReceiptOptions;
+ readonly items: ReadonlyArray<ContextReceiptItemInput>;
+ readonly finalText: string;
+ readonly budget?: Readonly<Record<string, unknown>>;
+ readonly extra?: Readonly<Record<string, unknown>>;
+}
+
+export interface ContextReceiptFilter {
+ readonly trigger?: ContextReceiptTrigger;
+ readonly host?: string;
+ readonly sessionId?: string;
+ readonly limit?: number;
+}
+
+export interface ContextReceiptSummary {
+ readonly id: string;
+ readonly created_at: string;
+ readonly trigger: ContextReceiptTrigger | null;
+ readonly host: string | null;
+ readonly session_id?: string;
+ readonly turn_id?: string;
+ readonly item_count: number | null;
+ readonly source_count: number;
+ readonly private: boolean;
+ readonly redacted: boolean;
+}
+
+export function emitContextReceipt(
+ vault: string,
+ input: EmitContextReceiptInput,
+): ContinuityRecord {
+ const createdAt = input.options.createdAt ?? new Date().toISOString();
+ const itemPayloads = input.items.map((item, index) => ({
+ id: item.id,
+ original_rank: index + 1,
+ ...(item.path ? { path: item.path } : {}),
+ ...(item.tokens !== undefined ? { tokens: item.tokens } : {}),
+ ...(item.tier ? { tier: item.tier } : {}),
+ ...(item.trimmed !== undefined ? { trimmed: item.trimmed } : {}),
+ ...(item.safetyFiltered !== undefined
+ ? { safety_filtered: item.safetyFiltered }
+ : {}),
+ ...(item.text ? { text_hash: sha256(item.text) } : {}),
+ }));
+ const payload: Record<string, unknown> = {
+ host: input.options.host,
+ trigger: input.options.trigger,
+ ...(input.options.sessionId ? { session_id: input.options.sessionId } : {}),
+ ...(input.options.turnId ? { turn_id: input.options.turnId } : {}),
+ item_count: input.items.length,
+ final_text_hash: sha256(input.finalText),
+ final_text_chars: [...input.finalText].length,
+ items: itemPayloads,
+ ...(input.budget ? { budget: input.budget } : {}),
+ };
+ mergeReceiptExtra(payload, input.extra);
+ return appendContinuityRecord(vault, {
+ kind: "context_receipt",
+ createdAt,
+ sourceRefs: input.items.map((item) => ({
+ id: item.id,
+ ...(item.path ? { path: item.path } : {}),
+ ...(item.text ? { hash: sha256(item.text) } : {}),
+ })),
+ payload,
+ });
+}
+
+function mergeReceiptExtra(
+ payload: Record<string, unknown>,
+ extra: Readonly<Record<string, unknown>> | undefined,
+): void {
+ if (!extra) return;
+ for (const [key, value] of Object.entries(extra)) {
+ if (Object.hasOwn(payload, key)) {
+ throw new Error(
+ `context receipt extra key collides with payload field: ${key}`,
+ );
+ }
+ payload[key] = value;
+ }
+}
+
+export function listContextReceipts(
+ vault: string,
+ filter: ContextReceiptFilter = {},
+): ReadonlyArray<ContinuityRecord> {
+ let receipts = listContinuityRecords(vault, {
+ kind: "context_receipt",
+ }).filter((record) => matchesReceiptFilter(record, filter));
+ receipts = receipts.toReversed();
+ if (filter.limit !== undefined)
+ receipts = receipts.slice(0, Math.max(0, Math.floor(filter.limit)));
+ return Object.freeze(receipts);
+}
+
+export function getContextReceipt(
+ vault: string,
+ id: string,
+): ContinuityRecord | null {
+ return (
+ listContinuityRecords(vault, { kind: "context_receipt" }).find(
+ (record) => record.id === id,
+ ) ?? null
+ );
+}
+
+export function summarizeContextReceipt(
+ record: ContinuityRecord,
+): ContextReceiptSummary {
+ const payload = record.payload;
+ return {
+ id: record.id,
+ created_at: record.createdAt,
+ trigger: isContextReceiptTrigger(payload["trigger"])
+ ? payload["trigger"]
+ : null,
+ host: typeof payload["host"] === "string" ? payload["host"] : null,
+ ...(typeof payload["session_id"] === "string"
+ ? { session_id: payload["session_id"] }
+ : {}),
+ ...(typeof payload["turn_id"] === "string"
+ ? { turn_id: payload["turn_id"] }
+ : {}),
+ item_count:
+ typeof payload["item_count"] === "number" ? payload["item_count"] : null,
+ source_count: record.sourceRefs.length,
+ private: record.private,
+ redacted: record.redacted,
+ };
+}
+
+export function isContextReceiptTrigger(
+ value: unknown,
+): value is ContextReceiptTrigger {
+ return value === "context_pack" || value === "pre_compress";
+}
+
+function sha256(text: string): string {
+ return createHash("sha256").update(text, "utf8").digest("hex");
+}
+
+function matchesReceiptFilter(
+ record: ContinuityRecord,
+ filter: ContextReceiptFilter,
+): boolean {
+ const payload = record.payload;
+ if (filter.trigger !== undefined && payload["trigger"] !== filter.trigger)
+ return false;
+ if (filter.host !== undefined && payload["host"] !== filter.host)
+ return false;
+ if (
+ filter.sessionId !== undefined &&
+ payload["session_id"] !== filter.sessionId
+ )
+ return false;
+ return true;
+}
diff --git a/src/core/brain/context-transforms.ts b/src/core/brain/context-transforms.ts
new file mode 100644
index 00000000..d6e11880
--- /dev/null
+++ b/src/core/brain/context-transforms.ts
@@ -0,0 +1,74 @@
+import { estimateTokens } from "./text/tokenizer.ts";
+
+export interface ContextTransformOptions {
+ readonly cacheStableOrdering?: boolean;
+ readonly deduplicateRepeatedContext?: boolean;
+}
+
+export interface ContextTransformAnnotations {
+ readonly originalRank?: number;
+ readonly stableRank?: number;
+ readonly dedupedFrom?: string;
+ readonly referenceHint?: string;
+}
+
+export interface ContextTransformItem {
+ readonly id: string;
+ readonly path: string;
+ readonly body: string;
+ readonly tokens: number;
+}
+
+function compareStable(a: string, b: string): number {
+ return a < b ? -1 : a > b ? 1 : 0;
+}
+
+export function applyContextTransforms<T extends ContextTransformItem>(
+ items: ReadonlyArray<T>,
+ opts: ContextTransformOptions | undefined,
+): ReadonlyArray<T & ContextTransformAnnotations> {
+ if (!opts?.cacheStableOrdering && !opts?.deduplicateRepeatedContext)
+ return Object.freeze([...items]);
+
+ const ranked = items.map((item, index) => ({
+ item,
+ originalRank: index + 1,
+ }));
+ if (opts.cacheStableOrdering) {
+ ranked.sort(
+ (a, b) =>
+ compareStable(a.item.id, b.item.id) ||
+ compareStable(a.item.path, b.item.path),
+ );
+ }
+
+ const firstByBody = new Map<string, string>();
+ const transformed = ranked.map(({ item, originalRank }, index) => {
+ const base: T & ContextTransformAnnotations = {
+ ...item,
+ originalRank,
+ ...(opts.cacheStableOrdering ? { stableRank: index + 1 } : {}),
+ };
+ if (!opts.deduplicateRepeatedContext) return base;
+
+ const bodyKey = item.body.trim();
+ if (bodyKey.length === 0) return base;
+ const firstId = firstByBody.get(bodyKey);
+ if (firstId === undefined) {
+ firstByBody.set(bodyKey, item.id);
+ return base;
+ }
+
+ const referenceHint = `see ${firstId}`;
+ const body = `Repeated context omitted; ${referenceHint}.`;
+ return {
+ ...base,
+ body,
+ tokens: estimateTokens(body),
+ dedupedFrom: firstId,
+ referenceHint,
+ };
+ });
+
+ return Object.freeze(transformed);
+}
diff --git a/src/core/brain/continuity/redaction.ts b/src/core/brain/continuity/redaction.ts
new file mode 100644
index 00000000..c11cb374
--- /dev/null
+++ b/src/core/brain/continuity/redaction.ts
@@ -0,0 +1,40 @@
+import { redactRawOutput, stripPrivateRegions } from "../../redactor.ts";
+
+export interface SafePayloadResult {
+ readonly payload: Readonly<Record<string, unknown>>;
+ readonly private: boolean;
+ readonly redacted: boolean;
+}
+
+const PRIVATE_REGION_RE = /<private\b[^>]*>.*?<\/private>/is;
+const REDACTED_RE = /\*\*\*REDACTED\*\*\*/;
+
+export function safeContinuityPayload(
+ payload: Readonly<Record<string, unknown>>,
+): SafePayloadResult {
+ let sawPrivate = false;
+ let sawRedaction = false;
+ const safe = sanitizeValue(payload) as Readonly<Record<string, unknown>>;
+ return Object.freeze({
+ payload: safe,
+ private: sawPrivate,
+ redacted: sawRedaction,
+ });
+
+ function sanitizeValue(value: unknown): unknown {
+ if (typeof value === "string") {
+ if (PRIVATE_REGION_RE.test(value)) sawPrivate = true;
+ const stripped = stripPrivateRegions(value);
+ const redacted = redactRawOutput(stripped);
+ if (REDACTED_RE.test(redacted) && redacted !== stripped) sawRedaction = true;
+ return redacted;
+ }
+ if (Array.isArray(value)) return Object.freeze(value.map((item) => sanitizeValue(item)));
+ if (value && typeof value === "object") {
+ const out: Record<string, unknown> = {};
+ for (const [key, child] of Object.entries(value)) out[key] = sanitizeValue(child);
+ return Object.freeze(out);
+ }
+ return value;
+ }
+}
diff --git a/src/core/brain/continuity/store.ts b/src/core/brain/continuity/store.ts
new file mode 100644
index 00000000..0e22dc1a
--- /dev/null
+++ b/src/core/brain/continuity/store.ts
@@ -0,0 +1,212 @@
+import { createHash } from "node:crypto";
+import {
+ existsSync,
+ mkdirSync,
+ readFileSync,
+ readdirSync,
+ statSync,
+ writeFileSync,
+} from "node:fs";
+import { join } from "node:path";
+
+import { BRAIN_LOG_REL, ensureInsideVault } from "../paths.ts";
+import { acquireLockSync } from "../sync-lockfile.ts";
+import { safeContinuityPayload } from "./redaction.ts";
+import type {
+ AppendContinuityRecordInput,
+ ContinuityRecord,
+ ContinuityRecordFilter,
+ ContinuityRecordKind,
+ ContinuityRecordPage,
+ ContinuitySourceRef,
+} from "./types.ts";
+
+export type {
+ AppendContinuityRecordInput,
+ ContinuityPayload,
+ ContinuityRecord,
+ ContinuityRecordFilter,
+ ContinuityRecordKind,
+ ContinuityRecordPage,
+ ContinuitySourceRef,
+} from "./types.ts";
+
+export interface AppendSourceInvalidationInput {
+ readonly createdAt: string;
+ readonly source: ContinuitySourceRef;
+ readonly reason: string;
+}
+
+export interface ContinuityPaginationOptions extends ContinuityRecordFilter {
+ readonly limit: number;
+ readonly cursor?: string;
+}
+
+const CONTINUITY_REL = `${BRAIN_LOG_REL}/continuity`;
+const CURSOR_PREFIX = "offset:";
+
+export function continuityLogPath(vault: string, month: string): string {
+ if (!/^\d{4}-\d{2}$/.test(month))
+ throw new Error(`invalid continuity month: ${month}`);
+ return ensureInsideVault(
+ join(vault, CONTINUITY_REL, `${month}.jsonl`),
+ vault,
+ );
+}
+
+export function appendContinuityRecord(
+ vault: string,
+ input: AppendContinuityRecordInput,
+): ContinuityRecord {
+ return appendRecord(vault, buildRecord(input));
+}
+
+export function appendContinuitySourceInvalidation(
+ vault: string,
+ input: AppendSourceInvalidationInput,
+): ContinuityRecord {
+ return appendRecord(
+ vault,
+ buildRecord({
+ kind: "source_invalidation",
+ createdAt: input.createdAt,
+ sourceRefs: [input.source],
+ payload: { reason: input.reason },
+ }),
+ );
+}
+
+export function listContinuityRecords(
+ vault: string,
+ filter: ContinuityRecordFilter = {},
+): ReadonlyArray<ContinuityRecord> {
+ return Object.freeze(
+ readAllRecords(vault).filter((record) => matches(record, filter)),
+ );
+}
+
+export function paginateContinuityRecords(
+ vault: string,
+ opts: ContinuityPaginationOptions,
+): ContinuityRecordPage {
+ const limit = Math.max(1, Math.floor(opts.limit));
+ const start = parseCursor(opts.cursor);
+ const filtered = listContinuityRecords(vault, opts);
+ const records = filtered.slice(start, start + limit);
+ const next =
+ start + limit < filtered.length ? `${CURSOR_PREFIX}${start + limit}` : null;
+ return Object.freeze({ records: Object.freeze(records), nextCursor: next });
+}
+
+function buildRecord(
+ input:
+ | AppendContinuityRecordInput
+ | {
+ readonly kind: "source_invalidation";
+ readonly createdAt: string;
+ readonly sourceRefs: ReadonlyArray<ContinuitySourceRef>;
+ readonly payload: Readonly<Record<string, unknown>>;
+ },
+): ContinuityRecord {
+ const payloadResult = safeContinuityPayload(input.payload ?? {});
+ const sourceRefs = Object.freeze([...(input.sourceRefs ?? [])]);
+ const id = recordId(
+ input.kind,
+ input.createdAt,
+ sourceRefs,
+ payloadResult.payload,
+ );
+ return Object.freeze({
+ id,
+ kind: input.kind,
+ createdAt: input.createdAt,
+ sourceRefs,
+ payload: payloadResult.payload,
+ private: payloadResult.private,
+ redacted: payloadResult.redacted,
+ });
+}
+
+function appendRecord(
+ vault: string,
+ record: ContinuityRecord,
+): ContinuityRecord {
+ const path = continuityLogPath(vault, record.createdAt.slice(0, 7));
+ mkdirSync(join(vault, CONTINUITY_REL), { recursive: true });
+ const handle = acquireLockSync(path);
+ try {
+ writeFileSync(path, `${JSON.stringify(record)}\n`, {
+ encoding: "utf8",
+ flag: "a",
+ });
+ } finally {
+ handle.release();
+ }
+ return record;
+}
+
+function readAllRecords(vault: string): ContinuityRecord[] {
+ const dir = ensureInsideVault(join(vault, CONTINUITY_REL), vault);
+ if (!existsSync(dir)) return [];
+ const records: ContinuityRecord[] = [];
+ for (const name of readdirSync(dir).toSorted()) {
+ if (!name.endsWith(".jsonl")) continue;
+ const path = ensureInsideVault(join(dir, name), vault);
+ let st;
+ try {
+ st = statSync(path);
+ } catch {
+ continue;
+ }
+ if (!st.isFile()) continue;
+ for (const line of readFileSync(path, "utf8").split("\n")) {
+ if (!line.trim()) continue;
+ try {
+ records.push(JSON.parse(line) as ContinuityRecord);
+ } catch {
+ continue;
+ }
+ }
+ }
+ records.sort(
+ (a, b) =>
+ a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id),
+ );
+ return records;
+}
+
+function matches(
+ record: ContinuityRecord,
+ filter: ContinuityRecordFilter,
+): boolean {
+ if (filter.kind && record.kind !== filter.kind) return false;
+ if (
+ filter.sourceId &&
+ !record.sourceRefs.some((source) => source.id === filter.sourceId)
+ ) {
+ return false;
+ }
+ if (filter.since && record.createdAt < filter.since) return false;
+ if (filter.until && record.createdAt > filter.until) return false;
+ return true;
+}
+
+function parseCursor(cursor: string | undefined): number {
+ if (cursor === undefined) return 0;
+ if (!cursor.startsWith(CURSOR_PREFIX)) return 0;
+ const value = Number.parseInt(cursor.slice(CURSOR_PREFIX.length), 10);
+ return Number.isFinite(value) && value >= 0 ? value : 0;
+}
+
+function recordId(
+ kind: ContinuityRecordKind,
+ createdAt: string,
+ sourceRefs: ReadonlyArray<ContinuitySourceRef>,
+ payload: Readonly<Record<string, unknown>>,
+): string {
+ const hash = createHash("sha256")
+ .update(JSON.stringify({ kind, createdAt, sourceRefs, payload }), "utf8")
+ .digest("hex")
+ .slice(0, 16);
+ return `ctn_${createdAt.replace(/[^0-9]/g, "").slice(0, 14)}_${hash}`;
+}
diff --git a/src/core/brain/continuity/types.ts b/src/core/brain/continuity/types.ts
new file mode 100644
index 00000000..0371f18e
--- /dev/null
+++ b/src/core/brain/continuity/types.ts
@@ -0,0 +1,45 @@
+export type ContinuityRecordKind =
+ | "context_receipt"
+ | "recall_telemetry"
+ | "pre_compact_extract"
+ | "session_turn"
+ | "session_summary_node"
+ | "source_invalidation";
+
+export type ContinuityPayload = Readonly<Record<string, unknown>>;
+
+export interface ContinuitySourceRef {
+ readonly id: string;
+ readonly path?: string;
+ readonly hash?: string;
+ readonly kind?: string;
+}
+
+export interface ContinuityRecord {
+ readonly id: string;
+ readonly kind: ContinuityRecordKind;
+ readonly createdAt: string;
+ readonly sourceRefs: ReadonlyArray<ContinuitySourceRef>;
+ readonly payload: ContinuityPayload;
+ readonly private: boolean;
+ readonly redacted: boolean;
+}
+
+export interface AppendContinuityRecordInput {
+ readonly kind: Exclude<ContinuityRecordKind, "source_invalidation">;
+ readonly createdAt: string;
+ readonly sourceRefs?: ReadonlyArray<ContinuitySourceRef>;
+ readonly payload?: ContinuityPayload;
+}
+
+export interface ContinuityRecordFilter {
+ readonly kind?: ContinuityRecordKind;
+ readonly sourceId?: string;
+ readonly since?: string;
+ readonly until?: string;
+}
+
+export interface ContinuityRecordPage {
+ readonly records: ReadonlyArray<ContinuityRecord>;
+ readonly nextCursor: string | null;
+}
diff --git a/src/core/brain/pre-compact-extract.ts b/src/core/brain/pre-compact-extract.ts
new file mode 100644
index 00000000..dce1dc84
--- /dev/null
+++ b/src/core/brain/pre-compact-extract.ts
@@ -0,0 +1,148 @@
+import { createHash } from "node:crypto";
+
+import { appendContinuityRecord, listContinuityRecords } from "./continuity/store.ts";
+import type { ContinuityRecord, ContinuitySourceRef } from "./continuity/types.ts";
+
+export type PreCompactExtractType =
+ | "decision"
+ | "commitment"
+ | "outcome"
+ | "rule"
+ | "open_question";
+
+export interface PreCompactExtractInput {
+ readonly sessionId: string;
+ readonly turnStart: string;
+ readonly turnEnd: string;
+ readonly text: string;
+ readonly host?: string;
+ readonly createdAt?: string;
+ readonly maxChars?: number;
+}
+
+export interface PreCompactExtractResult {
+ readonly records: ReadonlyArray<ContinuityRecord>;
+ readonly errors: ReadonlyArray<string>;
+ readonly skipped: number;
+}
+
+interface ExtractedLine {
+ readonly type: PreCompactExtractType;
+ readonly text: string;
+ readonly line: number;
+}
+
+const LABELS: ReadonlyArray<readonly [RegExp, PreCompactExtractType]> = Object.freeze([
+ [/^(?:[-*]\s*)?decision\s*:\s*(.+)$/i, "decision"],
+ [/^(?:[-*]\s*)?commitment\s*:\s*(.+)$/i, "commitment"],
+ [/^(?:[-*]\s*)?outcome\s*:\s*(.+)$/i, "outcome"],
+ [/^(?:[-*]\s*)?rule\s*:\s*(.+)$/i, "rule"],
+ [/^(?:[-*]\s*)?open\s+question\s*:\s*(.+)$/i, "open_question"],
+]);
+
+const DEFAULT_MAX_CHARS = 40_000;
+
+export function extractPreCompactRecords(
+ vault: string,
+ input: PreCompactExtractInput,
+): PreCompactExtractResult {
+ const errors: string[] = [];
+ const records: ContinuityRecord[] = [];
+ const sourceRefs = extractSourceRefs(input);
+ const boundedText = input.text.slice(0, input.maxChars ?? DEFAULT_MAX_CHARS);
+ const extracted = extractLines(sanitizePreCompactText(boundedText));
+ const createdAt = input.createdAt ?? new Date().toISOString();
+ const host = input.host?.trim();
+
+ for (const item of extracted) {
+ try {
+ const contentHash = hash(`${item.type}\n${item.text}`);
+ const dedupeKey = [
+ input.sessionId,
+ input.turnStart,
+ input.turnEnd,
+ item.type,
+ contentHash,
+ ].join(":");
+ const existing = findExistingExtract(vault, dedupeKey);
+ if (existing !== null) {
+ records.push(existing);
+ continue;
+ }
+ records.push(
+ appendContinuityRecord(vault, {
+ kind: "pre_compact_extract",
+ createdAt,
+ sourceRefs,
+ payload: {
+ extract_type: item.type,
+ text: item.text,
+ line: item.line,
+ session_id: input.sessionId,
+ turn_start: input.turnStart,
+ turn_end: input.turnEnd,
+ turn_range: `${input.turnStart}..${input.turnEnd}`,
+ ...(host !== undefined && host.length > 0 ? { host } : {}),
+ content_hash: contentHash,
+ dedupe_key: dedupeKey,
+ truncated_input: boundedText.length < input.text.length,
+ },
+ }),
+ );
+ } catch (error) {
+ errors.push(error instanceof Error ? error.message : String(error));
+ }
+ }
+
+ return Object.freeze({
+ records: Object.freeze(records),
+ errors: Object.freeze(errors),
+ skipped: extracted.length - records.length,
+ });
+}
+
+export function sanitizePreCompactText(text: string): string {
+ return text
+ .replace(/data:[^\s;,]+;base64,[A-Za-z0-9+/=]+/g, "[base64]")
+ .replace(/\b[A-Za-z0-9+/]{32,}={0,2}\b/g, "[base64]");
+}
+
+function extractLines(text: string): ExtractedLine[] {
+ const items: ExtractedLine[] = [];
+ const lines = text.split(/\r?\n/);
+ for (let index = 0; index < lines.length; index += 1) {
+ const line = lines[index]!.trim();
+ if (line.length === 0) continue;
+ for (const [pattern, type] of LABELS) {
+ const match = pattern.exec(line);
+ const value = match?.[1]?.trim();
+ if (value !== undefined && value.length > 0) {
+ items.push({ type, text: value, line: index + 1 });
+ break;
+ }
+ }
+ }
+ return items;
+}
+
+function extractSourceRefs(input: PreCompactExtractInput): ReadonlyArray<ContinuitySourceRef> {
+ return Object.freeze([
+ Object.freeze({ type: "session", id: input.sessionId }),
+ Object.freeze({
+ type: "turn_range",
+ id: `${input.turnStart}..${input.turnEnd}`,
+ }),
+ ]);
+}
+
+function findExistingExtract(vault: string, dedupeKey: string): ContinuityRecord | null {
+ return (
+ listContinuityRecords(vault, { kind: "pre_compact_extract" }).find(
+ (record) => record.payload["dedupe_key"] === dedupeKey,
+ ) ?? null
+ );
+}
+
+function hash(value: string): string {
+ return createHash("sha256").update(value).digest("hex").slice(0, 16);
+}
diff --git a/src/core/brain/pre-compress-pack.ts b/src/core/brain/pre-compress-pack.ts
index e8158f79..75aac699 100644
--- a/src/core/brain/pre-compress-pack.ts
+++ b/src/core/brain/pre-compress-pack.ts
@@ -21,6 +21,8 @@ import { join } from "node:path";
import { brainActivePath, brainDirs } from "./paths.ts";
import { parsePreference } from "./preference.ts";
import { applyCharBudget } from "./recall-budget.ts";
+import { emitContextReceipt, type ContextReceiptOptions } from "./context-receipts.ts";
+import { emitRecallTelemetry, type RecallTelemetryOptions } from "./recall-telemetry.ts";
import {
contextSafetyReport,
guardBrainContextSnippet,
@@ -47,6 +49,8 @@ export interface PreCompressPack {
readonly items: ReadonlyArray<PreCompressItem>;
readonly activeHeadIncluded: boolean;
readonly activeHeadSafety?: ContextSafetyReport;
+ readonly receiptId?: string;
+ readonly telemetryId?: string;
readonly totalChars: number;
}
@@ -57,6 +61,10 @@ export interface PreCompressOptions {
readonly maxCharsPerMemory?: number;
/** Total character cap across the bundle; <= 0 / undefined disables. */
readonly maxTotalChars?: number;
+ /** Opt-in audit receipt for the final emitted addendum. */
+ readonly receipt?: ContextReceiptOptions;
+ /** Opt-in telemetry for recall coverage and gap diagnostics. */
+ readonly telemetry?: RecallTelemetryOptions;
}
interface ConfirmedPref {
@@ -106,6 +114,7 @@ function readActiveHead(vault: string): string | null {
* `topK` plus the active head are bounded by the shared char budget.
*/
export function buildPreCompressPack(vault: string, opts: PreCompressOptions): PreCompressPack {
+ const startedAtMs = Date.now();
const ranked = collectConfirmed(vault).toSorted((a, b) => {
if (b.confidence !== a.confidence) return b.confidence - a.confidence;
if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? 1 : -1;
@@ -160,11 +169,75 @@ export function buildPreCompressPack(vault: string, opts: PreCompressOptions): P
sections.push(["Preferences:", ...items.map((i) => `- ${i.principle}`)].join("\n"));
}
+ const text = sections.join("\n\n");
+ const receipt = opts.receipt
+ ? emitContextReceipt(vault, {
+ options: opts.receipt,
+ items: [
+ ...(activeText !== null
+ ? [
+ {
+ id: ACTIVE_ID,
+ path: brainActivePath(vault),
+ text: activeText,
+ },
+ ]
+ : []),
+ ...items.map((item) => ({
+ id: item.id,
+ text: item.principle,
+ trimmed: item.trimmed,
+ safetyFiltered: item.safety?.filtered,
+ })),
+ ],
+ finalText: text,
+ budget: {
+ top_k: opts.topK,
+ ...(opts.maxCharsPerMemory !== undefined
+ ? { max_chars_per_memory: opts.maxCharsPerMemory }
+ : {}),
+ ...(opts.maxTotalChars !== undefined ? { max_total_chars: opts.maxTotalChars } : {}),
+ },
+ extra: { active_head_included: activeText !== null },
+ })
+ : null;
+
+ const telemetry = opts.telemetry
+ ? emitRecallTelemetry(vault, {
+ createdAt: opts.telemetry.createdAt,
+ host: opts.telemetry.host,
+ sessionId: opts.telemetry.sessionId,
+ turnId: opts.telemetry.turnId,
+ mode: "pre_compress",
+ status: activeText !== null || items.length > 0 ? "ok" : "empty",
+ durationMs: Date.now() - startedAtMs,
+ resultCount: items.length + (activeText !== null ? 1 : 0),
+ topArtifacts: [
+ ...(activeText !== null ? [{ id: ACTIVE_ID, path: brainActivePath(vault) }] : []),
+ ...items.slice(0, 10).map((item) => ({ id: item.id })),
+ ],
+ gaps: activeText === null && items.length === 0 ? ["no_matching_context"] : [],
+ metadata: {
+ ...opts.telemetry.metadata,
+ top_k: opts.topK,
+ total_chars: budgeted.totalChars,
+ active_head_included: activeText !== null,
+ ...(opts.maxCharsPerMemory !== undefined
+ ? { max_chars_per_memory: opts.maxCharsPerMemory }
+ : {}),
+ ...(opts.maxTotalChars !== undefined ? { max_total_chars: opts.maxTotalChars } : {}),
+ ...(receipt ? { receipt_id: receipt.id } : {}),
+ },
+ })
+ : null;
+
return Object.freeze({
- text: sections.join("\n\n"),
+ text,
items: Object.freeze(items),
activeHeadIncluded: activeText !== null,
...(safetyById.get(ACTIVE_ID) ? { activeHeadSafety: safetyById.get(ACTIVE_ID) } : {}),
+ ...(receipt ? { receiptId: receipt.id } : {}),
+ ...(telemetry ? { telemetryId: telemetry.id } : {}),
totalChars: budgeted.totalChars,
});
}
diff --git a/src/core/brain/recall-telemetry.ts b/src/core/brain/recall-telemetry.ts
new file mode 100644
index 00000000..e0a66bd5
--- /dev/null
+++ b/src/core/brain/recall-telemetry.ts
@@ -0,0 +1,151 @@
+import { appendContinuityRecord, listContinuityRecords } from "./continuity/store.ts";
+import type { ContinuityRecord } from "./continuity/types.ts";
+
+export type RecallTelemetryMode = "search" | "context_pack" | "pre_compress";
+export type RecallTelemetryStatus = "ok" | "empty" | "error" | "timeout";
+
+export interface RecallTelemetryArtifactInput {
+ readonly id: string;
+ readonly path?: string;
+ readonly score?: number;
+}
+
+export interface RecallTelemetryInput {
+ readonly createdAt?: string;
+ readonly host: string;
+ readonly sessionId?: string;
+ readonly turnId?: string;
+ readonly mode: RecallTelemetryMode;
+ readonly status: RecallTelemetryStatus;
+ readonly durationMs: number;
+ readonly resultCount: number;
+ readonly topArtifacts?: ReadonlyArray<RecallTelemetryArtifactInput>;
+ readonly gaps?: ReadonlyArray<string>;
+ readonly metadata?: Readonly<Record<string, unknown>>;
+}
+
+export interface RecallTelemetryOptions {
+ readonly host: string;
+ readonly createdAt?: string;
+ readonly sessionId?: string;
+ readonly turnId?: string;
+ readonly metadata?: Readonly<Record<string, unknown>>;
+}
+
+export interface RecallTelemetryFilter {
+ readonly mode?: RecallTelemetryMode;
+ readonly status?: RecallTelemetryStatus;
+ readonly host?: string;
+ readonly since?: string;
+ readonly until?: string;
+ readonly limit?: number;
+}
+
+export interface RecallTelemetrySummary {
+ readonly total: number;
+ readonly by_mode: Partial<Record<RecallTelemetryMode, number>>;
+ readonly by_status: Partial<Record<RecallTelemetryStatus, number>>;
+ readonly total_results: number;
+ readonly empty_runs: number;
+ readonly gap_counts: Record<string, number>;
+}
+
+export function emitRecallTelemetry(vault: string, input: RecallTelemetryInput): ContinuityRecord {
+ const createdAt = input.createdAt ?? new Date().toISOString();
+ const topArtifacts = [...(input.topArtifacts ?? [])];
+ const gaps = [...new Set((input.gaps ?? []).map((gap) => gap.trim()).filter(Boolean))];
+ return appendContinuityRecord(vault, {
+ kind: "recall_telemetry",
+ createdAt,
+ sourceRefs: topArtifacts.map((artifact) => ({
+ id: artifact.id,
+ ...(artifact.path ? { path: artifact.path } : {}),
+ })),
+ payload: {
+ host: input.host,
+ ...(input.sessionId ? { session_id: input.sessionId } : {}),
+ ...(input.turnId ? { turn_id: input.turnId } : {}),
+ mode: input.mode,
+ status: input.status,
+ duration_ms: Math.max(0, Math.floor(input.durationMs)),
+ result_count: Math.max(0, Math.floor(input.resultCount)),
+ top_artifacts: topArtifacts.map((artifact) => ({
+ id: artifact.id,
+ ...(artifact.path ? { path: artifact.path } : {}),
+ ...(artifact.score !== undefined ? { score: artifact.score } : {}),
+ })),
+ gaps,
+ ...(input.metadata ? { metadata: input.metadata } : {}),
+ },
+ });
+}
+
+export function listRecallTelemetry(
+ vault: string,
+ filter: RecallTelemetryFilter = {},
+): ReadonlyArray<ContinuityRecord> {
+ let records = listContinuityRecords(vault, {
+ kind: "recall_telemetry",
+ ...(filter.since !== undefined ? { since: filter.since } : {}),
+ ...(filter.until !== undefined ? { until: filter.until } : {}),
+ }).filter((record) => matchesTelemetryFilter(record, filter));
+ records = records.toReversed();
+ if (filter.limit !== undefined) records = records.slice(0, Math.max(0, Math.floor(filter.limit)));
+ return Object.freeze(records);
+}
+
+export function summarizeRecallTelemetry(
+ vault: string,
+ filter: RecallTelemetryFilter = {},
+): RecallTelemetrySummary {
+ const records = listRecallTelemetry(vault, filter);
+ const byMode: Partial<Record<RecallTelemetryMode, number>> = {};
+ const byStatus: Partial<Record<RecallTelemetryStatus, number>> = {};
+ const gapCounts: Record<string, number> = {};
+ let totalResults = 0;
+ let emptyRuns = 0;
+
+ for (const record of records) {
+ const mode = record.payload["mode"];
+ if (isRecallTelemetryMode(mode)) byMode[mode] = (byMode[mode] ?? 0) + 1;
+ const status = record.payload["status"];
+ if (isRecallTelemetryStatus(status)) {
+ byStatus[status] = (byStatus[status] ?? 0) + 1;
+ if (status === "empty") emptyRuns += 1;
+ }
+ const resultCount = record.payload["result_count"];
+ if (typeof resultCount === "number") totalResults += resultCount;
+ const gaps = record.payload["gaps"];
+ if (Array.isArray(gaps)) {
+ for (const gap of gaps) {
+ if (typeof gap !== "string" || gap.length === 0) continue;
+ gapCounts[gap] = (gapCounts[gap] ?? 0) + 1;
+ }
+ }
+ }
+
+ return Object.freeze({
+ total: records.length,
+ by_mode: Object.freeze(byMode),
+ by_status: Object.freeze(byStatus),
+ total_results: totalResults,
+ empty_runs: emptyRuns,
+ gap_counts: Object.freeze(gapCounts),
+ });
+}
+
+export function isRecallTelemetryMode(value: unknown): value is RecallTelemetryMode {
+ return value === "search" || value === "context_pack" || value === "pre_compress";
+}
+
+export function isRecallTelemetryStatus(value: unknown): value is RecallTelemetryStatus {
+ return value === "ok" || value === "empty" || value === "error" || value === "timeout";
+}
+
+function matchesTelemetryFilter(record: ContinuityRecord, filter: RecallTelemetryFilter): boolean {
+ const payload = record.payload;
+ if (filter.mode !== undefined && payload["mode"] !== filter.mode) return false;
+ if (filter.status !== undefined && payload["status"] !== filter.status) return false;
+ if (filter.host !== undefined && payload["host"] !== filter.host) return false;
+ return true;
+}
diff --git a/src/core/brain/session-recall.ts b/src/core/brain/session-recall.ts
new file mode 100644
index 00000000..99ac1fb4
--- /dev/null
+++ b/src/core/brain/session-recall.ts
@@ -0,0 +1,395 @@
+import { createHash } from "node:crypto";
+
+import { appendContinuityRecord, listContinuityRecords } from "./continuity/store.ts";
+import type { ContinuityRecord, ContinuitySourceRef } from "./continuity/types.ts";
+import type { SessionTurn } from "./sessions/types.ts";
+
+export interface ImportSessionRecallInput {
+ readonly sessionId: string;
+ readonly turns: ReadonlyArray<SessionTurn>;
+ readonly createdAt?: string;
+ readonly summaryGroupSize?: number;
+}
+
+export interface ImportSessionRecallResult {
+ readonly rawTurns: ReadonlyArray<ContinuityRecord>;
+ readonly summaryNodes: ReadonlyArray<ContinuityRecord>;
+}
+
+export interface SessionRecallSearchInput {
+ readonly query: string;
+ readonly sessionId?: string;
+ readonly limit?: number;
+ readonly snippetChars?: number;
+}
+
+export interface SessionRecallHit {
+ readonly id: string;
+ readonly kind: "session_turn" | "session_summary_node";
+ readonly score: number;
+ readonly snippet: string;
+ readonly turn_id?: string;
+ readonly role?: string;
+ readonly depth?: number;
+ readonly source_record_ids?: ReadonlyArray<string>;
+}
+
+export interface SessionRecallSearchResult {
+ readonly hits: ReadonlyArray<SessionRecallHit>;
+}
+
+export interface DescribeSessionRecallInput {
+ readonly sessionId: string;
+}
+
+export interface DescribeSessionRecallResult {
+ readonly session_id: string;
+ readonly raw_turns: number;
+ readonly summary_nodes: number;
+ readonly depths: Readonly<Record<string, number>>;
+}
+
+export interface ExpandSessionRecallInput {
+ readonly id: string;
+ readonly rawLimit?: number;
+ readonly cursor?: string;
+}
+
+export interface ExpandedRawTurn {
+ readonly id: string;
+ readonly turn_id: string;
+ readonly role: string;
+ readonly timestamp: string;
+ readonly text: string;
+}
+
+export interface ExpandSessionRecallResult {
+ readonly record: ContinuityRecord;
+ readonly immediate_sources: ReadonlyArray<ContinuityRecord>;
+ readonly raw_content: ReadonlyArray<ExpandedRawTurn>;
+ readonly next_cursor: string | null;
+}
+
+const DEFAULT_GROUP_SIZE = 8;
+const DEFAULT_LIMIT = 10;
+const DEFAULT_SNIPPET_CHARS = 160;
+
+export function importSessionRecall(
+ vault: string,
+ input: ImportSessionRecallInput,
+): ImportSessionRecallResult {
+ const createdAt = input.createdAt ?? new Date().toISOString();
+ const rawTurns = input.turns.map((turn) =>
+ importRawTurn(vault, input.sessionId, turn, createdAt),
+ );
+ const summaryNodes = [
+ ...importSummaryDepth(
+ vault,
+ input.sessionId,
+ rawTurns,
+ 1,
+ input.summaryGroupSize ?? DEFAULT_GROUP_SIZE,
+ createdAt,
+ ),
+ ];
+ summaryNodes.push(
+ ...importSummaryDepth(
+ vault,
+ input.sessionId,
+ summaryNodes,
+ 2,
+ input.summaryGroupSize ?? DEFAULT_GROUP_SIZE,
+ createdAt,
+ ),
+ );
+ return Object.freeze({
+ rawTurns: Object.freeze(rawTurns),
+ summaryNodes: Object.freeze(summaryNodes),
+ });
+}
+
+export function searchSessionRecall(
+ vault: string,
+ input: SessionRecallSearchInput,
+): SessionRecallSearchResult {
+ const needle = input.query.trim().toLowerCase();
+ if (needle.length === 0) return Object.freeze({ hits: Object.freeze([]) });
+ const limit = Math.max(1, input.limit ?? DEFAULT_LIMIT);
+ const snippetChars = Math.max(1, input.snippetChars ?? DEFAULT_SNIPPET_CHARS);
+ const hits = sessionRecallRecords(vault, input.sessionId)
+ .map((record) => hitFor(record, needle, snippetChars))
+ .filter((hit): hit is SessionRecallHit => hit !== null)
+ .sort((left, right) => right.score - left.score || left.id.localeCompare(right.id))
+ .slice(0, limit);
+ return Object.freeze({ hits: Object.freeze(hits) });
+}
+
+export function describeSessionRecall(
+ vault: string,
+ input: DescribeSessionRecallInput,
+): DescribeSessionRecallResult {
+ const records = sessionRecallRecords(vault, input.sessionId);
+ const rawTurns = records.filter((record) => record.kind === "session_turn");
+ const summaries = records.filter((record) => record.kind === "session_summary_node");
+ const depths: Record<string, number> = {};
+ for (const summary of summaries) {
+ const depth = String(summary.payload["depth"] ?? "unknown");
+ depths[depth] = (depths[depth] ?? 0) + 1;
+ }
+ return Object.freeze({
+ session_id: input.sessionId,
+ raw_turns: rawTurns.length,
+ summary_nodes: summaries.length,
+ depths: Object.freeze(depths),
+ });
+}
+
+export function expandSessionRecall(
+ vault: string,
+ input: ExpandSessionRecallInput,
+): ExpandSessionRecallResult {
+ const records = sessionRecallRecords(vault);
+ const byId = new Map(records.map((record) => [record.id, record]));
+ const record = byId.get(input.id);
+ if (record === undefined) throw new Error(`session recall record not found: ${input.id}`);
+ const immediate = sourceRecordIds(record)
+ .map((id) => byId.get(id))
+ .filter((source): source is ContinuityRecord => source !== undefined);
+ const rawRecords = collectRawRecords(record, byId);
+ const offset = Math.max(0, Number.parseInt(input.cursor ?? "0", 10) || 0);
+ const limit = Math.max(1, input.rawLimit ?? DEFAULT_LIMIT);
+ const page = rawRecords.slice(offset, offset + limit).map(expandedRawTurn);
+ const nextOffset = offset + limit;
+ return Object.freeze({
+ record,
+ immediate_sources: Object.freeze(immediate),
+ raw_content: Object.freeze(page),
+ next_cursor: nextOffset < rawRecords.length ? String(nextOffset) : null,
+ });
+}
+
+function importRawTurn(
+ vault: string,
+ sessionId: string,
+ turn: SessionTurn,
+ createdAt: string,
+): ContinuityRecord {
+ const text = turn.text ?? "";
+ const textHash = hash(text);
+ const dedupeKey = ["session_turn", sessionId, turn.turnId, textHash].join(":");
+ const existing = findByDedupeKey(vault, dedupeKey);
+ if (existing !== null) return existing;
+ return appendContinuityRecord(vault, {
+ kind: "session_turn",
+ createdAt,
+ sourceRefs: sourceRefs(sessionId, turn.turnId),
+ payload: {
+ session_id: sessionId,
+ turn_id: turn.turnId,
+ timestamp: turn.timestamp,
+ role: turn.role,
+ text,
+ text_hash: textHash,
+ dedupe_key: dedupeKey,
+ },
+ });
+}
+
+function importSummaryDepth(
+ vault: string,
+ sessionId: string,
+ sources: ReadonlyArray<ContinuityRecord>,
+ depth: number,
+ groupSize: number,
+ createdAt: string,
+): ContinuityRecord[] {
+ if (sources.length === 0) return [];
+ const nodes: ContinuityRecord[] = [];
+ const size = Math.max(1, groupSize);
+ for (let index = 0; index < sources.length; index += size) {
+ const group = sources.slice(index, index + size);
+ if (depth > 1 && group.length < 2) continue;
+ const sourceIds = group.map((record) => record.id);
+ const sourceTurnIds = collectTurnIds(group);
+ const summary = summarizeGroup(group);
+ const dedupeKey = [
+ "session_summary_node",
+ sessionId,
+ depth,
+ hash(sourceIds.join("\n")),
+ hash(summary),
+ ].join(":");
+ const existing = findByDedupeKey(vault, dedupeKey);
+ if (existing !== null) {
+ nodes.push(existing);
+ continue;
+ }
+ nodes.push(
+ appendContinuityRecord(vault, {
+ kind: "session_summary_node",
+ createdAt,
+ sourceRefs: sourceIds.map((id) => Object.freeze({ id, kind: "continuity_record" })),
+ payload: {
+ session_id: sessionId,
+ depth,
+ summary,
+ source_record_ids: sourceIds,
+ source_turn_ids: sourceTurnIds,
+ text_hash: hash(summary),
+ dedupe_key: dedupeKey,
+ },
+ }),
+ );
+ }
+ return nodes;
+}
+
+function sessionRecallRecords(vault: string, sessionId?: string): ContinuityRecord[] {
+ return listContinuityRecords(vault)
+ .filter(
+ (record) =>
+ (record.kind === "session_turn" || record.kind === "session_summary_node") &&
+ (sessionId === undefined || record.payload["session_id"] === sessionId),
+ )
+ .sort((left, right) => compareRecords(left, right));
+}
+
+function hitFor(
+ record: ContinuityRecord,
+ needle: string,
+ snippetChars: number,
+): SessionRecallHit | null {
+ const text = recordText(record);
+ const haystack = text.toLowerCase();
+ const index = haystack.indexOf(needle);
+ if (index < 0) return null;
+ const score = (record.kind === "session_turn" ? 2 : 1) + occurrenceCount(haystack, needle);
+ const base = {
+ id: record.id,
+ kind: record.kind as "session_turn" | "session_summary_node",
+ score,
+ snippet: snippet(text, index, snippetChars),
+ };
+ if (record.kind === "session_turn") {
+ return Object.freeze({
+ ...base,
+ turn_id: String(record.payload["turn_id"] ?? ""),
+ role: String(record.payload["role"] ?? ""),
+ });
+ }
+ return Object.freeze({
+ ...base,
+ depth: numberValue(record.payload["depth"]) ?? 0,
+ source_record_ids: sourceRecordIds(record),
+ });
+}
+
+function collectRawRecords(
+ record: ContinuityRecord,
+ byId: ReadonlyMap<string, ContinuityRecord>,
+): ContinuityRecord[] {
+ if (record.kind === "session_turn") return [record];
+ const out: ContinuityRecord[] = [];
+ for (const id of sourceRecordIds(record)) {
+ const source = byId.get(id);
+ if (source === undefined) continue;
+ out.push(...collectRawRecords(source, byId));
+ }
+ return out.sort(compareRecords);
+}
+
+function expandedRawTurn(record: ContinuityRecord): ExpandedRawTurn {
+ return Object.freeze({
+ id: record.id,
+ turn_id: String(record.payload["turn_id"] ?? ""),
+ role: String(record.payload["role"] ?? ""),
+ timestamp: String(record.payload["timestamp"] ?? ""),
+ text: String(record.payload["text"] ?? ""),
+ });
+}
+
+function summarizeGroup(records: ReadonlyArray<ContinuityRecord>): string {
+ return records.map(summaryLine).join("\n");
+}
+
+function summaryLine(record: ContinuityRecord): string {
+ if (record.kind === "session_turn") {
+ const turnId = String(record.payload["turn_id"] ?? "");
+ const role = String(record.payload["role"] ?? "");
+ return `${turnId} ${role}: ${oneLine(String(record.payload["text"] ?? ""), 120)}`;
+ }
+ const depth = String(record.payload["depth"] ?? "");
+ return `summary depth ${depth}: ${oneLine(String(record.payload["summary"] ?? ""), 160)}`;
+}
+
+function recordText(record: ContinuityRecord): string {
+ return String(record.payload[record.kind === "session_turn" ? "text" : "summary"] ?? "");
+}
+
+function sourceRefs(sessionId: string, turnId: string): ReadonlyArray<ContinuitySourceRef> {
+ return Object.freeze([
+ Object.freeze({ id: sessionId, kind: "session" }),
+ Object.freeze({ id: turnId, kind: "session_turn" }),
+ ]);
+}
+
+function sourceRecordIds(record: ContinuityRecord): string[] {
+ const raw = record.payload["source_record_ids"];
+ return Array.isArray(raw)
+ ? raw.filter((value): value is string => typeof value === "string")
+ : [];
+}
+
+function collectTurnIds(records: ReadonlyArray<ContinuityRecord>): ReadonlyArray<string> {
+ return Object.freeze(
+ records.flatMap((record) => {
+ if (record.kind === "session_turn")
+ return [String(record.payload["turn_id"] ?? "")].filter(Boolean);
+ const raw = record.payload["source_turn_ids"];
+ return Array.isArray(raw)
+ ? raw.filter((value): value is string => typeof value === "string")
+ : [];
+ }),
+ );
+}
+
+function findByDedupeKey(vault: string, dedupeKey: string): ContinuityRecord | null {
+ return (
+ listContinuityRecords(vault).find((record) => record.payload["dedupe_key"] === dedupeKey) ??
+ null
+ );
+}
+
+function snippet(text: string, index: number, maxChars: number): string {
+ const half = Math.floor(maxChars / 2);
+ const start = Math.max(0, index - half);
+ return text.slice(start, start + maxChars);
+}
+
+function oneLine(text: string, maxChars: number): string {
+ return text.replace(/\s+/g, " ").trim().slice(0, maxChars);
+}
+
+function occurrenceCount(text: string, needle: string): number {
+ let count = 0;
+ let index = text.indexOf(needle);
+ while (index >= 0) {
+ count += 1;
+ index = text.indexOf(needle, index + needle.length);
+ }
+ return count;
+}
+
+function compareRecords(left: ContinuityRecord, right: ContinuityRecord): number {
+ const leftTimestamp = String(left.payload["timestamp"] ?? left.createdAt);
+ const rightTimestamp = String(right.payload["timestamp"] ?? right.createdAt);
+ return leftTimestamp.localeCompare(rightTimestamp) || left.id.localeCompare(right.id);
+}
+
+function numberValue(value: unknown): number | null {
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
+}
+
+function hash(value: string): string {
+ return createHash("sha256").update(value).digest("hex").slice(0, 16);
+}
diff --git a/src/core/brain/sessions/import.ts b/src/core/brain/sessions/import.ts
index 0b499f7d..c398e44e 100644
--- a/src/core/brain/sessions/import.ts
+++ b/src/core/brain/sessions/import.ts
@@ -26,11 +26,12 @@
*/
import { existsSync, lstatSync, readdirSync, readFileSync, statSync } from "node:fs";
-import { join, resolve } from "node:path";
+import { basename, join, resolve } from "node:path";
import { buildDedupIndex, computeDedupHash, type DedupIndexEntry } from "../dedup-hash.ts";
import { discoverMarkersDetailed } from "../inline.ts";
import { writeSignal } from "../signal.ts";
+import { importSessionRecall } from "../session-recall.ts";
import { isoDate, isoSecond } from "../time.ts";
import { BRAIN_SIGNAL_SOURCE_TYPE } from "../types.ts";
import { detectAdapter, getAdapter } from "./registry.ts";
@@ -66,6 +67,10 @@ export interface ImportSessionOptions {
* (`writeSignal({ rawCodec: true })`). Default off -> verbatim bodies.
*/
readonly rawCodec?: boolean;
+ /** When true, also store normalized turns in the continuity-backed session recall DAG. */
+ readonly recall?: boolean;
+ readonly recallSessionId?: string;
+ readonly recallSummaryGroupSize?: number;
}
export interface ImportSessionResult {
@@ -76,6 +81,8 @@ export interface ImportSessionResult {
readonly signals_deduped: number;
readonly tool_replays: number;
readonly malformed: number;
+ readonly recall_turns_imported: number;
+ readonly recall_summary_nodes: number;
readonly errors: ReadonlyArray<{ path: string; message: string }>;
}
@@ -133,6 +140,7 @@ export async function importSession(
let signalsDeduped = 0;
let toolReplays = 0;
let malformed = 0;
+ const recallTurns: SessionTurn[] = [];
// Inline helper that wraps the writeSignal call with the consistent
// shape every session-imported signal shares.
@@ -190,6 +198,7 @@ export async function importSession(
const t = Date.parse(turn.timestamp);
if (Number.isFinite(t) && t < sinceMs) continue;
}
+ if (opts.recall === true) recallTurns.push(turn);
// Path A — markers in text.
if (turn.text && (turn.role === "user" || turn.role === "assistant")) {
@@ -245,6 +254,28 @@ export async function importSession(
}
}
+ let recallTurnsImported = 0;
+ let recallSummaryNodes = 0;
+ if (opts.recall === true && opts.dryRun !== true && recallTurns.length > 0) {
+ try {
+ const recalled = importSessionRecall(vault, {
+ sessionId: opts.recallSessionId ?? basename(absPath),
+ turns: recallTurns,
+ createdAt: isoSecond(now),
+ ...(opts.recallSummaryGroupSize !== undefined
+ ? { summaryGroupSize: opts.recallSummaryGroupSize }
+ : {}),
+ });
+ recallTurnsImported = recalled.rawTurns.length;
+ recallSummaryNodes = recalled.summaryNodes.length;
+ } catch (err) {
+ errors.push({
+ path: absPath,
+ message: `importSessionRecall failed: ${(err as Error).message ?? String(err)}`,
+ });
+ }
+ }
+
return Object.freeze({
file: absPath,
format: adapter.id,
@@ -253,6 +284,8 @@ export async function importSession(
signals_deduped: signalsDeduped,
tool_replays: toolReplays,
malformed,
+ recall_turns_imported: recallTurnsImported,
+ recall_summary_nodes: recallSummaryNodes,
errors: Object.freeze(errors),
});
}
diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.ts
index ab6488f8..d08c3f7b 100644
--- a/src/mcp/brain-tools.ts
+++ b/src/mcp/brain-tools.ts
@@ -69,6 +69,36 @@ import { loadTemporalConfigSafe } from "../core/brain/policy.ts";
import { isBrainLogEventKind, type BrainLogEventKind } from "../core/brain/types.ts";
import { packContext } from "../core/brain/context-pack.ts";
import { buildPreCompressPack } from "../core/brain/pre-compress-pack.ts";
+import {
+ getContextReceipt,
+ isContextReceiptTrigger,
+ listContextReceipts,
+ summarizeContextReceipt,
+ type ContextReceiptOptions,
+} from "../core/brain/context-receipts.ts";
+import {
+ isRecallTelemetryMode,
+ isRecallTelemetryStatus,
+ listRecallTelemetry,
+ summarizeRecallTelemetry,
+ type RecallTelemetryFilter,
+ type RecallTelemetryMode,
+ type RecallTelemetryOptions,
+ type RecallTelemetryStatus,
+} from "../core/brain/recall-telemetry.ts";
+import {
+ diffContextPreset,
+ getContextPreset,
+ listContextPresets,
+ suggestContextPreset,
+ type ContextPresetCurrentConfig,
+} from "../core/brain/context-presets.ts";
+import { extractPreCompactRecords } from "../core/brain/pre-compact-extract.ts";
+import {
+ describeSessionRecall,
+ expandSessionRecall,
+ searchSessionRecall,
+} from "../core/brain/session-recall.ts";
import { collectMaintenanceActions } from "../core/brain/maintenance/collect.ts";
import { normaliseWikilinkTarget } from "../core/brain/wikilink.ts";
import { renderDigest, type DigestFormat } from "../core/brain/digest.ts";
@@ -1701,14 +1731,28 @@ async function toolBrainContextPack(
}
const query = typeof args["query"] === "string" ? (args["query"] as string) : undefined;
const includeLanes = coerceBool(args, "lanes");
+ const cacheStable = coerceBool(args, "cache_stable");
+ const dedupRepeated = coerceBool(args, "dedup_repeated");
const maxCharsPerMemory = optionalPositiveInt(args, "max_chars_per_memory", "brain_context_pack");
const maxTotalChars = optionalPositiveInt(args, "max_total_chars", "brain_context_pack");
+ const receipt = receiptOptionsFromArgs("brain_context_pack", args, "context_pack", "mcp");
+ const telemetry = telemetryOptionsFromArgs("brain_context_pack", args, "mcp");
const report = packContext(ctx.vault, {
maxTokens,
...(query ? { query } : {}),
...(includeLanes ? { includeLanes: true } : {}),
+ ...(receipt !== undefined ? { receipt } : {}),
+ ...(cacheStable || dedupRepeated
+ ? {
+ transforms: {
+ ...(cacheStable ? { cacheStableOrdering: true } : {}),
+ ...(dedupRepeated ? { deduplicateRepeatedContext: true } : {}),
+ },
+ }
+ : {}),
...(maxCharsPerMemory !== undefined ? { maxCharsPerMemory } : {}),
...(maxTotalChars !== undefined ? { maxTotalChars } : {}),
+ ...(telemetry !== undefined ? { telemetry } : {}),
});
return {
vault_path: ctx.vault,
@@ -1721,6 +1765,10 @@ async function toolBrainContextPack(
tokens: i.tokens,
body: i.body,
trimmed: i.trimmed,
+ ...(i.originalRank !== undefined ? { original_rank: i.originalRank } : {}),
+ ...(i.stableRank !== undefined ? { stable_rank: i.stableRank } : {}),
+ ...(i.dedupedFrom !== undefined ? { deduped_from: i.dedupedFrom } : {}),
+ ...(i.referenceHint !== undefined ? { reference_hint: i.referenceHint } : {}),
...(i.safety ? { safety: i.safety } : {}),
})),
skipped: report.skipped.map((s) => ({
@@ -1728,10 +1776,281 @@ async function toolBrainContextPack(
tokens: s.tokens,
reason: s.reason,
})),
+ ...(report.receiptId ? { receipt_id: report.receiptId } : {}),
+ ...(report.telemetryId ? { telemetry_id: report.telemetryId } : {}),
...(report.lanes ? { lanes: report.lanes } : {}),
};
}
+// ----- brain_context_receipts ---------------------------------------------
+
+async function toolBrainContextReceipts(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const operation = optionalStringArg("brain_context_receipts", args, "operation");
+ if (operation === "list") {
+ const trigger = optionalStringArg("brain_context_receipts", args, "trigger");
+ if (trigger !== undefined && !isContextReceiptTrigger(trigger)) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_context_receipts: trigger must be context_pack or pre_compress",
+ );
+ }
+ const host = optionalStringArg("brain_context_receipts", args, "host");
+ const sessionId = optionalStringArg("brain_context_receipts", args, "session_id");
+ const limit = coercePositiveInteger("brain_context_receipts", "limit", args["limit"]);
+ const receipts = listContextReceipts(ctx.vault, {
+ ...(trigger !== undefined ? { trigger } : {}),
+ ...(host !== undefined ? { host } : {}),
+ ...(sessionId !== undefined ? { sessionId } : {}),
+ ...(limit !== undefined ? { limit } : {}),
+ });
+ const summaries = receipts.map(summarizeContextReceipt);
+ return {
+ vault_path: ctx.vault,
+ total: summaries.length,
+ receipts: summaries,
+ };
+ }
+
+ if (operation === "show") {
+ const id = optionalStringArg("brain_context_receipts", args, "id");
+ if (id === undefined) {
+ throw new MCPError(INVALID_PARAMS, "brain_context_receipts: id is required for show");
+ }
+ const receipt = getContextReceipt(ctx.vault, id);
+ if (receipt === null) {
+ throw new MCPError(INVALID_PARAMS, `brain_context_receipts: receipt not found: ${id}`);
+ }
+ return {
+ id: receipt.id,
+ kind: receipt.kind,
+ createdAt: receipt.createdAt,
+ sourceRefs: receipt.sourceRefs,
+ payload: receipt.payload,
+ private: receipt.private,
+ redacted: receipt.redacted,
+ };
+ }
+
+ throw new MCPError(INVALID_PARAMS, "brain_context_receipts: operation must be list or show");
+}
+
+function optionalStringArg(
+ tool: string,
+ args: Record<string, unknown>,
+ key: string,
+): string | undefined {
+ const raw = args[key];
+ if (raw === undefined || raw === null) return undefined;
+ if (typeof raw !== "string" || raw.trim().length === 0) {
+ throw new MCPError(INVALID_PARAMS, `${tool}: ${key} must be a non-empty string`);
+ }
+ return raw.trim();
+}
+
+function requiredStringArg(tool: string, args: Record<string, unknown>, key: string): string {
+ const value = optionalStringArg(tool, args, key);
+ if (value === undefined) throw new MCPError(INVALID_PARAMS, `${tool}: ${key} is required`);
+ return value;
+}
+
+// ----- brain_recall_telemetry ---------------------------------------------
+
+async function toolBrainRecallTelemetry(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const operation = optionalStringArg("brain_recall_telemetry", args, "operation");
+ const filter = recallTelemetryFilter(args);
+
+ if (operation === "list") {
+ const records = listRecallTelemetry(ctx.vault, filter);
+ return { vault_path: ctx.vault, total: records.length, records };
+ }
+ if (operation === "summary") {
+ const summary = summarizeRecallTelemetry(ctx.vault, filter);
+ return { ...summary };
+ }
+ throw new MCPError(INVALID_PARAMS, "brain_recall_telemetry: operation must be list or summary");
+}
+
+function recallTelemetryFilter(args: Record<string, unknown>): RecallTelemetryFilter {
+ const mode = coerceRecallTelemetryMode(args["mode"]);
+ const status = coerceRecallTelemetryStatus(args["status"]);
+ const host = optionalStringArg("brain_recall_telemetry", args, "host");
+ const since = optionalStringArg("brain_recall_telemetry", args, "since");
+ const until = optionalStringArg("brain_recall_telemetry", args, "until");
+ const limit = coercePositiveInteger("brain_recall_telemetry", "limit", args["limit"]);
+ return {
+ ...(mode !== undefined ? { mode } : {}),
+ ...(status !== undefined ? { status } : {}),
+ ...(host !== undefined ? { host } : {}),
+ ...(since !== undefined ? { since } : {}),
+ ...(until !== undefined ? { until } : {}),
+ ...(limit !== undefined ? { limit } : {}),
+ };
+}
+
+function coerceRecallTelemetryMode(raw: unknown): RecallTelemetryMode | undefined {
+ if (raw === undefined || raw === null) return undefined;
+ const trimmed = typeof raw === "string" ? raw.trim() : raw;
+ if (!isRecallTelemetryMode(trimmed)) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_recall_telemetry: mode must be search, context_pack, or pre_compress",
+ );
+ }
+ return trimmed;
+}
+
+function coerceRecallTelemetryStatus(raw: unknown): RecallTelemetryStatus | undefined {
+ if (raw === undefined || raw === null) return undefined;
+ const trimmed = typeof raw === "string" ? raw.trim() : raw;
+ if (!isRecallTelemetryStatus(trimmed)) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_recall_telemetry: status must be ok, empty, error, or timeout",
+ );
+ }
+ return trimmed;
+}
+
+// ----- brain_context_presets ----------------------------------------------
+
+async function toolBrainContextPresets(
+ _ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const operation = optionalStringArg("brain_context_presets", args, "operation");
+ if (operation === "show") {
+ const presetId = optionalStringArg("brain_context_presets", args, "preset_id");
+ const result =
+ presetId === undefined ? { presets: listContextPresets() } : getContextPreset(presetId);
+ if (result === null) {
+ throw new MCPError(INVALID_PARAMS, `brain_context_presets: unknown preset ${presetId}`);
+ }
+ return Array.isArray(result) ? { presets: result } : { ...result };
+ }
+ if (operation === "suggest") {
+ const model = optionalStringArg("brain_context_presets", args, "model");
+ const window = coercePositiveInteger(
+ "brain_context_presets",
+ "context_window_tokens",
+ args["context_window_tokens"],
+ );
+ return {
+ ...suggestContextPreset({
+ ...(model !== undefined ? { model } : {}),
+ ...(window !== undefined ? { contextWindowTokens: window } : {}),
+ }),
+ };
+ }
+ if (operation === "diff") {
+ const presetId = optionalStringArg("brain_context_presets", args, "preset_id");
+ if (presetId === undefined) {
+ throw new MCPError(INVALID_PARAMS, "brain_context_presets: preset_id is required for diff");
+ }
+ return {
+ ...diffContextPreset(presetId, contextPresetCurrentConfig(args["current"])),
+ };
+ }
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_context_presets: operation must be show, suggest, or diff",
+ );
+}
+
+function contextPresetCurrentConfig(raw: unknown): ContextPresetCurrentConfig {
+ if (raw === undefined || raw === null) return {};
+ if (typeof raw !== "object" || Array.isArray(raw)) {
+ throw new MCPError(INVALID_PARAMS, "brain_context_presets: current must be an object");
+ }
+ return raw as ContextPresetCurrentConfig;
+}
+
+// ----- brain_pre_compact_extract ------------------------------------------
+
+async function toolBrainPreCompactExtract(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const sessionId = requiredStringArg("brain_pre_compact_extract", args, "session_id");
+ const turnStart = requiredStringArg("brain_pre_compact_extract", args, "turn_start");
+ const turnEnd = requiredStringArg("brain_pre_compact_extract", args, "turn_end");
+ const text = requiredStringArg("brain_pre_compact_extract", args, "text");
+ const maxChars = coercePositiveInteger(
+ "brain_pre_compact_extract",
+ "max_chars",
+ args["max_chars"],
+ );
+ const result = extractPreCompactRecords(ctx.vault, {
+ sessionId,
+ turnStart,
+ turnEnd,
+ text,
+ ...(optionalStringArg("brain_pre_compact_extract", args, "host") !== undefined
+ ? { host: optionalStringArg("brain_pre_compact_extract", args, "host") }
+ : {}),
+ ...(maxChars !== undefined ? { maxChars } : {}),
+ });
+ return { count: result.records.length, ...result };
+}
+
+// ----- session recall DAG --------------------------------------------------
+
+async function toolBrainSessionGrep(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const limit = coercePositiveInteger("brain_session_grep", "limit", args["limit"]);
+ const snippetChars = coercePositiveInteger(
+ "brain_session_grep",
+ "snippet_chars",
+ args["snippet_chars"],
+ );
+ return {
+ ...searchSessionRecall(ctx.vault, {
+ query: requiredStringArg("brain_session_grep", args, "query"),
+ ...(optionalStringArg("brain_session_grep", args, "session_id") !== undefined
+ ? {
+ sessionId: optionalStringArg("brain_session_grep", args, "session_id"),
+ }
+ : {}),
+ ...(limit !== undefined ? { limit } : {}),
+ ...(snippetChars !== undefined ? { snippetChars } : {}),
+ }),
+ };
+}
+
+async function toolBrainSessionDescribe(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ return {
+ ...describeSessionRecall(ctx.vault, {
+ sessionId: requiredStringArg("brain_session_describe", args, "session_id"),
+ }),
+ };
+}
+
+async function toolBrainSessionExpand(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const rawLimit = coercePositiveInteger("brain_session_expand", "raw_limit", args["raw_limit"]);
+ return {
+ ...expandSessionRecall(ctx.vault, {
+ id: requiredStringArg("brain_session_expand", args, "id"),
+ ...(rawLimit !== undefined ? { rawLimit } : {}),
+ ...(optionalStringArg("brain_session_expand", args, "cursor") !== undefined
+ ? { cursor: optionalStringArg("brain_session_expand", args, "cursor") }
+ : {}),
+ }),
+ };
+}
+
// ----- brain_pre_compress_pack (v0.20.0) -----------------------------------
/** Parse an optional positive-integer arg, throwing INVALID_PARAMS otherwise. */
@@ -1770,10 +2089,14 @@ async function toolBrainPreCompressPack(
"brain_pre_compress_pack",
);
const maxTotalChars = optionalPositiveInt(args, "max_total_chars", "brain_pre_compress_pack");
+ const receipt = receiptOptionsFromArgs("brain_pre_compress_pack", args, "pre_compress", "mcp");
+ const telemetry = telemetryOptionsFromArgs("brain_pre_compress_pack", args, "mcp");
const pack = buildPreCompressPack(ctx.vault, {
topK,
...(maxCharsPerMemory !== undefined ? { maxCharsPerMemory } : {}),
...(maxTotalChars !== undefined ? { maxTotalChars } : {}),
+ ...(receipt !== undefined ? { receipt } : {}),
+ ...(telemetry !== undefined ? { telemetry } : {}),
});
return {
vault_path: ctx.vault,
@@ -1781,6 +2104,8 @@ async function toolBrainPreCompressPack(
active_head_included: pack.activeHeadIncluded,
...(pack.activeHeadSafety ? { active_head_safety: pack.activeHeadSafety } : {}),
total_chars: pack.totalChars,
+ ...(pack.receiptId ? { receipt_id: pack.receiptId } : {}),
+ ...(pack.telemetryId ? { telemetry_id: pack.telemetryId } : {}),
items: pack.items.map((i) => ({
id: i.id,
principle: i.principle,
@@ -1790,6 +2115,42 @@ async function toolBrainPreCompressPack(
};
}
+function receiptOptionsFromArgs(
+ tool: string,
+ args: Record<string, unknown>,
+ trigger: "context_pack" | "pre_compress",
+ defaultHost: string,
+): ContextReceiptOptions | undefined {
+ if (!coerceBool(args, "receipt")) return undefined;
+ return {
+ host: optionalStringArg(tool, args, "receipt_host") ?? defaultHost,
+ trigger,
+ ...(optionalStringArg(tool, args, "session_id") !== undefined
+ ? { sessionId: optionalStringArg(tool, args, "session_id") }
+ : {}),
+ ...(optionalStringArg(tool, args, "turn_id") !== undefined
+ ? { turnId: optionalStringArg(tool, args, "turn_id") }
+ : {}),
+ };
+}
+
+function telemetryOptionsFromArgs(
+ tool: string,
+ args: Record<string, unknown>,
+ defaultHost: string,
+): RecallTelemetryOptions | undefined {
+ if (!coerceBool(args, "telemetry")) return undefined;
+ return {
+ host: optionalStringArg(tool, args, "telemetry_host") ?? defaultHost,
+ ...(optionalStringArg(tool, args, "session_id") !== undefined
+ ? { sessionId: optionalStringArg(tool, args, "session_id") }
+ : {}),
+ ...(optionalStringArg(tool, args, "turn_id") !== undefined
+ ? { turnId: optionalStringArg(tool, args, "turn_id") }
+ : {}),
+ };
+}
+
async function toolMcpLandscape(ctx: ServerContext): Promise<Record<string, unknown>> {
const landscape = buildMcpLandscape(ctx.vault);
return {
@@ -2376,12 +2737,267 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
description:
"When true, also return polarity-aware directives, constraints, and consider lanes. Legacy flat `items` remains present.",
},
+ cache_stable: {
+ type: "boolean",
+ description:
+ "When true, reorder the selected items by stable id and annotate their original rank.",
+ },
+ dedup_repeated: {
+ type: "boolean",
+ description:
+ "When true, replace repeated context bodies with reference hints to an earlier emitted item.",
+ },
+ receipt: {
+ type: "boolean",
+ description: "When true, emit an opt-in context receipt for this context-pack run.",
+ },
+ receipt_host: {
+ type: "string",
+ description: "Optional host/runtime name for emitted receipts; defaults to `mcp`.",
+ },
+ telemetry: {
+ type: "boolean",
+ description:
+ "When true, emit an opt-in recall telemetry record for this context-pack run.",
+ },
+ telemetry_host: {
+ type: "string",
+ description: "Optional host/runtime name for emitted telemetry; defaults to `mcp`.",
+ },
+ session_id: {
+ type: "string",
+ description: "Optional session id recorded on emitted telemetry.",
+ },
+ turn_id: {
+ type: "string",
+ description: "Optional turn id recorded on emitted telemetry.",
+ },
},
required: ["max_tokens"],
additionalProperties: false,
},
handler: toolBrainContextPack,
},
+ {
+ name: "brain_context_receipts",
+ description:
+ "List context receipt summaries or show one full receipt by id. Receipts are append-only continuity records emitted by opt-in context injection callers. Read-only.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["list", "show"],
+ description: "Use list for summaries, show for one full receipt by id.",
+ },
+ id: {
+ type: "string",
+ description: "Receipt id required when operation is show.",
+ },
+ trigger: {
+ type: "string",
+ enum: ["context_pack", "pre_compress"],
+ description: "Optional list filter by injection trigger.",
+ },
+ host: {
+ type: "string",
+ description: "Optional list filter by host/runtime name.",
+ },
+ session_id: {
+ type: "string",
+ description: "Optional list filter by recorded session id.",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ description: "Optional maximum number of summaries to return.",
+ },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainContextReceipts,
+ },
+ {
+ name: "brain_recall_telemetry",
+ description:
+ "List recall telemetry records or summarize recall coverage and knowledge gaps. Records are emitted only by opt-in callers. Read-only.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["list", "summary"],
+ description: "Use list for raw records, summary for aggregate counts.",
+ },
+ mode: {
+ type: "string",
+ enum: ["search", "context_pack", "pre_compress"],
+ description: "Optional filter by recall mode.",
+ },
+ status: {
+ type: "string",
+ enum: ["ok", "empty", "error", "timeout"],
+ description: "Optional filter by telemetry status.",
+ },
+ host: {
+ type: "string",
+ description: "Optional filter by host/runtime name.",
+ },
+ since: {
+ type: "string",
+ description: "Optional inclusive lower timestamp bound.",
+ },
+ until: {
+ type: "string",
+ description: "Optional inclusive upper timestamp bound.",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ description: "Optional maximum record count for list.",
+ },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainRecallTelemetry,
+ },
+ {
+ name: "brain_context_presets",
+ description:
+ "Show, suggest, or diff read-only context budget presets. Diagnostics only; never writes configuration.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["show", "suggest", "diff"],
+ description:
+ "show returns presets, suggest chooses by model/window, diff compares current values.",
+ },
+ preset_id: {
+ type: "string",
+ description: "Preset id for show/diff, e.g. tight-context or long-context.",
+ },
+ model: {
+ type: "string",
+ description: "Optional model name hint for suggest.",
+ },
+ context_window_tokens: {
+ type: "integer",
+ minimum: 1,
+ description: "Optional context-window size hint for suggest.",
+ },
+ current: {
+ type: "object",
+ description:
+ "Optional current values for diff: { context_pack, pre_compress, overrides }. Overrides preserve caller-managed paths.",
+ },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainContextPresets,
+ },
+ {
+ name: "brain_pre_compact_extract",
+ description:
+ "Extract typed Decision/Commitment/Outcome/Rule/Open question records from bounded text into continuity storage.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ session_id: {
+ type: "string",
+ description: "Session identifier used for idempotency and source refs.",
+ },
+ turn_start: {
+ type: "string",
+ description: "First source turn id in the extracted segment.",
+ },
+ turn_end: {
+ type: "string",
+ description: "Last source turn id in the extracted segment.",
+ },
+ text: {
+ type: "string",
+ description: "Bounded text segment to scan for labeled extraction lines.",
+ },
+ host: { type: "string", description: "Optional host/client label." },
+ max_chars: {
+ type: "integer",
+ minimum: 1,
+ description: "Optional maximum input characters to scan before extracting.",
+ },
+ },
+ required: ["session_id", "turn_start", "turn_end", "text"],
+ additionalProperties: false,
+ },
+ handler: toolBrainPreCompactExtract,
+ },
+ {
+ name: "brain_session_grep",
+ description: "Search imported session recall raw turns and summary nodes.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ query: { type: "string", description: "Search text." },
+ session_id: {
+ type: "string",
+ description: "Optional session id filter.",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ description: "Maximum hits to return.",
+ },
+ snippet_chars: {
+ type: "integer",
+ minimum: 1,
+ description: "Maximum chars per hit snippet.",
+ },
+ },
+ required: ["query"],
+ additionalProperties: false,
+ },
+ handler: toolBrainSessionGrep,
+ },
+ {
+ name: "brain_session_describe",
+ description: "Describe counts and summary depths for an imported session recall DAG.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ session_id: { type: "string", description: "Session id to describe." },
+ },
+ required: ["session_id"],
+ additionalProperties: false,
+ },
+ handler: toolBrainSessionDescribe,
+ },
+ {
+ name: "brain_session_expand",
+ description:
+ "Expand a session recall raw or summary node to immediate sources and paginated exact raw turn content.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ id: { type: "string", description: "Session recall record id." },
+ raw_limit: {
+ type: "integer",
+ minimum: 1,
+ description: "Maximum raw turn items to return.",
+ },
+ cursor: {
+ type: "string",
+ description: "Raw turn pagination cursor from a previous response.",
+ },
+ },
+ required: ["id"],
+ additionalProperties: false,
+ },
+ handler: toolBrainSessionExpand,
+ },
{
// No preview budget: the addendum is meant to be injected whole and
// is already bounded by its own per-entry / total character caps.
@@ -2409,6 +3025,31 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
description:
"Optional total character cap (code points) across the addendum; lowest-priority overflow is dropped.",
},
+ receipt: {
+ type: "boolean",
+ description: "When true, emit an opt-in context receipt for this pre-compress run.",
+ },
+ receipt_host: {
+ type: "string",
+ description: "Optional host/runtime name for emitted receipts; defaults to `mcp`.",
+ },
+ telemetry: {
+ type: "boolean",
+ description:
+ "When true, emit an opt-in recall telemetry record for this pre-compress run.",
+ },
+ telemetry_host: {
+ type: "string",
+ description: "Optional host/runtime name for emitted telemetry; defaults to `mcp`.",
+ },
+ session_id: {
+ type: "string",
+ description: "Optional session id recorded on emitted telemetry.",
+ },
+ turn_id: {
+ type: "string",
+ description: "Optional turn id recorded on emitted telemetry.",
+ },
},
additionalProperties: false,
},
diff --git a/src/mcp/search-tools.ts b/src/mcp/search-tools.ts
index bcf1e1a4..f571dc9a 100644
--- a/src/mcp/search-tools.ts
+++ b/src/mcp/search-tools.ts
@@ -25,6 +25,7 @@ import type { ServerContext, ToolDefinition } from "./tools.ts";
import { coerceBoolOptional, coerceStringOptional } from "./coerce.ts";
import { MCP_PREVIEW_BUDGET } from "./preview-budget.ts";
import { deriveRecallHint } from "../core/search/recall-hint.ts";
+import { emitRecallTelemetry } from "../core/brain/recall-telemetry.ts";
const MCP_LIMIT_MAX = 50;
const MCP_CONTENT_MAX = 600;
@@ -42,6 +43,10 @@ const SEARCH_INPUT_SCHEMA: Record<string, unknown> = {
semantic: { type: "boolean" },
keyword_only: { type: "boolean" },
path_prefix: { type: "string", maxLength: 256 },
+ telemetry: { type: "boolean" },
+ telemetry_host: { type: "string", maxLength: 200 },
+ session_id: { type: "string", maxLength: 512 },
+ turn_id: { type: "string", maxLength: 512 },
properties: {
type: "object",
description:
@@ -108,6 +113,7 @@ const SEARCH_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {
total: { type: "integer" },
recall_hint: { type: "string" },
evidence_pack: { type: "object" },
+ telemetry_id: { type: "string" },
},
};
@@ -242,6 +248,10 @@ async function toolBrainSearch(
const keywordOnly = coerceBoolOptional(args, "keyword_only") ?? false;
const pathPrefix = coerceStringOptional(args, "path_prefix", 256);
const evidencePack = coerceBoolOptional(args, "evidence_pack") ?? false;
+ const telemetry = coerceBoolOptional(args, "telemetry") ?? false;
+ const telemetryHost = coerceStringOptional(args, "telemetry_host", 200) ?? "mcp";
+ const telemetrySessionId = coerceStringOptional(args, "session_id", 512);
+ const telemetryTurnId = coerceStringOptional(args, "turn_id", 512);
const rawQueryDocument = coerceStringOptional(args, "query_document", 4000);
const structuredQuery =
rawQueryDocument !== undefined
@@ -265,6 +275,7 @@ async function toolBrainSearch(
});
let outcome: SearchOutcome;
+ const startedAtMs = Date.now();
try {
outcome = await withTimeout(
search(config, {
@@ -283,12 +294,59 @@ async function toolBrainSearch(
searchTimeoutError,
);
} catch (e) {
+ if (telemetry) {
+ emitRecallTelemetry(ctx.vault, {
+ host: telemetryHost,
+ ...(telemetrySessionId !== undefined ? { sessionId: telemetrySessionId } : {}),
+ ...(telemetryTurnId !== undefined ? { turnId: telemetryTurnId } : {}),
+ mode: "search",
+ status: e instanceof MCPError && e.message.includes("timeout") ? "timeout" : "error",
+ durationMs: Date.now() - startedAtMs,
+ resultCount: 0,
+ gaps: [
+ e instanceof MCPError && e.message.includes("timeout")
+ ? "search_timeout"
+ : "search_error",
+ ],
+ metadata: {
+ limit,
+ keyword_only: keywordOnly,
+ semantic: semantic ?? null,
+ },
+ });
+ }
if (e instanceof SearchError) throw searchErrorToMcp(e);
if (e instanceof MCPError) throw e;
throw new MCPError(INTERNAL_ERROR, e instanceof Error ? e.message : String(e));
}
const recallHint = deriveRecallHint(outcome.results, outcome.total);
+ const telemetryRecord = telemetry
+ ? emitRecallTelemetry(ctx.vault, {
+ host: telemetryHost,
+ ...(telemetrySessionId !== undefined ? { sessionId: telemetrySessionId } : {}),
+ ...(telemetryTurnId !== undefined ? { turnId: telemetryTurnId } : {}),
+ mode: "search",
+ status: outcome.results.length > 0 ? "ok" : "empty",
+ durationMs: Date.now() - startedAtMs,
+ resultCount: outcome.results.length,
+ topArtifacts: outcome.results.slice(0, 10).map((result) => ({
+ id: `${result.documentId}:${result.chunkId}`,
+ path: result.path,
+ score: result.score,
+ })),
+ gaps: searchTelemetryGaps(outcome),
+ metadata: {
+ limit,
+ total: outcome.total,
+ keyword_only: keywordOnly,
+ semantic: semantic ?? null,
+ evidence_pack: evidencePack,
+ warnings_count: outcome.warnings.length,
+ ...(pathPrefix !== undefined ? { path_prefix: pathPrefix } : {}),
+ },
+ })
+ : null;
return {
results: outcome.results.map((r: BrainSearchResult) => ({
path: r.path,
@@ -306,9 +364,19 @@ async function toolBrainSearch(
total: outcome.total,
...(outcome.evidencePack ? { evidence_pack: mcpEvidencePack(outcome.evidencePack) } : {}),
...(recallHint !== null ? { recall_hint: recallHint } : {}),
+ ...(telemetryRecord ? { telemetry_id: telemetryRecord.id } : {}),
};
}
+function searchTelemetryGaps(outcome: SearchOutcome): ReadonlyArray<string> {
+ const gaps = new Set<string>();
+ if (outcome.total === 0) gaps.add("no_matching_context");
+ for (const term of outcome.evidencePack?.missingTerms ?? []) {
+ gaps.add(`missing_term:${term}`);
+ }
+ return [...gaps];
+}
+
function mcpEvidencePack(
pack: NonNullable<SearchOutcome["evidencePack"]>,
): Record<string, unknown> {
diff --git a/tests/cli/brain-context-pack.test.ts b/tests/cli/brain-context-pack.test.ts
index 50707b93..995788b5 100644
--- a/tests/cli/brain-context-pack.test.ts
+++ b/tests/cli/brain-context-pack.test.ts
@@ -4,6 +4,8 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { runCli } from "../helpers/run-cli.ts";
+import { listContextReceipts } from "../../src/core/brain/context-receipts.ts";
+import { listRecallTelemetry } from "../../src/core/brain/recall-telemetry.ts";
let vault: string;
@@ -39,3 +41,101 @@ test("brain context-pack --lanes --json returns polarity lanes", async () => {
"pref-constraint",
);
});
+
+test("brain context-pack can opt in to receipts and recall telemetry", async () => {
+ writePref("telemetry", "Prefer auditable context", "tier: core");
+
+ const out = await runCli(
+ [
+ "brain",
+ "context-pack",
+ "--vault",
+ vault,
+ "--max-tokens",
+ "10000",
+ "--receipt",
+ "--receipt-host",
+ "cli-test",
+ "--telemetry",
+ "--telemetry-host",
+ "cli-test",
+ "--json",
+ ],
+ {},
+ );
+
+ expect(out.returncode).toBe(0);
+ const json = JSON.parse(out.stdout);
+ expect(json.receipt_id).toStartWith("ctn_");
+ expect(json.telemetry_id).toStartWith("ctn_");
+ const receipts = listContextReceipts(vault, {
+ trigger: "context_pack",
+ host: "cli-test",
+ });
+ expect(receipts).toHaveLength(1);
+ expect(receipts[0]!.payload).toMatchObject({
+ trigger: "context_pack",
+ item_count: 1,
+ });
+ const records = listRecallTelemetry(vault, {
+ mode: "context_pack",
+ host: "cli-test",
+ });
+ expect(records).toHaveLength(1);
+ expect(records[0]!.payload).toMatchObject({ status: "ok", result_count: 1 });
+});
+
+test("brain context-pack exposes opt-in transform annotations", async () => {
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-zulu.md"),
+ [
+ "---",
+ "id: pref-zulu",
+ "topic: t",
+ "principle: shared body",
+ "tier: core",
+ "created_at: 2026-05-02T00:00:00Z",
+ "---",
+ "",
+ "shared body",
+ ].join("\n"),
+ );
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-alpha.md"),
+ [
+ "---",
+ "id: pref-alpha",
+ "topic: t",
+ "principle: shared body",
+ "tier: core",
+ "created_at: 2026-05-01T00:00:00Z",
+ "---",
+ "",
+ "shared body",
+ ].join("\n"),
+ );
+
+ const out = await runCli(
+ [
+ "brain",
+ "context-pack",
+ "--vault",
+ vault,
+ "--max-tokens",
+ "10000",
+ "--cache-stable",
+ "--dedup-repeated",
+ "--json",
+ ],
+ {},
+ );
+
+ expect(out.returncode).toBe(0);
+ const json = JSON.parse(out.stdout);
+ expect(json.items.map((item: { id: string }) => item.id)).toEqual(["pref-alpha", "pref-zulu"]);
+ expect(json.items[0]).toMatchObject({ original_rank: 2, stable_rank: 1 });
+ expect(json.items[1]).toMatchObject({
+ deduped_from: "pref-alpha",
+ reference_hint: "see pref-alpha",
+ });
+});
diff --git a/tests/cli/brain-context-presets.test.ts b/tests/cli/brain-context-presets.test.ts
new file mode 100644
index 00000000..33d7cee8
--- /dev/null
+++ b/tests/cli/brain-context-presets.test.ts
@@ -0,0 +1,45 @@
+import { expect, test } from "bun:test";
+
+import { runCli } from "../helpers/run-cli.ts";
+
+test("brain context-presets show/suggest/diff returns dry-run diagnostics", async () => {
+ const show = await runCli(["brain", "context-presets", "show", "tight-context", "--json"]);
+ expect(show.returncode).toBe(0);
+ expect(JSON.parse(show.stdout)).toMatchObject({
+ id: "tight-context",
+ context_pack: { max_tokens: 4000 },
+ });
+
+ const suggest = await runCli([
+ "brain",
+ "context-presets",
+ "suggest",
+ "--model",
+ "claude-sonnet-4",
+ "--context-window",
+ "200000",
+ "--json",
+ ]);
+ expect(suggest.returncode).toBe(0);
+ expect(JSON.parse(suggest.stdout)).toMatchObject({
+ preset_id: "long-context",
+ confidence: "high",
+ });
+
+ const diff = await runCli([
+ "brain",
+ "context-presets",
+ "diff",
+ "tight-context",
+ "--context-pack-max-tokens",
+ "9000",
+ "--override",
+ "context_pack.max_tokens",
+ "--json",
+ ]);
+ expect(diff.returncode).toBe(0);
+ expect(JSON.parse(diff.stdout)).toMatchObject({
+ preset_id: "tight-context",
+ preserved_overrides: [{ path: "context_pack.max_tokens", current: 9000, preset: 4000 }],
+ });
+});
diff --git a/tests/cli/brain-context-receipts.test.ts b/tests/cli/brain-context-receipts.test.ts
new file mode 100644
index 00000000..f56f3818
--- /dev/null
+++ b/tests/cli/brain-context-receipts.test.ts
@@ -0,0 +1,70 @@
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { emitContextReceipt } from "../../src/core/brain/context-receipts.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-context-receipts-cli-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+test("brain context-receipts lists and shows prompt receipt records", async () => {
+ const receipt = emitContextReceipt(vault, {
+ options: {
+ host: "cli-test",
+ trigger: "context_pack",
+ createdAt: "2026-05-20T12:00:00.000Z",
+ sessionId: "session-cli",
+ },
+ finalText: "Packed visible context",
+ items: [
+ {
+ id: "pref-alpha",
+ path: join(vault, "Brain", "preferences", "pref-alpha.md"),
+ text: "Prefer crisp answers",
+ tokens: 4,
+ tier: "core",
+ },
+ ],
+ budget: { max_tokens: 100 },
+ });
+
+ const list = await runCli(["brain", "context-receipts", "list", "--vault", vault, "--json"]);
+ expect(list.returncode).toBe(0);
+ const listJson = JSON.parse(list.stdout);
+ expect(listJson.total).toBe(1);
+ expect(listJson.receipts[0]).toMatchObject({
+ id: receipt.id,
+ created_at: "2026-05-20T12:00:00.000Z",
+ trigger: "context_pack",
+ host: "cli-test",
+ item_count: 1,
+ });
+
+ const show = await runCli([
+ "brain",
+ "context-receipts",
+ "show",
+ receipt.id,
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(show.returncode).toBe(0);
+ const showJson = JSON.parse(show.stdout);
+ expect(showJson.id).toBe(receipt.id);
+ expect(showJson.payload.items[0]).toMatchObject({
+ id: "pref-alpha",
+ tier: "core",
+ tokens: 4,
+ });
+});
diff --git a/tests/cli/brain-pre-compact-extract.test.ts b/tests/cli/brain-pre-compact-extract.test.ts
new file mode 100644
index 00000000..2f994336
--- /dev/null
+++ b/tests/cli/brain-pre-compact-extract.test.ts
@@ -0,0 +1,45 @@
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { runCli } from "../helpers/run-cli.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-cli-pre-compact-extract-"));
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+test("brain pre-compact-extract emits typed records without writing raw media", async () => {
+ const result = await runCli([
+ "brain",
+ "pre-compact-extract",
+ "--vault",
+ vault,
+ "--session-id",
+ "session-cli",
+ "--turn-start",
+ "turn-1",
+ "--turn-end",
+ "turn-2",
+ "--text",
+ "Decision: Keep it bounded.\nOpen question: data:image/png;base64,QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=",
+ "--json",
+ ]);
+
+ expect(result.returncode).toBe(0);
+ expect(result.stderr).toBe("");
+ const body = JSON.parse(result.stdout);
+ expect(body).toMatchObject({ count: 2, errors: [] });
+ expect(
+ body.records.map(
+ (record: { payload: { extract_type: string } }) => record.payload.extract_type,
+ ),
+ ).toEqual(["decision", "open_question"]);
+ expect(result.stdout).not.toContain("QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo");
+});
diff --git a/tests/cli/brain-recall-telemetry.test.ts b/tests/cli/brain-recall-telemetry.test.ts
new file mode 100644
index 00000000..316bf552
--- /dev/null
+++ b/tests/cli/brain-recall-telemetry.test.ts
@@ -0,0 +1,78 @@
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { emitRecallTelemetry } from "../../src/core/brain/recall-telemetry.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-recall-telemetry-cli-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+test("brain recall-telemetry lists records and summarizes gaps", async () => {
+ emitRecallTelemetry(vault, {
+ createdAt: "2026-05-20T16:00:00.000Z",
+ host: "cli-test",
+ mode: "context_pack",
+ status: "ok",
+ durationMs: 8,
+ resultCount: 2,
+ topArtifacts: [{ id: "pref-alpha" }],
+ });
+ emitRecallTelemetry(vault, {
+ createdAt: "2026-05-20T16:01:00.000Z",
+ host: "cli-test",
+ mode: "search",
+ status: "empty",
+ durationMs: 12,
+ resultCount: 0,
+ gaps: ["no_matching_context"],
+ });
+
+ const list = await runCli([
+ "brain",
+ "recall-telemetry",
+ "list",
+ "--vault",
+ vault,
+ "--mode",
+ "context_pack",
+ "--json",
+ ]);
+ expect(list.returncode).toBe(0);
+ const listJson = JSON.parse(list.stdout);
+ expect(listJson.total).toBe(1);
+ expect(listJson.records[0].payload).toMatchObject({
+ mode: "context_pack",
+ result_count: 2,
+ });
+
+ const summary = await runCli([
+ "brain",
+ "recall-telemetry",
+ "summary",
+ "--vault",
+ vault,
+ "--host",
+ "cli-test",
+ "--json",
+ ]);
+ expect(summary.returncode).toBe(0);
+ const summaryJson = JSON.parse(summary.stdout);
+ expect(summaryJson).toMatchObject({
+ total: 2,
+ by_mode: { context_pack: 1, search: 1 },
+ by_status: { ok: 1, empty: 1 },
+ total_results: 2,
+ empty_runs: 1,
+ gap_counts: { no_matching_context: 1 },
+ });
+});
diff --git a/tests/cli/brain-session-recall.test.ts b/tests/cli/brain-session-recall.test.ts
new file mode 100644
index 00000000..59e47056
--- /dev/null
+++ b/tests/cli/brain-session-recall.test.ts
@@ -0,0 +1,95 @@
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { importSessionRecall } from "../../src/core/brain/session-recall.ts";
+import type { SessionTurn } from "../../src/core/brain/sessions/types.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-cli-session-recall-"));
+ const turns: SessionTurn[] = [
+ {
+ turnId: "t1",
+ role: "user",
+ timestamp: "2026-05-20T17:00:01.000Z",
+ text: "Need receipt search.",
+ },
+ {
+ turnId: "t2",
+ role: "assistant",
+ timestamp: "2026-05-20T17:00:02.000Z",
+ text: "Decision: add session recall summaries.",
+ },
+ {
+ turnId: "t3",
+ role: "user",
+ timestamp: "2026-05-20T17:00:03.000Z",
+ text: "Another receipt ask.",
+ },
+ ];
+ importSessionRecall(vault, {
+ sessionId: "session-cli",
+ turns,
+ summaryGroupSize: 2,
+ createdAt: "2026-05-20T17:00:00.000Z",
+ });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+test("brain session-grep/describe/expand query imported recall DAG", async () => {
+ const describe = await runCli([
+ "brain",
+ "session-describe",
+ "--vault",
+ vault,
+ "--session-id",
+ "session-cli",
+ "--json",
+ ]);
+ expect(describe.returncode).toBe(0);
+ expect(JSON.parse(describe.stdout)).toMatchObject({
+ raw_turns: 3,
+ summary_nodes: 3,
+ });
+
+ const grep = await runCli([
+ "brain",
+ "session-grep",
+ "--vault",
+ vault,
+ "--query",
+ "receipt",
+ "--session-id",
+ "session-cli",
+ "--json",
+ ]);
+ expect(grep.returncode).toBe(0);
+ const hits = JSON.parse(grep.stdout).hits as Array<{
+ id: string;
+ kind: string;
+ }>;
+ expect(hits.some((hit) => hit.kind === "session_turn")).toBe(true);
+ expect(hits.some((hit) => hit.kind === "session_summary_node")).toBe(true);
+
+ const expand = await runCli([
+ "brain",
+ "session-expand",
+ hits.find((hit) => hit.kind === "session_summary_node")!.id,
+ "--vault",
+ vault,
+ "--raw-limit",
+ "1",
+ "--json",
+ ]);
+ expect(expand.returncode).toBe(0);
+ const expanded = JSON.parse(expand.stdout);
+ expect(expanded.immediate_sources.length).toBeGreaterThan(0);
+ expect(expanded.raw_content).toHaveLength(1);
+});
diff --git a/tests/cli/brain.test.ts b/tests/cli/brain.test.ts
index 2b9da7c8..12489937 100644
--- a/tests/cli/brain.test.ts
+++ b/tests/cli/brain.test.ts
@@ -1199,6 +1199,47 @@ describe("brain import-session", () => {
expect(parsed.files[0].format).toBe("codex");
});
+ test("--recall populates session recall DAG", async () => {
+ await bootstrap();
+ const fixture = join(process.cwd(), "tests/fixtures/sessions/codex-minimal.jsonl");
+ const r = await runCli(
+ [
+ "brain",
+ "import-session",
+ fixture,
+ "--vault",
+ vault,
+ "--recall",
+ "--recall-session-id",
+ "cli-import-recall",
+ "--json",
+ ],
+ {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ },
+ );
+ expect(r.returncode).toBe(0);
+ const parsed = JSON.parse(r.stdout);
+ expect(parsed.files[0].recall_turns_imported).toBeGreaterThan(0);
+
+ const describe = await runCli(
+ [
+ "brain",
+ "session-describe",
+ "--vault",
+ vault,
+ "--session-id",
+ "cli-import-recall",
+ "--json",
+ ],
+ {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ },
+ );
+ expect(describe.returncode).toBe(0);
+ expect(JSON.parse(describe.stdout).raw_turns).toBe(parsed.files[0].recall_turns_imported);
+ });
+
test("exit 2 on unknown format without --format flag", async () => {
await bootstrap();
const junk = join(tmp, "junk.jsonl");
diff --git a/tests/core/brain.sessions.import.test.ts b/tests/core/brain.sessions.import.test.ts
index f0f2c551..998bc861 100644
--- a/tests/core/brain.sessions.import.test.ts
+++ b/tests/core/brain.sessions.import.test.ts
@@ -16,6 +16,7 @@ import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/policy.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
import { importSession, importSessionPath } from "../../src/core/brain/sessions/import.ts";
import { SessionImportError } from "../../src/core/brain/sessions/types.ts";
+import { describeSessionRecall } from "../../src/core/brain/session-recall.ts";
const CLAUDE = resolve("tests/fixtures/sessions/claude-minimal.jsonl");
const CODEX = resolve("tests/fixtures/sessions/codex-minimal.jsonl");
@@ -86,12 +87,30 @@ describe("importSession", () => {
});
test("dry-run does not write signals", async () => {
- const res = await importSession(tmp, CLAUDE, { agent: "test", dryRun: true });
+ const res = await importSession(tmp, CLAUDE, {
+ agent: "test",
+ dryRun: true,
+ });
expect(res.signals_created).toBe(0);
const inbox = readdirSync(brainDirs(tmp).inbox).filter((n) => n.startsWith("sig-"));
expect(inbox.length).toBe(0);
});
+ test("can also store imported turns in the session recall DAG", async () => {
+ const res = await importSession(tmp, CLAUDE, {
+ agent: "test",
+ recall: true,
+ recallSessionId: "session-import-test",
+ recallSummaryGroupSize: 2,
+ });
+
+ expect(res.recall_turns_imported).toBeGreaterThan(0);
+ expect(res.recall_summary_nodes).toBeGreaterThan(0);
+ expect(describeSessionRecall(tmp, { sessionId: "session-import-test" }).raw_turns).toBe(
+ res.recall_turns_imported,
+ );
+ });
+
test("handles the codex fixture", async () => {
const res = await importSession(tmp, CODEX, { agent: "test" });
expect(res.format).toBe("codex");
@@ -136,7 +155,10 @@ describe("importSession", () => {
writeFileSync(junk, '{"foo":"bar"}\n');
// Should not throw — adapter chosen explicitly, iteration just
// yields nothing.
- const res = await importSession(tmp, junk, { agent: "test", format: "claude" });
+ const res = await importSession(tmp, junk, {
+ agent: "test",
+ format: "claude",
+ });
expect(res.format).toBe("claude");
expect(res.signals_created).toBe(0);
});
diff --git a/tests/core/brain/context-pack.test.ts b/tests/core/brain/context-pack.test.ts
index c90c5a50..2deaf7d4 100644
--- a/tests/core/brain/context-pack.test.ts
+++ b/tests/core/brain/context-pack.test.ts
@@ -26,6 +26,7 @@ function writePref(
tier?: string;
created_at?: string;
context_lane?: string;
+ body?: string;
},
) {
const lines = [
@@ -37,7 +38,7 @@ function writePref(
if (fields.tier) lines.push(`tier: ${fields.tier}`);
if (fields.created_at) lines.push(`created_at: ${fields.created_at}`);
if (fields.context_lane) lines.push(`context_lane: ${fields.context_lane}`);
- lines.push("---", "");
+ lines.push("---", "", fields.body ?? "");
writeFileSync(join(vault, "Brain", "preferences", `pref-${slug}.md`), lines.join("\n"));
}
@@ -134,6 +135,63 @@ describe("packContext", () => {
expect(r.items[1]!.id).toBe("pref-old");
});
+ test("cache-stable ordering is opt-in and annotates original rank", () => {
+ writePref("zulu", {
+ topic: "x",
+ principle: "zulu body",
+ body: "zulu body",
+ tier: "core",
+ created_at: "2026-05-02T00:00:00Z",
+ });
+ writePref("alpha", {
+ topic: "x",
+ principle: "alpha body",
+ body: "alpha body",
+ tier: "core",
+ created_at: "2026-05-01T00:00:00Z",
+ });
+
+ const defaultPack = packContext(vault, { maxTokens: 10_000 });
+ expect(defaultPack.items.map((item) => item.id)).toEqual(["pref-zulu", "pref-alpha"]);
+
+ const stablePack = packContext(vault, {
+ maxTokens: 10_000,
+ transforms: { cacheStableOrdering: true },
+ });
+ expect(stablePack.items.map((item) => item.id)).toEqual(["pref-alpha", "pref-zulu"]);
+ expect(stablePack.items.map((item) => item.originalRank)).toEqual([2, 1]);
+ expect(stablePack.items.map((item) => item.stableRank)).toEqual([1, 2]);
+ });
+
+ test("repeated-context dedup is opt-in and keeps an accessible reference", () => {
+ writePref("first", {
+ topic: "x",
+ principle: "shared body",
+ body: "shared body",
+ tier: "core",
+ created_at: "2026-05-02T00:00:00Z",
+ });
+ writePref("second", {
+ topic: "x",
+ principle: "shared body",
+ body: "shared body",
+ tier: "core",
+ created_at: "2026-05-01T00:00:00Z",
+ });
+
+ const defaultPack = packContext(vault, { maxTokens: 10_000 });
+ expect(defaultPack.items.map((item) => item.body)).toEqual(["shared body", "shared body"]);
+
+ const dedupedPack = packContext(vault, {
+ maxTokens: 10_000,
+ transforms: { deduplicateRepeatedContext: true },
+ });
+ expect(dedupedPack.items[0]!.body).toBe("shared body");
+ expect(dedupedPack.items[1]!.body).toBe("Repeated context omitted; see pref-first.");
+ expect(dedupedPack.items[1]!.dedupedFrom).toBe("pref-first");
+ expect(dedupedPack.items[1]!.referenceHint).toBe("see pref-first");
+ });
+
test("stops when next page would exceed budget", () => {
writePref("a", {
topic: "x",
diff --git a/tests/core/brain/context-presets.test.ts b/tests/core/brain/context-presets.test.ts
new file mode 100644
index 00000000..6dd588d8
--- /dev/null
+++ b/tests/core/brain/context-presets.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, test } from "bun:test";
+
+import {
+ diffContextPreset,
+ getContextPreset,
+ listContextPresets,
+ suggestContextPreset,
+} from "../../../src/core/brain/context-presets.ts";
+
+describe("context budget presets", () => {
+ test("exposes named tight and long context presets", () => {
+ const presets = listContextPresets();
+ expect(presets.map((preset) => preset.id)).toEqual(["tight-context", "long-context"]);
+ expect(getContextPreset("tight-context")).toMatchObject({
+ id: "tight-context",
+ context_pack: { max_tokens: 4000 },
+ pre_compress: { top_k: 5 },
+ });
+ });
+
+ test("suggests by model hint and context window", () => {
+ expect(
+ suggestContextPreset({
+ model: "gpt-4.1-mini",
+ contextWindowTokens: 8000,
+ }),
+ ).toMatchObject({
+ preset_id: "tight-context",
+ confidence: "high",
+ });
+ expect(
+ suggestContextPreset({
+ model: "claude-sonnet-4",
+ contextWindowTokens: 200000,
+ }),
+ ).toMatchObject({
+ preset_id: "long-context",
+ confidence: "high",
+ });
+ });
+
+ test("diffs preset values while reporting explicit overrides", () => {
+ const diff = diffContextPreset("tight-context", {
+ context_pack: {
+ max_tokens: 9000,
+ max_chars_per_memory: 1200,
+ max_total_chars: 6000,
+ },
+ pre_compress: {
+ top_k: 5,
+ max_chars_per_memory: 800,
+ max_total_chars: 4000,
+ },
+ overrides: ["context_pack.max_tokens"],
+ });
+
+ expect(diff).toMatchObject({
+ preset_id: "tight-context",
+ changes: [],
+ preserved_overrides: [
+ {
+ path: "context_pack.max_tokens",
+ current: 9000,
+ preset: 4000,
+ },
+ ],
+ invalid_overrides: [],
+ });
+ expect(diff.unchanged).toContain("context_pack.max_total_chars");
+ expect(diff.unchanged).toContain("pre_compress.top_k");
+ });
+});
diff --git a/tests/core/brain/context-receipts.test.ts b/tests/core/brain/context-receipts.test.ts
new file mode 100644
index 00000000..9044409d
--- /dev/null
+++ b/tests/core/brain/context-receipts.test.ts
@@ -0,0 +1,141 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { listContinuityRecords } from "../../../src/core/brain/continuity/store.ts";
+import { packContext } from "../../../src/core/brain/context-pack.ts";
+import { emitContextReceipt } from "../../../src/core/brain/context-receipts.ts";
+import { brainActivePath } from "../../../src/core/brain/paths.ts";
+import { buildPreCompressPack } from "../../../src/core/brain/pre-compress-pack.ts";
+import { writePreference } from "../../../src/core/brain/preference.ts";
+import {
+ BRAIN_CONFIDENCE,
+ BRAIN_PREFERENCE_STATUS,
+} from "../../../src/core/brain/types.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-context-receipts-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("context receipts", () => {
+ test("packContext can emit a redaction-safe receipt without changing selected items", () => {
+ writePref(
+ "alpha",
+ "alpha topic",
+ "Keep answers short",
+ "Body with token=secret-value",
+ );
+
+ const pack = packContext(vault, {
+ maxTokens: 10_000,
+ receipt: {
+ host: "unit-test",
+ sessionId: "session-a",
+ trigger: "context_pack",
+ createdAt: "2026-05-31T12:00:00Z",
+ },
+ });
+
+ expect(pack.items.map((item) => item.id)).toEqual(["pref-alpha"]);
+ expect(pack.receiptId).toStartWith("ctn_");
+
+ const receipts = listContinuityRecords(vault, { kind: "context_receipt" });
+ expect(receipts).toHaveLength(1);
+ expect(receipts[0]!.id).toBe(pack.receiptId!);
+ expect(receipts[0]!.sourceRefs).toEqual([
+ expect.objectContaining({
+ id: "pref-alpha",
+ path: expect.stringContaining("pref-alpha.md"),
+ }),
+ ]);
+ expect(receipts[0]!.payload).toEqual(
+ expect.objectContaining({
+ host: "unit-test",
+ session_id: "session-a",
+ trigger: "context_pack",
+ item_count: 1,
+ final_text_hash: expect.stringMatching(/^[a-f0-9]{64}$/),
+ }),
+ );
+ expect(JSON.stringify(receipts)).not.toContain("secret-value");
+ });
+
+ test("buildPreCompressPack can emit a receipt for active head and preference items", () => {
+ writeFileSync(
+ brainActivePath(vault),
+ "# Active\n\nUse project conventions.\n",
+ );
+ writePref("bravo", "bravo topic", "Prefer concrete release notes", "Body");
+
+ const pack = buildPreCompressPack(vault, {
+ topK: 10,
+ receipt: {
+ host: "unit-test",
+ sessionId: "session-b",
+ trigger: "pre_compress",
+ createdAt: "2026-05-31T12:05:00Z",
+ },
+ });
+
+ expect(pack.receiptId).toStartWith("ctn_");
+ const receipts = listContinuityRecords(vault, { kind: "context_receipt" });
+ expect(receipts).toHaveLength(1);
+ expect(receipts[0]!.payload).toEqual(
+ expect.objectContaining({
+ trigger: "pre_compress",
+ active_head_included: true,
+ item_count: 2,
+ }),
+ );
+ expect(receipts[0]!.sourceRefs.map((source) => source.id)).toEqual([
+ "__active__",
+ "pref-bravo",
+ ]);
+ });
+
+ test("rejects extra receipt fields that collide with core payload fields", () => {
+ expect(() =>
+ emitContextReceipt(vault, {
+ options: {
+ host: "unit-test",
+ trigger: "context_pack",
+ createdAt: "2026-05-31T12:10:00Z",
+ },
+ items: [],
+ finalText: "",
+ extra: { host: "override" },
+ }),
+ ).toThrow("context receipt extra key collides with payload field: host");
+ });
+});
+
+function writePref(
+ slug: string,
+ topic: string,
+ principle: string,
+ body: string,
+): void {
+ writePreference(vault, {
+ slug,
+ topic,
+ principle,
+ created_at: "2026-05-31T00:00:00Z",
+ unconfirmed_until: "2026-06-07T00:00:00Z",
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ evidenced_by: [`[[sig-2026-05-31-${slug}]]`],
+ confirmed_at: "2026-05-31T00:00:00Z",
+ howToApply: body,
+ confidence: BRAIN_CONFIDENCE.high,
+ confidence_value: 0.9,
+ });
+}
diff --git a/tests/core/brain/continuity-store.test.ts b/tests/core/brain/continuity-store.test.ts
new file mode 100644
index 00000000..b9ff3399
--- /dev/null
+++ b/tests/core/brain/continuity-store.test.ts
@@ -0,0 +1,135 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { acquireLockSync } from "../../../src/core/brain/sync-lockfile.ts";
+import {
+ appendContinuityRecord,
+ appendContinuitySourceInvalidation,
+ continuityLogPath,
+ listContinuityRecords,
+ paginateContinuityRecords,
+} from "../../../src/core/brain/continuity/store.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-continuity-store-"));
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("continuity store", () => {
+ test("appends redaction-safe records under the Brain continuity log", () => {
+ const record = appendContinuityRecord(vault, {
+ kind: "context_receipt",
+ createdAt: "2026-05-31T12:00:00Z",
+ sourceRefs: [
+ { id: "pref-alpha", path: "Brain/preferences/pref-alpha.md" },
+ ],
+ payload: {
+ query: "project setup",
+ text: "Keep this <private>do not persist</private> and token=secret-value",
+ },
+ });
+
+ expect(record.id).toStartWith("ctn_");
+ expect(record.payload).toEqual({
+ query: "project setup",
+ text: "Keep this ***PRIVATE*** and token=***REDACTED***",
+ });
+ expect(record.private).toBe(true);
+ expect(record.redacted).toBe(true);
+
+ const path = continuityLogPath(vault, "2026-05");
+ expect(existsSync(path)).toBe(true);
+ expect(readFileSync(path, "utf8")).toContain("context_receipt");
+
+ const listed = listContinuityRecords(vault, {
+ kind: "context_receipt",
+ sourceId: "pref-alpha",
+ });
+ expect(listed).toHaveLength(1);
+ expect(JSON.stringify(listed)).not.toContain("secret-value");
+ expect(JSON.stringify(listed)).not.toContain("do not persist");
+ });
+
+ test("paginates records with stable cursors", () => {
+ for (let index = 0; index < 3; index++) {
+ appendContinuityRecord(vault, {
+ kind: "recall_telemetry",
+ createdAt: `2026-05-31T12:00:0${index}Z`,
+ sourceRefs: [{ id: `query-${index}` }],
+ payload: { status: index === 2 ? "miss" : "hit", resultCount: index },
+ });
+ }
+
+ const first = paginateContinuityRecords(vault, { limit: 2 });
+ expect(first.records.map((record) => record.sourceRefs[0]!.id)).toEqual([
+ "query-0",
+ "query-1",
+ ]);
+ expect(first.nextCursor).not.toBeNull();
+
+ const second = paginateContinuityRecords(vault, {
+ limit: 2,
+ cursor: first.nextCursor!,
+ });
+ expect(second.records.map((record) => record.sourceRefs[0]!.id)).toEqual([
+ "query-2",
+ ]);
+ expect(second.nextCursor).toBeNull();
+ });
+
+ test("serializes appends with the brain sync lock", () => {
+ const path = continuityLogPath(vault, "2026-05");
+ const handle = acquireLockSync(path);
+ try {
+ expect(() =>
+ appendContinuityRecord(vault, {
+ kind: "context_receipt",
+ createdAt: "2026-05-31T12:00:00Z",
+ sourceRefs: [],
+ payload: { event: "locked" },
+ }),
+ ).toThrow("lock busy");
+ } finally {
+ handle.release();
+ }
+
+ const record = appendContinuityRecord(vault, {
+ kind: "context_receipt",
+ createdAt: "2026-05-31T12:00:01Z",
+ sourceRefs: [],
+ payload: { event: "unlocked" },
+ });
+ expect(record.id).toStartWith("ctn_");
+ });
+
+ test("records source invalidation markers without deleting history", () => {
+ appendContinuityRecord(vault, {
+ kind: "session_turn",
+ createdAt: "2026-05-31T12:00:00Z",
+ sourceRefs: [{ id: "session-a#turn-1", path: "sessions/a.jsonl" }],
+ payload: { role: "user", snippet: "Please remember this" },
+ });
+
+ const invalidation = appendContinuitySourceInvalidation(vault, {
+ createdAt: "2026-05-31T12:05:00Z",
+ source: { id: "session-a#turn-1", path: "sessions/a.jsonl" },
+ reason: "source-scoped forget dry run",
+ });
+
+ expect(invalidation.kind).toBe("source_invalidation");
+ const records = listContinuityRecords(vault, {
+ sourceId: "session-a#turn-1",
+ });
+ expect(records.map((record) => record.kind)).toEqual([
+ "session_turn",
+ "source_invalidation",
+ ]);
+ });
+});
diff --git a/tests/core/brain/pre-compact-extract.test.ts b/tests/core/brain/pre-compact-extract.test.ts
new file mode 100644
index 00000000..3d5ffbd0
--- /dev/null
+++ b/tests/core/brain/pre-compact-extract.test.ts
@@ -0,0 +1,70 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { listContinuityRecords } from "../../../src/core/brain/continuity/store.ts";
+import { extractPreCompactRecords } from "../../../src/core/brain/pre-compact-extract.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-pre-compact-extract-"));
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("pre-compact extraction", () => {
+ test("emits typed records with sanitized text and source turn refs", () => {
+ const result = extractPreCompactRecords(vault, {
+ createdAt: "2026-05-20T17:00:00.000Z",
+ host: "unit-test",
+ sessionId: "session-a",
+ turnStart: "turn-1",
+ turnEnd: "turn-3",
+ text: [
+ "Decision: Ship the receipt reader.",
+ "Commitment: Follow up with docs.",
+ "Outcome: Tests passed.",
+ "Rule: Keep telemetry opt-in.",
+ "Open question: Should presets be configurable?",
+ "Decision: Ignore inline image data:image/png;base64,QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=",
+ ].join("\n"),
+ });
+
+ expect(result.errors).toEqual([]);
+ expect(result.records.map((record) => record.payload["extract_type"])).toEqual([
+ "decision",
+ "commitment",
+ "outcome",
+ "rule",
+ "open_question",
+ "decision",
+ ]);
+ expect(result.records[0]!.sourceRefs.map((source) => source.id)).toEqual([
+ "session-a",
+ "turn-1..turn-3",
+ ]);
+ expect(JSON.stringify(result.records)).not.toContain("QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo");
+ expect(result.records[5]!.payload["text"]).toContain("[base64]");
+ });
+
+ test("is idempotent by session, turn range, type, and content hash", () => {
+ const input = {
+ createdAt: "2026-05-20T17:00:00.000Z",
+ host: "unit-test",
+ sessionId: "session-a",
+ turnStart: "turn-1",
+ turnEnd: "turn-2",
+ text: "Decision: Keep extraction deterministic.",
+ };
+
+ const first = extractPreCompactRecords(vault, input);
+ const second = extractPreCompactRecords(vault, input);
+
+ expect(first.records[0]!.id).toBe(second.records[0]!.id);
+ expect(listContinuityRecords(vault, { kind: "pre_compact_extract" })).toHaveLength(1);
+ });
+});
diff --git a/tests/core/brain/recall-telemetry.test.ts b/tests/core/brain/recall-telemetry.test.ts
new file mode 100644
index 00000000..e37fc869
--- /dev/null
+++ b/tests/core/brain/recall-telemetry.test.ts
@@ -0,0 +1,189 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { packContext } from "../../../src/core/brain/context-pack.ts";
+import { buildPreCompressPack } from "../../../src/core/brain/pre-compress-pack.ts";
+import { writePreference } from "../../../src/core/brain/preference.ts";
+import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../../src/core/brain/types.ts";
+import {
+ emitRecallTelemetry,
+ listRecallTelemetry,
+ summarizeRecallTelemetry,
+} from "../../../src/core/brain/recall-telemetry.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-recall-telemetry-"));
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("recall telemetry", () => {
+ test("emits redaction-safe recall telemetry records with source refs", () => {
+ const record = emitRecallTelemetry(vault, {
+ createdAt: "2026-05-20T15:00:00.000Z",
+ host: "unit-test",
+ mode: "search",
+ status: "ok",
+ durationMs: 42,
+ resultCount: 2,
+ topArtifacts: [
+ {
+ id: "pref-alpha",
+ path: join(vault, "Brain", "preferences", "pref-alpha.md"),
+ score: 0.9,
+ },
+ {
+ id: "note-bravo",
+ path: join(vault, "Daily", "2026-05-20.md"),
+ score: 0.5,
+ },
+ ],
+ gaps: ["missing_recent_decision"],
+ metadata: {
+ cache_hit: true,
+ raw: "public <private>secret-value</private>",
+ },
+ });
+
+ expect(record.id).toStartWith("ctn_");
+ expect(record.kind).toBe("recall_telemetry");
+ expect(record.sourceRefs.map((source) => source.id)).toEqual(["pref-alpha", "note-bravo"]);
+ expect(JSON.stringify(record.payload)).not.toContain("secret-value");
+ expect(record.payload).toMatchObject({
+ host: "unit-test",
+ mode: "search",
+ status: "ok",
+ duration_ms: 42,
+ result_count: 2,
+ gaps: ["missing_recent_decision"],
+ metadata: { cache_hit: true, raw: "public ***PRIVATE***" },
+ });
+ });
+
+ test("lists telemetry by mode/status and summarizes coverage gaps", () => {
+ emitRecallTelemetry(vault, {
+ createdAt: "2026-05-20T15:00:00.000Z",
+ host: "unit-test",
+ mode: "context_pack",
+ status: "ok",
+ durationMs: 5,
+ resultCount: 1,
+ topArtifacts: [{ id: "pref-alpha" }],
+ });
+ emitRecallTelemetry(vault, {
+ createdAt: "2026-05-20T15:01:00.000Z",
+ host: "unit-test",
+ mode: "context_pack",
+ status: "empty",
+ durationMs: 3,
+ resultCount: 0,
+ gaps: ["no_matching_context", "no_matching_context"],
+ });
+ emitRecallTelemetry(vault, {
+ createdAt: "2026-05-20T15:02:00.000Z",
+ host: "unit-test",
+ mode: "pre_compress",
+ status: "ok",
+ durationMs: 7,
+ resultCount: 1,
+ topArtifacts: [{ id: "pref-bravo" }],
+ });
+
+ const contextPack = listRecallTelemetry(vault, { mode: "context_pack" });
+ expect(contextPack.map((record) => record.payload["status"])).toEqual(["empty", "ok"]);
+
+ const summary = summarizeRecallTelemetry(vault, { host: "unit-test" });
+ expect(summary).toMatchObject({
+ total: 3,
+ by_mode: { context_pack: 2, pre_compress: 1 },
+ by_status: { ok: 2, empty: 1 },
+ total_results: 2,
+ empty_runs: 1,
+ gap_counts: { no_matching_context: 1 },
+ });
+ });
+
+ test("packContext can opt in to recall telemetry without changing defaults", () => {
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-alpha.md"),
+ [
+ "---",
+ "id: pref-alpha",
+ "topic: alpha",
+ "principle: Prefer crisp answers",
+ "tier: core",
+ "---",
+ "Body",
+ ].join("\n"),
+ );
+
+ const plain = packContext(vault, { maxTokens: 1000 });
+ expect(plain.telemetryId).toBeUndefined();
+
+ const instrumented = packContext(vault, {
+ maxTokens: 1000,
+ telemetry: { host: "unit-test", createdAt: "2026-05-20T16:00:00.000Z" },
+ });
+
+ expect(instrumented.telemetryId).toStartWith("ctn_");
+ const records = listRecallTelemetry(vault, { mode: "context_pack" });
+ expect(records).toHaveLength(1);
+ expect(records[0]!.payload).toMatchObject({
+ host: "unit-test",
+ mode: "context_pack",
+ status: "ok",
+ result_count: 1,
+ metadata: {
+ max_tokens: 1000,
+ tokens_used: instrumented.tokensUsed,
+ skipped_count: 0,
+ },
+ });
+ });
+
+ test("buildPreCompressPack can opt in to recall telemetry", () => {
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ writePreference(vault, {
+ slug: "bravo",
+ topic: "bravo",
+ principle: "Keep decisions explicit",
+ created_at: "2026-05-20T00:00:00.000Z",
+ unconfirmed_until: "2026-05-21T00:00:00.000Z",
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ evidenced_by: ["[[sig-2026-05-20-bravo]]"],
+ confirmed_at: "2026-05-20T01:00:00.000Z",
+ applied_count: 1,
+ violated_count: 0,
+ last_evidence_at: "2026-05-20T01:00:00.000Z",
+ confidence: BRAIN_CONFIDENCE.high,
+ confidence_value: 0.9,
+ });
+
+ const pack = buildPreCompressPack(vault, {
+ topK: 3,
+ telemetry: { host: "unit-test", createdAt: "2026-05-20T16:05:00.000Z" },
+ });
+
+ expect(pack.telemetryId).toStartWith("ctn_");
+ const records = listRecallTelemetry(vault, { mode: "pre_compress" });
+ expect(records).toHaveLength(1);
+ expect(records[0]!.payload).toMatchObject({
+ host: "unit-test",
+ mode: "pre_compress",
+ status: "ok",
+ result_count: 1,
+ metadata: {
+ top_k: 3,
+ total_chars: pack.totalChars,
+ active_head_included: false,
+ },
+ });
+ });
+});
diff --git a/tests/core/brain/session-recall.test.ts b/tests/core/brain/session-recall.test.ts
new file mode 100644
index 00000000..52fb34df
--- /dev/null
+++ b/tests/core/brain/session-recall.test.ts
@@ -0,0 +1,97 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ describeSessionRecall,
+ expandSessionRecall,
+ importSessionRecall,
+ searchSessionRecall,
+} from "../../../src/core/brain/session-recall.ts";
+import type { SessionTurn } from "../../../src/core/brain/sessions/types.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-session-recall-"));
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function turn(turnId: string, role: SessionTurn["role"], text: string): SessionTurn {
+ return {
+ turnId,
+ role,
+ text,
+ timestamp: `2026-05-20T17:00:0${turnId.slice(-1)}.000Z`,
+ };
+}
+
+describe("session recall DAG", () => {
+ test("imports raw turns and deterministic two-depth summary nodes idempotently", () => {
+ const turns = [
+ turn("t1", "user", "Need receipt search."),
+ turn("t2", "assistant", "Decision: build continuity receipts."),
+ turn("t3", "user", "Need session recall."),
+ turn("t4", "assistant", "Outcome: tests cover recall."),
+ ];
+
+ const first = importSessionRecall(vault, {
+ sessionId: "session-a",
+ turns,
+ summaryGroupSize: 2,
+ createdAt: "2026-05-20T17:00:00.000Z",
+ });
+ const second = importSessionRecall(vault, {
+ sessionId: "session-a",
+ turns,
+ summaryGroupSize: 2,
+ createdAt: "2026-05-20T17:00:00.000Z",
+ });
+
+ expect(first.rawTurns).toHaveLength(4);
+ expect(first.summaryNodes.map((record) => record.payload["depth"])).toEqual([1, 1, 2]);
+ expect(first.rawTurns.map((record) => record.id)).toEqual(
+ second.rawTurns.map((record) => record.id),
+ );
+ expect(describeSessionRecall(vault, { sessionId: "session-a" })).toMatchObject({
+ session_id: "session-a",
+ raw_turns: 4,
+ summary_nodes: 3,
+ depths: { "1": 2, "2": 1 },
+ });
+ });
+
+ test("searches bounded raw and summary hits and expands exact raw lineage", () => {
+ const imported = importSessionRecall(vault, {
+ sessionId: "session-a",
+ turns: [
+ turn("t1", "user", "Find continuity receipt details."),
+ turn("t2", "assistant", "Summary mentions receipts and tests."),
+ turn("t3", "user", "Unrelated turn."),
+ ],
+ summaryGroupSize: 2,
+ createdAt: "2026-05-20T17:00:00.000Z",
+ });
+
+ const search = searchSessionRecall(vault, {
+ query: "receipt",
+ sessionId: "session-a",
+ limit: 4,
+ });
+ expect(search.hits.some((hit) => hit.kind === "session_turn")).toBe(true);
+ expect(search.hits.some((hit) => hit.kind === "session_summary_node")).toBe(true);
+ expect(search.hits.every((hit) => hit.snippet.length <= 160)).toBe(true);
+
+ const expanded = expandSessionRecall(vault, {
+ id: imported.summaryNodes.find((record) => record.payload["depth"] === 2)!.id,
+ rawLimit: 2,
+ });
+ expect(expanded.immediate_sources).toHaveLength(2);
+ expect(expanded.raw_content.map((item) => item.turn_id)).toEqual(["t1", "t2"]);
+ expect(expanded.next_cursor).toBe("2");
+ });
+});
diff --git a/tests/mcp/context-pack-tool.test.ts b/tests/mcp/context-pack-tool.test.ts
index f0383ca3..eb2aa368 100644
--- a/tests/mcp/context-pack-tool.test.ts
+++ b/tests/mcp/context-pack-tool.test.ts
@@ -126,6 +126,51 @@ describe("brain_context_pack tool — round trip", () => {
expect(lanes.constraints.map((item) => item.id)).toContain("pref-constraint");
});
+ test("returns transform annotations when requested", async () => {
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-zulu.md"),
+ [
+ "---",
+ "id: pref-zulu",
+ "topic: t",
+ "principle: shared body",
+ "tier: core",
+ "created_at: 2026-05-02T00:00:00Z",
+ "---",
+ "",
+ "shared body",
+ ].join("\n"),
+ );
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-alpha.md"),
+ [
+ "---",
+ "id: pref-alpha",
+ "topic: t",
+ "principle: shared body",
+ "tier: core",
+ "created_at: 2026-05-01T00:00:00Z",
+ "---",
+ "",
+ "shared body",
+ ].join("\n"),
+ );
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const out = await callPack(server, {
+ max_tokens: 10_000,
+ cache_stable: true,
+ dedup_repeated: true,
+ });
+ const items = out["items"] as Array<Record<string, unknown>>;
+ expect(items.map((item) => item["id"])).toEqual(["pref-alpha", "pref-zulu"]);
+ expect(items[0]).toMatchObject({ original_rank: 2, stable_rank: 1 });
+ expect(items[1]).toMatchObject({
+ deduped_from: "pref-alpha",
+ reference_hint: "see pref-alpha",
+ });
+ });
+
test("rejects non-positive max_tokens via INVALID_PARAMS", async () => {
const server = new MCPServer({ vault, configPath });
await initialize(server);
diff --git a/tests/mcp/context-presets-tool.test.ts b/tests/mcp/context-presets-tool.test.ts
new file mode 100644
index 00000000..d7649f14
--- /dev/null
+++ b/tests/mcp/context-presets-tool.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, test } from "bun:test";
+
+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
+import { buildToolTable } from "../../src/mcp/tools.ts";
+
+async function initialize(server: MCPServer): Promise<void> {
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "context-presets-test", version: "0" },
+ },
+ });
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ method: "notifications/initialized",
+ });
+}
+
+async function callPresets(args: Record<string, unknown>): Promise<Record<string, unknown>> {
+ const server = new MCPServer({ vault: process.cwd(), configPath: null });
+ await initialize(server);
+ const response = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 9,
+ method: "tools/call",
+ params: { name: "brain_context_presets", arguments: args },
+ })) as { result: { content: ReadonlyArray<{ type: string; text: string }> } };
+ return JSON.parse(response.result.content[0]!.text);
+}
+
+describe("brain_context_presets tool registration", () => {
+ test("registered in the full tool table only", () => {
+ expect(
+ buildToolTable("full").find((tool) => tool.name === "brain_context_presets"),
+ ).toBeDefined();
+ expect(
+ buildToolTable("writer").find((tool) => tool.name === "brain_context_presets"),
+ ).toBeUndefined();
+ });
+});
+
+describe("brain_context_presets tool", () => {
+ test("shows, suggests, and diffs presets", async () => {
+ await expect(
+ callPresets({ operation: "show", preset_id: "tight-context" }),
+ ).resolves.toMatchObject({
+ id: "tight-context",
+ context_pack: { max_tokens: 4000 },
+ });
+ await expect(
+ callPresets({
+ operation: "suggest",
+ model: "claude-sonnet-4",
+ context_window_tokens: 200000,
+ }),
+ ).resolves.toMatchObject({ preset_id: "long-context", confidence: "high" });
+ await expect(
+ callPresets({
+ operation: "diff",
+ preset_id: "tight-context",
+ current: {
+ context_pack: { max_tokens: 9000 },
+ overrides: ["context_pack.max_tokens"],
+ },
+ }),
+ ).resolves.toMatchObject({
+ preset_id: "tight-context",
+ preserved_overrides: [{ path: "context_pack.max_tokens", current: 9000, preset: 4000 }],
+ });
+ });
+});
diff --git a/tests/mcp/context-receipts-tool.test.ts b/tests/mcp/context-receipts-tool.test.ts
new file mode 100644
index 00000000..dfea2652
--- /dev/null
+++ b/tests/mcp/context-receipts-tool.test.ts
@@ -0,0 +1,121 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { emitContextReceipt } from "../../src/core/brain/context-receipts.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
+import { buildToolTable } from "../../src/mcp/tools.ts";
+
+let tmp: string;
+let vault: string;
+let configHome: string;
+let configPath: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-context-receipts-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-context-receipts-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ for (const key of [
+ "VAULT_AGENT_NAME",
+ "VAULT_TIMEZONE",
+ "VAULT_DIR",
+ "OPEN_SECOND_BRAIN_CONFIG",
+ ]) {
+ savedEnv[key] = process.env[key];
+ delete process.env[key];
+ }
+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;
+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+ for (const [key, value] of Object.entries(savedEnv)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+});
+
+async function initialize(server: MCPServer): Promise<void> {
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "context-receipts-test", version: "0" },
+ },
+ });
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ method: "notifications/initialized",
+ });
+}
+
+async function callReceipts(
+ server: MCPServer,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const response = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 9,
+ method: "tools/call",
+ params: { name: "brain_context_receipts", arguments: args },
+ })) as { result: { content: ReadonlyArray<{ type: string; text: string }> } };
+ return JSON.parse(response.result.content[0]!.text);
+}
+
+describe("brain_context_receipts tool registration", () => {
+ test("registered in the full tool table", () => {
+ const tools = buildToolTable("full");
+ expect(tools.find((tool) => tool.name === "brain_context_receipts")).toBeDefined();
+ });
+
+ test("not registered in the writer-only tool table", () => {
+ const tools = buildToolTable("writer");
+ expect(tools.find((tool) => tool.name === "brain_context_receipts")).toBeUndefined();
+ });
+});
+
+describe("brain_context_receipts tool", () => {
+ test("lists summaries and shows a full receipt by id", async () => {
+ const receipt = emitContextReceipt(vault, {
+ options: {
+ host: "mcp-test",
+ trigger: "pre_compress",
+ createdAt: "2026-05-20T14:00:00.000Z",
+ sessionId: "session-mcp",
+ },
+ finalText: "pre-compress pack text",
+ items: [{ id: "pref-alpha", text: "Prefer crisp answers" }],
+ });
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+
+ const list = await callReceipts(server, {
+ operation: "list",
+ trigger: "pre_compress",
+ });
+ expect(list["total"]).toBe(1);
+ expect((list["receipts"] as Array<Record<string, unknown>>)[0]).toMatchObject({
+ id: receipt.id,
+ trigger: "pre_compress",
+ host: "mcp-test",
+ item_count: 1,
+ });
+
+ const show = await callReceipts(server, {
+ operation: "show",
+ id: receipt.id,
+ });
+ expect(show["id"]).toBe(receipt.id);
+ expect((show["payload"] as Record<string, unknown>)["session_id"]).toBe("session-mcp");
+ });
+});
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index 374d72b8..16eb6239 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -220,6 +220,14 @@ describe("tool listing", () => {
"brain_operator_summary",
// Pre-compress injection pack (added in v0.20.0).
"brain_pre_compress_pack",
+ // Context continuity and receipts (added in v0.29.0).
+ "brain_context_receipts",
+ "brain_recall_telemetry",
+ "brain_context_presets",
+ "brain_pre_compact_extract",
+ "brain_session_grep",
+ "brain_session_describe",
+ "brain_session_expand",
// Pay Memory (unchanged).
"payment_memory_init",
"payment_receipt_append",
@@ -482,7 +490,8 @@ describe("stdio loop", () => {
// + second_brain_capabilities (v0.23.0) = 47.
// + 9 schema admin tools + brain_watchdog = 57.
// + brain_recall_gate (v0.27.0) = 58.
- expect(list.result.tools.length).toBe(58);
+ // + 7 context continuity/session recall tools (v0.29.0) = 65.
+ expect(list.result.tools.length).toBe(65);
});
test("returns parse error for invalid JSON", async () => {
diff --git a/tests/mcp/pre-compact-extract-tool.test.ts b/tests/mcp/pre-compact-extract-tool.test.ts
new file mode 100644
index 00000000..f05cbcd9
--- /dev/null
+++ b/tests/mcp/pre-compact-extract-tool.test.ts
@@ -0,0 +1,77 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
+import { buildToolTable } from "../../src/mcp/tools.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-mcp-pre-compact-extract-"));
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+async function initialize(server: MCPServer): Promise<void> {
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "pre-compact-extract-test", version: "0" },
+ },
+ });
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ method: "notifications/initialized",
+ });
+}
+
+async function callExtract(args: Record<string, unknown>): Promise<Record<string, unknown>> {
+ const server = new MCPServer({ vault, configPath: null });
+ await initialize(server);
+ const response = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 9,
+ method: "tools/call",
+ params: { name: "brain_pre_compact_extract", arguments: args },
+ })) as { result: { content: ReadonlyArray<{ type: string; text: string }> } };
+ return JSON.parse(response.result.content[0]!.text);
+}
+
+describe("brain_pre_compact_extract tool registration", () => {
+ test("registered in the full tool table only", () => {
+ expect(
+ buildToolTable("full").find((tool) => tool.name === "brain_pre_compact_extract"),
+ ).toBeDefined();
+ expect(
+ buildToolTable("writer").find((tool) => tool.name === "brain_pre_compact_extract"),
+ ).toBeUndefined();
+ });
+});
+
+describe("brain_pre_compact_extract tool", () => {
+ test("emits sanitized typed continuity records idempotently", async () => {
+ const args = {
+ session_id: "session-mcp",
+ turn_start: "turn-1",
+ turn_end: "turn-2",
+ text: "Rule: Stay opt-in.\nCommitment: Remove data:image/png;base64,QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=",
+ };
+ const first = await callExtract(args);
+ const second = await callExtract(args);
+
+ expect(first).toMatchObject({ count: 2, errors: [] });
+ expect(second).toMatchObject({ count: 2, errors: [] });
+ expect((first.records as Array<{ id: string }>).map((record) => record.id)).toEqual(
+ (second.records as Array<{ id: string }>).map((record) => record.id),
+ );
+ expect(JSON.stringify(first)).not.toContain("QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo");
+ });
+});
diff --git a/tests/mcp/recall-telemetry-tool.test.ts b/tests/mcp/recall-telemetry-tool.test.ts
new file mode 100644
index 00000000..5ab81225
--- /dev/null
+++ b/tests/mcp/recall-telemetry-tool.test.ts
@@ -0,0 +1,216 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { emitRecallTelemetry } from "../../src/core/brain/recall-telemetry.ts";
+import { writePreference } from "../../src/core/brain/preference.ts";
+import {
+ BRAIN_CONFIDENCE,
+ BRAIN_PREFERENCE_STATUS,
+} from "../../src/core/brain/types.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import {
+ JSONRPC_VERSION,
+ MCPServer,
+ PROTOCOL_VERSION,
+} from "../../src/mcp/index.ts";
+import { buildToolTable } from "../../src/mcp/tools.ts";
+
+let tmp: string;
+let vault: string;
+let configHome: string;
+let configPath: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-recall-telemetry-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-recall-telemetry-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ for (const key of [
+ "VAULT_AGENT_NAME",
+ "VAULT_TIMEZONE",
+ "VAULT_DIR",
+ "OPEN_SECOND_BRAIN_CONFIG",
+ ]) {
+ savedEnv[key] = process.env[key];
+ delete process.env[key];
+ }
+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;
+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+ for (const [key, value] of Object.entries(savedEnv)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+});
+
+async function initialize(server: MCPServer): Promise<void> {
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "recall-telemetry-test", version: "0" },
+ },
+ });
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ method: "notifications/initialized",
+ });
+}
+
+async function callTelemetry(
+ server: MCPServer,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ return callTool(server, "brain_recall_telemetry", args);
+}
+
+async function callTool(
+ server: MCPServer,
+ name: string,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const response = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 9,
+ method: "tools/call",
+ params: { name, arguments: args },
+ })) as { result: { content: ReadonlyArray<{ type: string; text: string }> } };
+ return JSON.parse(response.result.content[0]!.text);
+}
+
+describe("brain_recall_telemetry tool registration", () => {
+ test("registered in the full tool table only", () => {
+ expect(
+ buildToolTable("full").find(
+ (tool) => tool.name === "brain_recall_telemetry",
+ ),
+ ).toBeDefined();
+ expect(
+ buildToolTable("writer").find(
+ (tool) => tool.name === "brain_recall_telemetry",
+ ),
+ ).toBeUndefined();
+ });
+});
+
+describe("brain_recall_telemetry tool", () => {
+ test("lists records and summarizes recall gaps", async () => {
+ emitRecallTelemetry(vault, {
+ createdAt: "2026-05-20T16:00:00.000Z",
+ host: "mcp-test",
+ mode: "context_pack",
+ status: "ok",
+ durationMs: 4,
+ resultCount: 1,
+ topArtifacts: [{ id: "pref-alpha" }],
+ });
+ emitRecallTelemetry(vault, {
+ createdAt: "2026-05-20T16:01:00.000Z",
+ host: "mcp-test",
+ mode: "search",
+ status: "empty",
+ durationMs: 9,
+ resultCount: 0,
+ gaps: ["missing_recent_decision"],
+ });
+
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+
+ const list = await callTelemetry(server, {
+ operation: "list",
+ mode: "context_pack",
+ });
+ expect(list["total"]).toBe(1);
+ expect(
+ (list["records"] as Array<Record<string, unknown>>)[0]!["payload"],
+ ).toMatchObject({
+ mode: "context_pack",
+ result_count: 1,
+ });
+
+ const summary = await callTelemetry(server, {
+ operation: "summary",
+ host: "mcp-test",
+ });
+ expect(summary).toMatchObject({
+ total: 2,
+ by_mode: { context_pack: 1, search: 1 },
+ by_status: { ok: 1, empty: 1 },
+ total_results: 1,
+ empty_runs: 1,
+ gap_counts: { missing_recent_decision: 1 },
+ });
+ });
+
+ test("context-pack and pre-compress tools can opt in to receipts and telemetry", async () => {
+ writePreference(vault, {
+ slug: "alpha",
+ topic: "alpha",
+ principle: "Prefer crisp answers",
+ created_at: "2026-05-20T00:00:00.000Z",
+ unconfirmed_until: "2026-05-21T00:00:00.000Z",
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ evidenced_by: ["[[sig-2026-05-20-alpha]]"],
+ confirmed_at: "2026-05-20T01:00:00.000Z",
+ applied_count: 1,
+ violated_count: 0,
+ last_evidence_at: "2026-05-20T01:00:00.000Z",
+ confidence: BRAIN_CONFIDENCE.high,
+ confidence_value: 0.9,
+ });
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+
+ const contextPack = await callTool(server, "brain_context_pack", {
+ max_tokens: 10000,
+ receipt: true,
+ receipt_host: "mcp-test",
+ telemetry: true,
+ telemetry_host: "mcp-test",
+ });
+ expect(contextPack["receipt_id"]).toStartWith("ctn_");
+ expect(contextPack["telemetry_id"]).toStartWith("ctn_");
+
+ const preCompress = await callTool(server, "brain_pre_compress_pack", {
+ receipt: true,
+ receipt_host: "mcp-test",
+ telemetry: true,
+ telemetry_host: "mcp-test",
+ });
+ expect(preCompress["receipt_id"]).toStartWith("ctn_");
+ expect(preCompress["telemetry_id"]).toStartWith("ctn_");
+
+ const receipts = await callTool(server, "brain_context_receipts", {
+ operation: "list",
+ host: "mcp-test",
+ });
+ expect(receipts["total"]).toBe(2);
+ expect(
+ (receipts["receipts"] as Array<Record<string, unknown>>)
+ .map((receipt) => receipt["trigger"])
+ .toSorted(),
+ ).toEqual(["context_pack", "pre_compress"]);
+
+ const summary = await callTelemetry(server, {
+ operation: "summary",
+ host: "mcp-test",
+ });
+ expect(summary).toMatchObject({
+ total: 2,
+ by_mode: { context_pack: 1, pre_compress: 1 },
+ by_status: { ok: 2 },
+ });
+ });
+});
diff --git a/tests/mcp/search.test.ts b/tests/mcp/search.test.ts
index 75d15414..4c0c1bb7 100644
--- a/tests/mcp/search.test.ts
+++ b/tests/mcp/search.test.ts
@@ -17,6 +17,7 @@ import { indexVault } from "../../src/core/search/indexer.ts";
import { resolveSearchConfig } from "../../src/core/search/index.ts";
import { LATEST_SCHEMA_VERSION } from "../../src/core/search/schema.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import { listRecallTelemetry } from "../../src/core/brain/recall-telemetry.ts";
let tmp: string;
let vault: string;
@@ -130,6 +131,30 @@ test("brain_search happy path returns paths and respects 600-char content cap",
expect((results[0] as Record<string, unknown>)["keywordScore"]).toBeUndefined();
});
+test("brain_search can opt in to recall telemetry", async () => {
+ writeMd("notes/telemetry.md", "# Telemetry\n\nrecall telemetry records search coverage.");
+ const cfg = resolveSearchConfig({ vault, configPath });
+ await indexVault(cfg);
+
+ const server = makeServer();
+ await initialize(server);
+ const resp = await call(server, "brain_search", {
+ query: "telemetry",
+ limit: 5,
+ telemetry: true,
+ telemetry_host: "mcp-search-test",
+ });
+ const body = extractToolResult(resp);
+ expect(body["telemetry_id"]).toStartWith("ctn_");
+
+ const records = listRecallTelemetry(vault, {
+ mode: "search",
+ host: "mcp-search-test",
+ });
+ expect(records).toHaveLength(1);
+ expect(records[0]!.payload).toMatchObject({ status: "ok", result_count: 1 });
+});
+
test("brain_search accepts structured query_document", async () => {
writeMd("notes/final.md", "# Final\n\nrelease notes mention recall diagnostics.");
writeMd("notes/draft.md", "# Draft\n\ndraft release notes mention recall diagnostics.");
diff --git a/tests/mcp/session-recall-tool.test.ts b/tests/mcp/session-recall-tool.test.ts
new file mode 100644
index 00000000..6d2b2d54
--- /dev/null
+++ b/tests/mcp/session-recall-tool.test.ts
@@ -0,0 +1,107 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { importSessionRecall } from "../../src/core/brain/session-recall.ts";
+import type { SessionTurn } from "../../src/core/brain/sessions/types.ts";
+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
+import { buildToolTable } from "../../src/mcp/tools.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-mcp-session-recall-"));
+ const turns: SessionTurn[] = [
+ {
+ turnId: "t1",
+ role: "user",
+ timestamp: "2026-05-20T17:00:01.000Z",
+ text: "Need receipt search.",
+ },
+ {
+ turnId: "t2",
+ role: "assistant",
+ timestamp: "2026-05-20T17:00:02.000Z",
+ text: "Receipt summary.",
+ },
+ ];
+ importSessionRecall(vault, {
+ sessionId: "session-mcp",
+ turns,
+ summaryGroupSize: 2,
+ createdAt: "2026-05-20T17:00:00.000Z",
+ });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+async function initialize(server: MCPServer): Promise<void> {
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "session-recall-test", version: "0" },
+ },
+ });
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ method: "notifications/initialized",
+ });
+}
+
+async function callTool(
+ name: string,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const server = new MCPServer({ vault, configPath: null });
+ await initialize(server);
+ const response = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 9,
+ method: "tools/call",
+ params: { name, arguments: args },
+ })) as { result: { content: ReadonlyArray<{ type: string; text: string }> } };
+ return JSON.parse(response.result.content[0]!.text);
+}
+
+describe("session recall MCP tool registration", () => {
+ test("registered in the full tool table only", () => {
+ for (const name of ["brain_session_grep", "brain_session_describe", "brain_session_expand"]) {
+ expect(buildToolTable("full").find((tool) => tool.name === name)).toBeDefined();
+ expect(buildToolTable("writer").find((tool) => tool.name === name)).toBeUndefined();
+ }
+ });
+});
+
+describe("session recall MCP tools", () => {
+ test("grep, describe, and expand imported session recall records", async () => {
+ const description = await callTool("brain_session_describe", {
+ session_id: "session-mcp",
+ });
+ expect(description).toMatchObject({ raw_turns: 2, summary_nodes: 1 });
+
+ const grep = await callTool("brain_session_grep", {
+ query: "receipt",
+ session_id: "session-mcp",
+ });
+ expect(
+ (grep.hits as Array<{ kind: string }>).some((hit) => hit.kind === "session_summary_node"),
+ ).toBe(true);
+
+ const summary = (grep.hits as Array<{ id: string; kind: string }>).find(
+ (hit) => hit.kind === "session_summary_node",
+ )!;
+ const expanded = await callTool("brain_session_expand", {
+ id: summary.id,
+ raw_limit: 1,
+ });
+ expect(expanded).toMatchObject({ next_cursor: "1" });
+ expect(expanded.raw_content).toHaveLength(1);
+ });
+});