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: Token Diet - budgeted injection, reminder cadence, consolidated MCP surface (#65)
Sol Aitken5066e7106bed
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 6e493f74..5646169e 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.33.0",+ "version": "0.34.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.jsonindex c2a93651..c8064d4a 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.33.0",+ "version": "0.34.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.mdindex ffe55a52..19a18404 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,84 @@ 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.34.0] - 2026-06-02++Token Diet: six changes that cut what an agent pays in context before it does+any work - a broken post-compaction injection fixed, the session preamble+budgeted and deduplicated, the per-edit reminder compressed to a nudge, three+consolidated read tools replacing seventeen, hard description caps with a+contract guard, and preview budgets on by default. All deterministic; the+behavior of every consolidated view is byte-identical to its predecessor.++### Fixed++- **Post-compaction preference injection.** Current Claude Code has no+ `PostCompact` hook event; emitting `additionalContext` under that name was+ rejected by the hook output schema, silently dropping the re-injection and+ echoing the full payload into a validation error. `active-inject` now emits+ only under a default-closed allowlist of context-bearing event names+ (`SessionStart`, `UserPromptSubmit`), and the post-compaction path is the+ SessionStart `compact` matcher. A contract test pins the allowlist.+- **Frontmatter escape amplification.** The YAML-like parser now unescapes+ double-quoted scalars symmetrically with the formatter, so+ parse -> format cycles are byte-stable instead of doubling backslashes on+ every rewrite - the root cause of the `\\\"` chains observed in live+ preference frontmatter. Principle text is additionally sanitised at every+ write seam (leaked tool-call XML fragments cut, escape chains collapsed),+ `brain_doctor` warns about files corrupted before the fix+ (`principle-corrupted`), and `o2b brain upgrade --apply` repairs them once,+ idempotently, behind the usual pre-apply snapshot.++### Added++- **Budgeted active.md injection.** The SessionStart hook drops the+ provenance frontmatter and fits the injected body into a character budget+ (default 8,000 chars; `active.inject_budget_chars` in `_brain.yaml`).+ Sections drop deterministically - recently retired first, then quarantine,+ then most-applied - and a one-line notice points the agent at+ `brain_context` for the full set. The `Most-applied (Nd)` section now+ renders id + scope + count one-liners; the principle bodies already appear+ verbatim under `Confirmed`, and the duplication was 31% of the injected+ bytes on a real vault. Backed by a shared pure section-aware text-budget+ core.+- **Once-per-session reminder cadence.** The ~1.3KB post-write reminder -+ the single largest recurring token cost of a long coding session - now+ shows its full text once per Claude Code session and a 181-char nudge on+ later writes (marker keyed by `session_id`, 48h opportunistic pruning,+ fail-soft to the full text on any IO problem; Codex one-shot runs always+ get the full text).+- **Consolidated read tools.** `brain_brief`+ (`view: morning | daily | weekly | monthly | operator | digest`),+ `brain_analytics`+ (`view: timeline | attention_flows | belief_evolution | concept_synthesis`),+ and `schema_inspect`+ (`view: graph | lint | stats | orphans | explain_type | active_pack | packs`)+ replace three overlapping families; dispatch goes to the exact predecessor+ handlers, locked by per-view equality tests. The 18 predecessor names stay+ callable through `tools/call` as deprecated aliases for at least one minor+ release but are hidden from `tools/list`, so clients stop paying for+ schemas slated for removal. `brain_recurrence` stays standalone - its+ learn/forget operations are writes, not analytics.+- **Registry guard.** Tool descriptions cap at 300 chars and per-property+ schema descriptions at 160, enforced by a contract test; long-form guidance+ moved to `docs/mcp.md` and a rewritten terse `initialize.instructions`+ (5.4KB to 1.6KB). Preview budgets flip from opt-in to default: nine more+ verbose read tools park oversized results in the artifact store, and every+ remaining budget-less tool must hold an explicit exempt-list entry with a+ reason. `scripts/measure-token-surface.ts` reports the advertised surface,+ hidden-alias overhead, instructions size, and the budgeted active.md+ injection so regressions stay visible.++### Notes++- Measured on the live vault: SessionStart injection 16,550 -> 8,012 chars+ (-52%); advertised tool count 71 -> 56 with 18 aliases hidden;+ `initialize.instructions` 5,434 -> 1,630 chars. The serialized schema+ surface of the advertised tools is 43,790 chars including output schemas.+- MCP clients calling the old per-view tool names keep working unchanged;+ migrate to the consolidated tools before the aliases are removed in a+ future minor release.+## [0.33.0] - 2026-06-02Recall Trust Suite: five features that make recall something an agent can@@ -3910,6 +3988,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.34.0]: https://github.com/itechmeat/open-second-brain/compare/v0.33.0...v0.34.0[0.33.0]: https://github.com/itechmeat/open-second-brain/compare/v0.32.1...v0.33.0[0.32.1]: https://github.com/itechmeat/open-second-brain/compare/v0.32.0...v0.32.1[0.32.0]: https://github.com/itechmeat/open-second-brain/compare/v0.31.2...v0.32.0diff --git a/README.md b/README.mdindex 19d111ee..a9729512 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.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. The v0.33.0 surface adds the Recall Trust Suite: relation-aware recall polarity for typed memory edges, an explicit retrieval feedback loop with bounded learned weights (`o2b search feedback` / `weights`, MCP `brain_recall_feedback`), time-aware recall (`--since` / `--until` with natural-language ranges), verified multi-record recall (per-token union records, IDF-weighted coverage, rare-term abstention), and a search-completeness verdict with a false-absence guard.+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. The v0.33.0 surface adds the Recall Trust Suite: relation-aware recall polarity for typed memory edges, an explicit retrieval feedback loop with bounded learned weights (`o2b search feedback` / `weights`, MCP `brain_recall_feedback`), time-aware recall (`--since` / `--until` with natural-language ranges), verified multi-record recall (per-token union records, IDF-weighted coverage, rare-term abstention), and a search-completeness verdict with a false-absence guard. The v0.34.0 surface adds the Token Diet: a budgeted SessionStart injection of `Brain/active.md` (default 8,000 chars, `active.inject_budget_chars`) with the post-compaction path moved to the supported SessionStart `compact` matcher, a once-per-session post-write reminder cadence, frontmatter escape-amplification fixed at the parser with a one-shot `brain upgrade --apply` repair for already-corrupted preference files, three consolidated read tools (`brain_brief`, `brain_analytics`, `schema_inspect`) with 18 hidden deprecated aliases, registry description caps with a contract guard, preview budgets by default, and a `scripts/measure-token-surface.ts` report.## CLIdiff --git a/docs/brainstorm/token-diet/cli-output/claude.md b/docs/brainstorm/token-diet/cli-output/claude.mdnew file mode 100644index 00000000..a6dfb2ee--- /dev/null+++ b/docs/brainstorm/token-diet/cli-output/claude.md@@ -0,0 +1,40 @@+### Variant 1: Shared budget kernel + registry guard seam (extract-and-reuse)++- **Approach**: Extract two reusable deterministic primitives early, then plug all six children into them. (a) A `text-budget` core lifted from `pre-compress-pack.ts` head-budget logic, used by both active.md slimming (child 2) and the hook reminder compaction (child 3); (b) a `registry-guard` seam over `buildToolTable` that enforces the description cap (child 5) and the preview-budget allowlist (child 6) from the same enumeration the contract test already pins. Tool consolidation (child 4) and the PostCompact bugfix (child 1) stay as standalone slices that consume these primitives but carry their own logic.+- **Trade-offs**:+ - Pro: One truncation implementation → determinism/idempotency property is proven once and inherited everywhere (satisfies the idempotent-write and identical-input constraints).+ - Pro: Description cap and preview allowlist share one registry walk, so both guard tests key off the existing sorted-name+count contract — low test sprawl.+ - Pro: Children stay independently shippable (one PR = one CHANGELOG version); P4 bugfix and P2 guards don't block each other.+ - Con: Two distinct seams (text vs registry) means the "shared infrastructure" is split, not unified — some conceptual overhead deciding where a change lands.+ - Con: Consolidation (child 4) and hooks (1–3) don't benefit from the registry seam, so coordination across the MCP/hook boundary is still manual.+- **Complexity**: medium+- **Risk**: low++### Variant 2: Independent priority-ordered vertical slices++- **Approach**: Treat each of the six children as a self-contained PR with no new shared abstractions, sequenced strictly by priority (P4 bugfix → P3 active.md/reminder/consolidation → P2 cap/preview). Each slice copies or inlines whatever budgeting/guard logic it needs locally; the only shared touch-point is the existing registry contract test, updated per slice.+- **Trade-offs**:+ - Pro: Fastest path to landing the P4 PostCompact bugfix and the silent-16KB-stdout leak with zero dependency on other work.+ - Pro: Minimal blast radius per PR; easiest review and rollback; CHANGELOG mapping is trivially one-per-child.+ - Pro: No upfront design cost; no risk of an over-built abstraction.+ - Con: Truncation/head-budget logic gets duplicated between active.md (child 2) and the reminder (child 3) — two places to keep deterministic, violating the single-source idempotency intent.+ - Con: Description cap (5) and preview allowlist (6) each grow their own registry walk and guard test → drift risk between two contract tests.+ - Con: Highest long-term maintenance; the duplicated determinism logic is exactly the kind of thing the audit is trying to reduce.+- **Complexity**: small+- **Risk**: medium++### Variant 3: Declarative tool-registry manifest + mirrored injection-budget module++- **Approach**: Introduce a single declarative manifest describing every MCP tool (capped description, preview-budget allowlist entry + reason, deprecation-alias mapping, consolidation group/param), and derive the serialized registry, both guard tests, the alias delegation, and the consolidated `brain_brief`/`brain_analytics`/`schema` dispatch from that one data model (children 4, 5, 6). A parallel `injection-budget` module owns all hook/SessionStart/PostCompact rendering with deterministic truncation (children 1, 2, 3), mirroring the manifest's budget philosophy on the hook side.+- **Trade-offs**:+ - Pro: Consolidation, description diet, and preview budget all fall out of one source of truth — adding a tool forces an explicit manifest entry (the "flip the default / explicit allowlist with reason" requirement becomes structural, not a test afterthought).+ - Pro: Strongest guarantee against future regression; the registry contract becomes a projection of the manifest.+ - Pro: Cleanly separates the two real domains (tool surface vs context injection) into two owned modules.+ - Con: Large upfront refactor of `tools.ts` + the 3,592-line `brain-tools.ts` to route definitions through a manifest — high churn, harder review, more chance of perturbing the sorted-name+count contract mid-flight.+ - Con: Couples the four MCP-surface children into one big structural change, working against one-PR-per-version and against landing the P4 bugfix quickly.+ - Con: Risk of over-engineering relative to a *static* surface reduction — and the manifest could be mistaken for the adaptive-selection work explicitly deferred to t_20dcb192.+- **Complexity**: large+- **Risk**: high++### Recommended: Variant 1+**Rationale**: It captures the one genuinely shared concern the audit exposes — deterministic, idempotent truncation reused by both active.md and the post-write reminder — without forcing the four MCP-surface children into a single high-churn manifest refactor that endangers the pinned registry contract and the one-PR-per-version rule. The two thin seams (text-budget kernel, registry guard) give the P2 guard tests a single enumeration to key off while keeping the P4 bugfix and consolidation independently shippable, fitting the project's strict TDD, fail-soft hook, and deprecation-window constraints far better than either the duplication of Variant 2 or the over-build of Variant 3.diff --git a/docs/brainstorm/token-diet/cli-output/prompt.md b/docs/brainstorm/token-diet/cli-output/prompt.mdnew file mode 100644index 00000000..10cb6805--- /dev/null+++ b/docs/brainstorm/token-diet/cli-output/prompt.md@@ -0,0 +1,78 @@+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++Epic: MCP/hooks token diet — cut per-session context overhead (kanban t_5e6826f3, six children).++Audit of 2026-06-02 (live vault, serialized tool registry):++- 71 MCP tools serialize to 44,912 chars (~12K tokens) of schemas; median ~140 tokens/tool but the top descriptions are 4x over median (payment_receipt_append 2,901 chars; brain_context_pack 2,350; brain_search 1,966; brain_pre_compress_pack 1,566; brain_feedback 1,493).+- SessionStart hook injects Brain/active.md verbatim: 16,550 bytes (~4.5K tokens) per session; 5.2KB (31%) duplicates full principle texts in the "Most-applied (30d)" section (already listed verbatim under "Confirmed"); several stored preference files carry multi-level backslash-escaping artifacts plus leaked tool-call XML fragments (`</principle>\n<parameter name="scope">...`) written at signal-recording time.+- PostCompact active-inject is rejected by the current Claude Code hook output schema (hookSpecificOutput.additionalContext is accepted only for UserPromptSubmit / PostToolUse / PostToolBatch) — preference re-injection after compaction is silently broken AND the validation error echoes the full 16KB payload to stdout.+- hooks/post-write-reminder.ts injects ~1.3KB (~350 tokens) after EVERY successful Write/Edit/MultiEdit/apply_patch — the single largest recurring cost over a long coding session.+- MCP preview budget (MCP_PREVIEW_BUDGET=2000 chars + artifact store + brain_artifact_get) covers only 9 of 71 tools; unbudgeted verbose read tools include brain_query, brain_audit, brain_backlinks, brain_unlinked_mentions, second_brain_query, schema_graph, brain_session_grep, brain_session_expand, brain_recall_telemetry.++Six child tasks:++1. (P4, bugfix) Fix PostCompact active-inject rejected by Claude Code hook schema. Either inject via a supported mechanism or suppress output on PostCompact; keep Codex runtime path intact; add a hook-output contract test pinning which event names may carry additionalContext.+2. (P3) Slim active.md injection: render Most-applied as one-liners (pref id + scope + applied count, no duplicated principle bodies); fix escaping corruption at the write source plus a one-shot cleanup/heal for existing files; add a hard character budget for the injected body with deterministic truncation order (reuse head-budget logic from brain_pre_compress_pack). Target: live vault active.md shrinks >= 35%.+3. (P3) Compress post-write-reminder: full reminder text once per session (it teaches the contract), short <= 200-char nudge afterwards; session-scoped state must be best-effort and fail-soft; Codex one-shot runtime keeps full text always.+4. (P3) Consolidate overlapping MCP read tools 71 -> ~40: six summary tools (brain_morning_brief, brain_daily_brief, brain_weekly_synthesis, brain_monthly_review, brain_operator_summary, brain_digest) -> one brain_brief with window/audience params; five analytics tools (brain_timeline, brain_recurrence, brain_attention_flows, brain_belief_evolution, brain_concept_synthesis) -> one brain_analytics with view param; seven schema read tools -> one schema tool with verb param (schema_apply_mutations stays separate, it writes). Old names remain as deprecated delegating aliases for >= 1 minor release.+5. (P2) Tool description diet: cap descriptions at ~300 chars (what + when), move parameter nuances to per-property schema descriptions and long-form guidance to server instructions/docs; registry guard test fails when any description exceeds the cap.+6. (P2) Extend preview budget: opt the listed verbose read tools into MCP_PREVIEW_BUDGET; flip the default — a registry test enumerates tools WITHOUT a budget and requires an explicit allowlist entry with a reason.++# Project context++Open Second Brain — TypeScript on Bun. Local-first Markdown/Obsidian vault with deterministic agent memory (preferences, signals, dream learning pass), SQLite FTS5+vec search, MCP server (stdio) with full/writer scopes, CLI `o2b`, Claude Code plugin with lifecycle hooks (SessionStart/PostCompact/PostToolUse/Stop), Codex support via the same o2b-hook entry.++Recent commits:+c494fd8 feat(search): Recall Trust Suite - relation polarity, learned weights, time-aware and verified recall (#64)+23ff4fb refactor(hermes): single intentional self-bootstrap for the plugin entrypoint (#63)+0952dfc feat: become a native Hermes memory provider (#62)+6fbab0b feat: hands-off post-upgrade migration (v0.31.2) (#61)+496dd2d fix: make plugin updates self-healing (v0.31.1) (#60)++Related files:+- src/mcp/tools.ts (buildToolTable, ToolDefinition, ToolScope full/writer)+- src/mcp/brain-tools.ts (3,592 lines; most brain_* tool definitions)+- src/mcp/search-tools.ts, src/mcp/schema-tools.ts, src/mcp/pay-memory-tools.ts, src/mcp/watchdog-tools.ts+- src/mcp/preview-budget.ts (MCP_PREVIEW_BUDGET seam), src/mcp/artifact-store.ts+- src/mcp/instructions.ts (full ~5.4KB + writer instructions)+- hooks/active-inject.ts, hooks/post-write-reminder.ts, hooks/stop-log-guardrail.ts, hooks/session-capture.ts, hooks/lib/messages.ts, hooks/lib/detect.ts (runtime detection claudecode/codex/unknown), hooks/hooks.json+- src/core/brain/active.ts (regenerateActive renders active.md), src/core/brain/most-applied.ts+- src/core/brain/preference.ts (parse/write preference frontmatter), src/core/brain/signal.ts+- src/core/brain/pre-compress-pack.ts (existing head-budget logic), src/core/brain/text/tokenizer.ts (estimateTokens)+- src/core/brain/doctor.ts (invariant checks), src/core/brain/heal-run.ts+- tests/mcp/mcp.test.ts (registry contract: sorted tool-name list + count)++Conventions:+- Strict TDD, bun test; oxlint baseline 111 warnings (must not grow); oxfmt formatter; tsc typecheck; `bun run validate` aggregates.+- Conventional commits, one PR = one CHANGELOG version; deterministic pure-function cores with thin IO shells; no LLM in deterministic paths.+- Hooks are fail-soft: never exit 2, never block the runtime; messages live in hooks/lib/messages.ts; runtime detection via payload shape.+- MCP registry contract test pins sorted tool names + count; output contracts validated via assertOutputContract.+- Public artifacts use the full product name "Open Second Brain"; no exclamation marks in docs.++Constraints:+- Do not break existing MCP clients abruptly: deprecated tool names must keep working for at least one minor release.+- Writer-scope surface (5 tools) must stay unchanged.+- Hook resilience contract: any internal problem -> warn on stderr and exit 0.+- No new external dependencies.+- Determinism: identical inputs produce identical rendered bodies (active.md idempotent-write property must survive).+- This is a static surface reduction; a separate task (t_20dcb192) covers adaptive per-request tool selection — do not design that here.++# 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/token-diet/design.md b/docs/brainstorm/token-diet/design.mdnew file mode 100644index 00000000..aa3e7626--- /dev/null+++ b/docs/brainstorm/token-diet/design.md@@ -0,0 +1,70 @@+# Token diet - cut per-session context overhead of the MCP surface and hooks++**Status:** draft+**Author:** claude-dev-agent (via feature-release-playbook)+**Audience:** implementation++## Problem statement++The Open Second Brain plugin spends context tokens before an agent does any work, and keeps spending them on every file edit. A 2026-06-02 audit measured: 71 MCP tools serializing to 44,912 chars (~12K tokens); a 16,550-byte `Brain/active.md` injected verbatim on every SessionStart with 31% internal duplication and escaping corruption; a ~1.3KB reminder injected after every successful Write/Edit; and a PostCompact hook whose output the current Claude Code rejects outright - the re-injection silently fails while the validation error echoes the full 16KB payload to stdout. The preview-budget seam that protects context from oversized tool results covers only 9 of 71 tools.++## Scope++Six kanban children under epic t_5e6826f3, shipped as one PR / one release:++1. **PostCompact hook fix** (t_a1602738, P4 bugfix). Current Claude Code has no `PostCompact` hook event at all; `SessionStart` supports a `compact` matcher instead (verified against https://code.claude.com/docs/en/hooks on 2026-06-02). Move re-injection to `SessionStart` with matcher `startup|resume|clear|compact`; teach `active-inject.ts` to emit `additionalContext` only under event names known to accept it (`SessionStart`, `UserPromptSubmit`) and exit silently otherwise; keep the `PostCompact` registration in `hooks.json` only as a silent no-op for older runtimes. Contract test pins which event names may carry `additionalContext`.+2. **Slim active.md** (t_40eb1de7, P3). Render `## Most-applied (Nd)` entries as one-liners (`- \`pref-id\` (scope, applied_in_window: N)`) without repeating principle bodies; sanitize principle text at the write seam (strip leaked tool-call XML fragments, collapse multi-level `\\"` escaping) plus a doctor warning and an idempotent `planUpgrade`/`applyUpgrade` migration step that rewrites already-corrupted preference files once (it already runs hands-off via `ensureVaultCurrent` on SessionStart); add a deterministic character budget to the injected body (new shared `text-budget` core), truncating lowest-priority sections first.+3. **Compress post-write-reminder** (t_9cc4f400, P3). Full reminder once per session (it teaches the contract), then a short steady-state nudge (<= 200 chars). Session-scoped marker state keyed by the payload `session_id`, stored under the vault state dir, best-effort and fail-soft. Codex runtime keeps the full text always (one-shot exec has no second turn).+4. **Consolidate MCP read tools** (t_3920db77, P3). Three families merge behind discriminator params: 6 summary tools -> `brain_brief` (`view: morning|daily|weekly|monthly|operator|digest`), 5 analytics tools -> `brain_analytics` (`view: timeline|recurrence|attention_flows|belief_evolution|concept_synthesis`), 7 schema read tools -> `schema_inspect` (`view: graph|lint|stats|orphans|explain_type|active_pack|packs`). Old names stay registered as deprecated delegating aliases for at least one minor release; alias descriptions are one line ("Deprecated alias for X with view=Y") so the surface still shrinks.+5. **Description diet** (t_352fd7f6, P2). Cap tool descriptions at 300 chars; move parameter nuance into per-property `inputSchema` descriptions and long-form guidance into `instructions.ts`/docs; new `registry-guard` test fails on any over-cap description.+6. **Preview budget by default** (t_c967abaf, P2). Opt the verbose read tools (`brain_query`, `brain_audit`, `brain_backlinks`, `brain_unlinked_mentions`, `second_brain_query`, `schema_inspect`, `brain_session_grep`, `brain_session_expand`, `brain_recall_telemetry`) into `MCP_PREVIEW_BUDGET`; the registry-guard test enumerates tools without a budget and requires an explicit exempt-list entry with a reason.++A small measurement script (`scripts/measure-token-surface.ts`) records serialized registry size and active.md size so regressions are visible; its output lands in the PR body and CHANGELOG.++## Out of scope++- Adaptive per-request tool-surface selection (t_20dcb192 owns it).+- Removing deprecated aliases (a later minor release).+- Any change to the writer-scope surface (5 tools, unchanged).+- LLM-based summarization anywhere in the pipeline.++## Chosen approach++Variant 1 from the consultant pass: two thin reusable seams plus independent slices. A pure `text-budget` core (`src/core/brain/text/text-budget.ts`), generalized from the head-budget logic in `pre-compress-pack.ts`, owns deterministic truncation for both the active.md injection budget and the steady-state reminder; a `registry-guard` module (`src/mcp/registry-guard.ts`) walks `buildToolTable("full")` once and exposes the description-cap and preview-budget-exemption checks that two new contract tests assert. The PostCompact fix and the tool consolidation remain standalone slices that consume these primitives. Rationale for not choosing the alternatives is recorded in `variants.md`.++## Design decisions++- **SessionStart `compact` matcher replaces PostCompact** - it is the documented mechanism in current Claude Code; the PostCompact event no longer exists. The hooks.json `PostCompact` block stays (harmless on current runtimes, useful on older ones) but `active-inject` emits nothing under that event name, eliminating both the broken injection and the 16KB error echo.+- **Allowlist of context-bearing event names lives in one exported constant** (`hooks/lib/context-events.ts`) so the contract test and the hook share a single source of truth.+- **Most-applied one-liners keep ids and counts only** - the full principle text is always present in the `## Confirmed` section of the same document; duplication carries zero information.+- **Sanitization happens at the write seam, not at render** - `signal.ts`/`preference.ts` normalize principle text when persisting (strip `</principle>`-style tool-call fragments, collapse `\\\\"`-chains to a single `"`); `regenerateActive` stays a pure projection. A `brain_doctor` warning flags stored files that still carry artifacts, and a `planUpgrade`/`applyUpgrade` migration step rewrites them once - that path is idempotent and already runs hands-off on SessionStart, unlike the opt-in dream heal phase which targets vault pages, not `Brain/preferences/`.+- **Injection budget defaults to 8,000 chars (~2K tokens)** configurable via `_brain.yaml:active.inject_budget_chars`; truncation order drops sections by priority (retired -> quarantine -> most-applied -> confirmed tail), never mid-line, and appends a one-line pointer to `brain_context` for the full view. Deterministic: same input bytes, same output bytes.+- **Reminder session state is a marker file** under `<vault>/.open-second-brain/state/reminder-<session_id>` written fail-soft; absence of a session_id (or any IO error) falls back to the full text, because over-reminding is safer than never teaching the contract.+- **Consolidated tools reuse the exact handler functions of the tools they replace** - dispatch by `view` param only; output shapes per view are byte-identical to the predecessor tools so existing consumers can migrate by renaming the call.+- **Aliases are data, not copies**: a `deprecatedAlias(name, target, view)` helper produces a ToolDefinition with a one-line description delegating to the consolidated handler, keeping the alias cost ~40 tokens each instead of ~150-600.+- **Registry guard is a test-time module, not a runtime gate** - runtime behavior never changes because of a long description; the cap is enforced where regressions are caught, in `bun test`.++## File changes++New:+- `src/core/brain/text/text-budget.ts` (+ test) - pure deterministic section-aware truncation.+- `src/mcp/registry-guard.ts` (+ test) - description cap, preview-budget exemption walk.+- `hooks/lib/context-events.ts` (+ test) - allowlisted context-bearing hook event names.+- `scripts/measure-token-surface.ts` - serialized registry + active.md size report.+Extended (tests already exist - no new hook test files): `tests/hooks/active-inject.test.ts`, `tests/hooks/post-write-reminder.test.ts`, `tests/hooks/hooks-json-shape.test.ts`.++Modified:+- `hooks/active-inject.ts` (event allowlist, injection budget), `hooks/hooks.json` (SessionStart matcher gains `compact`), `hooks/post-write-reminder.ts` + `hooks/lib/messages.ts` (cadence), `hooks/lib/detect.ts` (if session id extraction needs a helper).+- `src/core/brain/active.ts` (Most-applied one-liners, budget application), `src/core/brain/most-applied.ts` (no principle text needed in entries - keep struct, render changes only).+- `src/core/brain/signal.ts`, `src/core/brain/preference.ts` (principle sanitization at write), `src/core/brain/doctor.ts` (corruption warning), `src/core/brain/upgrade.ts` (one-shot migration rewrite).+- `src/mcp/brain-tools.ts`, `src/mcp/schema-tools.ts` (consolidated tools + aliases + preview budgets + trimmed descriptions), `src/mcp/tools.ts` (registry assembly), `src/mcp/instructions.ts` (relocated guidance, updated tool list), `src/mcp/search-tools.ts`, `src/mcp/pay-memory-tools.ts` (description trims).+- `tests/mcp/mcp.test.ts` (registry contract: new names + aliases + count), affected tool tests.+- `README.md`, `docs/mcp.md`, `docs/cli-reference.md`, `CHANGELOG.md`.++## Risks and open questions++- **Alias count vs surface goal**: keeping 18 aliases means the tool *count* rises before it falls; the token win comes from one-line alias descriptions. The measurement script reports both count and serialized size; acceptance keys on size.+- **Codex hook payloads** may carry different event names; the allowlist must default-closed (no emission for unknown events) while session-capture remains unaffected.+- **Existing tests asserting full descriptions** (e.g. capability report snapshots) may need updates; treat as part of each slice's TDD loop.+- **Live-vault heal** of corrupted preference files must preserve frontmatter round-tripping for fields it does not touch; covered by fixture tests built from the real corrupted shapes found in the audit.+- **mcp.test.ts count churn**: consolidation (+3 new, names kept) and guard tests land in separate commits so each registry change is reviewable on its own.diff --git a/docs/brainstorm/token-diet/plan.md b/docs/brainstorm/token-diet/plan.mdnew file mode 100644index 00000000..20dbd11d--- /dev/null+++ b/docs/brainstorm/token-diet/plan.md@@ -0,0 +1,50 @@+# Token diet - implementation plan++Order: shared seams first (they unblock everything), then the P4 bugfix, then the remaining slices by priority. Each task is one TDD loop ending in one conventional commit; formatter + linter run before every commit.++## Tasks++### Task 1: text-budget core+- **Files**: `src/core/brain/text/text-budget.ts` (new), `tests/core/brain/text-budget.test.ts` (new)+- **Acceptance**: pure function takes ordered sections `{key, text, priority}` plus a char budget and returns the included sections + a `truncated` flag; deterministic (same input -> same output), never cuts mid-line, drops lowest-priority sections first, zero budget returns the marker line only. Property test: output length <= budget for all fixture inputs.+- **Depends on**: none++### Task 2: context-events allowlist + PostCompact fix (t_a1602738)+- **Files**: `hooks/lib/context-events.ts` (new), `hooks/active-inject.ts`, `hooks/hooks.json`, extend `tests/hooks/active-inject.test.ts` + `tests/hooks/hooks-json-shape.test.ts`+- **Acceptance**: active-inject emits `hookSpecificOutput.additionalContext` only for event names in the allowlist (`SessionStart`, `UserPromptSubmit`); for `PostCompact` (and unknown names) it exits 0 with empty stdout; `hooks.json` SessionStart matcher becomes `startup|resume|clear|compact`; contract test pins the allowlist and the silent-no-op behavior.+- **Depends on**: none++### Task 3: Most-applied one-liners + principle sanitization + one-shot migration (t_40eb1de7, part 1)+- **Files**: `src/core/brain/active.ts`, `src/core/brain/signal.ts`, `src/core/brain/preference.ts`, `src/core/brain/doctor.ts`, `src/core/brain/upgrade.ts`, fixture tests+- **Acceptance**: Most-applied section renders `- \`pref-id\` (scope, applied_in_window: N)` with no principle text; principle text persisted via signal/preference writers strips leaked tool-call XML fragments and collapses repeated backslash-quote escaping (fixtures copied from the real corrupted files); doctor flags remaining artifacts; `planUpgrade`/`applyUpgrade` rewrites them once and is idempotent; regenerateActive stays idempotent (byte-stable across two runs).+- **Depends on**: none++### Task 4: active.md injection budget (t_40eb1de7, part 2)+- **Files**: `hooks/active-inject.ts`, `src/core/brain/active.ts` or a small adapter, `src/core/brain/policy.ts` (config key `active.inject_budget_chars`), tests+- **Acceptance**: injected body is budgeted through the text-budget core (default 8,000 chars), truncation order retired -> quarantine -> most-applied -> confirmed tail, pointer line to `brain_context` appended when truncated; config override honored; live-vault-shaped fixture shrinks >= 35% vs the unslimmed baseline.+- **Depends on**: Task 1, Task 3++### Task 5: post-write-reminder cadence (t_9cc4f400)+- **Files**: `hooks/post-write-reminder.ts`, `hooks/lib/messages.ts`, session-marker helper, extend `tests/hooks/post-write-reminder.test.ts`+- **Acceptance**: first successful artifact write in a Claude Code session emits the full reminder; later writes in the same session emit a <= 200-char nudge; missing session_id or marker IO failure falls back to full text; Codex runtime always gets the full one-shot text; marker files live under the vault state dir and never throw.+- **Depends on**: none++### Task 6: consolidated tools - brain_brief, brain_analytics, schema_inspect + aliases (t_3920db77)+- **Files**: `src/mcp/brain-tools.ts`, `src/mcp/schema-tools.ts`, `src/mcp/tools.ts`, `tests/mcp/mcp.test.ts`, per-tool tests+- **Acceptance**: three new tools dispatch by `view` to the exact existing handlers; per-view output is byte-identical to the predecessor tool (asserted by running both paths in tests); 18 predecessors re-register as `deprecatedAlias(...)` definitions with one-line descriptions; registry contract test updated (count + sorted names); invalid `view` raises INVALID_INPUT.+- **Depends on**: none++### Task 7: description diet + registry guard (t_352fd7f6)+- **Files**: `src/mcp/registry-guard.ts` (new), `tests/mcp/registry-guard.test.ts` (new), description edits across `src/mcp/*-tools.ts`, `src/mcp/instructions.ts`+- **Acceptance**: every tool description <= 300 chars (guard test enforces); relocated guidance lands in per-property schema descriptions or instructions; serialized full-scope registry shrinks >= 35% vs the 44,912-char baseline (asserted informationally by the measurement script, not hard-failed in CI).+- **Depends on**: Task 6 (descriptions of consolidated tools written once)++### Task 8: preview budget by default (t_c967abaf)+- **Files**: `src/mcp/brain-tools.ts`, `src/mcp/schema-tools.ts`, `src/mcp/registry-guard.ts`, tests+- **Acceptance**: listed verbose read tools carry `previewBudget: MCP_PREVIEW_BUDGET`; guard test requires every budget-less tool to appear in an exempt list with a reason string; at least one newly budgeted tool covered by an artifact-store roundtrip test.+- **Depends on**: Task 6, Task 7++### Task 9: measurement script+- **Files**: `scripts/measure-token-surface.ts` (new)+- **Acceptance**: prints per-tool serialized sizes, registry totals (count + chars + est. tokens) for both scopes, and active.md size for the configured vault; runs via `bun run scripts/measure-token-surface.ts`; used to produce the before/after table for the PR body.+- **Depends on**: Task 7, Task 8 (final numbers)diff --git a/docs/brainstorm/token-diet/variants.md b/docs/brainstorm/token-diet/variants.mdnew file mode 100644index 00000000..529b0706--- /dev/null+++ b/docs/brainstorm/token-diet/variants.md@@ -0,0 +1,47 @@+# Token diet - variants audit trail++Consultant: Claude Code (`claude -p`), primary, single pass. Raw output preserved verbatim in `cli-output/claude.md`; prompt in `cli-output/prompt.md`. Fallback consultant not invoked (primary returned 3 parseable variants).++## Variant 1: Shared budget kernel + registry guard seam (extract-and-reuse)++- **Approach**: Extract two reusable deterministic primitives early, then plug all six children into them. (a) A `text-budget` core lifted from `pre-compress-pack.ts` head-budget logic, used by both active.md slimming (child 2) and the hook reminder compaction (child 3); (b) a `registry-guard` seam over `buildToolTable` that enforces the description cap (child 5) and the preview-budget allowlist (child 6) from the same enumeration the contract test already pins. Tool consolidation (child 4) and the PostCompact bugfix (child 1) stay as standalone slices that consume these primitives but carry their own logic.+- **Trade-offs**:+ - Pro: One truncation implementation - determinism/idempotency property is proven once and inherited everywhere.+ - Pro: Description cap and preview allowlist share one registry walk; both guard tests key off the existing sorted-name+count contract.+ - Pro: Children stay independently shippable; P4 bugfix and P2 guards do not block each other.+ - Con: Two distinct seams (text vs registry) - shared infrastructure is split, not unified.+ - Con: Consolidation (child 4) and hooks (1-3) do not benefit from the registry seam; coordination across the MCP/hook boundary stays manual.+- **Complexity**: medium+- **Risk**: low++## Variant 2: Independent priority-ordered vertical slices++- **Approach**: Each of the six children is a self-contained slice with no new shared abstractions, sequenced strictly by priority. Each slice inlines whatever budgeting/guard logic it needs; the only shared touch-point is the existing registry contract test.+- **Trade-offs**:+ - Pro: Fastest path to landing the P4 PostCompact bugfix; minimal blast radius per slice; trivial rollback.+ - Pro: No upfront design cost; no over-built abstraction risk.+ - Con: Truncation/head-budget logic duplicated between active.md and the reminder - two places to keep deterministic.+ - Con: Description cap and preview allowlist each grow their own registry walk and guard test - drift risk.+ - Con: Highest long-term maintenance; duplicated determinism logic is exactly what the audit tries to reduce.+- **Complexity**: small+- **Risk**: medium++## Variant 3: Declarative tool-registry manifest + mirrored injection-budget module++- **Approach**: A single declarative manifest describes every MCP tool (capped description, preview-budget allowlist entry + reason, deprecation-alias mapping, consolidation group/param); the serialized registry, both guard tests, alias delegation, and the consolidated dispatch all derive from that one data model. A parallel `injection-budget` module owns all hook rendering with deterministic truncation.+- **Trade-offs**:+ - Pro: One source of truth; adding a tool forces an explicit manifest entry - the "explicit allowlist with reason" requirement becomes structural.+ - Pro: Strongest guarantee against future regression.+ - Con: Large upfront refactor of `tools.ts` plus the 3,592-line `brain-tools.ts`; high churn, harder review, risk to the pinned registry contract.+ - Con: Couples the MCP-surface children into one big structural change; works against landing the P4 bugfix quickly.+ - Con: Over-engineering risk for a static surface reduction; could be mistaken for the adaptive-selection work deferred to t_20dcb192.+- **Complexity**: large+- **Risk**: high++## Consultant recommendation++Variant 1. "It captures the one genuinely shared concern the audit exposes - deterministic, idempotent truncation reused by both active.md and the post-write reminder - without forcing the four MCP-surface children into a single high-churn manifest refactor that endangers the pinned registry contract and the one-PR-per-version rule."++## Orchestrator decision++**Variant 1 accepted.** Project context confirms the consultant's reasoning rather than overriding it: the repo already follows the "pure deterministic core + thin IO shell" pattern (preview-budget.ts, coverage.ts from the Recall Trust Suite), so two small seams fit the codebase idiom, while a manifest rewrite of brain-tools.ts would dwarf the six children combined and put the registry contract test in motion exactly when two new guard tests need it stable. Variant 2's duplicated truncation logic was rejected because the active.md idempotent-write property and the hook fail-soft contract both depend on truncation determinism - proving it once is the cheaper and safer route.diff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex 8eedfedd..d3d247fb 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -397,8 +397,7 @@ from the same source of truth (`Brain/preferences/`):flowchart LRDream[dream pass] -- regenerate --> Active[Brain/active.md]Pin[o2b brain pin / unpin] -- regenerate --> Active- Active -- SessionStart hook --> ClaudeStart["Claude Code / Codex<br/>session start"]- Active -- PostCompact hook --> ClaudeCompact["Claude Code / Codex<br/>after /compact"]+ Active -- "SessionStart hook<br/>(startup | resume | clear | compact)" --> ClaudeStart["Claude Code / Codex<br/>session start + after /compact"]Active -- "osb://preferences/active" --> MCPHost["MCP host (Hermes, others)"]Active -- "brain_context tool" --> PullRT["Cursor / Aider / raw API<br/>(no SessionStart hook)"]Pinned[Brain/pinned.md] -- "brain_context tool" --> PullRT@@ -409,19 +408,23 @@ flowchart LR`Most-applied (Nd)` section ranking confirmed/quarantine rulesby `apply-evidence (result: applied)` events in the trailingwindow (defaults to 30 days / top-10; configurable via- `active.most_applied_window_days` and `active.most_applied_limit`+ `active.most_applied_window_days`, `active.most_applied_limit`, and the+ SessionStart injection budget `active.inject_budget_chars`in `_brain.yaml`), quarantined preferences with their applied /violated counters, and the three most recently retired entries.The writer is idempotent — if the rendered body matches the fileon disk, no I/O happens. The same window / limit drive a mirrored`Most-applied (Nd)` section in `brain_digest` output.-- **SessionStart hook** (`startup | resume | clear`) and- **PostCompact hook** (`manual | auto`) inject the body as- `additionalContext` so the agent sees current rules at the start of- every session and again after `/compact` (otherwise the- hook-injected context is dropped from long sessions). Both fail- closed — any error path exits 0 with no output so the runtime- proceeds unaffected.+- **SessionStart hook** (`startup | resume | clear | compact`) injects+ the body as `additionalContext` so the agent sees current rules at+ the start of every session and again after `/compact` - the+ `compact` matcher replaced the former PostCompact injection, whose+ event no longer exists in current Claude Code. The injected body is+ budgeted (`active.inject_budget_chars`, default 8,000 chars):+ sections drop deterministically (recently retired first, then+ quarantine, then most-applied) and a one-line notice points the+ agent at `brain_context` for the full set. Fails closed - any error+ path exits 0 with no output so the runtime proceeds unaffected.- **MCP Resources** expose the same content for hosts that preferpull access (`osb://preferences/active` and friends in the tableabove). The MCP `initialize` reply advertises the `resources`diff --git a/docs/mcp.md b/docs/mcp.mdindex eade7680..aefbdb83 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -18,13 +18,15 @@ in Open Second Brain depends on the MCP server being running.## Tool Highlights-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-10% of the context window, causing `MCPSearch` tool-search deferral; use the-writer split below for the always-loaded writer subset, or the runtime-capability flags for a narrower per-process full server.+The full server currently advertises 56 tools; 18 further names stay callable+through `tools/call` as hidden deprecated aliases (see "Consolidated views and+deprecated aliases" below). The table 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, the full schema can push MCP definitions beyond 10% of+the context window, causing `MCPSearch` tool-search deferral; use the 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 || --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- |@@ -37,7 +39,8 @@ capability flags for a narrower per-process full server.| `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_brief` | Read-only Brain summary for any window: `view: morning \| daily \| weekly \| monthly \| operator \| digest`. | `view` |+| `brain_analytics` | Read-only Brain analytics for any lens: `view: timeline \| attention_flows \| belief_evolution \| concept_synthesis`. | `view` || `brain_search` | Read-only vault search with optional structured query lanes, explicit focus hints, time ranges, and evidence-pack diagnostics. | `query` || `brain_recall_feedback` | Record explicit up/down recall feedback for one search result; feeds the deterministic learned-weight fold. | `query`, `result_path`, `verdict` || `brain_recall_gate` | Read-only classifier for whether an automatic recall attempt should run; returns `retrieve` plus a stable reason. | `prompt` |@@ -50,15 +53,8 @@ capability flags for a narrower per-process full server.| `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_inspect` | Read-only schema inspection for any view: `view: graph \| lint \| stats \| orphans \| explain_type \| active_pack \| packs`. | `view` (`token` for `explain_type`) || `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. | — |@@ -70,6 +66,25 @@ capability flags for a narrower per-process full server.| `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` |+### Consolidated views and deprecated aliases++`brain_brief`, `brain_analytics`, and `schema_inspect` replaced three+overlapping tool families in v0.34.0; per-view output is identical to the+predecessor tools because dispatch goes to the same handlers. The 18+predecessor names (`brain_morning_brief`, `brain_daily_brief`,+`brain_weekly_synthesis`, `brain_monthly_review`, `brain_operator_summary`,+`brain_digest`, `brain_timeline`, `brain_attention_flows`,+`brain_belief_evolution`, `brain_concept_synthesis`, `get_active_schema_pack`,+`list_schema_packs`, `schema_stats`, `schema_lint`, `schema_graph`,+`schema_explain_type`, `schema_review_orphans`, `reload_schema_pack`) remain+callable through `tools/call` as deprecated aliases for at least one minor+release, but are hidden from `tools/list` so clients stop paying for their+schemas. Migrate by switching to the consolidated tool with the matching+`view` value; per-view parameters keep their old names (for example+`brain_brief` with `view: "daily"` accepts the same `date` argument+`brain_daily_brief` did, and `brain_analytics` with+`view: "attention_flows"` defaults `operation` to `list`).+`second_brain_query` accepts `pattern` (string) and `limit` (1–500, default 50).`vault_health` accepts `repo` (string) for plugin manifest validation.`brain_agent_query` accepts `agents` (string array), `topic`, `query`, `kind`@@ -339,7 +354,7 @@ server to your Codex MCP config the same way as Hermes.The plugin's `.mcp.json` ships **two** MCP-server entries:-- `open-second-brain` - the full surface (58 tools, including `brain_health`, `brain_mcp_landscape`, `brain_agent_query`, `brain_agent_diff`, `brain_recall_gate`, `brain_pinned_context`, `brain_pre_compress_pack`, `brain_audit`, `brain_morning_brief`, `brain_sources`, and `brain_switch_vault`); subject to Claude Code's `MCPSearch` tool-search deferral when MCP definitions push the system prompt past 10% of the context window.+- `open-second-brain` - the full surface: 56 advertised tools (including the consolidated `brain_brief`, `brain_analytics`, and `schema_inspect`, plus `brain_health`, `brain_mcp_landscape`, `brain_agent_query`, `brain_agent_diff`, `brain_recall_gate`, `brain_pinned_context`, `brain_pre_compress_pack`, `brain_audit`, `brain_sources`, and `brain_switch_vault`) and 18 hidden deprecated aliases listed under "Consolidated views and deprecated aliases" above; subject to Claude Code's `MCPSearch` tool-search deferral when MCP definitions push the system prompt past 10% of the context window.- `open-second-brain-writer` - a minimal always-loaded surface of five tools: `brain_feedback`, `brain_apply_evidence`, `brain_note`, `brain_pinned_context` (writers) and `brain_context` (read-only pull-bootstrap of `Brain/active.md` plus pinned context, v0.16.0). The agent records taste signals, evidence events, milestone notes, and current-task pinned facts - and fetches the active rule digest at session start in runtimes without a SessionStart hook - without a ToolSearch round-trip on every session boot.Both servers reuse the same backing CLI (`o2b mcp --scope writer` vs the default `--scope full`). Handlers are byte-identical; the writer-mode instructions text explicitly tells the agent to prefer the writer copy over any duplicate the full server still exposes (both call the same code path).diff --git a/hooks/README.md b/hooks/README.mdindex fe0e7ec5..ed70117c 100644--- a/hooks/README.md+++ b/hooks/README.md@@ -20,11 +20,11 @@ hook payload shape, not on the runtime.| Event | Matcher | Behaviour || ------------------ | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `SessionStart` | `startup\|resume\|clear` | Injects `Brain/active.md` and records a non-blocking `session-lifecycle` observation. |+| `SessionStart` | `startup\|resume\|clear\|compact` | Injects the budgeted `Brain/active.md` body (default 8,000 chars, `active.inject_budget_chars` in `_brain.yaml`) and records a non-blocking `session-lifecycle` observation. The `compact` matcher is the post-compaction re-injection path. || `UserPromptSubmit` | `*` | Captures explicit `@osb feedback ...` markers from the submitted prompt immediately through the signal/dedup boundary. || `PostToolUse` | `brain_feedback` | Replays successful `brain_feedback` tool input immediately through the same signal/dedup boundary. |-| `PostToolUse` | `Write\|Edit\|MultiEdit\|apply_patch` | Emits `additionalContext` pointing at the three Brain writer tools (`brain_feedback`, `brain_apply_evidence`, `brain_note`) for a durable edit. |-| `PostCompact` | `manual\|auto` | Re-injects `Brain/active.md` and records a post-compact lifecycle observation. |+| `PostToolUse` | `Write\|Edit\|MultiEdit\|apply_patch` | Emits `additionalContext` pointing at the three Brain writer tools. The full reminder is shown once per Claude Code session; later writes get a one-line nudge (Codex one-shot runs always get the full text). |+| `PostCompact` | `manual\|auto` | Records a post-compact lifecycle observation only. Current Claude Code has no PostCompact hook event and rejects `additionalContext` under that name - re-injection moved to the SessionStart `compact` matcher; the registration stays as a silent no-op for older runtimes. || `Stop` | (every Stop) | If the turn produced a durable artifact and none of `brain_feedback` / `brain_apply_evidence` / `brain_note` landed, returns `decision: "block"` once, then lets the second Stop pass. || `SessionEnd` | `*` | Records a non-blocking lifecycle observation for session close. |diff --git a/hooks/active-inject.ts b/hooks/active-inject.tsindex b33407ca..fc40283a 100644--- a/hooks/active-inject.ts+++ b/hooks/active-inject.ts@@ -30,10 +30,14 @@import { existsSync, readFileSync } from "node:fs";import { resolveVault } from "../src/core/config.ts";+import { parseFrontmatterText } from "../src/core/vault.ts";import { brainActivePath } from "../src/core/brain/paths.ts";+import { budgetActiveBody } from "../src/core/brain/active-budget.ts";+import { INJECT_BUDGET_CHARS_DEFAULT, loadBrainConfig } from "../src/core/brain/policy.ts";import { healCliSymlinks } from "../src/cli/install-cli.ts";import { ensureVaultCurrent } from "../src/core/maintenance/ensure-current.ts";import { asHookPayload, readHookInput } from "./lib/stdin.ts";+import { isContextEventName } from "./lib/context-events.ts";async function main(): Promise<void> {let payload;@@ -44,18 +48,21 @@ async function main(): Promise<void> {}// The hook is registered separately for each event; the payload's- // `hook_event_name` tells us which one fired. Echo the same name- // back unchanged so the runtime correlates request and response- // — including any future event we have not yet enumerated here.- // Default to `SessionStart` only when the field is missing entirely- // (e.g. an empty stdin payload, or a runtime that doesn't populate- // the name); a coerced unknown value would silently misreport- // which event fired.+ // `hook_event_name` tells us which one fired. Default to+ // `SessionStart` only when the field is missing entirely (e.g. an+ // empty stdin payload, or a runtime that doesn't populate the name).const hookEventName =typeof payload.hook_event_name === "string" && payload.hook_event_name.length > 0? payload.hook_event_name: "SessionStart";+ // Default-closed allowlist: only event names whose output schema+ // accepts `additionalContext` may produce stdout. Emitting under+ // any other name (PostCompact included) is rejected by the runtime+ // and echoes the full payload back as a validation error - the+ // post-compaction path is the SessionStart `compact` matcher.+ if (!isContextEventName(hookEventName)) return;+// Self-heal the ~/.local/bin CLI symlinks on SessionStart only: a plugin// update can leave them dangling or pointing at an old version. Runs from// the current checkout (resolved via $CLAUDE_PLUGIN_ROOT); strictly@@ -95,13 +102,29 @@ async function main(): Promise<void> {return;}- const trimmed = body.trim();+ // Drop the `kind: brain-active / generated_at` frontmatter - it+ // carries no signal for the agent, only provenance for tooling.+ const [, fmBody] = parseFrontmatterText(body);+ const trimmed = fmBody.trim();if (trimmed.length === 0) return;+ // Injection budget (token-diet): a large preference set must not+ // flood the session preamble. Config errors fall back to the+ // default budget - the hook is fail-soft by contract.+ let budget = INJECT_BUDGET_CHARS_DEFAULT;+ try {+ const cfg = loadBrainConfig(vault);+ if (cfg.active?.inject_budget_chars !== undefined) {+ budget = cfg.active.inject_budget_chars;+ }+ } catch {+ // intentional fallback - a corrupted _brain.yaml is doctor's job+ }+const out = {hookSpecificOutput: {hookEventName,- additionalContext: trimmed,+ additionalContext: budgetActiveBody(trimmed, budget),},};process.stdout.write(JSON.stringify(out) + "\n");diff --git a/hooks/hooks.json b/hooks/hooks.jsonindex 8ecadf46..8af70103 100644--- a/hooks/hooks.json+++ b/hooks/hooks.json@@ -26,7 +26,7 @@],"SessionStart": [{- "matcher": "startup|resume|clear",+ "matcher": "startup|resume|clear|compact","hooks": [{"type": "command",diff --git a/hooks/lib/context-events.ts b/hooks/lib/context-events.tsnew file mode 100644index 00000000..be148c4f--- /dev/null+++ b/hooks/lib/context-events.ts@@ -0,0 +1,25 @@+/**+ * Hook event names allowed to carry+ * `hookSpecificOutput.additionalContext` back to the runtime.+ *+ * Default-closed: any event not listed here gets NO stdout from+ * context-injecting hooks. Claude Code validates hook output against a+ * per-event schema and rejects `additionalContext` for events that do+ * not support it - the rejection both drops the payload and echoes it+ * into the validation error, so emitting on an unsupported event is+ * strictly worse than staying silent.+ *+ * `PostCompact` is deliberately absent: current Claude Code has no+ * such hook event at all (verified against+ * https://code.claude.com/docs/en/hooks, 2026-06-02). Post-compaction+ * re-injection is served by the `SessionStart` hook with the+ * `compact` matcher instead - see `hooks/hooks.json`.+ */++export const CONTEXT_EVENT_NAMES = Object.freeze(["SessionStart", "UserPromptSubmit"] as const);++export type ContextEventName = (typeof CONTEXT_EVENT_NAMES)[number];++export function isContextEventName(name: string): name is ContextEventName {+ return (CONTEXT_EVENT_NAMES as ReadonlyArray<string>).includes(name);+}diff --git a/hooks/lib/messages.ts b/hooks/lib/messages.tsindex 9b4df21b..a44d86ca 100644--- a/hooks/lib/messages.ts+++ b/hooks/lib/messages.ts@@ -121,3 +121,17 @@ export function stopGuardrailReason(runtime: HookRuntime = "unknown"): string {);return parts.join("\n");}++/**+ * Steady-state nudge (token-diet, t_9cc4f400): emitted after the full+ * reminder has already been shown once in the current Claude Code+ * session. Hard ceiling 200 characters - the whole point is that the+ * per-edit cost stays negligible over a long coding session.+ */+export function postWriteNudge(): string {+ return (+ "Open Second Brain: artifact written. If a taste signal or scoped " ++ "preference applies, call brain_feedback / brain_apply_evidence / " ++ "brain_note (full contract earlier in this session)."+ );+}diff --git a/hooks/post-write-reminder.ts b/hooks/post-write-reminder.tsindex 2d489d37..ec79ff66 100755--- a/hooks/post-write-reminder.ts+++ b/hooks/post-write-reminder.ts@@ -24,9 +24,62 @@* exit 0 so the turn proceeds; the Stop guardrail is the gating hook.*/+import { existsSync, mkdirSync, readdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { asHookPayload, readHookInput } from "./lib/stdin.ts";import { detectHookRuntime, isArtifactToolName } from "./lib/detect.ts";-import { postWriteReminder } from "./lib/messages.ts";+import { postWriteNudge, postWriteReminder } from "./lib/messages.ts";++/** Markers older than this are pruned opportunistically. */+const MARKER_TTL_MS = 48 * 3600 * 1000;++function markerStateDir(): string {+ const override = process.env["O2B_REMINDER_STATE_DIR"];+ return override && override.length > 0 ? override : join(tmpdir(), "o2b-reminder-markers");+}++/**+ * Record that the full reminder was shown for `sessionId`; returns+ * true when a marker already existed (steady state). Best-effort and+ * fail-soft: any IO problem reports "not seen yet", so the caller+ * falls back to the full reminder - over-reminding is safer than+ * never teaching the contract.+ */+function sessionAlreadyReminded(sessionId: string): boolean {+ try {+ const dir = markerStateDir();+ const name = sessionId.replace(/[^A-Za-z0-9._-]/g, "_");+ // "." and ".." survive the character filter but resolve to the+ // state dir / its parent - treat them as "no usable session id".+ if (/^\.{1,2}$/.test(name)) return false;+ const marker = join(dir, name);+ if (existsSync(marker)) return true;+ mkdirSync(dir, { recursive: true });+ pruneStaleMarkers(dir);+ writeFileSync(marker, "", "utf8");+ return false;+ } catch {+ return false;+ }+}++function pruneStaleMarkers(dir: string): void {+ try {+ const cutoff = Date.now() - MARKER_TTL_MS;+ for (const name of readdirSync(dir)) {+ const full = join(dir, name);+ try {+ if (statSync(full).mtimeMs < cutoff) unlinkSync(full);+ } catch {+ // a vanished marker is fine+ }+ }+ } catch {+ // pruning is opportunistic+ }+}async function main(): Promise<void> {let payload;@@ -48,7 +101,17 @@ async function main(): Promise<void> {const filePath = extractFilePath(payload.tool_input);const runtime = detectHookRuntime(payload);- const text = postWriteReminder({ toolName, filePath, runtime });++ // Session cadence (token-diet, t_9cc4f400): the full reminder+ // teaches the contract once per Claude Code session; afterwards a+ // <= 200-char nudge keeps the per-edit cost negligible. Codex+ // `codex exec` is one-shot, so steady state never applies there;+ // unknown runtimes and absent session ids stay on the full text.+ const sessionId = typeof payload.session_id === "string" ? payload.session_id : "";+ const steadyState =+ runtime === "claudecode" && sessionId.length > 0 && sessionAlreadyReminded(sessionId);++ const text = steadyState ? postWriteNudge() : postWriteReminder({ toolName, filePath, runtime });const out = {hookSpecificOutput: {diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex dcf2ce90..7e1c9f7b 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.33.0",+ "version": "0.34.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 3218554b..877965d7 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.33.0",+ "version": "0.34.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.yamlindex 16aad972..a3039c8c 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.33.0"+version: "0.34.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex 06f268e7..b81802b9 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.33.0",+ "version": "0.34.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.yamlindex 16aad972..a3039c8c 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.33.0"+version: "0.34.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/pyproject.toml b/pyproject.tomlindex 1e7074b9..dea514f4 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.33.0"+version = "0.34.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/scripts/measure-token-surface.ts b/scripts/measure-token-surface.tsnew file mode 100644index 00000000..446676c7--- /dev/null+++ b/scripts/measure-token-surface.ts@@ -0,0 +1,107 @@+#!/usr/bin/env -S bun+/**+ * Token-surface report (token-diet, epic t_5e6826f3).+ *+ * Prints the serialized size of the advertised MCP tool surface (what+ * every client of a non-deferred host pays per request), the hidden+ * deprecated-alias overhead, the server instructions, and - when a+ * vault is resolvable - the size of the budgeted active.md injection.+ *+ * Usage: bun run scripts/measure-token-surface.ts [--json]+ */++import { existsSync, readFileSync } from "node:fs";++import { resolveVault } from "../src/core/config.ts";+import { brainActivePath } from "../src/core/brain/paths.ts";+import { INJECT_BUDGET_CHARS_DEFAULT } from "../src/core/brain/policy.ts";+import { budgetActiveBody } from "../src/core/brain/active-budget.ts";+import { parseFrontmatterText } from "../src/core/vault.ts";+import { estimateTokens } from "../src/core/brain/text/tokenizer.ts";+import { buildInstructions } from "../src/mcp/instructions.ts";+import { buildToolTable, type ToolDefinition } from "../src/mcp/tools.ts";++interface ToolRow {+ readonly name: string;+ readonly chars: number;+ readonly tokens: number;+ readonly hidden: boolean;+}++function wireSize(tool: ToolDefinition): number {+ return JSON.stringify({+ name: tool.name,+ description: tool.description,+ inputSchema: tool.inputSchema,+ ...(tool.outputSchema ? { outputSchema: tool.outputSchema } : {}),+ }).length;+}++function sum(rows: ReadonlyArray<ToolRow>): { chars: number; tokens: number } {+ return rows.reduce((acc, r) => ({ chars: acc.chars + r.chars, tokens: acc.tokens + r.tokens }), {+ chars: 0,+ tokens: 0,+ });+}++const json = process.argv.includes("--json");++const rows: ToolRow[] = buildToolTable("full").map((t) => {+ const chars = wireSize(t);+ return {+ name: t.name,+ chars,+ tokens: estimateTokens(JSON.stringify(t.inputSchema) + t.description),+ hidden: t.hidden === true,+ };+});+const listed = rows.filter((r) => !r.hidden);+const hidden = rows.filter((r) => r.hidden);++const fullInstructions = buildInstructions({ agent: "agent", scope: "full" });+const writerInstructions = buildInstructions({ agent: "agent", scope: "writer" });++const vault = resolveVault();+let active: { raw: number; budgeted: number } | null = null;+if (vault !== null && existsSync(brainActivePath(vault))) {+ const raw = readFileSync(brainActivePath(vault), "utf8");+ const [, body] = parseFrontmatterText(raw);+ active = {+ raw: raw.length,+ budgeted: budgetActiveBody(body.trim(), INJECT_BUDGET_CHARS_DEFAULT).length,+ };+}++const report = {+ advertised_tools: listed.length,+ hidden_aliases: hidden.length,+ advertised_chars: sum(listed).chars,+ advertised_tokens_estimate: sum(listed).tokens,+ hidden_alias_chars: sum(hidden).chars,+ instructions_full_chars: fullInstructions.length,+ instructions_writer_chars: writerInstructions.length,+ active_md: active,+ top_tools: listed+ .toSorted((a, b) => b.chars - a.chars)+ .slice(0, 10)+ .map((r) => ({ name: r.name, chars: r.chars })),+};++if (json) {+ process.stdout.write(JSON.stringify(report, null, 2) + "\n");+} else {+ process.stdout.write(+ [+ `advertised tools ${report.advertised_tools} (${report.advertised_chars} chars, ~${report.advertised_tokens_estimate} tokens)`,+ `hidden aliases ${report.hidden_aliases} (${report.hidden_alias_chars} chars, callable but unlisted)`,+ `instructions (full) ${report.instructions_full_chars} chars`,+ `instructions (writer) ${report.instructions_writer_chars} chars`,+ active+ ? `active.md ${active.raw} chars raw -> ${active.budgeted} chars injected (budget ${INJECT_BUDGET_CHARS_DEFAULT})`+ : "active.md (no vault resolved)",+ "",+ "top tools by wire size:",+ ...report.top_tools.map((t) => ` ${String(t.chars).padStart(6)} ${t.name}`),+ ].join("\n") + "\n",+ );+}diff --git a/src/core/brain/active-budget.ts b/src/core/brain/active-budget.tsnew file mode 100644index 00000000..4d59f3eb--- /dev/null+++ b/src/core/brain/active-budget.ts@@ -0,0 +1,99 @@+/**+ * Injection budget for the rendered `Brain/active.md` body+ * (token-diet, t_40eb1de7 part 2).+ *+ * The SessionStart hook injects the file verbatim; on a vault with a+ * large preference set that preamble grows without bound. This module+ * fits the body into a character budget through the shared+ * section-aware truncation core: sections drop in fixed priority+ * order - recently retired first, then quarantine, then most-applied,+ * with the confirmed rules (and the document preamble) surviving+ * longest - and a one-line notice points the agent at `brain_context`+ * for the full view.+ *+ * Pure and deterministic; the hook stays a thin IO shell.+ */++import { applySectionBudget, type BudgetSection } from "./text/text-budget.ts";++export const ACTIVE_TRUNCATION_NOTICE =+ "_Injection truncated to budget. Call `brain_context` (or read `Brain/active.md`) for the full preference set._";++/**+ * Drop priority per known section heading; lower survives longer.+ * The preamble (everything before the first `## `) shares priority 0+ * with Confirmed. Unknown future sections sit between most-applied+ * and quarantine.+ */+const SECTION_PRIORITIES: ReadonlyArray<{ readonly prefix: string; readonly priority: number }> = [+ { prefix: "## Confirmed", priority: 0 },+ { prefix: "## Most-applied", priority: 1 },+ { prefix: "## Quarantine", priority: 3 },+ { prefix: "## Recently retired", priority: 4 },+];++const UNKNOWN_SECTION_PRIORITY = 2;++function priorityFor(heading: string): number {+ for (const { prefix, priority } of SECTION_PRIORITIES) {+ if (heading.startsWith(prefix)) return priority;+ }+ return UNKNOWN_SECTION_PRIORITY;+}++/**+ * Split a rendered active.md body into `## `-delimited sections,+ * keeping the preamble attached to the front of the first slice.+ */+function splitSections(body: string): BudgetSection[] {+ const lines = body.split("\n");+ const sections: BudgetSection[] = [];+ let currentKey = "preamble";+ let currentPriority = 0;+ let buffer: string[] = [];++ const flush = (): void => {+ // Trim the trailing blank separator off each slice; the budget+ // core re-joins sections with a blank line.+ while (buffer.length > 0 && buffer[buffer.length - 1] === "") buffer.pop();+ if (buffer.length === 0) return;+ sections.push({+ key: `${sections.length}:${currentKey}`,+ priority: currentPriority,+ text: buffer.join("\n"),+ });+ buffer = [];+ };++ for (const line of lines) {+ if (line.startsWith("## ")) {+ // The preamble merges into the first heading's section so the+ // document title can never be dropped ahead of its content.+ if (currentKey !== "preamble" || priorityFor(line) !== 0) flush();+ if (currentKey === "preamble" && priorityFor(line) === 0) {+ currentKey = line;+ currentPriority = 0;+ buffer.push(line);+ continue;+ }+ currentKey = line;+ currentPriority = priorityFor(line);+ }+ buffer.push(line);+ }+ flush();+ return sections;+}++/**+ * Fit `body` into `budgetChars`. Within budget the input passes+ * through byte-identical (the idempotent-write comparison upstream+ * stays valid); over budget the section drop order is deterministic.+ */+export function budgetActiveBody(body: string, budgetChars: number): string {+ if (body.length <= budgetChars) return body;+ const result = applySectionBudget(splitSections(body), budgetChars, {+ notice: ACTIVE_TRUNCATION_NOTICE,+ });+ return result.body;+}diff --git a/src/core/brain/active.ts b/src/core/brain/active.tsindex c8274b27..c3e18dc5 100644--- a/src/core/brain/active.ts+++ b/src/core/brain/active.ts@@ -294,7 +294,11 @@ function renderMostAppliedLine(m: MostAppliedEntry): string {// (`MostAppliedEntry.applied_30d`) keeps its v0.10.10 name so internal// consumers (MCP counts, e2e tests) don't break.tags.push(`applied_in_window: ${m.applied_30d}`);- return `- \`${p.id}\` (${tags.join(", ")}) — ${p.principle}`;+ // One-liner by design (token-diet): every most-applied preference is+ // confirmed or quarantined, so its principle text is already rendered+ // verbatim in the section above - repeating it here duplicated ~31%+ // of the injected bytes on a real vault.+ return `- \`${p.id}\` (${tags.join(", ")})`;}function renderQuarantineLine(p: BrainPreference): string {diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.tsindex eebfefe4..561286fd 100644--- a/src/core/brain/doctor.ts+++ b/src/core/brain/doctor.ts@@ -67,6 +67,7 @@ import {type SemanticHealthReport,} from "./health/reconcile.ts";import { parseSignal } from "./signal.ts";+import { principleNeedsRepair } from "./text/sanitize-principle.ts";import { findSimilarPairs, tokenise } from "./similarity.ts";import {BRAIN_LOG_EVENT_KIND,@@ -642,6 +643,19 @@ function checkPreferences(if (pref.supersedes) {checkWikilinks(path, "supersedes", [pref.supersedes], knownBasenames, issues);}+ // Principle corruption (token-diet, t_40eb1de7): leaked tool-call+ // fragments or escape-amplified quote chains written before the+ // sanitizing write seam shipped. `o2b brain upgrade --apply`+ // repairs these in place.+ if (principleNeedsRepair(pref.principle)) {+ issues.push({+ severity: "warning",+ code: "principle-corrupted",+ path,+ message:+ "principle carries leaked tool-call fragments or escape-amplified quotes; run `o2b brain upgrade --apply` to repair",+ });+ }} catch (err) {if (err instanceof BrainStatusFolderMismatchError) {issues.push({diff --git a/src/core/brain/policy.ts b/src/core/brain/policy.tsindex c92ccb04..08726799 100644--- a/src/core/brain/policy.ts+++ b/src/core/brain/policy.ts@@ -65,6 +65,17 @@ export const MOST_APPLIED_LIMIT_MIN = 1;export const MOST_APPLIED_LIMIT_MAX = 50;/** Default window when `_brain.yaml` lacks `active.most_applied.window_days`. */export const MOST_APPLIED_WINDOW_DAYS_DEFAULT = 30;++/**+ * Character budget for the active.md body injected at SessionStart+ * (token-diet, t_40eb1de7). ~2K tokens - enough for every confirmed+ * rule on a typical vault, small enough that a runaway preference set+ * cannot flood the session preamble. Override via+ * `active.inject_budget_chars`.+ */+export const INJECT_BUDGET_CHARS_DEFAULT = 8000;+export const INJECT_BUDGET_CHARS_MIN = 500;+export const INJECT_BUDGET_CHARS_MAX = 200_000;/** Default top-N limit when `_brain.yaml` lacks `active.most_applied.limit`. */export const MOST_APPLIED_LIMIT_DEFAULT = 10;@@ -790,16 +801,41 @@ export function validateBrainConfigDetailed(}mostApplied = { window_days: windowDays, limit };}+ let injectBudgetChars: number | undefined;+ if ("inject_budget_chars" in activeMap) {+ const raw = activeMap["inject_budget_chars"];+ if (+ typeof raw !== "number" ||+ !Number.isInteger(raw) ||+ raw < INJECT_BUDGET_CHARS_MIN ||+ raw > INJECT_BUDGET_CHARS_MAX+ ) {+ throw new BrainConfigError(+ `must be an integer between ${INJECT_BUDGET_CHARS_MIN} and ` ++ `${INJECT_BUDGET_CHARS_MAX}; got ${describe(raw)}`,+ "active.inject_budget_chars",+ source,+ );+ }+ injectBudgetChars = raw;+ }// Forward-compat: unknown sub-keys under `active:` → warning.for (const k of Object.keys(activeMap)) {- if (k !== "most_applied_window_days" && k !== "most_applied_limit") {+ if (+ k !== "most_applied_window_days" &&+ k !== "most_applied_limit" &&+ k !== "inject_budget_chars"+ ) {warnings.push({path: source ?? "<config>",message: `active.${k}: unknown field ignored (forward-compat)`,});}}- active = mostApplied !== undefined ? { most_applied: mostApplied } : {};+ active = {+ ...(mostApplied !== undefined ? { most_applied: mostApplied } : {}),+ ...(injectBudgetChars !== undefined ? { inject_budget_chars: injectBudgetChars } : {}),+ };}// Optional `discipline_report` section. On any type mismatch, emit adiff --git a/src/core/brain/preference.ts b/src/core/brain/preference.tsindex c2832ea4..3420e0d6 100644--- a/src/core/brain/preference.ts+++ b/src/core/brain/preference.ts@@ -45,6 +45,7 @@ import {type BrainSchemaVocabulary,} from "./schema-vocab.ts";import { brainDirs, preferencePath, retiredPath, validateSlug } from "./paths.ts";+import { sanitisePrinciple } from "./text/sanitize-principle.ts";import {BRAIN_CONFIDENCE,BRAIN_MEMORY_LAYER,@@ -359,7 +360,7 @@ function preferenceFrontmatter(input: WritePreferenceInput, id: string): Frontmatags: [...tags],topic: input.topic.trim(),_status: input.status,- principle: input.principle.trim(),+ principle: sanitisePrinciple(input.principle),_evidenced_by: [...input.evidenced_by],_applied_count: applied,_violated_count: violated,diff --git a/src/core/brain/signal.ts b/src/core/brain/signal.tsindex 416ba17f..d6a0ec7a 100644--- a/src/core/brain/signal.ts+++ b/src/core/brain/signal.ts@@ -26,6 +26,7 @@import type { FrontmatterMap } from "../types.ts";import { sanitiseTextField } from "../redactor.ts";+import { sanitisePrinciple } from "./text/sanitize-principle.ts";import { writeFrontmatterAtomic, parseFrontmatter } from "../vault.ts";import { compress, expand, CODEC_VERSION } from "./portability/codec.ts";import { allocateSlug, brainDirs, validateIsoDate } from "./paths.ts";@@ -247,7 +248,9 @@ const RAW_MAX_LEN = 4096;const SOURCE_ITEM_MAX_LEN = 512;function sanitiseSignalInput(input: WriteSignalInput): WriteSignalInput {- const principle = sanitiseTextField(input.principle, {+ // Principle-specific repair first (leaked tool-call fragments,+ // escape-amplified quote chains), then the generic field sanitiser.+ const principle = sanitiseTextField(sanitisePrinciple(input.principle), {maxLen: PRINCIPLE_MAX_LEN,singleLine: true,});diff --git a/src/core/brain/text/sanitize-principle.ts b/src/core/brain/text/sanitize-principle.tsnew file mode 100644index 00000000..71956fab--- /dev/null+++ b/src/core/brain/text/sanitize-principle.ts@@ -0,0 +1,68 @@+/**+ * Principle-text sanitizer (token-diet, t_40eb1de7).+ *+ * Two corruption shapes were found verbatim in live preference+ * frontmatter, both introduced at signal-recording time by malformed+ * MCP client payloads:+ *+ * 1. Leaked tool-call XML fragments: the principle string carried a+ * serialized tail of the tool call itself, e.g.+ * `...approval.</principle>\n<parameter name="scope">collaboration`.+ * 2. Multi-level backslash-quote chains (`\\\\\\"`) - escape+ * amplification from asymmetric frontmatter round-trips (fixed at+ * the parser; this collapse repairs already-amplified text).+ *+ * The sanitizer is idempotent and pure; it is applied at every write+ * seam that persists a principle (signal + preference writers) and by+ * the one-shot `planUpgrade` repair for files corrupted before the fix.+ */++/**+ * First leaked tool-call boundary, gated to high-confidence signatures+ * so legitimate prose is never mutated:+ *+ * - a closing XML-ish tag for a known tool-call field+ * (`</principle>`, `</parameter>`, `</antml...>`) - prose has no+ * reason to close a tag it never opened;+ * - an opening `<parameter ...>` fragment ONLY when its attribute+ * region carries escaped quotes (`name=\"...`) - the unmistakable+ * mark of a serialized tool call, unlike a plain `<parameter>`+ * mention in documentation text.+ *+ * Everything from the first match onward is dropped - the genuine+ * principle text always precedes the leak.+ */+const TOOL_CALL_LEAK_RE = /<\/(?:principle|parameter|antml[\w:-]*)>|<parameter\b[^>]*?\\+"/i;++/**+ * TWO or more backslashes immediately before a double quote: the+ * escape-amplification artifact. A single `\"` is left alone - it can+ * be legitimate prose about escaping.+ */+const ESCAPE_CHAIN_RE = /\\{2,}"/g;++/** Literal backslash-escape text (`\n`, `\\n`, ...) left at a cut edge. */+const TRAILING_ESCAPE_LITERALS_RE = /(?:\\+[nrt])+\s*$/;++export function sanitisePrinciple(value: unknown): string {+ if (typeof value !== "string") return "";+ let s = value;++ const leak = TOOL_CALL_LEAK_RE.exec(s);+ if (leak) {+ s = s.slice(0, leak.index);+ // Cut-edge residue (`...\n` literals) only exists when a leak was+ // cut; outside that branch a trailing literal `\n` may be the+ // rule's own text.+ s = s.replace(TRAILING_ESCAPE_LITERALS_RE, "");+ }++ s = s.replace(ESCAPE_CHAIN_RE, '"');++ return s.trim();+}++/** True when {@link sanitisePrinciple} would change the text. */+export function principleNeedsRepair(value: unknown): boolean {+ return typeof value === "string" && sanitisePrinciple(value) !== value;+}diff --git a/src/core/brain/text/text-budget.ts b/src/core/brain/text/text-budget.tsnew file mode 100644index 00000000..078ced31--- /dev/null+++ b/src/core/brain/text/text-budget.ts@@ -0,0 +1,156 @@+/**+ * Section-aware character budget (token-diet).+ *+ * Generalizes the head-budget idea from `pre-compress-pack.ts` /+ * `recall-budget.ts` to whole document sections: the caller hands an+ * ordered list of sections (render order) with a drop priority, and+ * the budget pass returns a body that fits the character budget by+ *+ * 1. dropping whole sections, least important first;+ * 2. when the remainder still overflows, trimming the least+ * important kept section from its tail at LINE boundaries -+ * never mid-line, so the output is always well-formed Markdown;+ * 3. appending an optional one-line truncation notice that rides+ * on top of the budget (it is the pointer to the full view, so+ * it must survive even a zero budget).+ *+ * Pure and deterministic: no I/O, clock, or randomness. Identical+ * inputs produce identical outputs - the property the active.md+ * idempotent-write check depends on.+ */++export interface BudgetSection {+ /** Stable identifier reported in `droppedKeys`. */+ readonly key: string;+ /**+ * Drop priority: LOWER value = more important. Sections with the+ * highest value drop first; ties drop the later section first.+ */+ readonly priority: number;+ /** Rendered section text, headers included. */+ readonly text: string;+}++export interface SectionBudgetOptions {+ /**+ * One-line notice appended (after a blank-line separator when any+ * content is kept) whenever truncation occurred. Not counted+ * against the budget.+ */+ readonly notice?: string;+}++export interface SectionBudgetResult {+ /** Budgeted body: kept sections in render order, plus the notice when truncated. */+ readonly body: string;+ /** True when any section was dropped or trimmed. */+ readonly truncated: boolean;+ /** Keys of fully dropped sections, in drop order. */+ readonly droppedKeys: ReadonlyArray<string>;+}++const SEPARATOR = "\n\n";++interface KeptSection extends BudgetSection {+ /** Position in the caller's render order. */+ readonly index: number;+}++function joinedLength(parts: ReadonlyArray<{ readonly text: string }>): number {+ if (parts.length === 0) return 0;+ let total = SEPARATOR.length * (parts.length - 1);+ for (const p of parts) total += p.text.length;+ return total;+}++/** Index of the least important kept section: max priority, ties -> later index. */+function leastImportantIndex(kept: ReadonlyArray<KeptSection>): number {+ let at = -1;+ for (let i = 0; i < kept.length; i++) {+ const s = kept[i]!;+ if (at === -1) {+ at = i;+ continue;+ }+ const cur = kept[at]!;+ if (s.priority > cur.priority || (s.priority === cur.priority && s.index > cur.index)) {+ at = i;+ }+ }+ return at;+}++/**+ * Trim `text` from the tail at line boundaries so the result fits+ * `maxChars`. Trailing blank lines left behind by the cut are removed.+ * Returns null when not even the first line fits.+ */+function trimToLines(text: string, maxChars: number): string | null {+ if (text.length <= maxChars) return text;+ const lines = text.split("\n");+ while (lines.length > 0) {+ lines.pop();+ while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();+ const candidate = lines.join("\n");+ if (candidate.length === 0) return null;+ if (candidate.length <= maxChars) return candidate;+ }+ return null;+}++/**+ * Fit ordered sections into `budgetChars`. See the module docblock for+ * the drop/trim policy. A non-positive budget keeps nothing - the+ * result is the notice alone (or an empty body without one).+ */+export function applySectionBudget(+ sections: ReadonlyArray<BudgetSection>,+ budgetChars: number,+ opts: SectionBudgetOptions = {},+): SectionBudgetResult {+ const budget = Number.isFinite(budgetChars) ? Math.max(0, Math.floor(budgetChars)) : 0;+ const kept: KeptSection[] = sections.map((s, index) => ({ ...s, index }));+ const droppedKeys: string[] = [];+ let trimmedAny = false;++ // 1. Whole-section drops, least important first. Intermediate+ // sections are never partially kept - a half section with its header+ // reads as complete and would mislead the consumer.+ while (kept.length > 1 && joinedLength(kept) > budget) {+ const at = leastImportantIndex(kept);+ droppedKeys.push(kept[at]!.key);+ kept.splice(at, 1);+ }++ // 2. Last resort: only the single most important section remains and+ // still overflows - trim its tail at line boundaries; drop it when+ // not even its first line fits.+ if (kept.length === 1 && joinedLength(kept) > budget) {+ const last = kept[0]!;+ const trimmed = trimToLines(last.text, budget);+ if (trimmed === null) {+ droppedKeys.push(last.key);+ kept.splice(0, 1);+ } else {+ kept[0] = { ...last, text: trimmed };+ trimmedAny = true;+ }+ }++ const truncated = trimmedAny || droppedKeys.length > 0;+ const content = kept+ .toSorted((a, b) => a.index - b.index)+ .map((s) => s.text)+ .join(SEPARATOR);++ let body = content;+ if (truncated && opts.notice !== undefined && opts.notice.length > 0) {+ body = content.length > 0 ? content + SEPARATOR + opts.notice : opts.notice;+ }++ return Object.freeze({+ body,+ truncated,+ droppedKeys: Object.freeze(droppedKeys),+ });+}diff --git a/src/core/brain/types.ts b/src/core/brain/types.tsindex ebac9031..dfd576e1 100644--- a/src/core/brain/types.ts+++ b/src/core/brain/types.ts@@ -856,6 +856,12 @@ export interface BrainMostAppliedConfig {/** Container for the `active:` block of `_brain.yaml`. */export interface BrainActiveConfig {readonly most_applied?: BrainMostAppliedConfig;+ /**+ * Character budget for the active.md body injected at SessionStart+ * (token-diet). Absent means the INJECT_BUDGET_CHARS_DEFAULT from+ * policy.ts applies.+ */+ readonly inject_budget_chars?: number;}/**diff --git a/src/core/brain/upgrade.ts b/src/core/brain/upgrade.tsindex ebfd39ed..5deddac4 100644--- a/src/core/brain/upgrade.ts+++ b/src/core/brain/upgrade.ts@@ -1,8 +1,11 @@/**- * Brain managed-file upgrade for the three release-owned files in- * `Brain/` (`_brain.yaml`, `_BRAIN.md`).- * User-owned content (`preferences/`, `retired/`, `inbox/`, `log/`)- * is never touched.+ * Brain managed-file upgrade for the release-owned files in+ * `Brain/` (`_brain.yaml`, `_BRAIN.md`), plus one narrow repair pass+ * over `preferences/`: principle frontmatter corrupted by leaked+ * tool-call fragments or escape-amplified quote chains is rewritten+ * once through `sanitisePrinciple` (token-diet, t_40eb1de7). Beyond+ * that repair, user-owned content (`preferences/`, `retired/`,+ * `inbox/`, `log/`) is never touched.** Key design choice: `_brain.yaml` is text-walked rather than* re-serialised through the strict parser, because the live file@@ -12,10 +15,12 @@* `status: "error"` so `--apply` refuses to half-merge.*/-import { existsSync, readFileSync } from "node:fs";+import { existsSync, readFileSync, readdirSync } from "node:fs";import { join } from "node:path";import { atomicWriteFileSync } from "../fs-atomic.ts";+import { formatFrontmatter, parseFrontmatterText } from "../vault.ts";+import { sanitisePrinciple } from "./text/sanitize-principle.ts";import { defaultConfigPath, resolveAgentName } from "../config.ts";import { appendLogEvent } from "./log.ts";import { brainConfigPath, brainManualPath, vaultRelative } from "./paths.ts";@@ -93,6 +98,7 @@ export function planUpgrade(vault: string): UpgradePlan {vaultRelative(brainManualPath(vault), vault),() => renderBrainManual(vault),),+ ...planCorruptedPreferences(vault),];const pending = files.filter((f) => f.status === "update").length;const errors = files.filter((f) => f.status === "error").length;@@ -529,3 +535,52 @@ function insertLinesAtSectionEnd(const after = lines.slice(insertAt);return [...before, ...newLines, ...after].join("\n");}++// ----- Corrupted preference repair (token-diet, t_40eb1de7) ----------------++/**+ * One narrow, idempotent repair over `Brain/preferences/`: rewrite+ * files whose `principle` frontmatter still carries leaked tool-call+ * fragments or escape-amplified quote chains (written before the+ * write-seam sanitizer and the frontmatter unescape fix shipped).+ *+ * The rewrite goes through the raw frontmatter map - not the typed+ * preference parser - so every other field round-trips through the+ * same `formatFrontmatter` the writers use and unknown keys survive+ * verbatim. Files that fail to parse, or whose principle is already+ * clean, are left untouched; on the pass after the repair the plan is+ * empty again.+ */+function planCorruptedPreferences(vault: string): UpgradeFilePlan[] {+ const dir = join(vault, "Brain", "preferences");+ if (!existsSync(dir)) return [];+ const plans: UpgradeFilePlan[] = [];+ for (const name of readdirSync(dir).toSorted()) {+ if (!name.endsWith(".md")) continue;+ const abs = join(dir, name);+ const rel = `Brain/preferences/${name}`;+ let before: string;+ try {+ before = readFileSync(abs, "utf8");+ } catch {+ continue; // unreadable file is doctor's domain, not upgrade's+ }+ const [meta, body] = parseFrontmatterText(before);+ const principle = meta["principle"];+ if (typeof principle !== "string") continue;+ const repaired = sanitisePrinciple(principle);+ if (repaired === principle || repaired.length === 0) continue;+ const after = formatFrontmatter({ ...meta, principle: repaired }, body);+ if (after === before) continue;+ plans.push(+ Object.freeze({+ path: rel,+ status: "update" as const,+ before,+ after,+ error: "",+ }),+ );+ }+ return plans;+}diff --git a/src/core/vault.ts b/src/core/vault.tsindex ad02a966..a09f8117 100644--- a/src/core/vault.ts+++ b/src/core/vault.ts@@ -338,15 +338,38 @@ function walk(}function stripQuotes(s: string): string {- if (- s.length >= 2 &&- ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'")))- ) {+ if (s.length >= 2 && s.startsWith('"') && s.endsWith('"')) {+ // Symmetric inverse of `formatYamlScalar`: the formatter escapes+ // \ " \n \r \t inside double-quoted scalars, so the parser must+ // unescape the same set. Without this inverse every+ // parse -> format cycle doubled the backslashes (escape+ // amplification - the source of the \\\\\\" chains observed in+ // live preference frontmatter).+ return unescapeDoubleQuoted(s.slice(1, -1));+ }+ if (s.length >= 2 && s.startsWith("'") && s.endsWith("'")) {+ // The formatter never emits single quotes; treat them as plain+ // delimiters (hand-written YAML) without escape processing.return s.slice(1, -1);}return s;}+const DOUBLE_QUOTED_ESCAPES: Readonly<Record<string, string>> = Object.freeze({+ "\\": "\\",+ '"': '"',+ n: "\n",+ r: "\r",+ t: "\t",+});++function unescapeDoubleQuoted(inner: string): string {+ // Single pass so `\\n` decodes to `\n` (backslash + n), not a+ // newline - sequential .replace calls would re-scan their own+ // output and corrupt exactly the chains we are trying to preserve.+ return inner.replace(/\\([\\"nrt])/g, (_, ch: string) => DOUBLE_QUOTED_ESCAPES[ch] ?? `\\${ch}`);+}+/*** Split the body of an inline YAML array on commas, but only on commas that* appear outside quoted runs. Without this, `[plain, "needs, comma"]` woulddiff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.tsindex 17f47746..c38d7b93 100644--- a/src/mcp/brain-tools.ts+++ b/src/mcp/brain-tools.ts@@ -172,7 +172,7 @@ import {} from "../core/brain/pinned.ts";import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "./protocol.ts";-import type { ServerContext, ToolDefinition } from "./tools.ts";+import { deprecatedAlias, type ServerContext, type ToolDefinition } from "./tools.ts";import { MCP_PREVIEW_BUDGET } from "./preview-budget.ts";import {coerceStr,@@ -2372,7 +2372,180 @@ async function toolMcpLandscape(ctx: ServerContext): Promise<Record<string, unkn};}+// ----- Consolidated view tools (token-diet, t_3920db77) ---------------------++const BRIEF_VIEW_HANDLERS: Readonly<+ Record<string, (ctx: ServerContext, args: Record<string, unknown>) => Promise<unknown> | unknown>+> = Object.freeze({+ morning: toolBrainMorningBrief,+ daily: toolBrainDailyBrief,+ weekly: toolBrainWeeklySynthesis,+ monthly: toolBrainMonthlyReview,+ operator: toolBrainOperatorSummary,+ digest: toolBrainDigest,+});++const ANALYTICS_VIEW_HANDLERS: Readonly<+ Record<string, (ctx: ServerContext, args: Record<string, unknown>) => Promise<unknown> | unknown>+> = Object.freeze({+ timeline: toolBrainTimeline,+ attention_flows: toolBrainAttentionFlows,+ belief_evolution: toolBrainBeliefEvolution,+ concept_synthesis: toolBrainConceptSynthesis,+});++function dispatchByView(+ table: Readonly<+ Record<+ string,+ (ctx: ServerContext, args: Record<string, unknown>) => Promise<unknown> | unknown+ >+ >,+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<unknown> | unknown {+ const view = typeof args["view"] === "string" ? args["view"] : "";+ const handler = table[view];+ if (handler === undefined) {+ throw new MCPError(+ INVALID_PARAMS,+ `view must be one of ${Object.keys(table).join(", ")}; got ${JSON.stringify(args["view"])}`,+ );+ }+ return handler(ctx, args);+}++async function toolBrainBrief(ctx: ServerContext, args: Record<string, unknown>): Promise<unknown> {+ return await dispatchByView(BRIEF_VIEW_HANDLERS, ctx, args);+}++async function toolBrainAnalytics(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<unknown> {+ // attention_flows requires an `operation`; the consolidated surface+ // defaults it to the read-only `list` so `{view}` alone is valid.+ const withDefaults = args["view"] === "attention_flows" ? { operation: "list", ...args } : args;+ return await dispatchByView(ANALYTICS_VIEW_HANDLERS, ctx, withDefaults);+}+export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([+ {+ name: "brain_brief",+ previewBudget: MCP_PREVIEW_BUDGET,+ description:+ "Read-only Brain summary, one tool for every window: view=morning (session-start brief), daily, weekly, monthly, operator (maintenance dashboard), or digest (activity window). Replaces the per-window brief tools.",+ inputSchema: {+ type: "object",+ properties: {+ view: {+ type: "string",+ enum: ["morning", "daily", "weekly", "monthly", "operator", "digest"],+ description: "Which summary to produce.",+ },+ date: {+ type: "string",+ description: "view=daily: ISO date (YYYY-MM-DD), default today UTC.",+ },+ week_end: {+ type: "string",+ description: "view=weekly: ISO end date (exclusive), default today UTC.",+ },+ month: {+ type: "string",+ description: "view=monthly: target month (YYYY-MM), default current UTC month.",+ },+ since: {+ type: "string",+ description: "view=digest: inclusive ISO lower bound, default until - 24h.",+ },+ until: {+ type: "string",+ description: "view=digest: exclusive ISO upper bound, default now.",+ },+ format: {+ type: "string",+ enum: ["markdown", "json"],+ description: "view=digest: output format, default markdown.",+ },+ top_k: {+ type: "integer",+ minimum: 1,+ description: "view=morning: max confirmed preferences (default 10).",+ },+ lookback_days: {+ type: "integer",+ minimum: 1,+ description: "view=morning: days of log history (default 7).",+ },+ max_chars_per_memory: {+ type: "integer",+ minimum: 1,+ description: "view=morning: per-entry character cap.",+ },+ max_total_chars: {+ type: "integer",+ minimum: 1,+ description: "view=morning: total character cap.",+ },+ include_dream: {+ type: "boolean",+ description: "view=operator: fold a dry-run dream delta in (default true).",+ },+ top_actions: {+ type: "integer",+ minimum: 0,+ description: "view=operator: cap on ranked actions (default 5).",+ },+ },+ required: ["view"],+ additionalProperties: false,+ },+ handler: toolBrainBrief,+ },+ {+ name: "brain_analytics",+ previewBudget: MCP_PREVIEW_BUDGET,+ description:+ "Read-only Brain analytics, one tool for every lens: view=timeline (event history), attention_flows, belief_evolution, or concept_synthesis. Replaces the per-lens analytics tools.",+ inputSchema: {+ type: "object",+ properties: {+ view: {+ type: "string",+ enum: ["timeline", "attention_flows", "belief_evolution", "concept_synthesis"],+ description: "Which analytics lens to run.",+ },+ pref_id: {+ type: "string",+ description: "timeline / belief_evolution: target preference id.",+ },+ topic: { type: "string", description: "timeline / belief_evolution: target topic slug." },+ kind: { type: "string", description: "view=timeline: restrict to one event kind." },+ since: { type: "string", description: "view=timeline: inclusive ISO lower bound." },+ until: { type: "string", description: "view=timeline: exclusive ISO upper bound." },+ limit: { type: "integer", minimum: 1, description: "view=timeline: max events returned." },+ id: { type: "string", description: "view=concept_synthesis: target id (e.g. pref-foo)." },+ include_unlinked: {+ type: "boolean",+ description: "view=concept_synthesis: include raw-text mentions (default false).",+ },+ operation: {+ type: "string",+ enum: ["list", "evaluate", "render"],+ description: "view=attention_flows: operation, default list.",+ },+ flow_id: {+ type: "string",+ description: "view=attention_flows: flow id for evaluate/render.",+ },+ },+ required: ["view"],+ additionalProperties: false,+ },+ handler: toolBrainAnalytics,+ },+{name: "brain_feedback",description:@@ -2415,7 +2588,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([force_confirmed: {type: "boolean",description:- "When true, additionally creates a `pref-*` resource with `status: confirmed` alongside the inbox signal. The signal is always written to `Brain/inbox/`; this flag only adds an immediately-active preference (skipping the usual dream-pass promotion step).",+ "When true, also creates an immediately-active confirmed `pref-*` alongside the inbox signal, skipping the dream-pass promotion step.",},},required: ["topic", "signal", "principle"],@@ -2442,7 +2615,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([agent: {type: "string",description:- "Optional caller identity. Compared against `Brain/_brain.yaml.primary_agent`; a mismatch emits a `non-primary-dream-run` warning in the response. Defaults to the server-resolved agent name.",+ "Optional caller identity; a mismatch with the configured primary agent emits a warning. Defaults to the server-resolved name.",},},additionalProperties: false,@@ -2484,26 +2657,18 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([handler: toolBrainRetention,},{- name: "brain_monthly_review",+ ...deprecatedAlias({+ name: "brain_monthly_review",+ target: "brain_brief",+ view: "monthly",+ handler: toolBrainMonthlyReview,+ }),previewBudget: MCP_PREVIEW_BUDGET,- description:- "Read-only monthly synthesis over Brain timeline activity: event count, status transitions, retirements, contradictions, and neglected areas.",- inputSchema: {- type: "object",- properties: {- month: {- type: "string",- description: "Optional target month in YYYY-MM form. Defaults to the current UTC month.",- },- },- additionalProperties: false,- },- handler: toolBrainMonthlyReview,},{name: "brain_review_candidates",description:- "Read-only preview of what the next `brain_dream` invocation would do. Returns `would_create`, `would_promote`, `would_retire`, `would_supersede`, `clusters_below_threshold`, `gated_retires`, and `intent_reviews` without mutating any files. Useful for agents that want to be deliberate before triggering the learning pass, or for operators inspecting the dream pass intent.",+ "Read-only preview of the next `brain_dream` pass: would_create / would_promote / would_retire / would_supersede, clusters below threshold, gated retires, and intent reviews. Mutates nothing.",inputSchema: {type: "object",properties: {@@ -2531,13 +2696,13 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([artifact: {type: "string",description:- "Wikilink identifying the artifact. Accepts an optional inclusive line-range suffix for claim-level provenance, e.g. `[[src/cli/main.ts:120-145]]` or `[[src/cli/main.ts:42]]`.",+ "Wikilink identifying the artifact; optional inclusive line-range suffix, e.g. `[[src/cli/main.ts:120-145]]`.",},result: {type: "string",enum: ["applied", "violated", "outdated"],description:- "`applied` if the rule held in this artifact, `violated` if it was broken, `outdated` if the rule's scope still matches but the artifact shows the rule itself is obsolete (e.g. framework migration).",+ "`applied` if the rule held, `violated` if broken, `outdated` if the artifact shows the rule itself is obsolete.",},agent: {type: "string",@@ -2556,7 +2721,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_note",description:- "Append one narrative-milestone line to today's Brain log (`Brain/log/<today>.md` plus its JSONL sidecar) under the `note` event kind. Use for events that are neither a new preference nor evidence against an existing one — release shipped, PR merged, fact discovered. Multi-line text is collapsed to one space-joined line; secret-shaped tokens are redacted.",+ "Append one narrative-milestone line (release shipped, PR merged, fact discovered) to today's Brain log under the `note` event kind. Use when neither brain_feedback nor brain_apply_evidence fits.",inputSchema: {type: "object",properties: {@@ -2610,33 +2775,17 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([handler: toolBrainContext,},{- name: "brain_digest",+ ...deprecatedAlias({+ name: "brain_digest",+ target: "brain_brief",+ view: "digest",+ handler: toolBrainDigest,+ }),previewBudget: MCP_PREVIEW_BUDGET,- description:- "Render a human-readable summary of Brain activity in the last 24h (default) or a custom window. Read-only.",- inputSchema: {- type: "object",- properties: {- since: {- type: "string",- description: "Inclusive lower bound (ISO-8601). Defaults to `until - 24h`.",- },- until: {- type: "string",- description: "Exclusive upper bound (ISO-8601). Defaults to `now`.",- },- format: {- type: "string",- enum: ["markdown", "json"],- description: "Output format. Defaults to `markdown`.",- },- },- additionalProperties: false,- },- handler: toolBrainDigest,},{name: "brain_query",+ previewBudget: MCP_PREVIEW_BUDGET,description:"Read-only lookup: one preference + its evidence trail, all artifacts under a topic, or every log event after a timestamp. Exactly one of `preference`, `topic`, `since` must be supplied.",inputSchema: {@@ -2669,6 +2818,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_agent_query",+ previewBudget: MCP_PREVIEW_BUDGET,description:"Read-only source-agent retrieval over Brain provenance. Filters by agents, topic, free-text query, contribution kind, and limit; returns deterministic matched contributions plus a summary.",inputSchema: {@@ -2820,6 +2970,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_backlinks",+ previewBudget: MCP_PREVIEW_BUDGET,description:"List inbound references to a Brain artifact id (preference, retired, or signal). Returns every source that points at the id via wikilink, in any preference/retired frontmatter field, body prose, signal source, or log payload. Read-only.",inputSchema: {@@ -2838,8 +2989,9 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_audit",+ previewBudget: MCP_PREVIEW_BUDGET,description:- "Return a preference's full mutation audit trail (create / promote / update / retire / merge), oldest first, with agent, reason, and revision + content-hash before/after. The trail is keyed by the original `pref-<slug>` id; a `ret-<slug>`, bare `<slug>`, or wikilink-decorated argument resolves to the same trail. Read-only.",+ "Return a preference's full mutation audit trail (create / promote / update / retire / merge), oldest first, with agent, reason, and revisions. Accepts pref-/ret-/bare/wikilink ids. Read-only.",inputSchema: {type: "object",properties: {@@ -2855,36 +3007,12 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([handler: toolBrainAudit,},{- name: "brain_morning_brief",- description:- "Return a read-only session-start summary: top confirmed preferences (confidence then recency), open questions raised by the recent reconcile phase, and recent narrative notes. Bounded by per-entry and total character caps. Read-only.",- inputSchema: {- type: "object",- properties: {- top_k: {- type: "integer",- minimum: 1,- description: "Max confirmed preferences to consider (default 10).",- },- lookback_days: {- type: "integer",- minimum: 1,- description: "Days of log history scanned for open questions + notes (default 7).",- },- max_chars_per_memory: {- type: "integer",- minimum: 1,- description: "Per-entry character cap (code points).",- },- max_total_chars: {- type: "integer",- minimum: 1,- description: "Total character cap across the brief.",- },- },- additionalProperties: false,- },- handler: toolBrainMorningBrief,+ ...deprecatedAlias({+ name: "brain_morning_brief",+ target: "brain_brief",+ view: "morning",+ handler: toolBrainMorningBrief,+ }),},{name: "brain_sources",@@ -2932,7 +3060,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([type: "integer",minimum: 1,description:- "Optional per-page character cap (code points): trim any single oversized page's body before it consumes the token budget, so one huge page cannot crowd out the rest. Trimmed pages carry `trimmed: true`.",+ "Optional per-page character cap so one huge page cannot crowd out the rest; trimmed pages carry `trimmed: true`.",},max_total_chars: {type: "integer",@@ -3034,6 +3162,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_recall_telemetry",+ previewBudget: MCP_PREVIEW_BUDGET,description:"List recall telemetry records or summarize recall coverage and knowledge gaps. Records are emitted only by opt-in callers. Read-only.",inputSchema: {@@ -3221,26 +3350,13 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([handler: toolBrainProceduralGraph,},{- name: "brain_attention_flows",- description:- "List/evaluate/render declarative attention-flow recipes for open loops and learnings.",- inputSchema: {- type: "object",- properties: {- operation: {- type: "string",- enum: ["list", "evaluate", "render"],- description: "Tool operation.",- },- flow_id: {- type: "string",- description: "Flow id for evaluate/render operations.",- },- },- required: ["operation"],- additionalProperties: false,- },- handler: toolBrainAttentionFlows,+ ...deprecatedAlias({+ name: "brain_attention_flows",+ target: "brain_analytics",+ view: "attention_flows",+ handler: toolBrainAttentionFlows,+ }),+ previewBudget: MCP_PREVIEW_BUDGET,},{name: "brain_pre_compact_extract",@@ -3279,6 +3395,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_session_grep",+ previewBudget: MCP_PREVIEW_BUDGET,description: "Search imported session recall raw turns and summary nodes.",inputSchema: {type: "object",@@ -3319,6 +3436,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_session_expand",+ previewBudget: MCP_PREVIEW_BUDGET,description:"Expand a session recall raw or summary node to immediate sources and paginated exact raw turn content.",inputSchema: {@@ -3345,7 +3463,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([// is already bounded by its own per-entry / total character caps.name: "brain_pre_compress_pack",description:- "Return a compact system-prompt addendum of the top-K highest-confidence confirmed preferences plus the head of active.md, so a host runtime can inject it just before a context-compression event and keep high-salience constraints from rotating out. Bounded by optional per-memory and total character caps. Read-only.",+ "Return a compact system-prompt addendum (top-K confirmed preferences plus the head of active.md) for a host to inject right before context compression. Char-budgeted. Read-only.",inputSchema: {type: "object",properties: {@@ -3399,6 +3517,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_unlinked_mentions",+ previewBudget: MCP_PREVIEW_BUDGET,description:"Raw-text mentions of a target's title / aliases that are NOT already inside `[[...]]`. Walks Brain/preferences and Brain/retired; match boundary is Unicode-aware (codepoint class), language-agnostic. Read-only.",inputSchema: {@@ -3422,27 +3541,13 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([handler: toolBrainUnlinkedMentions,},{- name: "brain_concept_synthesis",+ ...deprecatedAlias({+ name: "brain_concept_synthesis",+ target: "brain_analytics",+ view: "concept_synthesis",+ handler: toolBrainConceptSynthesis,+ }),previewBudget: MCP_PREVIEW_BUDGET,- description:- "Concept-scoped cluster: target note + every artifact that wikilinks to it (depth-1), optionally including unlinked-mention rows. Deterministic JSON envelope, no LLM call inside. Read-only.",- inputSchema: {- type: "object",- properties: {- id: {- type: "string",- description: "Target id (e.g. `pref-foo`). Wikilink decoration is stripped if present.",- },- include_unlinked: {- type: "boolean",- description:- "When true, also populate `unlinked_mentions` (raw-text mentions outside `[[...]]`). Defaults to false.",- },- },- required: ["id"],- additionalProperties: false,- },- handler: toolBrainConceptSynthesis,},{name: "brain_moc_audit",@@ -3462,63 +3567,22 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([handler: toolBrainMocAudit,},{- name: "brain_timeline",+ ...deprecatedAlias({+ name: "brain_timeline",+ target: "brain_analytics",+ view: "timeline",+ handler: toolBrainTimeline,+ }),previewBudget: MCP_PREVIEW_BUDGET,- description:- "Chronological list of Brain events filtered by any combination of pref_id, topic, kind, since, until, limit. Returns the canonical TimelineIndex projection. Read-only.",- inputSchema: {- type: "object",- properties: {- pref_id: {- type: "string",- description: "Restrict to events for this preference / retired / signal id.",- },- topic: {- type: "string",- description: "Restrict to events for this topic slug.",- },- kind: {- type: "string",- description: "Restrict to events of this BrainLogEventKind (e.g. `apply-evidence`).",- },- since: {- type: "string",- description: "Inclusive lower bound (ISO date or ISO timestamp). Defaults to epoch.",- },- until: {- type: "string",- description: "Exclusive upper bound (ISO date or ISO timestamp). Defaults to now.",- },- limit: {- type: "integer",- minimum: 1,- description: "Maximum number of events to return after filtering. Omit for no cap.",- },- },- additionalProperties: false,- },- handler: toolBrainTimeline,},{- name: "brain_belief_evolution",- description:- "Per-preference or per-topic chronological story: status transitions (creation/promotion/retirement) derived from dream summaries, evidence rollup with running counts, and retirement chain. Read-only.",- inputSchema: {- type: "object",- properties: {- pref_id: {- type: "string",- description: "Target preference id (e.g. `pref-foo`). Mutually exclusive with `topic`.",- },- topic: {- type: "string",- description:- "Target topic slug. Aggregates every pref-* / ret-* sharing the topic. Mutually exclusive with `pref_id`.",- },- },- additionalProperties: false,- },- handler: toolBrainBeliefEvolution,+ ...deprecatedAlias({+ name: "brain_belief_evolution",+ target: "brain_analytics",+ view: "belief_evolution",+ handler: toolBrainBeliefEvolution,+ }),+ previewBudget: MCP_PREVIEW_BUDGET,},{name: "brain_stale_scan",@@ -3532,61 +3596,30 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([handler: toolBrainStaleScan,},{- name: "brain_daily_brief",+ ...deprecatedAlias({+ name: "brain_daily_brief",+ target: "brain_brief",+ view: "daily",+ handler: toolBrainDailyBrief,+ }),previewBudget: MCP_PREVIEW_BUDGET,- description:- "Deterministic daily brief: events grouped by kind, status transitions, vault delta (newPromotions / newRetired / newFeedback / evidenceApplied / evidenceViolated), and deduplicated artifact wikilinks. Read-only.",- inputSchema: {- type: "object",- properties: {- date: {- type: "string",- description: "ISO date (`YYYY-MM-DD`) the brief targets. Defaults to today UTC.",- },- },- additionalProperties: false,- },- handler: toolBrainDailyBrief,},{- name: "brain_weekly_synthesis",+ ...deprecatedAlias({+ name: "brain_weekly_synthesis",+ target: "brain_brief",+ view: "weekly",+ handler: toolBrainWeeklySynthesis,+ }),previewBudget: MCP_PREVIEW_BUDGET,- description:- "Deterministic 7-day synthesis: events grouped by kind, status transitions, retired-in-window list, contradictions (signal-suppressed + apply-evidence violated), vault delta, and source pointers. Read-only.",- inputSchema: {- type: "object",- properties: {- week_end: {- type: "string",- description:- "ISO date (`YYYY-MM-DD`) the 7-day window ends at (exclusive). Defaults to today UTC.",- },- },- additionalProperties: false,- },- handler: toolBrainWeeklySynthesis,},{- name: "brain_operator_summary",+ ...deprecatedAlias({+ name: "brain_operator_summary",+ target: "brain_brief",+ view: "operator",+ handler: toolBrainOperatorSummary,+ }),previewBudget: MCP_PREVIEW_BUDGET,- description:- "Aggregate operator dashboard: trust verdict, doctor + dream counts, verification delta, ranked maintenance actions, and instruction-file ceiling warnings. Read-only.",- inputSchema: {- type: "object",- properties: {- include_dream: {- type: "boolean",- description:- "When true (default), run a dry-run dream pass and fold its verification delta into the summary.",- },- top_actions: {- type: "integer",- minimum: 0,- description: "Cap on the ranked maintenance action list. Defaults to 5.",- },- },- additionalProperties: false,- },- handler: toolBrainOperatorSummary,},]);diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.tsindex 67dcc963..f0aa12f0 100644--- a/src/mcp/instructions.ts+++ b/src/mcp/instructions.ts@@ -56,99 +56,37 @@ export function buildInstructions(opts: BuildInstructionsOpts | string): stringif (scope === "writer") return WRITER_INSTRUCTIONS;+ // Deliberately terse (token-diet): per-tool detail lives in the tool+ // descriptions and docs/mcp.md; this text carries only the contract+ // that cannot be read off the schemas.return (`You are @${agent} on this Open Second Brain vault. ` +"Always log under this identity; do not invent or change the name.\n\n" +- "Brain tools are the agent-facing writable surface (design doc §9).\n" +- " - brain_feedback — call once per taste signal the user (or a " +- 'teammate agent) expresses: corrections ("don\'t do X"), stated ' +- 'preferences ("use A instead of B"), or process rules that ' +- "should outlast the current turn. With `force_confirmed: true` " +- "the preference is created directly (skipping the dream trial " +- "window).\n" +- " - brain_apply_evidence — call right after you produce a " +- "durable artifact (code shipped, config / instruction edited, " +- "content drafted) and at least one preference in " +- "`Brain/preferences/` scopes to that artifact. Record " +- "`result: applied | violated | outdated` per (preference, " +- "artifact) pair.\n" +- " - brain_note — call when this turn produced a durable " +- "narrative milestone (release shipped, PR merged, fact " +- "discovered) that fits neither `brain_feedback` nor " +- "`brain_apply_evidence`. Lands one line under event kind " +- "`note` in `Brain/log/<today>.md` (and the JSONL sidecar). " +- "This is the Brain-native replacement for the retired " +- "`event_log_append` tool.\n" +- " - brain_pinned_context — read/write/append/clear " +- "`Brain/pinned.md` for current-task facts that should survive " +- "context rotation without becoming permanent preferences.\n" +- " - brain_context — read-only session bootstrap that returns " +- "`Brain/active.md`, pinned current-task context, and active " +- "preference counts. Use it at session start when the host runtime " +- "does not inject active.md via a hook.\n" +- " - brain_dream — runs the deterministic learning pass " +- "(clusters signals, promotes preferences, retires stale rules). " +- "Usually scheduled via cron, not invoked interactively.\n" +- " - brain_review_candidates — read-only preview of what the " +- "next `brain_dream` invocation would do. Returns `would_create`, " +- "`would_promote`, `would_retire`, `would_supersede`, " +- "`clusters_below_threshold`, and `gated_retires` without mutating " +- "any files. Use it when you want to be deliberate before " +- "triggering the learning pass.\n" +- " - brain_digest — read-only summary of the last activity " +- 'window. Default format is Markdown; pass `format: "json"` for ' +- "programmatic use.\n" +- " - brain_query — read-only lookup by `preference`, `topic`, " +- "or `since` (exactly one). Use this to discover applicable rules " +- "before calling `brain_apply_evidence`.\n" +- " - brain_doctor — invariant / schema health check. With " +- "`strict: true`, warnings demote the `ok` flag.\n" +- " - brain_audit — read-only mutation trail for one preference " +- "(create / promote / update / retire / merge), with agent, reason, " +- "and revision + content-hash before/after.\n" +- " - brain_morning_brief — read-only session-start summary: top " +- "confirmed preferences, recent reconcile open questions, and recent " +- "notes, bounded by a character budget.\n" +- " - brain_sources — read-only dashboard of signals grouped by " +- "(agent, source_type) with active/processed and distinct-topic counts.\n" +- " - brain_switch_vault — activate a named vault profile; the change " +- "takes effect on the next server launch.\n\n" +- "Skip Brain calls for casual chat, exploration without a stated " +- "rule, read-only inspection, and trivial edits. A misrecorded " +- "signal is worse than a missed one — the dream pass surfaces " +- "real patterns from repeat events, so prefer precision over " +- "coverage.\n\n" +- "Other tools: second_brain_status (config status), " +- "vault_health (verify vault), second_brain_query (list vault pages " +- "by title - read-only). brain_pre_compress_pack returns a compact " +- "system-prompt addendum (top confirmed preferences + the head of " +- "active.md) for a host runtime to inject just before a " +- "context-compression event - read-only.\n\n" +- "Preview budget: large tool results may come back as a preview " +- "envelope - a JSON object with `preview_truncated: true`, " +- "`bytes_preview` (a head slice), `full_chars`, and an `artifact_id`. " +- "The full payload is not lost: call brain_artifact_get with that " +- "`artifact_id` to retrieve the complete result. Only fetch the full " +- "payload when the preview is insufficient - that is the point of the " +- "budget, to keep your context lean by default.\n\n" +- "Pay Memory tools record paid agent actions as inspectable Markdown:\n" +- " - payment_memory_init bootstraps the layout and writes the " +- "spending policy template (run once per vault).\n" +- " - payment_policy_check evaluates a prospective paid call against " +- `\`${PAY_MEMORY_SPENDING_JSON_REL}\` (allowed / approval_required / denied).\n` +- " - payment_request_approval creates a pending-payment-request the " +- "user must approve before you run `pay`; payment_request_status polls " +- "for approval; payment_request_consume links the eventual receipt.\n" +- " - payment_receipt_append saves a Markdown receipt for one paid " +- "API call (`raw_output` is redacted before persisting).\n" +- " - asset_capture saves a generated asset note linked back to its " +- "source receipt.\n" +- " - payment_report_generate aggregates a date's receipts into a " +- "Markdown report.\n" +- "These tools never execute payments — they only persist memory. " +- "When an approval workflow is in use, the recommended sequence " +- "is: payment_policy_check → payment_request_approval → poll " +- "payment_request_status → run `pay` → payment_receipt_append → " +- "asset_capture → payment_request_consume."+ "Memory contract: call brain_feedback once per taste signal the " ++ "user expresses; brain_apply_evidence right after producing a " ++ "durable artifact a preference in `Brain/preferences/` scopes to " ++ "(result: applied | violated | outdated); brain_note for narrative " ++ "milestones that fit neither; brain_pinned_context for current-task " ++ "facts that must survive context rotation. brain_context " ++ "bootstraps a session when the host injects no active.md hook. " ++ "Skip Brain calls for casual chat, exploration, and trivial edits - " ++ "a misrecorded signal is worse than a missed one.\n\n" ++ "Consolidated read views: brain_brief (view: morning | daily | " ++ "weekly | monthly | operator | digest), brain_analytics (view: " ++ "timeline | attention_flows | belief_evolution | concept_synthesis), " ++ "schema_inspect (view: graph | lint | stats | orphans | " ++ "explain_type | active_pack | packs). The per-view predecessor " ++ "names still resolve via tools/call as deprecated aliases.\n\n" ++ "Preview budget: a large result may arrive as a JSON envelope with " ++ "`preview_truncated: true` and an `artifact_id`; fetch the full " ++ "payload with brain_artifact_get only when the preview is not " ++ "enough.\n\n" ++ "Pay Memory tools persist payment memory, never execute payments. " ++ "payment_memory_init bootstraps once per vault; approval sequence: " ++ "payment_policy_check (against " ++ `\`${PAY_MEMORY_SPENDING_JSON_REL}\`) → payment_request_approval → ` ++ "poll payment_request_status → run `pay` → payment_receipt_append → " ++ "asset_capture → payment_request_consume; payment_report_generate " ++ "aggregates a date's receipts.");}diff --git a/src/mcp/pay-memory-tools.ts b/src/mcp/pay-memory-tools.tsindex 8cf17f4f..16c11a6c 100644--- a/src/mcp/pay-memory-tools.ts+++ b/src/mcp/pay-memory-tools.ts@@ -399,7 +399,7 @@ export const PAY_MEMORY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([type: "string",enum: ["allowed", "approval_required", "denied", "not_checked"],description:- "Real outcome of the spending-policy check. Defaults to `not_checked` when omitted — the receipt body will explicitly say so rather than claiming the policy approved the call.",+ "Real outcome of the spending-policy check; defaults to `not_checked` and the receipt says so explicitly.",},policy_rule: {type: "string",diff --git a/src/mcp/registry-guard.ts b/src/mcp/registry-guard.tsnew file mode 100644index 00000000..5ebfc4b2--- /dev/null+++ b/src/mcp/registry-guard.ts@@ -0,0 +1,166 @@+/**+ * Registry guard (token-diet, t_352fd7f6 + t_c967abaf).+ *+ * One walk over the assembled tool table backs two contract tests:+ *+ * 1. Description caps - tool descriptions and per-property schema+ * descriptions have hard character ceilings so the serialized+ * registry (paid by every MCP client on every request in+ * non-deferred hosts) cannot silently regrow. Long-form guidance+ * belongs in server instructions or docs/mcp.md, not in schemas.+ * 2. Preview-budget default - every tool either carries a+ * `previewBudget` or appears in the explicit exempt list below+ * with a reason. Unbounded tool output is a deliberate, reviewed+ * property, never an accident of omission.+ *+ * Test-time module: nothing here runs on the MCP request path.+ */++import type { ToolDefinition } from "./tools.ts";++export const TOOL_DESCRIPTION_MAX = 300;+export const PROPERTY_DESCRIPTION_MAX = 160;++export interface DescriptionViolation {+ readonly tool: string;+ /** "" for the tool description itself, else the property path. */+ readonly path: string;+ readonly length: number;+ readonly limit: number;+}++function walkSchema(+ tool: string,+ schema: unknown,+ path: string,+ out: DescriptionViolation[],+): void {+ if (schema === null || typeof schema !== "object") return;+ const node = schema as Record<string, unknown>;+ const description = node["description"];+ if (+ path !== "" &&+ typeof description === "string" &&+ description.length > PROPERTY_DESCRIPTION_MAX+ ) {+ out.push({ tool, path, length: description.length, limit: PROPERTY_DESCRIPTION_MAX });+ }+ const properties = node["properties"];+ if (properties !== null && typeof properties === "object") {+ for (const [key, child] of Object.entries(properties)) {+ walkSchema(tool, child, `${path}.${key}`, out);+ }+ }+ if (node["items"] !== undefined) walkSchema(tool, node["items"], `${path}[]`, out);+}++/** Every description over its cap, tool-level and property-level. */+export function auditToolDescriptions(+ tools: ReadonlyArray<ToolDefinition>,+): DescriptionViolation[] {+ const out: DescriptionViolation[] = [];+ for (const tool of tools) {+ if (tool.description.length > TOOL_DESCRIPTION_MAX) {+ out.push({+ tool: tool.name,+ path: "",+ length: tool.description.length,+ limit: TOOL_DESCRIPTION_MAX,+ });+ }+ walkSchema(tool.name, tool.inputSchema, "", out);+ }+ return out;+}++/**+ * Tools deliberately running without a preview budget, each with the+ * reason the omission is safe. Grouped by the property that bounds+ * their output instead.+ */+export const PREVIEW_BUDGET_EXEMPT: Readonly<Record<string, string>> = Object.freeze({+ // Writers and small acks - the result is a fixed-shape receipt.+ brain_feedback: "write; returns a small fixed-shape ack",+ brain_apply_evidence: "write; returns a small fixed-shape ack",+ brain_note: "write; returns a small fixed-shape ack",+ brain_pinned_context: "pinned.md is operator-curated and small by practice",+ brain_recall_feedback: "write; returns one event receipt plus bounded weights",+ brain_switch_vault: "write; returns a small profile ack",+ schema_apply_mutations: "write; returns a bounded mutation receipt",+ payment_memory_init: "write; returns a bootstrap receipt",+ payment_receipt_append: "write; returns a single receipt path",+ asset_capture: "write; returns a single asset note path",+ payment_request_approval: "write; returns one pending-request descriptor",+ payment_request_status: "read of one request; fixed-shape status",+ payment_request_consume: "write; returns a small link receipt",+ payment_policy_check: "fixed-shape policy verdict",+ payment_report_generate: "write; returns one report path plus totals",++ // Bounded-by-construction reads.+ second_brain_capabilities: "fixed-size capability report",+ brain_context:+ "session bootstrap; deliberately returns the full preference set - it is the full-view target the budgeted SessionStart injection points at",+ brain_pre_compress_pack: "self-budgeting; enforces its own char budget internally",+ brain_morning_brief: "self-budgeting via max_chars_per_memory / max_total_chars",+ brain_artifact_get: "the preview-budget escape hatch; truncating it would defeat itself",+ brain_health: "fixed-shape counters",+ brain_doctor: "issue list bounded by vault invariants; CLI surface renders full detail",+ brain_recall_gate: "single verdict object",+ vault_health: "fixed list of manifest checks",+ brain_watchdog: "bounded probe report",+ brain_dream: "returns pass counters, not content",+ brain_intent_review: "bounded review window summary",+ brain_retention: "bounded retention counters",+ brain_review_candidates: "dry-run counters and short id lists",+ brain_sources: "per-(agent, source_type) counts only",+ brain_stale_scan: "bounded staleness list with caps in the handler",+ brain_moc_audit: "bounded audit summary",+ brain_mcp_landscape: "fixed-shape landscape summary",+ brain_session_describe: "single-session metadata only",+ brain_context_receipts: "bounded receipt list per session",+ brain_context_presets: "small preset list",+ brain_pre_compact_extract: "bounded extract; host injects it whole by design",+ brain_skill_proposals: "bounded proposal list",+ brain_procedural_memory: "bounded hint list",+ brain_procedural_graph: "bounded graph summary",+ brain_recurrence: "bounded recurrence records; learn/forget are writes",+ brain_agent_diff: "bounded two-agent comparison",++ // Deprecated aliases (token-diet): the consolidated tool carries the+ // budget; the alias keeps its predecessor's budget status until+ // removal.+ get_active_schema_pack: "deprecated alias for schema_inspect; slated for removal",+ list_schema_packs: "deprecated alias for schema_inspect; slated for removal",+ schema_stats: "deprecated alias for schema_inspect; slated for removal",+ schema_lint: "deprecated alias for schema_inspect; slated for removal",+ schema_graph: "deprecated alias for schema_inspect; slated for removal",+ schema_explain_type: "deprecated alias for schema_inspect; slated for removal",+ schema_review_orphans: "deprecated alias for schema_inspect; slated for removal",+ reload_schema_pack: "deprecated alias for schema_inspect; slated for removal",+});++export interface PreviewBudgetAudit {+ /** Tools with neither a budget nor an exempt entry - the guard fails on these. */+ readonly unbudgetedAndUnexempted: ReadonlyArray<string>;+ /** Exempt entries that now carry a budget - stale exemptions to clean up. */+ readonly exemptButBudgeted: ReadonlyArray<string>;+ /** Exempt entries naming tools that no longer exist. */+ readonly exemptButUnknown: ReadonlyArray<string>;+}++export function auditPreviewBudgets(tools: ReadonlyArray<ToolDefinition>): PreviewBudgetAudit {+ const names = new Set(tools.map((t) => t.name));+ const unbudgetedAndUnexempted: string[] = [];+ const exemptButBudgeted: string[] = [];+ for (const tool of tools) {+ const exempt = tool.name in PREVIEW_BUDGET_EXEMPT;+ if (tool.previewBudget === undefined && !exempt) unbudgetedAndUnexempted.push(tool.name);+ if (tool.previewBudget !== undefined && exempt) exemptButBudgeted.push(tool.name);+ }+ const exemptButUnknown = Object.keys(PREVIEW_BUDGET_EXEMPT).filter((n) => !names.has(n));+ return Object.freeze({+ unbudgetedAndUnexempted: Object.freeze(unbudgetedAndUnexempted),+ exemptButBudgeted: Object.freeze(exemptButBudgeted),+ exemptButUnknown: Object.freeze(exemptButUnknown),+ });+}diff --git a/src/mcp/schema-tools.ts b/src/mcp/schema-tools.tsindex 47756781..6a93aee4 100644--- a/src/mcp/schema-tools.ts+++ b/src/mcp/schema-tools.ts@@ -12,61 +12,104 @@ import {import type { SchemaMutation } from "../core/brain/schema-mutate.ts";import { INVALID_PARAMS, MCPError } from "./protocol.ts";import { coerceStr } from "./coerce.ts";-import type { ToolDefinition } from "./tools.ts";+import { MCP_PREVIEW_BUDGET } from "./preview-budget.ts";+import { deprecatedAlias, type ServerContext, type ToolDefinition } from "./tools.ts";++// Read-side handlers shared by the consolidated `schema_inspect` and+// its deprecated per-view aliases (token-diet, t_3920db77).+const SCHEMA_INSPECT_VIEWS: Readonly<+ Record<string, (ctx: ServerContext, args: Record<string, unknown>) => Promise<unknown> | unknown>+> = Object.freeze({+ graph: (ctx: ServerContext) => buildSchemaGraph(ctx.vault),+ lint: (ctx: ServerContext) => buildSchemaLint(ctx.vault),+ stats: (ctx: ServerContext) => buildSchemaStats(ctx.vault),+ orphans: (ctx: ServerContext) => reviewSchemaOrphans(ctx.vault),+ explain_type: (ctx: ServerContext, args: Record<string, unknown>) =>+ explainSchemaToken(ctx.vault, coerceStr(args, "token")!),+ active_pack: (ctx: ServerContext) => getActiveSchemaPack(ctx.vault),+ packs: (ctx: ServerContext) => listSchemaPacks(ctx.vault),+});++function toolSchemaInspect(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<unknown> | unknown {+ const view = typeof args["view"] === "string" ? args["view"] : "";+ const handler = SCHEMA_INSPECT_VIEWS[view];+ if (handler === undefined) {+ throw new MCPError(+ INVALID_PARAMS,+ `view must be one of ${Object.keys(SCHEMA_INSPECT_VIEWS).join(", ")}; got ${JSON.stringify(+ args["view"],+ )}`,+ );+ }+ return handler(ctx, args);+}export const SCHEMA_TOOLS: ReadonlyArray<ToolDefinition> = [{- name: "get_active_schema_pack",- description: "Return the active Brain schema pack from Brain/_brain.yaml. Read-only.",- inputSchema: emptySchema(),- handler: (ctx) => getActiveSchemaPack(ctx.vault),- },- {- name: "list_schema_packs",- description: "List available Brain schema packs. Read-only.",- inputSchema: emptySchema(),- handler: (ctx) => listSchemaPacks(ctx.vault),- },- {- name: "schema_stats",- description: "Return Brain schema declaration, usage, metadata, and finding counts. Read-only.",- inputSchema: emptySchema(),- handler: (ctx) => buildSchemaStats(ctx.vault),- },- {- name: "schema_lint",+ name: "schema_inspect",+ previewBudget: MCP_PREVIEW_BUDGET,description:- "Return schema lint findings for unknown tokens and unused declarations. Read-only.",- inputSchema: emptySchema(),- handler: (ctx) => buildSchemaLint(ctx.vault),- },- {- name: "schema_graph",- description:- "Return schema graph nodes and edges for types, aliases, prefixes, and routing. Read-only.",- inputSchema: emptySchema(),- handler: (ctx) => buildSchemaGraph(ctx.vault),- },- {- name: "schema_explain_type",- description:- "Explain one schema token across declarations, usage, aliases, prefixes, and routing. Read-only.",+ "Read-only Brain schema inspection, one tool for every view: graph, lint, stats, orphans, explain_type (needs token), active_pack, or packs. Replaces the per-view schema read tools.",inputSchema: {type: "object",properties: {- token: { type: "string", description: "Schema token to explain." },+ view: {+ type: "string",+ enum: ["graph", "lint", "stats", "orphans", "explain_type", "active_pack", "packs"],+ description: "Which schema view to produce.",+ },+ token: { type: "string", description: "view=explain_type: schema token to explain." },},- required: ["token"],+ required: ["view"],additionalProperties: false,},- handler: (ctx, args) => explainSchemaToken(ctx.vault, coerceStr(args, "token")!),+ handler: toolSchemaInspect,},- {+ deprecatedAlias({+ name: "get_active_schema_pack",+ target: "schema_inspect",+ view: "active_pack",+ handler: SCHEMA_INSPECT_VIEWS["active_pack"]!,+ }),+ deprecatedAlias({+ name: "list_schema_packs",+ target: "schema_inspect",+ view: "packs",+ handler: SCHEMA_INSPECT_VIEWS["packs"]!,+ }),+ deprecatedAlias({+ name: "schema_stats",+ target: "schema_inspect",+ view: "stats",+ handler: SCHEMA_INSPECT_VIEWS["stats"]!,+ }),+ deprecatedAlias({+ name: "schema_lint",+ target: "schema_inspect",+ view: "lint",+ handler: SCHEMA_INSPECT_VIEWS["lint"]!,+ }),+ deprecatedAlias({+ name: "schema_graph",+ target: "schema_inspect",+ view: "graph",+ handler: SCHEMA_INSPECT_VIEWS["graph"]!,+ }),+ deprecatedAlias({+ name: "schema_explain_type",+ target: "schema_inspect",+ view: "explain_type",+ handler: SCHEMA_INSPECT_VIEWS["explain_type"]!,+ }),+ deprecatedAlias({name: "schema_review_orphans",- description: "Return declared schema tokens that are currently unused. Read-only.",- inputSchema: emptySchema(),- handler: (ctx) => reviewSchemaOrphans(ctx.vault),- },+ target: "schema_inspect",+ view: "orphans",+ handler: SCHEMA_INSPECT_VIEWS["orphans"]!,+ }),{name: "schema_apply_mutations",description:@@ -108,14 +151,10 @@ export const SCHEMA_TOOLS: ReadonlyArray<ToolDefinition> = [});},},- {+ deprecatedAlias({name: "reload_schema_pack",- description: "Reload and return the active Brain schema pack from disk. Read-only.",- inputSchema: emptySchema(),- handler: (ctx) => getActiveSchemaPack(ctx.vault),- },+ target: "schema_inspect",+ view: "active_pack",+ handler: SCHEMA_INSPECT_VIEWS["active_pack"]!,+ }),];--function emptySchema(): Record<string, unknown> {- return { type: "object", properties: {}, additionalProperties: false };-}diff --git a/src/mcp/search-tools.ts b/src/mcp/search-tools.tsindex 8dfdc52b..201592f3 100644--- a/src/mcp/search-tools.ts+++ b/src/mcp/search-tools.ts@@ -77,7 +77,7 @@ const SEARCH_INPUT_SCHEMA: Record<string, unknown> = {visibility: {type: "array",description:- "Optional content-visibility scope (v3). Pages with no `visibility:` frontmatter are always returned; a page that declares visibility values is returned only when this scope includes one of them. Absent = default scope (untagged pages only).",+ "Optional content-visibility scope; untagged pages always match, tagged pages only when this scope includes one of their values.",items: { type: "string" },},},diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex 7f188796..d1327f07 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -205,13 +205,17 @@ export class MCPServer {}private handleToolsList(): Record<string, unknown> {+ // Hidden tools (deprecated aliases) stay callable but are not+ // advertised - the list is what every client pays tokens for.return {- tools: this.tools.map((t) => ({- name: t.name,- description: t.description,- inputSchema: t.inputSchema,- ...(t.outputSchema ? { outputSchema: t.outputSchema } : {}),- })),+ tools: this.tools+ .filter((t) => t.hidden !== true)+ .map((t) => ({+ name: t.name,+ description: t.description,+ inputSchema: t.inputSchema,+ ...(t.outputSchema ? { outputSchema: t.outputSchema } : {}),+ })),};}diff --git a/src/mcp/tools.ts b/src/mcp/tools.tsindex 5db5b843..75c8d75a 100644--- a/src/mcp/tools.ts+++ b/src/mcp/tools.ts@@ -71,6 +71,12 @@ export interface ToolDefinition {* - opt-in only. The CLI bridge ignores the budget entirely.*/readonly previewBudget?: number;+ /**+ * When true the tool stays callable via `tools/call` but is omitted+ * from `tools/list` (token-diet): deprecated aliases keep working+ * for old clients without re-paying their schema in every list.+ */+ readonly hidden?: boolean;readonly handler: (ctx: ServerContext,args: Record<string, unknown>,@@ -282,6 +288,31 @@ const CAPABILITIES_OUTPUT_SCHEMA: OutputSchema = {export type ToolScope = "full" | "writer";+/**+ * Deprecated delegating alias (token-diet, t_3920db77): the tool name+ * stays callable for at least one minor release after its capability+ * moved into a consolidated view tool, but its registry footprint+ * shrinks to a one-line description and a permissive input schema.+ * The handler is the exact function the consolidated tool dispatches+ * to, so behavior is byte-identical under either name.+ */+export function deprecatedAlias(opts: {+ readonly name: string;+ readonly target: string;+ readonly view: string;+ readonly handler: ToolDefinition["handler"];+ readonly previewBudget?: number;+}): ToolDefinition {+ return {+ name: opts.name,+ description: `Deprecated alias for ${opts.target} with view="${opts.view}". Will be removed in a future minor release.`,+ inputSchema: { type: "object" },+ hidden: true,+ ...(opts.previewBudget !== undefined ? { previewBudget: opts.previewBudget } : {}),+ handler: opts.handler,+ };+}+// The set is named after the original payload (mutating writers). As// of v0.10.10 it also hosts `brain_context`, a *reader* tool that has// to be always-loaded to be useful at session start. Renaming thediff --git a/tests/core/brain.active.test.ts b/tests/core/brain.active.test.tsindex ebbb9c88..04457852 100644--- a/tests/core/brain.active.test.ts+++ b/tests/core/brain.active.test.ts@@ -247,10 +247,25 @@ describe("regenerateActive — Most-applied (30d) section", () => {const body = readActive();expect(body).toContain("## Most-applied (30d) (1)");expect(body).toContain("`pref-a` (scope: writing, applied_in_window: 2)");- expect(body).toContain("Rule A");expect(result.counts.most_applied_30d).toBe(1);});+ test("entries are id + count one-liners - the principle body lives in Confirmed only", () => {+ // The Most-applied section used to repeat the full principle text+ // of preferences already rendered verbatim under Confirmed; on a+ // real vault that duplication was 31% of the injected bytes.+ seedConfirmed("a", "Rule A unique principle body", "medium");+ seedAppliedEvidence("pref-a", "2026-05-15T10:00:00Z");+ regenerateActive(vault, { now: new Date("2026-05-20T00:00:00Z") });+ const body = readActive();+ const line = body+ .split("\n")+ .find((l) => l.startsWith("- ") && l.includes("applied_in_window"));+ expect(line).toBe("- `pref-a` (scope: writing, applied_in_window: 1)");+ // Exactly one copy of the principle text in the whole document.+ expect(body.split("Rule A unique principle body").length - 1).toBe(1);+ });+test("section appears between Confirmed and Quarantine", () => {seedConfirmed("a", "Confirmed rule", "high");seedQuarantine("q", "Quarantined rule");diff --git a/tests/core/brain.doctor.test.ts b/tests/core/brain.doctor.test.tsindex 1564f532..a4e52f8d 100644--- a/tests/core/brain.doctor.test.ts+++ b/tests/core/brain.doctor.test.ts@@ -754,3 +754,55 @@ vault:expect(res.warnings.find((w) => w.code === "vault-ignore-missing-path")).toBeUndefined();});});++describe("corrupted principle frontmatter", () => {+ test("a preference whose principle carries leaked tool-call fragments raises principle-corrupted", () => {+ const path = preferencePath(tmp, "leaky");+ writeFileSync(+ path,+ [+ "---",+ "kind: brain-preference",+ "id: pref-leaky",+ "created_at: 2026-05-14T10:42:00Z",+ "_confirmed_at: null",+ "unconfirmed_until: 2026-05-28T10:42:00Z",+ "tags: [brain, brain/preference]",+ "topic: leaky",+ 'principle: "real rule.</principle>\\\\n<parameter name=\\\\\\"scope\\\\\\">writing"',+ "_status: unconfirmed",+ "_evidenced_by: []",+ "_applied_count: 0",+ "_violated_count: 0",+ "_last_evidence_at: null",+ "_confidence: low",+ "pinned: false",+ "---",+ "",+ "## Principle",+ "rule",+ "",+ ].join("\n"),+ "utf8",+ );+ const res = runDoctor(tmp);+ expect(res.errors).toEqual([]);+ expect(res.warnings.some((w) => w.code === "principle-corrupted" && w.path === path)).toBe(+ true,+ );+ });++ test("clean principles raise no principle-corrupted warning", () => {+ writePreference(tmp, {+ slug: "clean",+ topic: "clean",+ principle: 'Quote "plain text" freely.',+ created_at: "2026-05-14T10:00:00Z",+ unconfirmed_until: "2026-05-28T10:00:00Z",+ status: "unconfirmed",+ evidenced_by: [],+ });+ const res = runDoctor(tmp);+ expect(res.warnings.filter((w) => w.code === "principle-corrupted")).toEqual([]);+ });+});diff --git a/tests/core/brain/active-budget.test.ts b/tests/core/brain/active-budget.test.tsnew file mode 100644index 00000000..7f2c3fef--- /dev/null+++ b/tests/core/brain/active-budget.test.ts@@ -0,0 +1,74 @@+/**+ * `budgetActiveBody` (token-diet, t_40eb1de7 part 2): fits the+ * rendered active.md body into the SessionStart injection budget,+ * dropping sections in fixed priority order (retired first, confirmed+ * last) and pointing the agent at `brain_context` when truncated.+ */++import { describe, expect, test } from "bun:test";++import { budgetActiveBody } from "../../../src/core/brain/active-budget.ts";++function body(): string {+ return [+ "# Active Brain Preferences",+ "",+ "Auto-generated by `dream`. Do not edit — changes will be overwritten.",+ "",+ "## Confirmed (2)",+ "",+ "- `pref-a` (confidence: high (0.95)) — Rule A",+ "- `pref-b` (confidence: medium (0.50)) — Rule B",+ "",+ "## Most-applied (30d) (1)",+ "",+ "- `pref-a` (applied_in_window: 4)",+ "",+ "## Quarantine (1)",+ "",+ "_Probationary rules — still active._",+ "",+ "- `pref-q` (applied: 0 / violated: 2) — Quarantined rule",+ "",+ "## Recently retired (last 1)",+ "",+ "- `pref-r` — low_confidence on 2026-05-01",+ ].join("\n");+}++describe("budgetActiveBody", () => {+ test("body within budget passes through byte-identical", () => {+ const input = body();+ const out = budgetActiveBody(input, 10_000);+ expect(out).toBe(input);+ });++ test("over budget: retired drops first, then quarantine, then most-applied", () => {+ const input = body();+ // Budget that can hold everything except the retired tail.+ const out = budgetActiveBody(input, input.length - 20);+ expect(out).toContain("## Confirmed");+ expect(out).not.toContain("## Recently retired");+ expect(out).toContain("brain_context");+ });++ test("tight budget keeps the confirmed head and points at brain_context", () => {+ const out = budgetActiveBody(body(), 250);+ expect(out).toContain("# Active Brain Preferences");+ expect(out).toContain("## Confirmed");+ expect(out).not.toContain("## Quarantine");+ expect(out).not.toContain("## Recently retired");+ expect(out).toContain("brain_context");+ });++ test("deterministic", () => {+ expect(budgetActiveBody(body(), 700)).toBe(budgetActiveBody(body(), 700));+ });++ test("unsectioned body still respects the budget", () => {+ const flat = Array.from({ length: 50 }, (_, i) => `line ${i}`).join("\n");+ const out = budgetActiveBody(flat, 120);+ expect(out.length).toBeLessThanOrEqual(120 + 200); // content budget + notice overhead+ expect(out).toContain("line 0");+ });+});diff --git a/tests/core/brain/policy-active.test.ts b/tests/core/brain/policy-active.test.tsindex 7caa8af7..5636bfe1 100644--- a/tests/core/brain/policy-active.test.ts+++ b/tests/core/brain/policy-active.test.ts@@ -95,3 +95,27 @@ describe("active.most_applied_* config block", () => {expect(() => validate(HEAD + `active: not-a-map\n`)).toThrow(BrainConfigError);});});++describe("active.inject_budget_chars (token-diet, t_40eb1de7)", () => {+ test("absent → undefined; consumers fall back to the default budget", () => {+ const { config } = validate(HEAD + `active:\n most_applied_limit: 5\n`);+ expect(config.active?.inject_budget_chars).toBeUndefined();+ });++ test("present → loaded", () => {+ const { config } = validate(HEAD + `active:\n inject_budget_chars: 4000\n`);+ expect(config.active?.inject_budget_chars).toBe(4000);+ });++ test("below minimum rejected", () => {+ expect(() => validate(HEAD + `active:\n inject_budget_chars: 100\n`)).toThrow(+ BrainConfigError,+ );+ });++ test("non-integer rejected", () => {+ expect(() => validate(HEAD + `active:\n inject_budget_chars: many\n`)).toThrow(+ BrainConfigError,+ );+ });+});diff --git a/tests/core/brain/sanitize-principle.test.ts b/tests/core/brain/sanitize-principle.test.tsnew file mode 100644index 00000000..72f052c3--- /dev/null+++ b/tests/core/brain/sanitize-principle.test.ts@@ -0,0 +1,67 @@+/**+ * Principle-text sanitizer (token-diet, t_40eb1de7): strips leaked+ * tool-call XML fragments and collapses multi-level backslash-quote+ * escaping at the write seam, so corrupted client payloads can no+ * longer poison `Brain/preferences/` frontmatter and every derived+ * view (active.md, digest, MCP resources).+ *+ * Fixture strings mirror the real corruption found on the live vault+ * on 2026-06-02 (see docs/brainstorm/token-diet/design.md).+ */++import { describe, expect, test } from "bun:test";++import { sanitisePrinciple } from "../../../src/core/brain/text/sanitize-principle.ts";++describe("sanitisePrinciple", () => {+ test("clean text passes through unchanged", () => {+ const s = 'Use "o2b search" before answering vault questions.';+ expect(sanitisePrinciple(s)).toBe(s);+ });++ test("collapses multi-level backslash-quote chains to a single quote", () => {+ const corrupted =+ 'phrasing like \\\\\\"давай так:\\\\\\" or \\\\\\"пусть агент делает X\\\\\\"';+ expect(sanitisePrinciple(corrupted)).toBe(+ 'phrasing like "давай так:" or "пусть агент делает X"',+ );+ });++ test("cuts a leaked closing tool-call tag and everything after it", () => {+ const corrupted =+ 'everything else needs explicit per-edit approval.</principle>\\\\n<parameter name=\\\\\\"scope\\\\\\">collaboration';+ expect(sanitisePrinciple(corrupted)).toBe("everything else needs explicit per-edit approval.");+ });++ test("cuts at a leaked parameter-open fragment whose attributes carry escaped quotes", () => {+ const corrupted = 'real rule text<parameter name=\\"scope\\">writing';+ expect(sanitisePrinciple(corrupted)).toBe("real rule text");+ });++ test("legitimate prose mentioning <parameter> with plain quotes passes through", () => {+ const legit = 'Document tool calls as <parameter name="scope"> blocks in examples.';+ expect(sanitisePrinciple(legit)).toBe(legit);+ });++ test("a single escaped quote is legitimate prose and survives", () => {+ const legit = 'Inside JSON strings write \\" instead of a bare quote.';+ expect(sanitisePrinciple(legit)).toBe(legit);+ });++ test("a trailing literal newline escape outside a leak cut survives", () => {+ const legit = "End streamed lines with \\n";+ expect(sanitisePrinciple(legit)).toBe(legit);+ });++ test("idempotent: sanitizing twice equals sanitizing once", () => {+ const corrupted =+ 'rule \\\\\\"with quotes\\\\\\" and tail</principle>\\\\n<parameter name=\\\\\\"scope\\\\\\">x';+ const once = sanitisePrinciple(corrupted);+ expect(sanitisePrinciple(once)).toBe(once);+ });++ test("non-string input coerces to empty string", () => {+ expect(sanitisePrinciple(undefined)).toBe("");+ expect(sanitisePrinciple(42)).toBe("");+ });+});diff --git a/tests/core/brain/text-budget.test.ts b/tests/core/brain/text-budget.test.tsnew file mode 100644index 00000000..69ee838b--- /dev/null+++ b/tests/core/brain/text-budget.test.ts@@ -0,0 +1,105 @@+/**+ * Section-aware character budget (token-diet, plan Task 1): pure+ * deterministic truncation shared by the active.md injection budget+ * and any future hook-side body budgeting. Sections drop whole+ * (lowest priority first); the most important remaining section is+ * trimmed at line boundaries, never mid-line.+ */++import { describe, expect, test } from "bun:test";++import {+ applySectionBudget,+ type BudgetSection,+} from "../../../src/core/brain/text/text-budget.ts";++const NOTICE = "_Truncated to fit the injection budget. Call `brain_context` for the full view._";++function sections(): BudgetSection[] {+ return [+ { key: "confirmed", priority: 0, text: "## Confirmed\n\n- a one\n- a two\n- a three" },+ { key: "most-applied", priority: 1, text: "## Most-applied\n\n- m one\n- m two" },+ { key: "quarantine", priority: 2, text: "## Quarantine\n\n- q one" },+ { key: "retired", priority: 3, text: "## Retired\n\n- r one" },+ ];+}++describe("applySectionBudget", () => {+ test("everything fits: identity join, no truncation", () => {+ const out = applySectionBudget(sections(), 10_000, { notice: NOTICE });+ expect(out.truncated).toBe(false);+ expect(out.droppedKeys).toEqual([]);+ expect(out.body).toBe(+ [+ "## Confirmed\n\n- a one\n- a two\n- a three",+ "## Most-applied\n\n- m one\n- m two",+ "## Quarantine\n\n- q one",+ "## Retired\n\n- r one",+ ].join("\n\n"),+ );+ });++ test("over budget: drops the lowest-priority sections first, keeps render order", () => {+ const full = applySectionBudget(sections(), 10_000, { notice: NOTICE }).body.length;+ // Budget one section short of the full body: only `retired` drops.+ const out = applySectionBudget(sections(), full - 20, { notice: NOTICE });+ expect(out.truncated).toBe(true);+ expect(out.droppedKeys).toEqual(["retired"]);+ expect(out.body).toContain("## Confirmed");+ expect(out.body).not.toContain("## Retired");+ expect(out.body.endsWith(NOTICE)).toBe(true);+ });++ test("still over budget after drops: trims the least important kept section at line boundaries", () => {+ const out = applySectionBudget(sections(), 30, { notice: NOTICE });+ expect(out.truncated).toBe(true);+ expect(out.droppedKeys).toEqual(["retired", "quarantine", "most-applied"]);+ // The confirmed section is line-trimmed from the tail: every kept+ // line must be a complete line from the original text.+ const kept = out.body.slice(0, out.body.length - NOTICE.length).trimEnd();+ for (const line of kept.split("\n")) {+ expect("## Confirmed\n\n- a one\n- a two\n- a three".split("\n")).toContain(line);+ }+ expect(kept).toContain("## Confirmed");+ expect(kept).not.toContain("- a three");+ });++ test("zero budget returns the notice only", () => {+ const out = applySectionBudget(sections(), 0, { notice: NOTICE });+ expect(out.truncated).toBe(true);+ expect(out.body).toBe(NOTICE);+ expect(out.droppedKeys).toEqual(["retired", "quarantine", "most-applied", "confirmed"]);+ });++ test("deterministic: identical inputs produce identical outputs", () => {+ const a = applySectionBudget(sections(), 90, { notice: NOTICE });+ const b = applySectionBudget(sections(), 90, { notice: NOTICE });+ expect(a).toEqual(b);+ });++ test("priority ties drop the later section first", () => {+ const tied: BudgetSection[] = [+ { key: "first", priority: 1, text: "first body" },+ { key: "second", priority: 1, text: "second body" },+ ];+ const out = applySectionBudget(tied, "first body".length + 2, { notice: NOTICE });+ expect(out.droppedKeys).toEqual(["second"]);+ expect(out.body.startsWith("first body")).toBe(true);+ });++ test("budget respected across a fixture sweep (content within budget, notice rides on top)", () => {+ const secs = sections();+ const overhead = NOTICE.length + 2; // separator + notice when truncated+ for (let budget = 0; budget <= 400; budget += 7) {+ const out = applySectionBudget(secs, budget, { notice: NOTICE });+ expect(out.body.length).toBeLessThanOrEqual(budget + overhead);+ }+ });++ test("no notice configured: truncation still works, body stays within budget", () => {+ const out = applySectionBudget(sections(), 50, {});+ expect(out.truncated).toBe(true);+ expect(out.body.length).toBeLessThanOrEqual(50);+ expect(out.body).toContain("## Confirmed");+ });+});diff --git a/tests/core/brain/upgrade.test.ts b/tests/core/brain/upgrade.test.tsindex 38788f37..0ab85680 100644--- a/tests/core/brain/upgrade.test.ts+++ b/tests/core/brain/upgrade.test.ts@@ -262,3 +262,106 @@ describe("applyUpgrade", () => {expect(listSnapshots(vault).some((s) => s.run_id === res.run_id)).toBe(true);});});++// ── Corrupted preference principle repair (token-diet, t_40eb1de7) ─────────++describe("planUpgrade / applyUpgrade — preference principle repair", () => {+ const PREF_DIR = "Brain/preferences";++ function writeCorruptedPref(slug: string): string {+ const path = join(vault, PREF_DIR, `pref-${slug}.md`);+ // Faithful copy of the live-vault corruption shape: six on-disk+ // backslashes per quote (three in memory after the parser's single+ // unescape - the \\{2,} amplification signature) plus a leaked+ // tool-call XML fragment, inside a double-quoted YAML scalar.+ const principle =+ 'When the user describes a rule like \\\\\\\\\\\\"давай так:\\\\\\\\\\\\" wait for approval.</principle>\\\\n<parameter name=\\\\\\\\\\\\"scope\\\\\\\\\\\\">collaboration';+ const content = [+ "---",+ "kind: brain-preference",+ `id: pref-${slug}`,+ 'created_at: "2026-05-17T15:12:12Z"',+ 'unconfirmed_until: "2026-05-17T15:12:12Z"',+ `tags: [brain, brain/preference, brain/topic/${slug}]`,+ `topic: ${slug}`,+ "_status: confirmed",+ `principle: "${principle}"`,+ "_applied_count: 0",+ "_violated_count: 0",+ "_last_evidence_at: null",+ "_confidence: low",+ "_confidence_value: 0",+ "pinned: false",+ "---",+ "",+ "## Origin",+ "",+ "test fixture",+ "",+ ].join("\n");+ atomicWriteFileSync(path, content);+ return path;+ }++ function writeCleanPref(slug: string): string {+ const path = join(vault, PREF_DIR, `pref-${slug}.md`);+ const content = [+ "---",+ "kind: brain-preference",+ `id: pref-${slug}`,+ 'created_at: "2026-05-17T15:12:12Z"',+ 'unconfirmed_until: "2026-05-17T15:12:12Z"',+ `tags: [brain, brain/preference, brain/topic/${slug}]`,+ `topic: ${slug}`,+ "_status: confirmed",+ 'principle: "Use measured punctuation in docs."',+ "_applied_count: 2",+ "_violated_count: 0",+ "_last_evidence_at: null",+ "_confidence: medium",+ "_confidence_value: 0.5",+ "pinned: false",+ "---",+ "",+ "## Origin",+ "",+ "test fixture",+ "",+ ].join("\n");+ atomicWriteFileSync(path, content);+ return path;+ }++ test("plan flags a corrupted principle and leaves clean preferences alone", () => {+ writeCorruptedPref("broken");+ writeCleanPref("healthy");+ const plan = planUpgrade(vault);+ const prefPlans = plan.files.filter((f) => f.path.startsWith(PREF_DIR));+ expect(prefPlans.map((f) => f.path)).toEqual([`${PREF_DIR}/pref-broken.md`]);+ expect(prefPlans[0]!.status).toBe("update");+ expect(prefPlans[0]!.after).not.toContain("</principle>");+ expect(prefPlans[0]!.after).not.toContain("<parameter");+ });++ test("apply rewrites the corrupted file once and is idempotent", () => {+ const path = writeCorruptedPref("broken");+ const res = applyUpgrade(vault, { agent: "claude-dev-agent" });+ expect(res.files_updated).toContain(`${PREF_DIR}/pref-broken.md`);++ const bytes = readFileSync(path, "utf8");+ expect(bytes).not.toContain("</principle>");+ expect(bytes).not.toContain("<parameter");+ expect(bytes).not.toContain('\\\\"');+ expect(bytes).toContain('\\"давай так:\\"');+ // Untouched fields survive verbatim.+ expect(bytes).toContain("_status: confirmed");+ expect(bytes).toContain("topic: broken");+ expect(bytes).toContain("## Origin");++ // Second pass: nothing pending.+ const plan2 = planUpgrade(vault);+ expect(plan2.files.filter((f) => f.path.startsWith(PREF_DIR))).toEqual([]);+ const res2 = applyUpgrade(vault, { agent: "claude-dev-agent" });+ expect(res2.files_updated).toEqual([]);+ });+});diff --git a/tests/core/vault.test.ts b/tests/core/vault.test.tsindex e89c1621..f80e048f 100644--- a/tests/core/vault.test.ts+++ b/tests/core/vault.test.ts@@ -96,6 +96,39 @@ describe("writeFrontmatter", () => {const [meta] = parseFrontmatter(path);expect(meta["tags"]).toEqual([]);});++ test("double-quoted scalar with quotes round-trips without escape amplification", () => {+ // The formatter escapes `"` to `\"` inside double-quoted scalars;+ // the parser must unescape symmetrically. Before the fix every+ // parse -> format cycle doubled the backslashes, which is how the+ // live vault accumulated \\\\\\" chains in preference frontmatter.+ const path = join(tmp, "note.md");+ const value = 'phrasing like "давай так:" or "пусть так"';+ writeFrontmatter(path, { principle: value }, "Body.");+ const [meta] = parseFrontmatter(path);+ expect(meta["principle"]).toBe(value);++ // Second cycle: rewrite what we parsed; bytes must be stable.+ const firstBytes = readFileSync(path, "utf8");+ writeFrontmatter(path, { principle: meta["principle"] as string }, "Body.");+ expect(readFileSync(path, "utf8")).toBe(firstBytes);+ });++ test("escaped newline and backslash round-trip through double-quoted scalars", () => {+ const path = join(tmp, "note.md");+ const value = "line one\nline two with backslash \\ and tab\there";+ writeFrontmatter(path, { summary: value }, "Body.");+ const [meta] = parseFrontmatter(path);+ expect(meta["summary"]).toBe(value);+ });++ test("inline array elements with quotes round-trip", () => {+ const path = join(tmp, "note.md");+ const tags = ["plain", 'say "hi"'];+ writeFrontmatter(path, { tags }, "Body.");+ const [meta] = parseFrontmatter(path);+ expect(meta["tags"]).toEqual(tags);+ });});describe("slugify", () => {diff --git a/tests/hooks/active-inject.test.ts b/tests/hooks/active-inject.test.tsindex e9f31828..5537217f 100644--- a/tests/hooks/active-inject.test.ts+++ b/tests/hooks/active-inject.test.ts@@ -81,7 +81,12 @@ describe("active-inject hook", () => {expect(out.hookSpecificOutput.additionalContext).toContain("pref-foo");});- test("echoes PostCompact as the hookEventName when fired post-compact", async () => {+ test("stays silent under PostCompact - the event cannot carry additionalContext", async () => {+ // Current Claude Code has no PostCompact hook event; runtimes that+ // still fire one reject `hookSpecificOutput.additionalContext` for+ // it, echoing the whole payload back as a validation error. The+ // post-compact re-injection path is the SessionStart `compact`+ // matcher instead.writeActive("---\nkind: brain-active\ngenerated_at: 2026-05-15T10:00:00Z\n---\n\n# Active Brain Preferences\n\n## Confirmed (0)\n\n_No confirmed preferences yet._\n",);@@ -93,9 +98,32 @@ describe("active-inject hook", () => {{ VAULT_DIR: vault },);expect(r.exit).toBe(0);+ expect(r.stdout).toBe("");+ });++ test("injects under UserPromptSubmit - an allowlisted context-bearing event", async () => {+ writeActive(+ "---\nkind: brain-active\ngenerated_at: 2026-05-15T10:00:00Z\n---\n\n# Active Brain Preferences\n\n## Confirmed (1)\n\n- `pref-foo` — Rule body\n",+ );++ const r = await runHook(+ {+ hook_event_name: "UserPromptSubmit",+ },+ { VAULT_DIR: vault },+ );+ expect(r.exit).toBe(0);const out = JSON.parse(r.stdout);- expect(out.hookSpecificOutput.hookEventName).toBe("PostCompact");- expect(out.hookSpecificOutput.additionalContext).toContain("# Active Brain Preferences");+ expect(out.hookSpecificOutput.hookEventName).toBe("UserPromptSubmit");+ expect(out.hookSpecificOutput.additionalContext).toContain("pref-foo");+ });++ test("stays silent under an unknown future event name (default-closed)", async () => {+ writeActive("---\nkind: brain-active\ngenerated_at: 2026-05-15T10:00:00Z\n---\n\nbody\n");++ const r = await runHook({ hook_event_name: "SomeFutureEvent" }, { VAULT_DIR: vault });+ expect(r.exit).toBe(0);+ expect(r.stdout).toBe("");});test("stays silent when Brain/active.md does not exist", async () => {@@ -136,6 +164,48 @@ describe("active-inject hook", () => {expect(out.hookSpecificOutput.hookEventName).toBe("SessionStart");});+ test("budgets an oversized active.md body and points at brain_context", async () => {+ const hugeRules = Array.from(+ { length: 400 },+ (_, i) => `- \`pref-rule-${i}\` (confidence: low (0.10)) — Rule number ${i} body text`,+ ).join("\n");+ writeActive(+ `---\nkind: brain-active\ngenerated_at: 2026-05-15T10:00:00Z\n---\n\n# Active Brain Preferences\n\n## Confirmed (400)\n\n${hugeRules}\n\n## Recently retired (last 1)\n\n- \`pref-r\` — low_confidence on 2026-05-01\n`,+ );++ const r = await runHook({ hook_event_name: "SessionStart" }, { VAULT_DIR: vault });+ expect(r.exit).toBe(0);+ const out = JSON.parse(r.stdout);+ const injected: string = out.hookSpecificOutput.additionalContext;+ // Default budget is 8,000 chars (+ the one-line truncation notice).+ expect(injected.length).toBeLessThanOrEqual(8300);+ expect(injected).toContain("# Active Brain Preferences");+ expect(injected).toContain("brain_context");+ expect(injected).not.toContain("## Recently retired");+ });++ test("honors active.inject_budget_chars from _brain.yaml", async () => {+ writeFileSync(+ join(vault, "Brain", "_brain.yaml"),+ "schema_version: 1\nactive:\n inject_budget_chars: 500\n",+ "utf8",+ );+ const rules = Array.from(+ { length: 40 },+ (_, i) => `- \`pref-rule-${i}\` — Rule number ${i} body text`,+ ).join("\n");+ writeActive(+ `---\nkind: brain-active\ngenerated_at: 2026-05-15T10:00:00Z\n---\n\n# Active Brain Preferences\n\n## Confirmed (40)\n\n${rules}\n`,+ );++ const r = await runHook({ hook_event_name: "SessionStart" }, { VAULT_DIR: vault });+ expect(r.exit).toBe(0);+ const out = JSON.parse(r.stdout);+ const injected: string = out.hookSpecificOutput.additionalContext;+ expect(injected.length).toBeLessThanOrEqual(800);+ expect(injected).toContain("brain_context");+ });+test("stays silent when active.md is empty whitespace only", async () => {writeActive(" \n \n");const r = await runHook({ hook_event_name: "SessionStart" }, { VAULT_DIR: vault });diff --git a/tests/hooks/hooks-json-shape.test.ts b/tests/hooks/hooks-json-shape.test.tsindex 9a1cb1a4..108a9222 100644--- a/tests/hooks/hooks-json-shape.test.ts+++ b/tests/hooks/hooks-json-shape.test.ts@@ -53,6 +53,17 @@ describe("hooks.json command shape", () => {}});+ test("SessionStart matcher covers compact - the supported post-compaction re-injection path", () => {+ const parsed = JSON.parse(readFileSync(HOOKS_JSON, "utf8")) as {+ hooks: Record<string, Array<{ matcher?: string }>>;+ };+ const sessionStart = parsed.hooks["SessionStart"] ?? [];+ expect(sessionStart.length).toBeGreaterThan(0);+ for (const group of sessionStart) {+ expect(group.matcher).toBe("startup|resume|clear|compact");+ }+ });+test("a command never blocks when nothing resolves (exit 0)", () => {const cmd = cmds[0]!;const env = { ...process.env } as Record<string, string | undefined>;diff --git a/tests/hooks/post-write-reminder.test.ts b/tests/hooks/post-write-reminder.test.tsindex 52d982f7..acb62fe7 100644--- a/tests/hooks/post-write-reminder.test.ts+++ b/tests/hooks/post-write-reminder.test.ts@@ -158,3 +158,94 @@ describe("post-write-reminder hook", () => {expect(text).toContain("brain_apply_evidence");});});++// ── Session cadence (token-diet, t_9cc4f400) ────────────────────────────────++async function runHookEnv(payload: unknown, env: Record<string, string>): Promise<RunResult> {+ const proc = Bun.spawn(["bun", "run", HOOK], {+ stdin: "pipe",+ stdout: "pipe",+ stderr: "pipe",+ env: { ...process.env, ...env },+ });+ proc.stdin.write(JSON.stringify(payload));+ await proc.stdin.end();+ const stdout = await new Response(proc.stdout).text();+ const exit = await proc.exited;+ return { stdout, exit };+}++const claudePayload = (file: string) => ({+ hook_event_name: "PostToolUse",+ tool_name: "Write",+ tool_input: { file_path: file, content: "hi" },+ transcript_path: "/Users/x/.claude/projects/-srv/foo.jsonl",+ session_id: "sess-cadence-1",+});++describe("post-write-reminder session cadence", () => {+ test("first Claude Code write gets the full reminder, later writes a short nudge", async () => {+ const stateDir = join(tmp, "markers");+ const env = { O2B_REMINDER_STATE_DIR: stateDir };++ const first = await runHookEnv(claudePayload("/tmp/a.md"), env);+ const firstText = JSON.parse(first.stdout).hookSpecificOutput.additionalContext as string;+ expect(firstText).toContain("Trivial edits");++ const second = await runHookEnv(claudePayload("/tmp/b.md"), env);+ const secondText = JSON.parse(second.stdout).hookSpecificOutput.additionalContext as string;+ expect(secondText).not.toContain("Trivial edits");+ expect(secondText.length).toBeLessThanOrEqual(200);+ expect(secondText).toContain("brain_");+ });++ test("a different session id gets the full reminder again", async () => {+ const stateDir = join(tmp, "markers");+ const env = { O2B_REMINDER_STATE_DIR: stateDir };+ await runHookEnv(claudePayload("/tmp/a.md"), env);++ const other = await runHookEnv({ ...claudePayload("/tmp/b.md"), session_id: "sess-2" }, env);+ const text = JSON.parse(other.stdout).hookSpecificOutput.additionalContext as string;+ expect(text).toContain("Trivial edits");+ });++ test("missing session id falls back to the full reminder every time", async () => {+ const stateDir = join(tmp, "markers");+ const env = { O2B_REMINDER_STATE_DIR: stateDir };+ const payload = {+ hook_event_name: "PostToolUse",+ tool_name: "Write",+ tool_input: { file_path: "/tmp/a.md", content: "hi" },+ transcript_path: "/Users/x/.claude/projects/-srv/foo.jsonl",+ };+ await runHookEnv(payload, env);+ const again = await runHookEnv(payload, env);+ const text = JSON.parse(again.stdout).hookSpecificOutput.additionalContext as string;+ expect(text).toContain("Trivial edits");+ });++ test("Codex one-shot runs keep the full reminder on every write", async () => {+ const stateDir = join(tmp, "markers");+ const env = { O2B_REMINDER_STATE_DIR: stateDir };+ const patch = "*** Begin Patch\n*** Update File: /tmp/x\n*** End Patch\n";+ const payload = {+ hook_event_name: "PostToolUse",+ tool_name: "apply_patch",+ tool_input: { input: patch },+ session_id: "sess-codex",+ };+ await runHookEnv(payload, env);+ const again = await runHookEnv(payload, env);+ const text = JSON.parse(again.stdout).hookSpecificOutput.additionalContext as string;+ expect(text).toContain("codex exec");+ expect(text).toContain("Trivial edits");+ });++ test("unwritable state dir fails soft to the full reminder", async () => {+ const env = { O2B_REMINDER_STATE_DIR: "/proc/definitely-not-writable/x" };+ const r = await runHookEnv(claudePayload("/tmp/a.md"), env);+ expect(r.exit).toBe(0);+ const text = JSON.parse(r.stdout).hookSpecificOutput.additionalContext as string;+ expect(text).toContain("Trivial edits");+ });+});diff --git a/tests/mcp/consolidated-tools.test.ts b/tests/mcp/consolidated-tools.test.tsnew file mode 100644index 00000000..d441b0c4--- /dev/null+++ b/tests/mcp/consolidated-tools.test.ts@@ -0,0 +1,240 @@+/**+ * Consolidated read tools (token-diet, t_3920db77): `brain_brief`,+ * `brain_analytics`, and `schema_inspect` dispatch by `view` to the+ * exact handlers of the tools they replace; every predecessor stays+ * registered as a deprecated delegating alias for at least one minor+ * release, so existing MCP clients migrate by renaming the call.+ */++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 { bootstrapBrain } from "../../src/core/brain/init.ts";+import { writePreference } from "../../src/core/brain/preference.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";++let tmp: string;+let vault: string;+let configPath: string;+let ctx: ServerContext;++const TOOLS = buildToolTable("full");++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-consolidated-"));+ vault = join(tmp, "vault");+ configPath = join(tmp, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);+ bootstrapBrain(vault, { configPath });+ writePreference(vault, {+ slug: "fixture",+ topic: "fixture",+ principle: "Always test consolidated views.",+ created_at: "2026-05-01T10:00:00Z",+ unconfirmed_until: "2026-05-15T10:00:00Z",+ status: "confirmed",+ evidenced_by: [],+ });+ ctx = { vault, configPath } as unknown as ServerContext;+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++async function run(name: string, args: Record<string, unknown>): Promise<unknown> {+ return await findTool(TOOLS, name).handler(ctx, args);+}++/**+ * Volatile keys stripped before equality: handlers stamp a wall-clock+ * `generated_at` per call, so two back-to-back runs of the SAME code+ * path differ in that field alone. Everything else must match byte+ * for byte.+ */+function stable(value: unknown): string {+ return JSON.stringify(value, (key, v) => (key === "generated_at" ? undefined : v));+}++describe("brain_brief", () => {+ const CASES: ReadonlyArray<{+ view: string;+ alias: string;+ args?: Record<string, unknown>;+ }> = [+ { view: "morning", alias: "brain_morning_brief" },+ { view: "daily", alias: "brain_daily_brief", args: { date: "2026-05-02" } },+ { view: "weekly", alias: "brain_weekly_synthesis", args: { week_end: "2026-05-08" } },+ { view: "monthly", alias: "brain_monthly_review", args: { month: "2026-05" } },+ { view: "operator", alias: "brain_operator_summary", args: { include_dream: false } },+ {+ view: "digest",+ alias: "brain_digest",+ args: { since: "2026-05-01T00:00:00Z", until: "2026-05-03T00:00:00Z" },+ },+ ];++ for (const { view, alias, args } of CASES) {+ test(`view=${view} returns exactly what ${alias} returns`, async () => {+ const consolidated = await run("brain_brief", { view, ...args });+ const predecessor = await run(alias, args ?? {});+ expect(stable(consolidated)).toBe(stable(predecessor));+ });+ }++ test("invalid view raises a clear error", async () => {+ await expect(run("brain_brief", { view: "hourly" })).rejects.toThrow(/view/);+ });++ test("missing view raises a clear error", async () => {+ await expect(run("brain_brief", {})).rejects.toThrow(/view/);+ });+});++describe("brain_analytics", () => {+ test("view=timeline returns exactly what brain_timeline returns", async () => {+ // Explicit window: the tool defaults `until` to wall-clock now,+ // which would differ between two back-to-back calls.+ const args = { pref_id: "pref-fixture", since: "2026-05-01", until: "2026-06-01" };+ const consolidated = await run("brain_analytics", { view: "timeline", ...args });+ const predecessor = await run("brain_timeline", args);+ expect(stable(consolidated)).toBe(stable(predecessor));+ });++ test("view=belief_evolution returns exactly what brain_belief_evolution returns", async () => {+ const args = { pref_id: "pref-fixture" };+ const consolidated = await run("brain_analytics", { view: "belief_evolution", ...args });+ const predecessor = await run("brain_belief_evolution", args);+ expect(stable(consolidated)).toBe(stable(predecessor));+ });++ test("view=concept_synthesis returns exactly what brain_concept_synthesis returns", async () => {+ const args = { id: "pref-fixture" };+ const consolidated = await run("brain_analytics", { view: "concept_synthesis", ...args });+ const predecessor = await run("brain_concept_synthesis", args);+ expect(stable(consolidated)).toBe(stable(predecessor));+ });++ test("view=attention_flows defaults the operation to list", async () => {+ const consolidated = await run("brain_analytics", { view: "attention_flows" });+ const predecessor = await run("brain_attention_flows", { operation: "list" });+ expect(stable(consolidated)).toBe(stable(predecessor));+ });++ test("invalid view raises a clear error", async () => {+ await expect(run("brain_analytics", { view: "recurrence" })).rejects.toThrow(/view/);+ });+});++describe("schema_inspect", () => {+ const CASES: ReadonlyArray<{ view: string; alias: string; args?: Record<string, unknown> }> = [+ { view: "graph", alias: "schema_graph" },+ { view: "lint", alias: "schema_lint" },+ { view: "stats", alias: "schema_stats" },+ { view: "orphans", alias: "schema_review_orphans" },+ { view: "active_pack", alias: "get_active_schema_pack" },+ { view: "packs", alias: "list_schema_packs" },+ ];++ for (const { view, alias, args } of CASES) {+ test(`view=${view} returns exactly what ${alias} returns`, async () => {+ const consolidated = await run("schema_inspect", { view, ...args });+ const predecessor = await run(alias, args ?? {});+ expect(stable(consolidated)).toBe(stable(predecessor));+ });+ }++ test("view=explain_type forwards the token", async () => {+ const consolidated = run("schema_inspect", { view: "explain_type", token: "no-such-token" });+ const predecessor = run("schema_explain_type", { token: "no-such-token" });+ // Both paths must agree - either both resolve or both reject with+ // the same message.+ const [a, b] = await Promise.allSettled([consolidated, predecessor]);+ expect(a.status).toBe(b.status);+ if (a.status === "rejected" && b.status === "rejected") {+ expect((a.reason as Error).message).toBe((b.reason as Error).message);+ } else if (a.status === "fulfilled" && b.status === "fulfilled") {+ expect(stable(a.value)).toBe(stable(b.value));+ }+ });++ test("invalid view raises a clear error", async () => {+ await expect(run("schema_inspect", { view: "everything" })).rejects.toThrow(/view/);+ });+});++describe("deprecated aliases", () => {+ const ALIASES = [+ "brain_morning_brief",+ "brain_daily_brief",+ "brain_weekly_synthesis",+ "brain_monthly_review",+ "brain_operator_summary",+ "brain_digest",+ "brain_timeline",+ "brain_attention_flows",+ "brain_belief_evolution",+ "brain_concept_synthesis",+ "schema_graph",+ "schema_lint",+ "schema_stats",+ "schema_review_orphans",+ "schema_explain_type",+ "get_active_schema_pack",+ "list_schema_packs",+ "reload_schema_pack",+ ];++ test("every alias stays registered with a one-line deprecation description", () => {+ for (const name of ALIASES) {+ const tool = findTool(TOOLS, name);+ expect(tool.description).toContain("Deprecated alias");+ expect(tool.description.length).toBeLessThanOrEqual(160);+ }+ });++ test("consolidated tools are registered", () => {+ for (const name of ["brain_brief", "brain_analytics", "schema_inspect"]) {+ expect(() => findTool(TOOLS, name)).not.toThrow();+ }+ });+});++describe("alias listing", () => {+ test("aliases are callable but hidden from the advertised tool list", async () => {+ const { MCPServer } = await import("../../src/mcp/server.ts");+ const server = new MCPServer({ vault, configPath });+ await server.handleRequest({+ jsonrpc: "2.0",+ id: 1,+ method: "initialize",+ params: {+ protocolVersion: "2025-06-18",+ capabilities: {},+ clientInfo: { name: "t", version: "0" },+ },+ });+ await server.handleRequest({ jsonrpc: "2.0", method: "notifications/initialized" });+ const list = (await server.handleRequest({+ jsonrpc: "2.0",+ id: 2,+ method: "tools/list",+ })) as { result: { tools: Array<{ name: string }> } };+ const listed = new Set(list.result.tools.map((t) => t.name));+ expect(listed.has("brain_brief")).toBe(true);+ expect(listed.has("brain_daily_brief")).toBe(false);+ expect(listed.has("schema_stats")).toBe(false);++ // Still callable: the alias resolves through tools/call.+ const call = (await server.handleRequest({+ jsonrpc: "2.0",+ id: 3,+ method: "tools/call",+ params: { name: "brain_daily_brief", arguments: { date: "2026-05-02" } },+ })) as { result: { isError?: boolean } };+ expect(call.result.isError).not.toBe(true);+ });+});diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.tsindex 7c7eac7b..38d87f4b 100644--- a/tests/mcp/mcp.test.ts+++ b/tests/mcp/mcp.test.ts@@ -188,13 +188,11 @@ describe("tool listing", () => {"brain_dream","brain_intent_review","brain_retention",- "brain_monthly_review","brain_review_candidates","brain_apply_evidence","brain_note","brain_pinned_context","brain_context",- "brain_digest","brain_query","brain_agent_query","brain_agent_diff",@@ -204,20 +202,13 @@ describe("tool listing", () => {"brain_backlinks",// Per-preference mutation audit + morning brief (added in v0.21.0)."brain_audit",- "brain_morning_brief",// Vault portability suite (added in v0.22.0)."brain_sources","brain_switch_vault","brain_context_pack","brain_unlinked_mentions",- "brain_concept_synthesis","brain_moc_audit",- "brain_timeline",- "brain_belief_evolution","brain_stale_scan",- "brain_daily_brief",- "brain_weekly_synthesis",- "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).@@ -233,7 +224,10 @@ describe("tool listing", () => {"brain_procedural_memory","brain_procedural_graph","brain_recurrence",- "brain_attention_flows",+ // Consolidated view tools (token-diet, v0.34.0); the per-view+ // names above stay registered as deprecated aliases.+ "brain_brief",+ "brain_analytics",// Pay Memory (unchanged)."payment_memory_init","payment_receipt_append",@@ -248,15 +242,8 @@ describe("tool listing", () => {"brain_recall_gate","brain_search",// Schema admin + watchdog recovery probes.- "get_active_schema_pack",- "list_schema_packs",- "schema_stats",- "schema_lint",- "schema_graph",- "schema_explain_type",- "schema_review_orphans","schema_apply_mutations",- "reload_schema_pack",+ "schema_inspect","brain_watchdog",].toSorted(),);@@ -501,8 +488,11 @@ describe("stdio loop", () => {// + 3 procedural-learning tools (v0.30.0) = 68.// + brain_procedural_graph (v0.31.0) = 69.// + brain_attention_flows (v0.31.0) = 70.- // + brain_recall_feedback (recall-trust-suite) = 71.- expect(list.result.tools.length).toBe(71);+ // + brain_recall_feedback (recall-trust-suite) = 71,+ // + brain_brief / brain_analytics / schema_inspect (token-diet) = 74+ // - 18 predecessors hidden as deprecated aliases (callable via+ // tools/call, not advertised) = 56.+ expect(list.result.tools.length).toBe(56);});test("returns parse error for invalid JSON", async () => {diff --git a/tests/mcp/preview-budget-wiring.test.ts b/tests/mcp/preview-budget-wiring.test.tsdeleted file mode 100644index d3b3f07f..00000000--- a/tests/mcp/preview-budget-wiring.test.ts+++ /dev/null@@ -1,52 +0,0 @@-import { describe, expect, test } from "bun:test";--import { buildToolTable } from "../../src/mcp/tools.ts";-import { MCP_PREVIEW_BUDGET } from "../../src/mcp/preview-budget.ts";--/**- * The exact set of tools that opt into the preview budget. Kept explicit- * so adding/removing a budget is a deliberate, reviewed change rather- * than an accident of a default.- */-const BUDGETED = new Set<string>([- "brain_search",- "brain_context_pack",- "brain_digest",- "brain_timeline",- "brain_concept_synthesis",- "brain_operator_summary",- "brain_weekly_synthesis",- "brain_monthly_review",- "brain_daily_brief",- "second_brain_status",- "second_brain_query",-]);--describe("preview-budget wiring", () => {- test("exactly the enumerated large tools carry the shared budget", () => {- const table = buildToolTable("full");- const withBudget = new Set<string>();- for (const tool of table) {- if (tool.previewBudget !== undefined) {- withBudget.add(tool.name);- expect(tool.previewBudget).toBe(MCP_PREVIEW_BUDGET);- }- }- expect([...withBudget].toSorted()).toEqual([...BUDGETED].toSorted());- });-- test("small status/echo and writer tools stay unbudgeted", () => {- const table = buildToolTable("full");- const byName = new Map(table.map((t) => [t.name, t]));- for (const name of [- "brain_feedback",- "brain_note",- "brain_apply_evidence",- "brain_artifact_get",- "vault_health",- "brain_doctor",- ]) {- expect(byName.get(name)?.previewBudget).toBeUndefined();- }- });-});diff --git a/tests/mcp/registry-guard.test.ts b/tests/mcp/registry-guard.test.tsnew file mode 100644index 00000000..1320af76--- /dev/null+++ b/tests/mcp/registry-guard.test.ts@@ -0,0 +1,46 @@+/**+ * Registry guard (token-diet, t_352fd7f6 + t_c967abaf): the serialized+ * tool registry is paid by every MCP client on every request in+ * non-deferred hosts, so description growth and unbounded outputs are+ * contract violations, not style issues.+ */++import { describe, expect, test } from "bun:test";++import {+ auditPreviewBudgets,+ auditToolDescriptions,+ PREVIEW_BUDGET_EXEMPT,+} from "../../src/mcp/registry-guard.ts";+import { buildToolTable } from "../../src/mcp/tools.ts";++const TOOLS = buildToolTable("full");++describe("description caps", () => {+ test("no tool or property description exceeds its cap", () => {+ const violations = auditToolDescriptions(TOOLS);+ const rendered = violations+ .map((v) => `${v.tool}${v.path} (${v.length} > ${v.limit})`)+ .join("\n");+ expect(rendered).toBe("");+ });+});++describe("preview-budget default", () => {+ test("every tool carries a budget or an explicit exempt entry with a reason", () => {+ const audit = auditPreviewBudgets(TOOLS);+ expect(audit.unbudgetedAndUnexempted).toEqual([]);+ });++ test("no stale exemptions: exempt tools must stay budget-less and must exist", () => {+ const audit = auditPreviewBudgets(TOOLS);+ expect(audit.exemptButBudgeted).toEqual([]);+ expect(audit.exemptButUnknown).toEqual([]);+ });++ test("every exemption states a non-empty reason", () => {+ for (const [name, reason] of Object.entries(PREVIEW_BUDGET_EXEMPT)) {+ expect(reason.trim().length, name).toBeGreaterThan(10);+ }+ });+});diff --git a/tests/mcp/schema-tools.test.ts b/tests/mcp/schema-tools.test.tsindex 22e80eac..bc66f92d 100644--- a/tests/mcp/schema-tools.test.ts+++ b/tests/mcp/schema-tools.test.ts@@ -87,15 +87,11 @@ describe("schema MCP tools", () => {(tool) => tool.name,);- expect(names).toContain("get_active_schema_pack");- expect(names).toContain("list_schema_packs");- expect(names).toContain("schema_stats");- expect(names).toContain("schema_lint");- expect(names).toContain("schema_graph");- expect(names).toContain("schema_explain_type");- expect(names).toContain("schema_review_orphans");+ // token-diet: the consolidated schema_inspect is advertised; the+ // per-view predecessors stay callable as hidden deprecated aliases.+ expect(names).toContain("schema_inspect");expect(names).toContain("schema_apply_mutations");- expect(names).toContain("reload_schema_pack");+ expect(names).not.toContain("schema_stats");});test("applies schema mutations through the MCP handler", async () => {diff --git a/tests/mcp/session-recall-tool.test.ts b/tests/mcp/session-recall-tool.test.tsindex 6d2b2d54..ec675426 100644--- a/tests/mcp/session-recall-tool.test.ts+++ b/tests/mcp/session-recall-tool.test.ts@@ -55,19 +55,41 @@ async function initialize(server: MCPServer): Promise<void> {});}-async function callTool(+async function callOn(+ server: MCPServer,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);+ const parsed = JSON.parse(response.result.content[0]!.text) as Record<string, unknown>;+ // Session tools carry a preview budget (token-diet); when the result+ // came back as a preview envelope, fetch the full payload through+ // the same server's artifact store - exactly what a client does.+ if (parsed["preview_truncated"] === true) {+ const full = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 10,+ method: "tools/call",+ params: { name: "brain_artifact_get", arguments: { artifact_id: parsed["artifact_id"] } },+ })) as { result: { content: ReadonlyArray<{ type: string; text: string }> } };+ const envelope = JSON.parse(full.result.content[0]!.text) as { content: string };+ return JSON.parse(envelope.content) as Record<string, unknown>;+ }+ return parsed;+}++async function callTool(+ name: string,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const server = new MCPServer({ vault, configPath: null });+ await initialize(server);+ return await callOn(server, name, args);}describe("session recall MCP tool registration", () => {