Skip to content

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

TypeScript

refactor: SOLID/DRY decomposition - domain modules, unified helpers, surface guards (v1.2.0) (#86)

Sol Aitken8972f1391951
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 99b9714f..9fc93b51 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.1.0",
+ "version": "1.2.0",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 4f6f6a96..30e134b9 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.1.0",
+ "version": "1.2.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"skills": "./skills",
"hooks": "./hooks/hooks.json",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b7c1b980..8e4f7635 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,62 @@ 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).
+## [1.2.0] - 2026-06-09
+
+Codebase-wide SOLID/DRY refactor: god modules decomposed into cohesive
+domain modules and duplicated helpers unified, with zero behavior change.
+The public surface is untouched - MCP tool names, CLI verbs, file formats,
+output strings, and exit codes are all byte-identical to 1.1.0, and a new
+frozen-surface parity test now guards the MCP tool-name set mechanically.
+
+### Changed
+
+- **MCP brain tools split by domain**: the 5,614-line `src/mcp/brain-tools.ts`
+ monolith (54 tools, 100+ helpers) is now 16 cohesive modules under
+ `src/mcp/brain/` (feedback, review, context, pack, query, entity, health,
+ brief, analytics, knowledge, admin, recall, workspace, procedure, landscape,
+ shared), mirroring the per-domain split the sibling tool files already used.
+ `brain-tools.ts` remains the aggregation seam exporting `BRAIN_TOOLS`, so
+ every existing import keeps working. Tool registration order within
+ `tools/list` enumeration changed; the name set and each tool's schema,
+ description, and handler are unchanged.
+- **Dream pass decomposed**: `dream.ts` (2,239 lines) now orchestrates four
+ extracted modules - `dream-plan.ts` (scan-record and plan-state shapes),
+ `confidence.ts` (Wilson-bound confidence computation), `dream-refresh.ts`
+ (apply-evidence scan and refresh/promotion planning), and
+ `reconcile-outcomes.ts` (contradiction classification) - each independently
+ unit-tested.
+- **Brain config parser extracted**: the 230-line YAML subset parser moved out
+ of `policy.ts` into `yaml-parse.ts`; `policy.ts` keeps config semantics only.
+ The grammar is unchanged.
+- **One wikilink syntax module**: seven divergent `[[...]]` regex definitions
+ collapsed into named, purpose-documented variants in
+ `src/core/brain/wikilink.ts`, with characterization tests pinning each
+ former call site's contract.
+- **One atomic-write module**: `src/core/reliability/atomic.ts` merged into
+ `src/core/fs-atomic.ts`; the validate-hook and private-mode variant
+ (`atomicWriteText`) now shares the single temp-file + fsync + rename
+ pipeline.
+- **CLI brain verbs share context helpers**: 76 verb files replaced the
+ repeated config/vault/agent resolution boilerplate with
+ `brainVerbContext(flags)` and `resolveBrainAgent(flags, config)` from the
+ helpers barrel, called at the exact position of the former inline code so
+ validation order and error output stay identical.
+
+### Added
+
+- **Frozen-surface parity test**: `tests/mcp/brain-tools-parity.test.ts` pins
+ the exact v1.x Brain tool-name set; any future registry change that drops,
+ duplicates, or renames a tool fails CI.
+- **Core layering guard**: `tests/core/layering.test.ts` fails when anything
+ under `src/core` calls `process.exit`, `process.stdout.write`, or
+ `console.log` - the calls that belong to the CLI layer.
+
+### Removed
+
+- **`scripts/sync-version.py`**: superseded by `scripts/sync-version.ts`
+ (the only version the build invokes) since 0.8.1.
+
## [1.1.0] - 2026-06-09
Removal of the Pay Memory layer. The pay.sh integration and the entire
@@ -4989,7 +5045,9 @@ 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.
-[Unreleased]: https://github.com/itechmeat/open-second-brain/compare/v1.0.1...HEAD
+[Unreleased]: https://github.com/itechmeat/open-second-brain/compare/v1.2.0...HEAD
+[1.2.0]: https://github.com/itechmeat/open-second-brain/compare/v1.1.0...v1.2.0
+[1.1.0]: https://github.com/itechmeat/open-second-brain/compare/v1.0.1...v1.1.0
[1.0.1]: https://github.com/itechmeat/open-second-brain/compare/v1.0.0...v1.0.1
[1.0.0]: https://github.com/itechmeat/open-second-brain/compare/v0.45.0...v1.0.0
[0.45.0]: https://github.com/itechmeat/open-second-brain/compare/v0.44.0...v0.45.0
diff --git a/docs/brainstorm/solid-dry-refactor/cli-output/claude.md b/docs/brainstorm/solid-dry-refactor/cli-output/claude.md
new file mode 100644
index 00000000..af1964a9
--- /dev/null
+++ b/docs/brainstorm/solid-dry-refactor/cli-output/claude.md
@@ -0,0 +1,35 @@
+### Variant 1: Mechanical Extraction with Compatibility Shims
+
+- **Approach**: Each unit is a pure code move with the old paths kept as thin re-export shims. brain-tools.ts splits into per-domain modules but stays as an aggregator file re-exporting `BRAIN_TOOLS`; fs-atomic.ts becomes a re-export of reliability/atomic.ts wrappers; the seven wikilink regexes are replaced by imports from a new canonical module while the old exported names survive as aliases; CLI verbs gain a `runBrainCommand()` helper but each verb file keeps its own entry function. Layering guard is a grep-based bun test.
+- **Trade-offs**:
+ - Pro: lowest blast radius — no import path changes outside the touched modules, so tests, plugins/hermes, hooks/, and the openclaw bundle are untouched by construction.
+ - Pro: each commit is trivially revertable; diffs are mostly moves, easy to review.
+ - Con: shims are new dead weight — DRY violations are hidden behind aliases rather than removed, leaving a second cleanup pass for later.
+ - Con: 89 verb files still each contain boilerplate (a call to the wrapper) and divergent flag parsing may survive inside the wrapper callbacks.
+- **Complexity**: small
+- **Risk**: low
+
+### Variant 2: Canonical Modules with Direct Call-Site Migration
+
+- **Approach**: For every duplication, pick one winning implementation, delete the loser, and migrate all call sites in the same commit — no shims except where an export is verifiably consumed externally (checked by grepping tests, plugins/hermes, hooks/, openclaw imports first). `atomicWriteText` (the richer API with validate hook) absorbs fs-atomic.ts; one `wikilink.ts` in link-graph exports parse/format/regex and all seven sites import it; CLI verbs are rewritten onto a `withBrainContext(flags, handler)` higher-order wrapper that owns config resolution and fail() formatting; policy/dream extractions get explicit input/output interfaces. Layering guard is a bun test that scans src/core for `process.exit`/`stdout`/`console` with an allowlist.
+- **Trade-offs**:
+ - Pro: actually removes the ~600 duplicated CLI lines and the duplicate atomic/wikilink implementations — the codebase ends smaller, not larger.
+ - Pro: unifying divergent wikilink edge-case handling under one tested module surfaces latent inconsistencies now instead of letting them drift further.
+ - Con: call-site migration per commit means bigger diffs (the CLI unit touches ~89 files at once), so review and revert granularity within a unit is coarser.
+ - Con: merging divergent regex behavior risks subtle behavior change; needs characterization tests for the edge cases before unifying.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Variant 3: Registry-Driven Framework Refactor
+
+- **Approach**: Go beyond extraction to declarative registration: per-domain MCP tool modules export descriptor arrays that an aggregator concatenates with a parity test asserting the frozen v1.0.0 tool-name set; CLI verbs convert to a `defineBrainVerb({flags, run})` factory that centralizes parsing, context, error formatting, and exit codes, with verbs discovered from a manifest; wikilink and atomic-write become a small `src/core/text/` and `src/core/fs/` primitives layer. Layering guard is a hand-rolled AST walk (Bun's transpiler API, no new deps) enforcing import direction as well as the process/console ban.
+- **Trade-offs**:
+ - Pro: strongest long-term shape — new tools/verbs get the conventions for free, and the parity test mechanically guards the frozen public surface.
+ - Pro: the import-direction guard prevents the next god module, not just this one.
+ - Con: largest diff and most new abstraction in a "zero behavior change" PR; a verb factory changes flag-parsing code paths for all 89 verbs at once, the hardest place to prove output-identical behavior (error message formatting, exit codes).
+ - Con: stretches the release scope — framework design questions (manifest format, descriptor shape) invite bikeshedding and make units less independently revertable since later units depend on the new primitives layer.
+- **Complexity**: large
+- **Risk**: high
+
+### Recommended: Variant 2
+**Rationale**: The task's stated goal is removing duplication, and Variant 1 mostly relocates it behind shims while Variant 3 smuggles a framework redesign into a pure-refactor PR with a frozen v1.0.0 surface. Variant 2 deletes the duplicates outright, follows the already-established per-domain split pattern in src/mcp/, and keeps each unit a self-contained conventional commit; its main risk (wikilink behavior drift) is contained by writing characterization tests for the divergent edge cases before unifying, which the 541-test suite and per-unit green requirement already mandate.
diff --git a/docs/brainstorm/solid-dry-refactor/cli-output/prompt.md b/docs/brainstorm/solid-dry-refactor/cli-output/prompt.md
new file mode 100644
index 00000000..57d92794
--- /dev/null
+++ b/docs/brainstorm/solid-dry-refactor/cli-output/prompt.md
@@ -0,0 +1,60 @@
+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
+
+## Goal
+One release-scoped refactor pass over the Open Second Brain TypeScript codebase: decompose god modules, remove DRY violations, unify duplicated helpers, and clean superseded files. No behavior changes; the public CLI/MCP surface stays identical.
+
+## Scope (six refactor units, one PR)
+1. Split src/mcp/brain-tools.ts (5614 lines, 52 tool handlers) into per-domain tool modules behind a thin aggregator. Sibling files (search-tools.ts, schema-tools.ts, watchdog-tools.ts, skill-tools.ts) already follow a per-domain split; tests and src/mcp/tools.ts import only the BRAIN_TOOLS array and one helper.
+2. Introduce a shared CLI brain-command context wrapper: ~89 files in src/cli/brain/verbs/ repeat parse flags + defaultConfigPath() + resolveBrainVault() + try/catch with ad-hoc fail() formatting (~600 duplicated lines).
+3. Unify the two atomic file-write implementations: src/core/fs-atomic.ts (atomicWriteFileSync, atomicCreateFileSyncExclusive) vs src/core/reliability/atomic.ts (atomicWriteText with validate hook and configurable mode). Identical temp-file naming, fsync, rename logic.
+4. Centralize wikilink regex parsing: seven divergent WIKILINK regex definitions (vault.ts, lint-consolidate.ts, link-graph/parse-wikilink.ts, link-graph/format-wikilink.ts, search/links.ts, search/entities.ts, search/query-plan.ts); two exact duplicates, the rest drift in edge-case handling.
+5. Extract the 230-line hand-rolled YAML subset parser from src/core/brain/policy.ts (1871 lines) into its own module; extract evidence-refresh (~340 lines) and reconcile-outcomes sub-modules from src/core/brain/dream.ts (2239 lines) with explicit input/output interfaces.
+6. Cleanup: delete superseded scripts/sync-version.py (replaced by sync-version.ts); add an automated layering guard so src/core never calls process.exit/process.stdout/console directly.
+
+# Project context
+
+Open Second Brain - TypeScript on Bun runtime, ~500 source files, ~95k LOC. Markdown/Obsidian vault second brain for AI agents (Hermes, Claude Code, Codex, OpenClaw). Strict tsconfig (strict, noUncheckedIndexedAccess), oxlint + oxfmt, 541 tests via bun test.
+
+Recent commits:
+6651228 refactor: language-agnostic fact extraction + README slim (v1.1.0) (#85)
+9886d9a refactor: make search and classification language-agnostic (#84)
+618870e refactor!: remove the pay.sh integration and the Pay Memory layer (#83)
+72bac52 fix(hermes): advertise static tool schemas so the provider registers with its full tool set (#81)
+ff43abd fix(ci): treat an existing release as success in the release workflow (#80)
+957a403 feat!: Stability & Trust - 1.0.0 API freeze, deprecation sweep, safeguard, staged dream, timezone, report deltas (#79)
+
+Related files:
+src/mcp/brain-tools.ts, src/mcp/tools.ts, src/cli/brain/verbs/*.ts (89 files), src/cli/brain/helpers.ts, src/core/fs-atomic.ts, src/core/reliability/atomic.ts, src/core/vault.ts, src/core/brain/policy.ts, src/core/brain/dream.ts, src/core/brain/link-graph/*.ts, src/core/search/links.ts, scripts/sync-version.py
+
+Conventions:
+- v1.0.0 froze the public API: MCP tool names, CLI verbs, and file formats must not change.
+- Established per-domain split pattern in src/mcp/ (search-tools.ts, schema-tools.ts, watchdog-tools.ts, skill-tools.ts).
+- Core layer never calls process.exit or writes to stdout; CLI owns exit codes and formatting.
+- Conventional commits; one PR = one CHANGELOG version.
+- Some duplication is documented as intentional (e.g. log-jsonl.ts ISO regex comment says writer/reader must not share a constant).
+
+Constraints:
+- Pure refactor: zero behavior change, existing 541 tests must stay green after every atomic unit.
+- No new external dependencies.
+- Do not change public exports that tests, plugins/hermes, hooks/, or openclaw bundle import.
+- No language-specific regexes or hardcoded natural-language phrases.
+- Each unit lands as a separate conventional commit on one feature branch; units must be independently revertable.
+
+# 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/solid-dry-refactor/design.md b/docs/brainstorm/solid-dry-refactor/design.md
new file mode 100644
index 00000000..1594dd2f
--- /dev/null
+++ b/docs/brainstorm/solid-dry-refactor/design.md
@@ -0,0 +1,67 @@
+# SOLID/DRY refactor - decompose god modules and unify duplicated helpers
+
+**Status:** draft
+**Author:** claude-dev-agent (via feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+The codebase has grown to ~500 TypeScript files and ~95k lines through 20+ feature suites, and several hotspots now violate single-responsibility and DRY principles. `src/mcp/brain-tools.ts` is a 5614-line god module holding 52 tool handlers across 13+ domains while its siblings follow a per-domain split. Eighty-nine CLI verb files repeat the same context-resolution and error-handling boilerplate. Atomic file writes, wikilink parsing, YAML config parsing, and dream sub-phases each exist in duplicated or entangled form. Nothing enforces the layering rule that core modules never talk to the process directly.
+
+## Scope
+
+- Split `src/mcp/brain-tools.ts` into per-domain tool modules; `brain-tools.ts` remains only as the aggregation point exporting `BRAIN_TOOLS` (the registration seam that `tools.ts` and tests already import - not a compatibility shim).
+- Add `withBrainCommand` context wrapper in `src/cli/brain/` and migrate the verb files onto it, deleting the repeated vault/config/try-catch boilerplate.
+- Unify atomic writes on `src/core/reliability/atomic.ts` (the richer API); migrate `fs-atomic.ts` call sites and delete the duplicate implementation.
+- Create one canonical wikilink module; migrate all seven regex sites onto named, purpose-documented variants. Characterization tests pin current behavior per site before migration.
+- Extract the YAML subset parser out of `policy.ts`; extract evidence-refresh and reconcile-outcomes out of `dream.ts` with explicit input/output interfaces.
+- Delete `scripts/sync-version.py`; add a layering-guard test that scans `src/core` for `process.exit` / `process.stdout` / `console.*` usage.
+
+## Out of scope
+
+- Any behavior, output-format, or public-surface change (v1.0.0 froze MCP tool names, CLI verbs, file formats).
+- Registry/manifest-driven command frameworks (consultant variant 3) - rejected as scope creep.
+- ISO-8601 regex consolidation in `log-jsonl.ts` / `truth/store.ts` - the in-code comments document that writer/reader pairs intentionally do not share constants; respected as-is.
+- `.toISOString()` to `isoSecond()` codemod - would change stored timestamp precision; not a pure refactor.
+- New external dependencies.
+
+## Chosen approach
+
+Consultant variant 2: canonical modules with direct call-site migration. For every duplication pick one winning implementation, migrate all call sites in the same commit, and delete the loser. No alias re-export shims; the only surviving indirection is `brain-tools.ts` as the existing aggregation seam. Each unit is one conventional commit with the full suite green, so units stay independently revertable.
+
+## Design decisions
+
+- **brain-tools.ts stays as aggregator, not shim**: `tools.ts` and six test files import `BRAIN_TOOLS` from it; keeping that one seam gives a zero-churn registration point and matches how `ALL_TOOLS` already concatenates domain arrays.
+- **Domain split by tool cohesion, ~13 modules**: feedback/dream writes, review lifecycle, context packing, queries, health, briefs, analytics, entities, knowledge graph, admin, recall/benchmark, procedural, landscape - mirrors the dispatcher groups already present inside the file. A parity test asserts the before/after tool-name set is identical.
+- **`reliability/atomic.ts` wins over `fs-atomic.ts`**: it is the newer API with the validate hook and configurable mode; the exclusive-create primitive from `fs-atomic.ts` moves into it so one module owns temp-file naming + fsync + rename.
+- **Wikilink variants are named, not merged into one regex**: the seven sites have three genuinely different contracts (quoted/heading-aware, strict no-newline, alias-capturing). Forcing one regex would change behavior; instead one module exports documented named variants and the two exact duplicates collapse.
+- **Wrapper does not own flag schemas**: `withBrainCommand` resolves context (vault, config, json mode) and uniform error formatting only; each verb keeps its own `parse()` schema so output strings and exit codes stay byte-identical.
+- **Layering guard is a bun test, not an AST walk**: a source scan over `src/core/**` for `process.exit` / `process.stdout` / `console.` with an explicit allowlist is sufficient, dependency-free, and runs in the normal test suite.
+
+## File changes
+
+New files:
+- `src/mcp/brain/` domain modules (~13 files) plus shared helpers module for coercion/serialization used by several domains.
+- `src/cli/brain/command.ts` - `withBrainCommand` wrapper and `CommandContext` type.
+- `src/core/brain/wikilink.ts` - existing helper module extended with the named regex variants (chosen over a new file: search and core layers already import brain modules, and a second `wikilink.ts` would recreate the twin-module problem).
+- `src/core/brain/yaml-parse.ts` - YAML subset parser moved from `policy.ts`.
+- `src/core/brain/dream-refresh.ts`, `src/core/brain/reconcile-outcomes.ts` - extracted from `dream.ts`.
+- `tests/core/layering.test.ts` - layering guard.
+- Characterization/unit tests for wikilink variants, atomic write paths, extracted modules, tool-set parity.
+
+Modified files:
+- `src/mcp/brain-tools.ts` (becomes aggregator), `src/mcp/tools.ts` (unchanged imports, verify only).
+- `src/cli/brain/verbs/*.ts` (~89 files migrate to wrapper).
+- `src/core/reliability/atomic.ts` (absorbs exclusive create), all `fs-atomic.ts` importers.
+- `src/core/vault.ts`, `lint-consolidate.ts`, `link-graph/parse-wikilink.ts`, `link-graph/format-wikilink.ts`, `search/links.ts`, `search/entities.ts`, `search/query-plan.ts` (wikilink imports).
+- `src/core/brain/policy.ts`, `src/core/brain/dream.ts` (shrink via extraction).
+
+Deleted files:
+- `src/core/fs-atomic.ts`, `scripts/sync-version.py`.
+
+## Risks and open questions
+
+- **Wikilink unification could surface latent edge-case differences** - mitigated by writing characterization tests against the current behavior of each site before touching imports.
+- **CLI wrapper migration touches ~89 files in one commit** - mitigated by keeping the wrapper minimal (context + catch) and relying on the existing CLI tests that assert output strings and exit codes.
+- **openclaw bundle (`openclaw/index.js`) is a committed build artifact** - must be rebuilt via `bun run build:openclaw` if anything it bundles changes, and verified in QA.
+- **plugins/hermes and hooks/ may import moved symbols** - grep before each move; anything externally imported keeps its export path through the canonical module.
diff --git a/docs/brainstorm/solid-dry-refactor/plan.md b/docs/brainstorm/solid-dry-refactor/plan.md
new file mode 100644
index 00000000..e0ef1b5d
--- /dev/null
+++ b/docs/brainstorm/solid-dry-refactor/plan.md
@@ -0,0 +1,38 @@
+# SOLID/DRY refactor - implementation plan
+
+One feature branch (`feat/solid-dry-refactor`), six atomic units, each its own conventional commit with the full suite green. TDD: characterization or unit tests land before each move.
+
+## Tasks
+
+### Task 1: Canonical wikilink module (kanban t_c82bdae0)
+- **Files**: new `src/core/brain/wikilink.ts`; new `tests/core/brain/wikilink.test.ts`; migrate `src/core/vault.ts`, `src/core/brain/lint-consolidate.ts`, `src/core/brain/link-graph/parse-wikilink.ts`, `src/core/brain/link-graph/format-wikilink.ts`, `src/core/search/links.ts`, `src/core/search/entities.ts`, `src/core/search/query-plan.ts`
+- **Acceptance**: characterization tests pin each variant's contract (quoted/heading, strict, alias-capturing, minimal) and pass before and after migration; no regex literal for `[[...]]` remains outside the module; full suite green.
+- **Depends on**: none
+
+### Task 2: Unify atomic file writes (kanban t_82213b08)
+- **Files**: `src/core/reliability/atomic.ts` (absorbs exclusive create), delete `src/core/fs-atomic.ts`, migrate its importers; new/extended tests in `tests/core/reliability/atomic.test.ts`
+- **Acceptance**: one implementation of temp-name + fsync + rename; tests cover simple write, validated write, exclusive create (success and already-exists), mode override; full suite green.
+- **Depends on**: none
+
+### Task 3: Extract policy YAML parser and dream sub-modules (kanban t_3d9369d0)
+- **Files**: new `src/core/brain/yaml-parse.ts` (from `policy.ts`), new `src/core/brain/dream-refresh.ts` and `src/core/brain/reconcile-outcomes.ts` (from `dream.ts`); unit tests for each new module
+- **Acceptance**: `policy.ts` no longer contains parsing code; `dream.ts` shrinks by the extracted ranges; extracted modules unit-tested in isolation; existing policy/dream tests green unchanged.
+- **Depends on**: none
+
+### Task 4: Split brain-tools.ts into domain modules (kanban t_c567a35e)
+- **Files**: new `src/mcp/brain/` domain modules (~13) plus shared helper module; `src/mcp/brain-tools.ts` becomes the aggregator; new parity test asserting the BRAIN_TOOLS name set is unchanged
+- **Acceptance**: parity test green; no file in `src/mcp` over ~700 lines; `tools.ts` and existing test imports unchanged; full suite green.
+- **Depends on**: Task 1 (wikilink), Task 2 (atomic) so moved code imports canonical modules once.
+
+### Task 5: CLI brain-command wrapper migration (kanban t_6467b4af)
+- **Files**: new `src/cli/brain/command.ts` (+ unit tests for context resolution and error formatting); migrate `src/cli/brain/verbs/*.ts`
+- **Acceptance**: wrapper unit tests green; verb files contain no repeated vault/config/catch boilerplate; CLI output strings and exit codes unchanged (existing CLI tests); full suite green.
+- **Depends on**: none (parallel-safe, but lands after Task 4 to avoid merge noise in shared helper files).
+
+### Task 6: Cleanup and layering guard (kanban t_bee11d1a)
+- **Files**: delete `scripts/sync-version.py`; new `tests/core/layering.test.ts`
+- **Acceptance**: layering test fails on injected `process.exit` in a core fixture-style check and passes on the real tree; `bun run sync-version:check` still works; full suite green.
+- **Depends on**: Tasks 1-5 (guard validates the final tree).
+
+## QA gate (after all tasks)
+`bun run validate` (typecheck + lint + test), `bun run fmt:check`, `bun run sync-version:check`, rebuild `openclaw/index.js` via `bun run build:openclaw` if bundled sources moved, smoke-test `o2b` CLI and MCP server startup.
diff --git a/docs/brainstorm/solid-dry-refactor/variants.md b/docs/brainstorm/solid-dry-refactor/variants.md
new file mode 100644
index 00000000..8200457a
--- /dev/null
+++ b/docs/brainstorm/solid-dry-refactor/variants.md
@@ -0,0 +1,49 @@
+# SOLID/DRY refactor - brainstorm audit trail
+
+Consultant: Claude Code (`claude -p`), single run, no fallback needed. Raw output: `cli-output/claude.md`. Prompt: `cli-output/prompt.md`.
+
+## Variant 1: Mechanical Extraction with Compatibility Shims
+
+- **Approach**: Each unit is a pure code move with the old paths kept as thin re-export shims. brain-tools.ts splits into per-domain modules but stays as an aggregator file re-exporting `BRAIN_TOOLS`; fs-atomic.ts becomes a re-export of reliability/atomic.ts wrappers; the seven wikilink regexes are replaced by imports from a new canonical module while the old exported names survive as aliases; CLI verbs gain a `runBrainCommand()` helper but each verb file keeps its own entry function. Layering guard is a grep-based bun test.
+- **Trade-offs**:
+ - Pro: lowest blast radius - no import path changes outside the touched modules, so tests, plugins/hermes, hooks/, and the openclaw bundle are untouched by construction.
+ - Pro: each commit is trivially revertable; diffs are mostly moves, easy to review.
+ - Con: shims are new dead weight - DRY violations are hidden behind aliases rather than removed, leaving a second cleanup pass for later.
+ - Con: 89 verb files still each contain boilerplate (a call to the wrapper) and divergent flag parsing may survive inside the wrapper callbacks.
+- **Complexity**: small
+- **Risk**: low
+
+## Variant 2: Canonical Modules with Direct Call-Site Migration
+
+- **Approach**: For every duplication, pick one winning implementation, delete the loser, and migrate all call sites in the same commit - no shims except where an export is verifiably consumed externally (checked by grepping tests, plugins/hermes, hooks/, openclaw imports first). `atomicWriteText` (the richer API with validate hook) absorbs fs-atomic.ts; one `wikilink.ts` exports parse/format/regex and all seven sites import it; CLI verbs are rewritten onto a `withBrainContext(flags, handler)` higher-order wrapper that owns config resolution and fail() formatting; policy/dream extractions get explicit input/output interfaces. Layering guard is a bun test that scans src/core for `process.exit`/`stdout`/`console` with an allowlist.
+- **Trade-offs**:
+ - Pro: actually removes the ~600 duplicated CLI lines and the duplicate atomic/wikilink implementations - the codebase ends smaller, not larger.
+ - Pro: unifying divergent wikilink edge-case handling under one tested module surfaces latent inconsistencies now instead of letting them drift further.
+ - Con: call-site migration per commit means bigger diffs (the CLI unit touches ~89 files at once), so review and revert granularity within a unit is coarser.
+ - Con: merging divergent regex behavior risks subtle behavior change; needs characterization tests for the edge cases before unifying.
+- **Complexity**: medium
+- **Risk**: medium
+
+## Variant 3: Registry-Driven Framework Refactor
+
+- **Approach**: Go beyond extraction to declarative registration: per-domain MCP tool modules export descriptor arrays that an aggregator concatenates with a parity test asserting the frozen v1.0.0 tool-name set; CLI verbs convert to a `defineBrainVerb({flags, run})` factory that centralizes parsing, context, error formatting, and exit codes, with verbs discovered from a manifest; wikilink and atomic-write become a small `src/core/text/` and `src/core/fs/` primitives layer. Layering guard is a hand-rolled AST walk (Bun transpiler API, no new deps) enforcing import direction as well as the process/console ban.
+- **Trade-offs**:
+ - Pro: strongest long-term shape - new tools/verbs get the conventions for free, and the parity test mechanically guards the frozen public surface.
+ - Pro: the import-direction guard prevents the next god module, not just this one.
+ - Con: largest diff and most new abstraction in a "zero behavior change" PR; a verb factory changes flag-parsing code paths for all 89 verbs at once, the hardest place to prove output-identical behavior (error message formatting, exit codes).
+ - Con: stretches the release scope - framework design questions (manifest format, descriptor shape) invite bikeshedding and make units less independently revertable since later units depend on the new primitives layer.
+- **Complexity**: large
+- **Risk**: high
+
+## Consultant recommendation
+
+Variant 2. "The task's stated goal is removing duplication, and Variant 1 mostly relocates it behind shims while Variant 3 smuggles a framework redesign into a pure-refactor PR with a frozen v1.0.0 surface. Variant 2 deletes the duplicates outright, follows the already-established per-domain split pattern in src/mcp/, and keeps each unit a self-contained conventional commit; its main risk (wikilink behavior drift) is contained by writing characterization tests for the divergent edge cases before unifying."
+
+## Orchestrator decision
+
+Adopt Variant 2 with two amendments borrowed from the other variants:
+
+1. From Variant 1: `brain-tools.ts` stays as the aggregation seam exporting `BRAIN_TOOLS` - not as a compatibility shim but because `tools.ts` and six test files already treat it as the registration point; removing it would be churn without benefit.
+2. From Variant 3: the tool-name parity test is adopted as a cheap mechanical guard for the frozen v1.0.0 MCP surface.
+
+Shim-based variant 1 is rejected because the operator brief explicitly forbids crutch-style indirection that hides duplication instead of removing it. Variant 3 is rejected as scope creep inside a zero-behavior-change release.
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index cbf1dfb7..97ee6791 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": "1.1.0",
+ "version": "1.2.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index eab8255c..c47dc577 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.1.0",
+ "version": "1.2.0",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
"keywords": [
diff --git a/plugin.yaml b/plugin.yaml
index c85fb696..eac2abdd 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.1.0"
+version: "1.2.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index 6308a7e7..ff04e261 100644
--- a/plugins/codex/.codex-plugin/plugin.json
+++ b/plugins/codex/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.1.0",
+ "version": "1.2.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index c85fb696..eac2abdd 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.1.0"
+version: "1.2.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/pyproject.toml b/pyproject.toml
index 7d1667ff..fa6fac47 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 = "1.1.0"
+version = "1.2.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/sync-version.py b/scripts/sync-version.py
deleted file mode 100755
index 8e86b184..00000000
--- a/scripts/sync-version.py
+++ /dev/null
@@ -1,153 +0,0 @@
-#!/usr/bin/env python3
-"""Propagate the version from ``pyproject.toml`` to runtime manifests.
-
-The single source of truth for the Open Second Brain version is the
-``[project] version`` field in ``pyproject.toml``. Python code resolves it
-dynamically (see ``src/open_second_brain/__init__.py``).
-
-Manifests consumed by external runtimes (Hermes, OpenClaw, Claude Code,
-Codex, npm) are read raw without templating, so they have to carry a copy
-of the version on disk. This script propagates the canonical value into
-every such file. It is idempotent: rerunning when nothing changed exits
-cleanly with no writes.
-
-Files NOT touched by design:
-
- - ``CHANGELOG.md`` — historical record, edited by hand on release.
- - ``install.md`` — install commands MUST NOT pin a specific version
- (``@vX.Y.Z``); they always pull the latest from the default branch.
- - ``docs/architecture.md`` — same rule as ``install.md`` for example
- commands inside the doc.
- - ``tests/`` — fixtures may reference specific historical versions.
-
-Usage::
-
- python3 scripts/sync-version.py # write changes
- python3 scripts/sync-version.py --check # exit 1 if any drift
-"""
-
-from __future__ import annotations
-
-import argparse
-import re
-import sys
-import tomllib
-from pathlib import Path
-
-ROOT = Path(__file__).resolve().parents[1]
-
-# ---------------------------------------------------------------------------
-# Targets
-# ---------------------------------------------------------------------------
-
-# Files where ``version: "X.Y.Z"`` appears once, on its own line (YAML).
-YAML_TARGETS: tuple[str, ...] = (
- "plugin.yaml",
- "plugins/hermes/plugin.yaml",
-)
-
-# Files where ``"version": "X.Y.Z"`` appears once at the top level (JSON).
-# We do NOT round-trip through ``json.loads``/``json.dumps`` because that
-# rewrites whitespace, key order, and trailing newlines. Regex replacement
-# preserves the file byte-for-byte except for the version string itself.
-JSON_TARGETS: tuple[str, ...] = (
- "package.json",
- ".claude-plugin/plugin.json",
- ".codex-plugin/plugin.json",
- "openclaw.plugin.json",
-)
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-_YAML_RE = re.compile(r'^(version:\s*)"[^"]*"', re.MULTILINE)
-_JSON_RE = re.compile(r'("version"\s*:\s*)"[^"]*"')
-
-
-def canonical_version() -> str:
- pyproject = ROOT / "pyproject.toml"
- with pyproject.open("rb") as fh:
- data = tomllib.load(fh)
- project = data.get("project") or {}
- version = project.get("version")
- if not isinstance(version, str) or not version:
- raise SystemExit(f"{pyproject} is missing [project].version")
- return version
-
-
-def _replace(text: str, regex: re.Pattern[str], version: str) -> str:
- return regex.sub(rf'\g<1>"{version}"', text, count=1)
-
-
-def update_file(path: Path, regex: re.Pattern[str], version: str, *, write: bool) -> tuple[bool, bool]:
- """Return ``(matched, would_change)``.
-
- ``matched`` — the regex found a version line in this file at all.
- ``would_change`` — the current value differs from ``version``.
- """
- text = path.read_text(encoding="utf-8")
- new = _replace(text, regex, version)
- if not regex.search(text):
- return False, False
- if new == text:
- return True, False
- if write:
- path.write_text(new, encoding="utf-8")
- return True, True
-
-
-# ---------------------------------------------------------------------------
-# Entry point
-# ---------------------------------------------------------------------------
-
-
-def main(argv: list[str] | None = None) -> int:
- parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
- parser.add_argument(
- "--check",
- action="store_true",
- help="Exit 1 if any manifest drifts from pyproject.toml; do not write.",
- )
- args = parser.parse_args(argv)
-
- version = canonical_version()
- print(f"canonical version: {version}")
-
- drifted: list[str] = []
- for rel in YAML_TARGETS:
- path = ROOT / rel
- matched, would_change = update_file(path, _YAML_RE, version, write=not args.check)
- if not matched:
- print(f" WARN no version line in {rel}", file=sys.stderr)
- continue
- if would_change:
- drifted.append(rel)
- print(f" {'DRIFT' if args.check else 'wrote'}: {rel}")
- else:
- print(f" ok: {rel}")
-
- for rel in JSON_TARGETS:
- path = ROOT / rel
- matched, would_change = update_file(path, _JSON_RE, version, write=not args.check)
- if not matched:
- print(f" WARN no version line in {rel}", file=sys.stderr)
- continue
- if would_change:
- drifted.append(rel)
- print(f" {'DRIFT' if args.check else 'wrote'}: {rel}")
- else:
- print(f" ok: {rel}")
-
- if args.check and drifted:
- print(
- f"\n{len(drifted)} file(s) out of sync with pyproject.toml; "
- "run scripts/sync-version.py to fix.",
- file=sys.stderr,
- )
- return 1
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/src/cli/brain/helpers.ts b/src/cli/brain/helpers.ts
index 4f5e186e..ad1032ef 100644
--- a/src/cli/brain/helpers.ts
+++ b/src/cli/brain/helpers.ts
@@ -23,7 +23,12 @@
* file because they are tiny and called by every verb.
*/
-import { resolveTimezone, resolveVault } from "../../core/config.ts";
+import {
+ defaultConfigPath,
+ resolveAgentName,
+ resolveTimezone,
+ resolveVault,
+} from "../../core/config.ts";
import { formatLocalTimestamp } from "../../core/brain/present-time.ts";
import { isoSecond } from "../../core/brain/time.ts";
@@ -46,6 +51,35 @@ export function resolveBrainVault(flagVal: string | undefined, configPath: strin
return vault;
}
+// ── Verb context ────────────────────────────────────────────────────────────
+
+/** Parsed flags shape every Brain verb receives from {@link parse}. */
+export type BrainVerbFlags = Record<string, string | boolean | string[] | undefined>;
+
+export interface BrainVerbContext {
+ readonly config: string;
+ readonly vault: string;
+}
+
+/**
+ * Resolve the (config, vault) pair every Brain verb needs.
+ *
+ * Call it exactly where the verb used to resolve the vault — flag
+ * validation that must precede vault resolution (and its error
+ * output) stays ahead of this call, so verb output is unchanged.
+ * Throws `CliError` for a missing or explicitly empty vault, same as
+ * {@link resolveBrainVault}.
+ */
+export function brainVerbContext(flags: BrainVerbFlags): BrainVerbContext {
+ const config = defaultConfigPath();
+ return { config, vault: resolveBrainVault(flags["vault"] as string | undefined, config) };
+}
+
+/** Acting agent name: an explicit `--agent` flag wins over the config. */
+export function resolveBrainAgent(flags: BrainVerbFlags, config: string): string {
+ return (flags["agent"] as string | undefined) ?? resolveAgentName(config);
+}
+
// ── Flag-parsing wrapper ────────────────────────────────────────────────────
export function parse(
diff --git a/src/cli/brain/verbs/actions.ts b/src/cli/brain/verbs/actions.ts
index 91ec1cd0..489b9857 100644
--- a/src/cli/brain/verbs/actions.ts
+++ b/src/cli/brain/verbs/actions.ts
@@ -6,12 +6,11 @@
* by impact descending.
*/
-import { defaultConfigPath } from "../../../core/config.ts";
import { findDuplicateCandidates } from "../../../core/brain/page-dedup.ts";
import { lintConsolidate } from "../../../core/brain/lint-consolidate.ts";
import { computeTokenFootprint } from "../../../core/brain/token-footprint.ts";
import { scoreActions, type ActionInputs } from "../../../core/brain/maintenance/action-scorer.ts";
-import { parse, fail, okJson, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, okJson, parse } from "../helpers.ts";
export async function cmdBrainActions(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
@@ -19,8 +18,7 @@ export async function cmdBrainActions(argv: string[]): Promise<number> {
json: { type: "boolean" },
"top-n": { type: "string" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
const topNRaw = flags["top-n"] as string | undefined;
let topN = 10;
if (topNRaw !== undefined) {
diff --git a/src/cli/brain/verbs/activation.ts b/src/cli/brain/verbs/activation.ts
index f1a43335..f6427aee 100644
--- a/src/cli/brain/verbs/activation.ts
+++ b/src/cli/brain/verbs/activation.ts
@@ -15,8 +15,7 @@ import {
loadAccessEvents,
sweepActivationEvents,
} from "../../../core/search/activation/store.ts";
-import { defaultConfigPath } from "../../../core/config.ts";
-import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";
const USAGE =
"usage: o2b brain activation <status|sweep> " +
@@ -47,7 +46,7 @@ export async function cmdBrainActivation(argv: string[]): Promise<number> {
return 2;
}
const asJson = flags["json"] === true;
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
try {
if (op === "status") {
diff --git a/src/cli/brain/verbs/agent-diff.ts b/src/cli/brain/verbs/agent-diff.ts
index 23affbfe..9dc16109 100644
--- a/src/cli/brain/verbs/agent-diff.ts
+++ b/src/cli/brain/verbs/agent-diff.ts
@@ -1,11 +1,10 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import {
diffAgentSources,
type AgentSourceDiffMode,
type AgentSourceDiffResult,
} from "../../../core/brain/agent-source/diff.ts";
import type { AgentSourceContributionKind } from "../../../core/brain/agent-source/types.ts";
-import { parse, fail, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, parse } from "../helpers.ts";
export async function cmdBrainAgentDiff(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
@@ -18,8 +17,7 @@ export async function cmdBrainAgentDiff(argv: string[]): Promise<number> {
limit: { type: "string" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
const { value: mode, error: modeError } = parseMode(flags["mode"] as string | undefined);
if (modeError) return fail(modeError);
const { value: kind, error: kindError } = parseKind(flags["kind"] as string | undefined);
diff --git a/src/cli/brain/verbs/agent-query.ts b/src/cli/brain/verbs/agent-query.ts
index 2d7fc7a8..4ef1ef72 100644
--- a/src/cli/brain/verbs/agent-query.ts
+++ b/src/cli/brain/verbs/agent-query.ts
@@ -1,10 +1,9 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import {
queryAgentSources,
type AgentSourceQueryResult,
} from "../../../core/brain/agent-source/query.ts";
import type { AgentSourceContributionKind } from "../../../core/brain/agent-source/types.ts";
-import { parse, fail, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, parse } from "../helpers.ts";
export async function cmdBrainAgentQuery(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
@@ -16,8 +15,7 @@ export async function cmdBrainAgentQuery(argv: string[]): Promise<number> {
limit: { type: "string" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
const { value: kind, error: kindError } = parseKind(flags["kind"] as string | undefined);
if (kindError) return fail(kindError);
const { value: limit, error: limitError } = parseLimit(flags["limit"] as string | undefined);
diff --git a/src/cli/brain/verbs/apply-evidence.ts b/src/cli/brain/verbs/apply-evidence.ts
index 10bcac66..644ec229 100644
--- a/src/cli/brain/verbs/apply-evidence.ts
+++ b/src/cli/brain/verbs/apply-evidence.ts
@@ -1,9 +1,9 @@
-import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import { resolveAgentName } from "../../../core/config.ts";
import {
appendApplyEvidence,
BrainPreferenceNotFoundError,
} from "../../../core/brain/apply-evidence.ts";
-import { parse, fail, normalizeFlagString, ok, okJson, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, normalizeFlagString, ok, okJson, parse } from "../helpers.ts";
export async function cmdBrainApplyEvidence(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
@@ -21,8 +21,7 @@ export async function cmdBrainApplyEvidence(argv: string[]): Promise<number> {
return fail(`brain apply-evidence missing required flag: --${field}`);
}
}
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
const explicitAgent = normalizeFlagString(flags["agent"]);
if (flags["agent"] !== undefined && explicitAgent === null) {
return fail("--agent must be a non-empty string when provided");
diff --git a/src/cli/brain/verbs/architect.ts b/src/cli/brain/verbs/architect.ts
index a07b4253..eab8f92e 100644
--- a/src/cli/brain/verbs/architect.ts
+++ b/src/cli/brain/verbs/architect.ts
@@ -5,10 +5,9 @@
* operator edits survive every re-scan.
*/
-import { defaultConfigPath } from "../../../core/config.ts";
import { generateArchDocs } from "../../../core/brain/architect/generate.ts";
import { RegionError } from "../../../core/brain/regions.ts";
-import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";
export async function cmdBrainArchitect(argv: string[]): Promise<number> {
const { flags, positional } = parse(argv, {
@@ -20,7 +19,7 @@ export async function cmdBrainArchitect(argv: string[]): Promise<number> {
return fail("usage: o2b brain architect <project-path> [--vault V] [--json]");
}
try {
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const res = generateArchDocs(vault, target);
if (flags["json"] === true) {
okJson({
diff --git a/src/cli/brain/verbs/attention-flows.ts b/src/cli/brain/verbs/attention-flows.ts
index bf7f8d07..52ae3340 100644
--- a/src/cli/brain/verbs/attention-flows.ts
+++ b/src/cli/brain/verbs/attention-flows.ts
@@ -1,10 +1,9 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import {
evaluateAttentionFlow,
listAttentionFlows,
renderAttentionFlow,
} from "../../../core/brain/attention-flows.ts";
-import { CliError, parse, resolveBrainVault } from "../helpers.ts";
+import { CliError, brainVerbContext, parse } from "../helpers.ts";
export async function cmdBrainAttentionFlows(argv: string[]): Promise<number> {
const sub = argv[0];
@@ -20,7 +19,7 @@ function list(argv: string[]): number {
vault: { type: "string" },
json: { type: "boolean" },
});
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const flows = listAttentionFlows(vault);
if (flags["json"]) {
process.stdout.write(JSON.stringify({ total: flows.length, flows }, null, 2) + "\n");
@@ -40,7 +39,7 @@ function evaluate(argv: string[]): number {
});
const flowId = positional[0];
if (!flowId) throw new CliError("brain attention-flows evaluate: flow id is required");
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
let report;
try {
report = evaluateAttentionFlow(vault, flowId);
@@ -65,7 +64,7 @@ function render(argv: string[]): number {
});
const flowId = positional[0];
if (!flowId) throw new CliError("brain attention-flows render: flow id is required");
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
let text: string;
try {
text = renderAttentionFlow(vault, flowId);
diff --git a/src/cli/brain/verbs/attr.ts b/src/cli/brain/verbs/attr.ts
index 38fe3c49..1b608142 100644
--- a/src/cli/brain/verbs/attr.ts
+++ b/src/cli/brain/verbs/attr.ts
@@ -17,9 +17,8 @@ import {
} from "../../../core/brain/attributes.ts";
import { loadSchemaPack } from "../../../core/brain/schema-pack.ts";
import { resolveNotePath } from "../../../core/brain/note-path.ts";
-import { defaultConfigPath } from "../../../core/config.ts";
import { parseFrontmatter } from "../../../core/vault.ts";
-import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";
const USAGE =
"usage: o2b brain attr <path> <field>=<value> | " +
@@ -44,8 +43,7 @@ export async function cmdBrainAttr(argv: string[]): Promise<number> {
return 2;
}
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
try {
if (show) {
diff --git a/src/cli/brain/verbs/audit.ts b/src/cli/brain/verbs/audit.ts
index aaa4ea59..10875597 100644
--- a/src/cli/brain/verbs/audit.ts
+++ b/src/cli/brain/verbs/audit.ts
@@ -1,6 +1,5 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import { readPrefAudit, renderPrefAudit } from "../../../core/brain/pref-audit.ts";
-import { fail, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, parse } from "../helpers.ts";
/**
* `o2b brain audit <pref-id>` - render a preference's full mutation
@@ -21,8 +20,7 @@ export async function cmdBrainAudit(argv: string[]): Promise<number> {
}
const prefId = `pref-${slug}`;
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
let result;
try {
diff --git a/src/cli/brain/verbs/backlinks.ts b/src/cli/brain/verbs/backlinks.ts
index 895fa426..1d53754c 100644
--- a/src/cli/brain/verbs/backlinks.ts
+++ b/src/cli/brain/verbs/backlinks.ts
@@ -1,15 +1,13 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import { buildBacklinkIndex } from "../../../core/brain/backlinks.ts";
import { normaliseWikilinkTarget } from "../../../core/brain/wikilink.ts";
-import { parse, fail, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, parse } from "../helpers.ts";
export async function cmdBrainBacklinks(argv: string[]): Promise<number> {
const { positional, flags } = parse(argv, {
vault: { type: "string" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
const id = positional[0];
if (!id) return fail("brain backlinks requires a target id (e.g. pref-foo, ret-bar, sig-...)");
diff --git a/src/cli/brain/verbs/benchmark.ts b/src/cli/brain/verbs/benchmark.ts
index 166ba908..5403f86a 100644
--- a/src/cli/brain/verbs/benchmark.ts
+++ b/src/cli/brain/verbs/benchmark.ts
@@ -16,8 +16,7 @@ import { appendMetric } from "../../../core/brain/metrics.ts";
import { isoSecond } from "../../../core/brain/time.ts";
import { resolveSearchConfig } from "../../../core/search/index.ts";
import { SearchError } from "../../../core/search/types.ts";
-import { defaultConfigPath } from "../../../core/config.ts";
-import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";
const USAGE =
"usage: o2b brain benchmark run --dataset <path> [--k N] [--expand] [--vault <path>] [--json]";
@@ -42,8 +41,7 @@ export async function cmdBrainBenchmark(argv: string[]): Promise<number> {
return 2;
}
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
try {
let raw: unknown;
diff --git a/src/cli/brain/verbs/bridges.ts b/src/cli/brain/verbs/bridges.ts
index 83d5d0ef..b284a44a 100644
--- a/src/cli/brain/verbs/bridges.ts
+++ b/src/cli/brain/verbs/bridges.ts
@@ -35,9 +35,8 @@ import { isoSecond } from "../../../core/brain/time.ts";
import { resolveSearchConfig } from "../../../core/search/index.ts";
import { Store } from "../../../core/search/store.ts";
import { SearchError } from "../../../core/search/types.ts";
-import { defaultConfigPath } from "../../../core/config.ts";
import { parseFrontmatter } from "../../../core/vault.ts";
-import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";
const USAGE =
"usage: o2b brain bridges discover [--max N] [--min-similarity X] | list | " +
@@ -62,8 +61,7 @@ export async function cmdBrainBridges(argv: string[]): Promise<number> {
return 2;
}
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
try {
if (action === "accept") {
diff --git a/src/cli/brain/verbs/clusters.ts b/src/cli/brain/verbs/clusters.ts
index eaf0500f..2b8d3330 100644
--- a/src/cli/brain/verbs/clusters.ts
+++ b/src/cli/brain/verbs/clusters.ts
@@ -28,9 +28,8 @@ import { isoSecond } from "../../../core/brain/time.ts";
import { resolveSearchConfig } from "../../../core/search/index.ts";
import { Store } from "../../../core/search/store.ts";
import { SearchError } from "../../../core/search/types.ts";
-import { defaultConfigPath } from "../../../core/config.ts";
import { parseFrontmatter } from "../../../core/vault.ts";
-import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";
const USAGE = "usage: o2b brain clusters run [--min-size N] | list [--vault <path>] [--json]";
@@ -47,8 +46,7 @@ export async function cmdBrainClusters(argv: string[]): Promise<number> {
return 2;
}
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
try {
if (action === "list") {
diff --git a/src/cli/brain/verbs/context-pack.ts b/src/cli/brain/verbs/context-pack.ts
index ed054d64..27c62326 100644
--- a/src/cli/brain/verbs/context-pack.ts
+++ b/src/cli/brain/verbs/context-pack.ts
@@ -6,9 +6,8 @@
* filter on topic + principle.
*/
-import { defaultConfigPath } from "../../../core/config.ts";
import { packContext } from "../../../core/brain/context-pack.ts";
-import { parse, fail, okJson, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, okJson, parse } from "../helpers.ts";
export async function cmdBrainContextPack(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
@@ -26,8 +25,7 @@ export async function cmdBrainContextPack(argv: string[]): Promise<number> {
"cache-stable": { type: "boolean" },
"dedup-repeated": { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
const maxTokensRaw = flags["max-tokens"] as string | undefined;
if (!maxTokensRaw) {
diff --git a/src/cli/brain/verbs/context-receipts.ts b/src/cli/brain/verbs/context-receipts.ts
index 9ac29c70..fe3cb7b6 100644
--- a/src/cli/brain/verbs/context-receipts.ts
+++ b/src/cli/brain/verbs/context-receipts.ts
@@ -1,11 +1,10 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import {
getContextReceipt,
isContextReceiptTrigger,
listContextReceipts,
summarizeContextReceipt,
} from "../../../core/brain/context-receipts.ts";
-import { CliError, parse, resolveBrainVault } from "../helpers.ts";
+import { CliError, brainVerbContext, parse } from "../helpers.ts";
export async function cmdBrainContextReceipts(argv: string[]): Promise<number> {
const subcommand = argv[0];
@@ -24,7 +23,7 @@ function listReceipts(argv: string[]): number {
"session-id": { type: "string" },
limit: { type: "string" },
});
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const triggerRaw = trimOrUndefined(flags["trigger"]);
if (triggerRaw !== undefined && !isContextReceiptTrigger(triggerRaw)) {
throw new CliError(`brain context-receipts list: unknown trigger '${triggerRaw}'`);
@@ -65,7 +64,7 @@ function showReceipt(argv: string[]): number {
});
const id = trimOrUndefined(positional[0]);
if (id === undefined) throw new CliError("brain context-receipts show: receipt id is required");
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const receipt = getContextReceipt(vault, id);
if (receipt === null) throw new CliError(`brain context-receipts show: receipt not found: ${id}`);
diff --git a/src/cli/brain/verbs/continuity.ts b/src/cli/brain/verbs/continuity.ts
index 42cce519..0dddc564 100644
--- a/src/cli/brain/verbs/continuity.ts
+++ b/src/cli/brain/verbs/continuity.ts
@@ -13,7 +13,6 @@
import { mkdirSync, writeFileSync } from "node:fs";
import { join, resolve } from "node:path";
-import { defaultConfigPath } from "../../../core/config.ts";
import { loadNormalizedContinuityRecords } from "../../../core/brain/continuity/read-model.ts";
import { renderAtofEvents } from "../../../core/brain/continuity/export-atof.ts";
import {
@@ -21,7 +20,7 @@ import {
renderAtifTrajectories,
} from "../../../core/brain/continuity/export-atif.ts";
import packageJson from "../../../../package.json" with { type: "json" };
-import { fail, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, parse } from "../helpers.ts";
const CLI_VERSION: string = packageJson.version;
@@ -52,7 +51,7 @@ function exportContinuity(argv: string[]): number {
const session = typeof flags["session"] === "string" ? flags["session"].trim() : undefined;
const outDir = resolve(typeof flags["out"] === "string" ? flags["out"].trim() : ".");
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const records = loadNormalizedContinuityRecords(vault, {
...(session !== undefined && session !== "" ? { sessionId: session } : {}),
...(month !== undefined ? { since: `${month}-01`, until: `${month}-31T23:59:59.999Z` } : {}),
diff --git a/src/cli/brain/verbs/dead-end.ts b/src/cli/brain/verbs/dead-end.ts
index a0092d92..d147430f 100644
--- a/src/cli/brain/verbs/dead-end.ts
+++ b/src/cli/brain/verbs/dead-end.ts
@@ -9,8 +9,7 @@
*/
import { DEAD_END_MAX_ACTIVE, listDeadEnds, recordDeadEnd } from "../../../core/brain/dead-ends.ts";
-import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
-import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, ok, okJson, parse, resolveBrainAgent } from "../helpers.ts";
const USAGE =
"usage: o2b brain dead-end <record|list> " +
@@ -32,8 +31,7 @@ export async function cmdBrainDeadEnd(argv: string[]): Promise<number> {
return 2;
}
const asJson = flags["json"] === true;
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
try {
if (op === "record") {
@@ -53,7 +51,7 @@ export async function cmdBrainDeadEnd(argv: string[]): Promise<number> {
approach,
reason,
...(typeof flags["context"] === "string" ? { context: flags["context"] as string } : {}),
- agent: (flags["agent"] as string | undefined) ?? resolveAgentName(config),
+ agent: resolveBrainAgent(flags, config),
now: new Date(),
maxActive,
});
diff --git a/src/cli/brain/verbs/digest.ts b/src/cli/brain/verbs/digest.ts
index 7e8254a7..3c21d0bc 100644
--- a/src/cli/brain/verbs/digest.ts
+++ b/src/cli/brain/verbs/digest.ts
@@ -1,8 +1,8 @@
-import { defaultConfigPath, resolveLinkOutputFormat } from "../../../core/config.ts";
+import { resolveLinkOutputFormat } from "../../../core/config.ts";
import { captureReportDelta, renderReportDelta } from "../../../core/brain/report-snapshot.ts";
import { isoDate } from "../../../core/brain/time.ts";
import { renderDigest, type RenderDigestOptions } from "../../../core/brain/digest.ts";
-import { parse, fail, resolveBrainVault, parseOptionalIsoDate } from "../helpers.ts";
+import { brainVerbContext, fail, parse, parseOptionalIsoDate } from "../helpers.ts";
export function parseWindow(raw: string): number {
const m = /^(\d+)(?:d)?$/.exec(raw);
@@ -21,8 +21,7 @@ export async function cmdBrainDigest(argv: string[]): Promise<number> {
json: { type: "boolean" },
"silent-if-empty": { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
const { value: parsedSinceDate, error: sinceErr } = parseOptionalIsoDate(flags, "since");
if (sinceErr) return fail(sinceErr);
diff --git a/src/cli/brain/verbs/doctor.ts b/src/cli/brain/verbs/doctor.ts
index db5615fd..3303e1de 100644
--- a/src/cli/brain/verbs/doctor.ts
+++ b/src/cli/brain/verbs/doctor.ts
@@ -1,4 +1,3 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import { resolveSearchConfig } from "../../../core/search/index.ts";
import { runDoctor } from "../../../core/brain/doctor.ts";
import {
@@ -7,7 +6,7 @@ import {
planRemediation,
} from "../../../core/brain/health/remediation.ts";
import { loadBrainConfigDetailed, resolveHealth } from "../../../core/brain/policy.ts";
-import { parse, fail, ok, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, ok, parse } from "../helpers.ts";
export async function cmdBrainDoctor(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
@@ -17,8 +16,7 @@ export async function cmdBrainDoctor(argv: string[]): Promise<number> {
remediate: { type: "boolean" },
"dry-run": { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
let result;
try {
diff --git a/src/cli/brain/verbs/dream.ts b/src/cli/brain/verbs/dream.ts
index 33d00447..1b29a9a2 100644
--- a/src/cli/brain/verbs/dream.ts
+++ b/src/cli/brain/verbs/dream.ts
@@ -11,7 +11,7 @@
* failed validation - scripts gate on it), 2 on usage errors.
*/
-import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import { resolveAgentName } from "../../../core/config.ts";
import { dream } from "../../../core/brain/dream.ts";
import {
applyDreamBundle,
@@ -25,7 +25,7 @@ import {
resolveSafeguardTimeoutMs,
SafeguardTimeoutError,
} from "../../../core/brain/safeguard.ts";
-import { parse, fail, ok, okJson, resolveBrainVault, parseOptionalIsoDate } from "../helpers.ts";
+import { brainVerbContext, fail, ok, okJson, parse, parseOptionalIsoDate } from "../helpers.ts";
const USAGE =
"usage: o2b brain dream [run] [--dry-run] | stage | validate <run-id> | " +
@@ -52,8 +52,7 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {
process.stderr.write(`${USAGE}\n`);
return 2;
}
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
const agentFlag = flags["agent"];
let agent: string;
diff --git a/src/cli/brain/verbs/entity.ts b/src/cli/brain/verbs/entity.ts
index a25d4454..227c66f4 100644
--- a/src/cli/brain/verbs/entity.ts
+++ b/src/cli/brain/verbs/entity.ts
@@ -4,7 +4,7 @@
* the MCP surface exposes the read-only subset (`brain_entity`).
*/
-import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import { resolveAgentName } from "../../../core/config.ts";
import {
archiveEntity,
getEntity,
@@ -13,7 +13,7 @@ import {
upsertEntity,
} from "../../../core/brain/entities/registry.ts";
import { BRAIN_ENTITY_STATUS, type BrainEntity } from "../../../core/brain/entities/types.ts";
-import { parse, fail, ok, okJson, normalizeFlagString, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, normalizeFlagString, ok, okJson, parse } from "../helpers.ts";
function entityPayload(entity: BrainEntity): Record<string, unknown> {
return {
@@ -70,8 +70,7 @@ function entitySet(argv: string[]): number {
if (positional.length < 2) {
return fail("brain entity set requires <category> and <name> arguments");
}
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
const agent = resolveAgentName(config);
const body = normalizeFlagString(flags["body"]);
const confidence = normalizeFlagString(flags["confidence"]);
@@ -103,7 +102,7 @@ function entityGet(argv: string[]): number {
json: { type: "boolean" },
});
if (positional.length < 1) return fail("brain entity get requires a <name-or-alias> argument");
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const category = normalizeFlagString(flags["category"]);
try {
const entity = getEntity(vault, {
@@ -133,7 +132,7 @@ function entityList(argv: string[]): number {
status: { type: "string" },
json: { type: "boolean" },
});
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const category = normalizeFlagString(flags["category"]);
const statusRaw = normalizeFlagString(flags["status"]);
if (
@@ -171,7 +170,7 @@ function entityRelate(argv: string[]): number {
if (positional.length < 3) {
return fail("brain entity relate requires <from> <relation> <to> arguments");
}
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const fromCategory = normalizeFlagString(flags["from-category"]);
const toCategory = normalizeFlagString(flags["to-category"]);
try {
@@ -202,7 +201,7 @@ function entityArchive(argv: string[]): number {
if (positional.length < 1) {
return fail("brain entity archive requires a <name-or-alias> argument");
}
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const category = normalizeFlagString(flags["category"]);
try {
const entity = archiveEntity(
diff --git a/src/cli/brain/verbs/explorer.ts b/src/cli/brain/verbs/explorer.ts
index 579b3ba0..8fc8fff0 100644
--- a/src/cli/brain/verbs/explorer.ts
+++ b/src/cli/brain/verbs/explorer.ts
@@ -1,5 +1,4 @@
import { existsSync } from "node:fs";
-import { defaultConfigPath } from "../../../core/config.ts";
import { atomicWriteFileSync } from "../../../core/fs-atomic.ts";
import {
buildLiveServer,
@@ -7,7 +6,7 @@ import {
renderExportedHtml,
type LiveServerHandle,
} from "../../../core/brain/explorer.ts";
-import { parse, fail, ok, info, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, info, ok, parse } from "../helpers.ts";
export async function cmdBrainExplorer(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
@@ -16,8 +15,7 @@ export async function cmdBrainExplorer(argv: string[]): Promise<number> {
export: { type: "string" },
force: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
const exportPath = flags["export"] as string | undefined;
const force = flags["force"] === true;
diff --git a/src/cli/brain/verbs/export.ts b/src/cli/brain/verbs/export.ts
index b7f26aa9..bb23561f 100644
--- a/src/cli/brain/verbs/export.ts
+++ b/src/cli/brain/verbs/export.ts
@@ -1,8 +1,7 @@
import { existsSync } from "node:fs";
-import { defaultConfigPath } from "../../../core/config.ts";
import { atomicWriteFileSync } from "../../../core/fs-atomic.ts";
import { exportPreferencesJson, exportPreferencesLlmsTxt } from "../../../core/brain/export.ts";
-import { parse, fail, ok, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, ok, parse } from "../helpers.ts";
export async function cmdBrainExport(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
@@ -11,8 +10,7 @@ export async function cmdBrainExport(argv: string[]): Promise<number> {
out: { type: "string" },
force: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
const format = flags["format"] as string | undefined;
if (format !== "json" && format !== "llms-txt") {
process.stderr.write("error: --format is required and must be one of json|llms-txt\n");
diff --git a/src/cli/brain/verbs/facts.ts b/src/cli/brain/verbs/facts.ts
index b1e1c804..770434bf 100644
--- a/src/cli/brain/verbs/facts.ts
+++ b/src/cli/brain/verbs/facts.ts
@@ -16,8 +16,7 @@ import { buildEntityIndex } from "../../../core/brain/entities/index-builder.ts"
import { isoSecond } from "../../../core/brain/time.ts";
import { claimsFromAssertion } from "../../../core/brain/truth/ingest.ts";
import { appendClaimEvent } from "../../../core/brain/truth/store.ts";
-import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
-import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, ok, okJson, parse, resolveBrainAgent } from "../helpers.ts";
const USAGE =
"usage: o2b brain facts decompose (--file <path> | --text <text>) " +
@@ -50,8 +49,7 @@ export async function cmdBrainFacts(argv: string[]): Promise<number> {
process.stderr.write(`brain facts decompose: --ingest requires --entity\n${USAGE}\n`);
return 2;
}
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
try {
let text: string;
@@ -74,7 +72,7 @@ export async function cmdBrainFacts(argv: string[]): Promise<number> {
let ingested = 0;
if (ingest) {
- const agent = (flags["agent"] as string | undefined) ?? resolveAgentName(config);
+ const agent = resolveBrainAgent(flags, config);
const ts = isoSecond(new Date());
for (const assertion of assertions) {
const claims = claimsFromAssertion(assertion, {
diff --git a/src/cli/brain/verbs/feedback.ts b/src/cli/brain/verbs/feedback.ts
index 194c2af7..49bc1faf 100644
--- a/src/cli/brain/verbs/feedback.ts
+++ b/src/cli/brain/verbs/feedback.ts
@@ -1,5 +1,4 @@
import { readFileSync } from "node:fs";
-import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
import { mirrorSignal, resolveSharedNamespace } from "../../../core/brain/shared-namespace.ts";
import { writeSignal } from "../../../core/brain/signal.ts";
import { appendLogEvent } from "../../../core/brain/log.ts";
@@ -11,7 +10,7 @@ import {
BRAIN_SIGNAL_SIGN,
} from "../../../core/brain/types.ts";
import { renderPrefLink } from "../../../core/brain/wikilink.ts";
-import { parse, fail, ok, okJson, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, ok, okJson, parse, resolveBrainAgent } from "../helpers.ts";
export async function cmdBrainFeedback(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
@@ -41,9 +40,8 @@ export async function cmdBrainFeedback(argv: string[]): Promise<number> {
return fail(`--signal must be 'positive' or 'negative'; got ${JSON.stringify(signalSign)}`);
}
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
- const agent = (flags["agent"] as string | undefined) ?? resolveAgentName(config);
+ const { config, vault } = brainVerbContext(flags);
+ const agent = resolveBrainAgent(flags, config);
let raw: string | undefined;
const rawFile = flags["raw-file"] as string | undefined;
diff --git a/src/cli/brain/verbs/foresight.ts b/src/cli/brain/verbs/foresight.ts
index 3da0041d..30e1100a 100644
--- a/src/cli/brain/verbs/foresight.ts
+++ b/src/cli/brain/verbs/foresight.ts
@@ -18,9 +18,8 @@ import {
type ForesightEnvelope,
} from "../../../core/brain/temporal/foresight.ts";
import { isoDate } from "../../../core/brain/time.ts";
-import { defaultConfigPath } from "../../../core/config.ts";
import { writeFrontmatterAtomic } from "../../../core/vault.ts";
-import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";
const USAGE = "usage: o2b brain foresight [--horizon-days N] [--write] [--vault <path>] [--json]";
@@ -46,7 +45,7 @@ export async function cmdBrainForesight(argv: string[]): Promise<number> {
json: { type: "boolean" },
});
const asJson = flags["json"] === true;
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const horizonRaw = flags["horizon-days"] as string | undefined;
const horizonDays = horizonRaw !== undefined ? Number(horizonRaw) : FORESIGHT_HORIZON_DAYS;
if (!Number.isInteger(horizonDays) || horizonDays < 1) {
diff --git a/src/cli/brain/verbs/git.ts b/src/cli/brain/verbs/git.ts
index 06edd205..ed35fe70 100644
--- a/src/cli/brain/verbs/git.ts
+++ b/src/cli/brain/verbs/git.ts
@@ -7,12 +7,11 @@
* answers work even when the repo is gone.
*/
-import { defaultConfigPath } from "../../../core/config.ts";
import { mineCommitDecisions } from "../../../core/brain/git/decisions.ts";
import { GitIngestError, ingestGitHistory } from "../../../core/brain/git/ingest.ts";
import { listGitCommits, listGitRepos, listGitTags } from "../../../core/brain/git/store.ts";
import type { GitCommitFilter, GitCommitRecord } from "../../../core/brain/git/store.ts";
-import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";
const USAGE = "usage: o2b brain git <ingest|status|find|mine> [args] [--vault V] [--json]";
@@ -34,7 +33,7 @@ async function cmdMine(argv: string[]): Promise<number> {
repo: { type: "string" },
});
try {
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const repoFilter = flags["repo"] as string | undefined;
const repos = listGitRepos(vault).filter(
(entry) => repoFilter === undefined || entry.key === repoFilter,
@@ -89,7 +88,7 @@ async function cmdIngest(argv: string[]): Promise<number> {
}
}
try {
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const res = ingestGitHistory(vault, target, maxCount !== undefined ? { maxCount } : {});
if (flags["json"] === true) {
okJson({
@@ -125,7 +124,7 @@ async function cmdStatus(argv: string[]): Promise<number> {
json: { type: "boolean" },
});
try {
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const repos = listGitRepos(vault).map((entry) => ({
key: entry.key,
repo_path: entry.state?.repoPath ?? null,
@@ -183,7 +182,7 @@ async function cmdFind(argv: string[]): Promise<number> {
if (!Number.isInteger(limit) || limit < 1) return fail("--limit must be a positive integer");
}
try {
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const filter: GitCommitFilter = {
...(text !== undefined ? { text } : {}),
...(flags["file"] !== undefined ? { file: flags["file"] as string } : {}),
diff --git a/src/cli/brain/verbs/graph-export.ts b/src/cli/brain/verbs/graph-export.ts
index 2b964c65..1bbe5fc6 100644
--- a/src/cli/brain/verbs/graph-export.ts
+++ b/src/cli/brain/verbs/graph-export.ts
@@ -1,7 +1,6 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import { atomicWriteFileSync } from "../../../core/fs-atomic.ts";
import { exportVaultGraph } from "../../../core/brain/portability/graph.ts";
-import { fail, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, parse } from "../helpers.ts";
/**
* `o2b brain graph-export [--out <file>]` - serialise the user's vault
@@ -10,8 +9,7 @@ import { fail, parse, resolveBrainVault } from "../helpers.ts";
*/
export async function cmdBrainGraphExport(argv: string[]): Promise<number> {
const { flags } = parse(argv, { vault: { type: "string" }, out: { type: "string" } });
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
let json: string;
try {
diff --git a/src/cli/brain/verbs/graph-import.ts b/src/cli/brain/verbs/graph-import.ts
index 0c6fbf2b..bc7205d2 100644
--- a/src/cli/brain/verbs/graph-import.ts
+++ b/src/cli/brain/verbs/graph-import.ts
@@ -1,8 +1,7 @@
import { readFileSync } from "node:fs";
-import { defaultConfigPath } from "../../../core/config.ts";
import { importVaultGraph, type GraphImportMode } from "../../../core/brain/portability/graph.ts";
-import { fail, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, parse } from "../helpers.ts";
const MODES: ReadonlyArray<GraphImportMode> = ["skip", "overwrite", "merge"];
@@ -25,8 +24,7 @@ export async function cmdBrainGraphImport(argv: string[]): Promise<number> {
return fail(`graph-import: --mode must be one of ${MODES.join(" | ")}; got ${mode}`);
}
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
let graph: { nodes?: unknown };
try {
diff --git a/src/cli/brain/verbs/handoff.ts b/src/cli/brain/verbs/handoff.ts
index cc39d4e1..8426dc7b 100644
--- a/src/cli/brain/verbs/handoff.ts
+++ b/src/cli/brain/verbs/handoff.ts
@@ -6,7 +6,7 @@
import { existsSync, readFileSync } from "node:fs";
import { basename } from "node:path";
-import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import { resolveAgentName } from "../../../core/config.ts";
import { writeHandoffNote } from "../../../core/brain/handoff.ts";
import {
detectAdapter,
@@ -14,7 +14,7 @@ import {
isSessionAdapterId,
} from "../../../core/brain/sessions/registry.ts";
import type { SessionTurn } from "../../../core/brain/sessions/types.ts";
-import { fail, normalizeFlagString, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, normalizeFlagString, ok, okJson, parse } from "../helpers.ts";
export async function cmdBrainHandoff(argv: string[]): Promise<number> {
const { flags, positional } = parse(argv, {
@@ -28,8 +28,7 @@ export async function cmdBrainHandoff(argv: string[]): Promise<number> {
const sessionPath = positional[0]!;
if (!existsSync(sessionPath)) return fail(`session file does not exist: ${sessionPath}`);
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
const agent = normalizeFlagString(flags["agent"]) ?? resolveAgentName(config);
const sessionId = normalizeFlagString(flags["session-id"]) ?? basename(sessionPath);
diff --git a/src/cli/brain/verbs/health.ts b/src/cli/brain/verbs/health.ts
index 08cf432a..6a2890b2 100644
--- a/src/cli/brain/verbs/health.ts
+++ b/src/cli/brain/verbs/health.ts
@@ -1,6 +1,5 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import { runDoctor } from "../../../core/brain/doctor.ts";
-import { fail, ok, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, ok, parse } from "../helpers.ts";
/**
* `o2b brain health` - print the semantic-health report (contradictory
@@ -12,8 +11,7 @@ export async function cmdBrainHealth(argv: string[]): Promise<number> {
vault: { type: "string" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
let result;
try {
diff --git a/src/cli/brain/verbs/history.ts b/src/cli/brain/verbs/history.ts
index b4594c82..8955120d 100644
--- a/src/cli/brain/verbs/history.ts
+++ b/src/cli/brain/verbs/history.ts
@@ -1,6 +1,5 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import { readEditHistory, renderEditHistory } from "../../../core/brain/health/edit-history.ts";
-import { fail, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, parse } from "../helpers.ts";
/**
* `o2b brain history <slug>` - render a preference's edit-history
@@ -16,8 +15,7 @@ export async function cmdBrainHistory(argv: string[]): Promise<number> {
if (!raw) return fail("usage: o2b brain history <slug>");
const slug = raw.replace(/^pref-/, "");
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
let entries;
try {
diff --git a/src/cli/brain/verbs/import-session.ts b/src/cli/brain/verbs/import-session.ts
index fa760e5d..49634c92 100644
--- a/src/cli/brain/verbs/import-session.ts
+++ b/src/cli/brain/verbs/import-session.ts
@@ -1,9 +1,5 @@
import { statSync } from "node:fs";
-import {
- defaultConfigPath,
- resolveAgentName,
- resolveSessionCaptureRoles,
-} from "../../../core/config.ts";
+import { resolveAgentName, resolveSessionCaptureRoles } from "../../../core/config.ts";
import { importSession, importSessionPath } from "../../../core/brain/sessions/import.ts";
import { SessionImportError, type SessionAdapterId } from "../../../core/brain/sessions/types.ts";
import {
@@ -14,15 +10,15 @@ import { appendLogEvent } from "../../../core/brain/log.ts";
import { BRAIN_LOG_EVENT_KIND } from "../../../core/brain/types.ts";
import { isoSecond } from "../../../core/brain/time.ts";
import {
- parse,
+ CliError,
+ brainVerbContext,
fail,
info,
normalizeFlagString,
ok,
okJson,
- resolveBrainVault,
+ parse,
parseOptionalIsoDate,
- CliError,
} from "../helpers.ts";
export async function cmdBrainImportSession(argv: string[]): Promise<number> {
@@ -42,8 +38,7 @@ export async function cmdBrainImportSession(argv: string[]): Promise<number> {
});
if (positional.length < 1) return fail("brain import-session requires a <path> argument");
const sessionPath = positional[0]!;
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
const explicitAgent = normalizeFlagString(flags["agent"]);
if (flags["agent"] !== undefined && explicitAgent === null) {
return fail("--agent must be a non-empty string when provided");
diff --git a/src/cli/brain/verbs/intent-review.ts b/src/cli/brain/verbs/intent-review.ts
index fe08bb28..25eeb749 100644
--- a/src/cli/brain/verbs/intent-review.ts
+++ b/src/cli/brain/verbs/intent-review.ts
@@ -1,6 +1,5 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import { buildIntentReview } from "../../../core/brain/intent-review.ts";
-import { CliError, parse, resolveBrainVault } from "../helpers.ts";
+import { CliError, brainVerbContext, parse } from "../helpers.ts";
/**
* `o2b brain intent-review [--vault PATH] [--now ISO] [--json]`
@@ -13,8 +12,7 @@ export async function cmdBrainIntentReview(argv: string[]): Promise<number> {
now: { type: "string" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
const now = parseNow(flags["now"]);
const report = buildIntentReview(vault, now ? { now } : {});
diff --git a/src/cli/brain/verbs/intention.ts b/src/cli/brain/verbs/intention.ts
index 07d19579..3d789d80 100644
--- a/src/cli/brain/verbs/intention.ts
+++ b/src/cli/brain/verbs/intention.ts
@@ -4,14 +4,14 @@
* lifecycle.
*/
-import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import { resolveAgentName } from "../../../core/config.ts";
import {
listIntentions,
moveIntentionToHistory,
setIntention,
showIntention,
} from "../../../core/brain/intentions.ts";
-import { fail, normalizeFlagString, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, normalizeFlagString, ok, okJson, parse } from "../helpers.ts";
export async function cmdBrainIntention(argv: string[]): Promise<number> {
const action = argv[0];
@@ -24,8 +24,7 @@ export async function cmdBrainIntention(argv: string[]): Promise<number> {
text: { type: "string" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
const scope = normalizeFlagString(flags["scope"]);
const json = flags["json"] === true;
diff --git a/src/cli/brain/verbs/label.ts b/src/cli/brain/verbs/label.ts
index 133211a0..93d9ba19 100644
--- a/src/cli/brain/verbs/label.ts
+++ b/src/cli/brain/verbs/label.ts
@@ -18,9 +18,9 @@ import {
} from "../../../core/brain/labels.ts";
import { loadSchemaPack } from "../../../core/brain/schema-pack.ts";
import { resolveNotePath } from "../../../core/brain/note-path.ts";
-import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import { resolveAgentName } from "../../../core/config.ts";
import { parseFrontmatter } from "../../../core/vault.ts";
-import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";
const USAGE =
"usage: o2b brain label <path> <dimension>=<value> | " +
@@ -46,8 +46,7 @@ export async function cmdBrainLabel(argv: string[]): Promise<number> {
return 2;
}
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
try {
if (show) {
diff --git a/src/cli/brain/verbs/lint.ts b/src/cli/brain/verbs/lint.ts
index 3dc149eb..5a36b528 100644
--- a/src/cli/brain/verbs/lint.ts
+++ b/src/cli/brain/verbs/lint.ts
@@ -4,9 +4,8 @@
* fix per finding.
*/
-import { defaultConfigPath } from "../../../core/config.ts";
import { lintConsolidate } from "../../../core/brain/lint-consolidate.ts";
-import { parse, fail, okJson, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, okJson, parse } from "../helpers.ts";
export async function cmdBrainLint(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
@@ -16,8 +15,7 @@ export async function cmdBrainLint(argv: string[]): Promise<number> {
yes: { type: "boolean" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
if (!flags["consolidate"]) {
return fail("brain lint requires --consolidate (no other modes yet)");
diff --git a/src/cli/brain/verbs/maintenance.ts b/src/cli/brain/verbs/maintenance.ts
index 25e2be38..88456615 100644
--- a/src/cli/brain/verbs/maintenance.ts
+++ b/src/cli/brain/verbs/maintenance.ts
@@ -36,9 +36,9 @@ import {
type DailyWindow,
} from "../../../core/brain/maintenance/lane.ts";
import { listJournal } from "../../../core/brain/maintenance/journal.ts";
-import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import { resolveAgentName } from "../../../core/config.ts";
import { indexVault, resolveSearchConfig } from "../../../core/search/index.ts";
-import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";
const USAGE =
"usage: o2b brain maintenance run [--force] [--window H-H] [--tz ZONE] " +
@@ -63,8 +63,7 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {
return 2;
}
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
const now = new Date();
try {
diff --git a/src/cli/brain/verbs/mcp-landscape.ts b/src/cli/brain/verbs/mcp-landscape.ts
index 32405955..a3bca73b 100644
--- a/src/cli/brain/verbs/mcp-landscape.ts
+++ b/src/cli/brain/verbs/mcp-landscape.ts
@@ -1,14 +1,12 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import { buildMcpLandscape } from "../../../core/graph/mcp-config.ts";
-import { parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, parse } from "../helpers.ts";
export async function cmdBrainMcpLandscape(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
vault: { type: "string" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
const landscape = buildMcpLandscape(vault);
diff --git a/src/cli/brain/verbs/merge.ts b/src/cli/brain/verbs/merge.ts
index 4c3d3634..12308158 100644
--- a/src/cli/brain/verbs/merge.ts
+++ b/src/cli/brain/verbs/merge.ts
@@ -1,6 +1,13 @@
-import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
import { mergePreferences, BrainMergeError } from "../../../core/brain/merge.ts";
-import { parse, fail, ok, okJson, resolveBrainVault, readSingleLine } from "../helpers.ts";
+import {
+ brainVerbContext,
+ fail,
+ ok,
+ okJson,
+ parse,
+ readSingleLine,
+ resolveBrainAgent,
+} from "../helpers.ts";
export async function cmdBrainMerge(argv: string[]): Promise<number> {
const { flags, positional } = parse(argv, {
@@ -13,9 +20,8 @@ export async function cmdBrainMerge(argv: string[]): Promise<number> {
if (positional.length !== 2)
return fail("brain merge requires exactly two positional ids: <keep-pref-id> <drop-pref-id>");
const [keepId, dropId] = positional as [string, string];
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
- const agent = (flags["agent"] as string | undefined) ?? resolveAgentName(config);
+ const { config, vault } = brainVerbContext(flags);
+ const agent = resolveBrainAgent(flags, config);
const dryRun = flags["dry-run"] === true;
const force = flags["force"] === true;
const wantJson = flags["json"] === true;
diff --git a/src/cli/brain/verbs/moc-audit.ts b/src/cli/brain/verbs/moc-audit.ts
index d02b10c4..93b0e549 100644
--- a/src/cli/brain/verbs/moc-audit.ts
+++ b/src/cli/brain/verbs/moc-audit.ts
@@ -1,7 +1,6 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import { auditMoc, MocAuditError } from "../../../core/brain/link-graph/moc-audit.ts";
import { normaliseWikilinkTarget } from "../../../core/brain/wikilink.ts";
-import { parse, fail, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, parse } from "../helpers.ts";
/**
* `o2b brain moc-audit <hub-id> [--vault PATH] [--json]`
@@ -15,8 +14,7 @@ export async function cmdBrainMocAudit(argv: string[]): Promise<number> {
vault: { type: "string" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
const id = positional[0];
if (!id) return fail("brain moc-audit requires a hub note id");
diff --git a/src/cli/brain/verbs/monthly.ts b/src/cli/brain/verbs/monthly.ts
index 20e16f11..129a5be8 100644
--- a/src/cli/brain/verbs/monthly.ts
+++ b/src/cli/brain/verbs/monthly.ts
@@ -1,9 +1,8 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import {
buildMonthlyReview,
normalizeMonthlyReviewMonth,
} from "../../../core/brain/monthly-review.ts";
-import { CliError, parse, resolveBrainVault, localTimeFields } from "../helpers.ts";
+import { CliError, brainVerbContext, localTimeFields, parse } from "../helpers.ts";
const MONTH_RE = /^\d{4}-\d{2}$/;
@@ -18,8 +17,7 @@ export async function cmdBrainMonthly(argv: string[]): Promise<number> {
month: { type: "string" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
const month = parseMonth(flags["month"]);
const report = buildMonthlyReview(vault, month ? { month } : {});
diff --git a/src/cli/brain/verbs/morning-brief.ts b/src/cli/brain/verbs/morning-brief.ts
index 857422dc..59534d70 100644
--- a/src/cli/brain/verbs/morning-brief.ts
+++ b/src/cli/brain/verbs/morning-brief.ts
@@ -1,11 +1,11 @@
-import { defaultConfigPath, resolveTriggerCooldownDays } from "../../../core/config.ts";
+import { resolveTriggerCooldownDays } from "../../../core/config.ts";
import { buildMorningBrief } from "../../../core/brain/morning-brief.ts";
import {
deliverBriefTriggers,
renderTriggerBriefSection,
} from "../../../core/brain/triggers/brief.ts";
import { parseOptionalNumberFlag } from "../../coerce.ts";
-import { fail, parse, resolveBrainVault, localTimeFields } from "../helpers.ts";
+import { brainVerbContext, fail, localTimeFields, parse } from "../helpers.ts";
/**
* `o2b brain morning-brief` - render a read-only session-start summary:
@@ -22,8 +22,7 @@ export async function cmdBrainMorningBrief(argv: string[]): Promise<number> {
"max-total-chars": { type: "string" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
// Positive-integer validation mirroring the MCP tool's
// optionalPositiveInt, so the CLI and MCP surfaces share semantics.
diff --git a/src/cli/brain/verbs/page-dedup.ts b/src/cli/brain/verbs/page-dedup.ts
index 5817de5f..0597c86e 100644
--- a/src/cli/brain/verbs/page-dedup.ts
+++ b/src/cli/brain/verbs/page-dedup.ts
@@ -8,9 +8,8 @@
* vault to point at the canonical page.
*/
-import { defaultConfigPath } from "../../../core/config.ts";
import { findDuplicateCandidates, mergePage } from "../../../core/brain/page-dedup.ts";
-import { parse, fail, okJson, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, okJson, parse } from "../helpers.ts";
export async function cmdBrainPageDedup(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
@@ -19,8 +18,7 @@ export async function cmdBrainPageDedup(argv: string[]): Promise<number> {
json: { type: "boolean" },
yes: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
const apply = Boolean(flags["apply"]);
if (apply && !flags["yes"] && (flags["json"] || !process.stdin.isTTY)) {
diff --git a/src/cli/brain/verbs/panel.ts b/src/cli/brain/verbs/panel.ts
index 247ede62..8bc20d4b 100644
--- a/src/cli/brain/verbs/panel.ts
+++ b/src/cli/brain/verbs/panel.ts
@@ -7,7 +7,6 @@
import { readFileSync } from "node:fs";
-import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
import {
WriteSessionRequestError,
sessionEnvelope,
@@ -15,7 +14,7 @@ import {
import { openPanelSession, submitToPanelSession } from "../../../core/brain/write-session/panel.ts";
import { readWriteSession } from "../../../core/brain/write-session/store.ts";
import type { WriteSessionEnvelope } from "../../../core/brain/write-session/types.ts";
-import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, ok, okJson, parse, resolveBrainAgent } from "../helpers.ts";
const USAGE =
"usage: o2b brain panel <open <topic...>|submit <session-id>|status <session-id>> " +
@@ -63,8 +62,7 @@ export async function cmdBrainPanel(argv: string[]): Promise<number> {
});
const op = positional[0];
const asJson = flags["json"] === true;
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
try {
switch (op) {
@@ -76,7 +74,7 @@ export async function cmdBrainPanel(argv: string[]): Promise<number> {
}
const personasFlag = flags["personas"] as string | undefined;
const env = openPanelSession(vault, {
- agent: (flags["agent"] as string | undefined) ?? resolveAgentName(config),
+ agent: resolveBrainAgent(flags, config),
topic,
requireReview: flags["require-review"] === true,
...(personasFlag
diff --git a/src/cli/brain/verbs/pin.ts b/src/cli/brain/verbs/pin.ts
index 5b6bc0ce..c38dd8dc 100644
--- a/src/cli/brain/verbs/pin.ts
+++ b/src/cli/brain/verbs/pin.ts
@@ -1,7 +1,7 @@
-import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import { resolveAgentName } from "../../../core/config.ts";
import { setPinned } from "../../../core/brain/pin.ts";
import { BrainPreferenceNotFoundError } from "../../../core/brain/apply-evidence.ts";
-import { parse, fail, normalizeFlagString, ok, okJson, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, normalizeFlagString, ok, okJson, parse } from "../helpers.ts";
async function pinOrUnpin(argv: string[], value: boolean): Promise<number> {
const { flags } = parse(argv, {
@@ -16,8 +16,7 @@ async function pinOrUnpin(argv: string[], value: boolean): Promise<number> {
if (id === null) {
return fail(`brain ${value ? "pin" : "unpin"} missing required flag: --id`);
}
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
const agent = resolveAgentName(config);
try {
diff --git a/src/cli/brain/verbs/procedural-graph.ts b/src/cli/brain/verbs/procedural-graph.ts
index 0f9aceef..b718da9a 100644
--- a/src/cli/brain/verbs/procedural-graph.ts
+++ b/src/cli/brain/verbs/procedural-graph.ts
@@ -1,4 +1,3 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import {
readProceduralGraph,
rebuildProceduralGraph,
@@ -7,7 +6,7 @@ import {
readProceduralHints,
rebuildProceduralHints,
} from "../../../core/brain/procedural-hints.ts";
-import { CliError, parse, resolveBrainVault } from "../helpers.ts";
+import { CliError, brainVerbContext, parse } from "../helpers.ts";
export async function cmdBrainProceduralGraph(argv: string[]): Promise<number> {
const sub = argv[0];
@@ -23,7 +22,7 @@ function rebuild(argv: string[]): number {
vault: { type: "string" },
json: { type: "boolean" },
});
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const graph = rebuildProceduralGraph(vault);
const hintProjection = rebuildProceduralHints(vault, { graph });
@@ -60,7 +59,7 @@ function show(argv: string[]): number {
vault: { type: "string" },
json: { type: "boolean" },
});
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const graph = readProceduralGraph(vault);
if (!graph) throw new CliError("brain procedural-graph show: graph projection not found");
@@ -80,7 +79,7 @@ function hints(argv: string[]): number {
vault: { type: "string" },
json: { type: "boolean" },
});
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const projection = readProceduralHints(vault);
if (!projection) throw new CliError("brain procedural-graph hints: hints projection not found");
diff --git a/src/cli/brain/verbs/procedural-memory.ts b/src/cli/brain/verbs/procedural-memory.ts
index fecc27b5..443c98f5 100644
--- a/src/cli/brain/verbs/procedural-memory.ts
+++ b/src/cli/brain/verbs/procedural-memory.ts
@@ -1,10 +1,9 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import {
listProceduralMemory,
markProceduralMemoryUsed,
reconcileProceduralMemory,
} from "../../../core/brain/procedural-memory.ts";
-import { CliError, parse, resolveBrainVault } from "../helpers.ts";
+import { CliError, brainVerbContext, parse } from "../helpers.ts";
import { join } from "node:path";
export async function cmdBrainProceduralMemory(argv: string[]): Promise<number> {
@@ -22,7 +21,7 @@ function reconcile(argv: string[]): number {
json: { type: "boolean" },
root: { type: "string-array" },
});
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const roots = normalizeRoots(vault, flags["root"]);
const result = reconcileProceduralMemory(vault, { roots });
@@ -42,7 +41,7 @@ function list(argv: string[]): number {
vault: { type: "string" },
json: { type: "boolean" },
});
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const entries = listProceduralMemory(vault);
if (flags["json"]) {
@@ -66,7 +65,7 @@ function markUsed(argv: string[]): number {
});
const id = trim(positional[0]);
if (!id) throw new CliError("brain procedural-memory mark-used: entry id is required");
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const updated = markProceduralMemoryUsed(vault, id);
if (!updated) throw new CliError(`brain procedural-memory mark-used: unknown entry: ${id}`);
diff --git a/src/cli/brain/verbs/protect.ts b/src/cli/brain/verbs/protect.ts
index 15961744..ef0b2e16 100644
--- a/src/cli/brain/verbs/protect.ts
+++ b/src/cli/brain/verbs/protect.ts
@@ -1,4 +1,3 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import {
applyProtect,
BrainProtectError,
@@ -7,7 +6,7 @@ import {
PROTECT_TARGETS,
unprotect,
} from "../../../core/brain/protect.ts";
-import { parse, fail, ok, okJson, info, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, info, ok, okJson, parse } from "../helpers.ts";
export async function cmdBrainProtect(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
@@ -23,7 +22,7 @@ export async function cmdBrainProtect(argv: string[]): Promise<number> {
);
}
const target = rawTarget;
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
try {
if (flags["apply"]) {
@@ -73,7 +72,7 @@ export async function cmdBrainUnprotect(argv: string[]): Promise<number> {
);
}
const target = rawTarget;
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
try {
unprotect({ target, vault });
diff --git a/src/cli/brain/verbs/query.ts b/src/cli/brain/verbs/query.ts
index 95482f40..4e19671b 100644
--- a/src/cli/brain/verbs/query.ts
+++ b/src/cli/brain/verbs/query.ts
@@ -1,4 +1,3 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import {
queryByLogSince,
queryByPreference,
@@ -6,13 +5,13 @@ import {
BrainNotFoundError,
} from "../../../core/brain/query.ts";
import {
- parse,
+ brainVerbContext,
fail,
- resolveBrainVault,
+ parse,
parseOptionalIsoDate,
+ renderQueryLogText,
renderQueryPreferenceText,
renderQueryTopicText,
- renderQueryLogText,
} from "../helpers.ts";
export async function cmdBrainQuery(argv: string[]): Promise<number> {
@@ -23,8 +22,7 @@ export async function cmdBrainQuery(argv: string[]): Promise<number> {
since: { type: "string" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
const modes = ["preference", "topic", "since"].filter(
(k) => typeof flags[k] === "string" && (flags[k] as string).trim() !== "",
diff --git a/src/cli/brain/verbs/recall-telemetry.ts b/src/cli/brain/verbs/recall-telemetry.ts
index 0f64753e..4fcc04c1 100644
--- a/src/cli/brain/verbs/recall-telemetry.ts
+++ b/src/cli/brain/verbs/recall-telemetry.ts
@@ -1,4 +1,3 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import {
isRecallTelemetryMode,
isRecallTelemetryStatus,
@@ -6,7 +5,7 @@ import {
summarizeRecallTelemetry,
} from "../../../core/brain/recall-telemetry.ts";
import { listGateTelemetry, summarizeGateTelemetry } from "../../../core/brain/gate-telemetry.ts";
-import { CliError, parse, resolveBrainVault } from "../helpers.ts";
+import { CliError, brainVerbContext, parse } from "../helpers.ts";
export async function cmdBrainRecallTelemetry(argv: string[]): Promise<number> {
const subcommand = argv[0];
@@ -21,7 +20,7 @@ export async function cmdBrainRecallTelemetry(argv: string[]): Promise<number> {
function listTelemetry(argv: string[]): number {
const { flags } = parseTelemetryFlags(argv);
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const filter = telemetryFilter(flags, "brain recall-telemetry list");
const records = listRecallTelemetry(vault, filter);
@@ -41,7 +40,7 @@ function listTelemetry(argv: string[]): number {
function summarizeTelemetry(argv: string[]): number {
const { flags } = parseTelemetryFlags(argv);
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const summary = summarizeRecallTelemetry(
vault,
telemetryFilter(flags, "brain recall-telemetry summary"),
@@ -78,7 +77,7 @@ function rejectRecallOnlyFlags(
function listGate(argv: string[]): number {
const { flags } = parseTelemetryFlags(argv);
rejectRecallOnlyFlags(flags, "brain recall-telemetry gate-list");
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const filter = telemetryFilter(flags, "brain recall-telemetry gate-list");
const records = listGateTelemetry(vault, {
...(filter.host !== undefined ? { host: filter.host } : {}),
@@ -102,7 +101,7 @@ function listGate(argv: string[]): number {
function summarizeGate(argv: string[]): number {
const { flags } = parseTelemetryFlags(argv);
rejectRecallOnlyFlags(flags, "brain recall-telemetry gate-summary", ["limit"]);
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const filter = telemetryFilter(flags, "brain recall-telemetry gate-summary");
const summary = summarizeGateTelemetry(vault, {
...(filter.host !== undefined ? { host: filter.host } : {}),
diff --git a/src/cli/brain/verbs/recurrence.ts b/src/cli/brain/verbs/recurrence.ts
index 683a7c4c..019f3e4d 100644
--- a/src/cli/brain/verbs/recurrence.ts
+++ b/src/cli/brain/verbs/recurrence.ts
@@ -1,11 +1,10 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import {
applyRecurrenceEvidence,
getRecurrenceEntry,
listRecurrenceEntries,
purgeRecurrenceSource,
} from "../../../core/brain/recurrence.ts";
-import { CliError, parse, resolveBrainVault } from "../helpers.ts";
+import { CliError, brainVerbContext, parse } from "../helpers.ts";
export async function cmdBrainRecurrence(argv: string[]): Promise<number> {
const sub = argv[0];
@@ -23,7 +22,7 @@ function list(argv: string[]): number {
vault: { type: "string" },
json: { type: "boolean" },
});
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const entries = listRecurrenceEntries(vault);
if (flags["json"]) {
@@ -47,7 +46,7 @@ function show(argv: string[]): number {
});
const hash = trim(positional[0]);
if (!hash) throw new CliError("brain recurrence show: content hash is required");
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const entry = getRecurrenceEntry(vault, hash);
if (!entry) throw new CliError(`brain recurrence show: not found: ${hash}`);
@@ -78,7 +77,7 @@ function mutate(argv: string[], action: "learn" | "forget"): number {
throw new CliError(`brain recurrence ${action}: --hash, --scope, and --source are required`);
}
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const entry = applyRecurrenceEvidence(vault, {
contentHash: hash,
scope,
@@ -103,7 +102,7 @@ function purgeSource(argv: string[]): number {
});
const source = trim(flags["source"]);
if (!source) throw new CliError("brain recurrence purge-source: --source is required");
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
purgeRecurrenceSource(vault, source);
if (flags["json"]) {
diff --git a/src/cli/brain/verbs/reject.ts b/src/cli/brain/verbs/reject.ts
index 3aae85c8..7656d3d3 100644
--- a/src/cli/brain/verbs/reject.ts
+++ b/src/cli/brain/verbs/reject.ts
@@ -1,12 +1,12 @@
import { existsSync } from "node:fs";
-import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import { resolveAgentName } from "../../../core/config.ts";
import { moveToRetired, parsePreference } from "../../../core/brain/preference.ts";
import { preferencePath } from "../../../core/brain/paths.ts";
import { isoDate, isoSecond } from "../../../core/brain/time.ts";
import { renderPrefLink } from "../../../core/brain/wikilink.ts";
import { appendLogEvent } from "../../../core/brain/log.ts";
import { BRAIN_LOG_EVENT_KIND } from "../../../core/brain/types.ts";
-import { parse, fail, ok, okJson, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";
export async function cmdBrainReject(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
@@ -24,8 +24,7 @@ export async function cmdBrainReject(argv: string[]): Promise<number> {
"brain reject missing required flag: --reason (free-form text; persisted on the retired file)",
);
}
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
const agent = resolveAgentName(config);
const rawId = String(flags["id"]).trim();
diff --git a/src/cli/brain/verbs/retention.ts b/src/cli/brain/verbs/retention.ts
index 638c646a..a2eb7e32 100644
--- a/src/cli/brain/verbs/retention.ts
+++ b/src/cli/brain/verbs/retention.ts
@@ -1,6 +1,5 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import { buildRetentionReview } from "../../../core/brain/retention.ts";
-import { CliError, parse, resolveBrainVault } from "../helpers.ts";
+import { CliError, brainVerbContext, parse } from "../helpers.ts";
/**
* `o2b brain retention [--vault PATH] [--now ISO] [--json]`
@@ -13,8 +12,7 @@ export async function cmdBrainRetention(argv: string[]): Promise<number> {
now: { type: "string" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
const now = parseNow(flags["now"]);
const report = buildRetentionReview(vault, now ? { now } : {});
diff --git a/src/cli/brain/verbs/rollback.ts b/src/cli/brain/verbs/rollback.ts
index bde18f17..b57a729a 100644
--- a/src/cli/brain/verbs/rollback.ts
+++ b/src/cli/brain/verbs/rollback.ts
@@ -1,4 +1,3 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import {
listSnapshots,
extractSnapshotToTemp,
@@ -20,12 +19,12 @@ import { appendLogEvent } from "../../../core/brain/log.ts";
import { BRAIN_LOG_EVENT_KIND } from "../../../core/brain/types.ts";
import { isoSecond } from "../../../core/brain/time.ts";
import {
- parse,
+ brainVerbContext,
+ diffSummary,
fail,
ok,
okJson,
- resolveBrainVault,
- diffSummary,
+ parse,
readSingleLine,
} from "../helpers.ts";
@@ -38,8 +37,7 @@ export async function cmdBrainRollback(argv: string[]): Promise<number> {
"force-rollback": { type: "boolean" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
const forceRollback = Boolean(flags["force-rollback"]);
if (flags["list"]) {
diff --git a/src/cli/brain/verbs/scan-inline.ts b/src/cli/brain/verbs/scan-inline.ts
index ec28961c..bcf4bd05 100644
--- a/src/cli/brain/verbs/scan-inline.ts
+++ b/src/cli/brain/verbs/scan-inline.ts
@@ -1,9 +1,8 @@
-import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
import { scanInline } from "../../../core/brain/inline-scan.ts";
import { appendLogEvent } from "../../../core/brain/log.ts";
import { BRAIN_LOG_EVENT_KIND } from "../../../core/brain/types.ts";
import { isoSecond } from "../../../core/brain/time.ts";
-import { parse, fail, ok, okJson, info, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, info, ok, okJson, parse, resolveBrainAgent } from "../helpers.ts";
export async function cmdBrainScanInline(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
@@ -15,9 +14,8 @@ export async function cmdBrainScanInline(argv: string[]): Promise<number> {
agent: { type: "string" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
- const agent = (flags["agent"] as string | undefined) ?? resolveAgentName(config);
+ const { config, vault } = brainVerbContext(flags);
+ const agent = resolveBrainAgent(flags, config);
let result;
try {
diff --git a/src/cli/brain/verbs/secret.ts b/src/cli/brain/verbs/secret.ts
index 5a2b014f..2ccd8ade 100644
--- a/src/cli/brain/verbs/secret.ts
+++ b/src/cli/brain/verbs/secret.ts
@@ -10,10 +10,10 @@
* operational failure, 2 on usage errors.
*/
-import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import { resolveAgentName } from "../../../core/config.ts";
import { runWithSecret, SecretExecDeniedError } from "../../../core/brain/secrets/exec.ts";
import { listSecrets, removeSecret, setSecret } from "../../../core/brain/secrets/store.ts";
-import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";
const USAGE =
"usage: o2b brain secret set <name> [--env-var V] [--allow PATTERN]... [--from-env SRC] [--agent N] [--vault <path>] [--json] | " +
@@ -47,8 +47,7 @@ export async function cmdBrainSecret(argv: string[]): Promise<number> {
return 2;
}
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
const agent = (flags["agent"] as string | undefined)?.trim() || resolveAgentName(config);
const now = new Date();
diff --git a/src/cli/brain/verbs/semantics-backfill.ts b/src/cli/brain/verbs/semantics-backfill.ts
index 5e8915b7..b5604479 100644
--- a/src/cli/brain/verbs/semantics-backfill.ts
+++ b/src/cli/brain/verbs/semantics-backfill.ts
@@ -1,14 +1,12 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import { planSemanticsBackfill } from "../../../core/brain/semantics-backfill.ts";
-import { info, okJson, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, info, okJson, parse } from "../helpers.ts";
export async function cmdBrainSemanticsBackfill(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
vault: { type: "string" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
const plan = planSemanticsBackfill(vault);
if (flags["json"]) {
diff --git a/src/cli/brain/verbs/session-recall.ts b/src/cli/brain/verbs/session-recall.ts
index f0bb0a4a..b9ace2fb 100644
--- a/src/cli/brain/verbs/session-recall.ts
+++ b/src/cli/brain/verbs/session-recall.ts
@@ -1,10 +1,9 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import {
describeSessionRecall,
expandSessionRecall,
searchSessionRecall,
} from "../../../core/brain/session-recall.ts";
-import { CliError, parse, resolveBrainVault } from "../helpers.ts";
+import { CliError, brainVerbContext, parse } from "../helpers.ts";
export async function cmdBrainSessionGrep(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
@@ -15,7 +14,7 @@ export async function cmdBrainSessionGrep(argv: string[]): Promise<number> {
limit: { type: "string" },
"snippet-chars": { type: "string" },
});
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const result = searchSessionRecall(vault, {
query: requiredString(flags["query"], "brain session-grep", "--query"),
...(stringOptional(flags["session-id"]) !== undefined
@@ -47,7 +46,7 @@ export async function cmdBrainSessionDescribe(argv: string[]): Promise<number> {
json: { type: "boolean" },
"session-id": { type: "string" },
});
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const result = describeSessionRecall(vault, {
sessionId: requiredString(flags["session-id"], "brain session-describe", "--session-id"),
});
@@ -62,7 +61,7 @@ export async function cmdBrainSessionExpand(argv: string[]): Promise<number> {
"raw-limit": { type: "string" },
cursor: { type: "string" },
});
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const id = positional[0];
if (id === undefined) throw new CliError("brain session-expand: record id is required");
const result = expandSessionRecall(vault, {
diff --git a/src/cli/brain/verbs/session.ts b/src/cli/brain/verbs/session.ts
index cb846777..b584aef5 100644
--- a/src/cli/brain/verbs/session.ts
+++ b/src/cli/brain/verbs/session.ts
@@ -11,7 +11,6 @@
import { readFileSync } from "node:fs";
-import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
import {
WriteSessionRequestError,
abandonSession,
@@ -29,8 +28,7 @@ import type {
WriteSessionEnvelope,
WriteSessionIntent,
} from "../../../core/brain/write-session/types.ts";
-import { fail, ok, okJson, parse } from "../helpers.ts";
-import { resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, ok, okJson, parse, resolveBrainAgent } from "../helpers.ts";
const USAGE =
"usage: o2b brain session <open|submit|approve|abandon|status|list|sweep> " +
@@ -102,8 +100,7 @@ export async function cmdBrainSession(argv: string[]): Promise<number> {
});
const op = positional[0];
const asJson = flags["json"] === true;
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
try {
switch (op) {
@@ -120,7 +117,7 @@ export async function cmdBrainSession(argv: string[]): Promise<number> {
}
const retryCapRaw = flags["retry-cap"] as string | undefined;
const env = openArtifactSession(vault, {
- agent: (flags["agent"] as string | undefined) ?? resolveAgentName(config),
+ agent: resolveBrainAgent(flags, config),
targetPath: target,
intent: intentRaw as WriteSessionIntent,
requireReview: flags["require-review"] === true,
diff --git a/src/cli/brain/verbs/set-primary.ts b/src/cli/brain/verbs/set-primary.ts
index e34aa11c..332b712f 100644
--- a/src/cli/brain/verbs/set-primary.ts
+++ b/src/cli/brain/verbs/set-primary.ts
@@ -1,6 +1,5 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import { setPrimaryAgent } from "../../../core/brain/set-primary.ts";
-import { parse, fail, ok, okJson, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";
export async function cmdBrainSetPrimary(argv: string[]): Promise<number> {
const { flags, positional } = parse(argv, {
@@ -8,8 +7,7 @@ export async function cmdBrainSetPrimary(argv: string[]): Promise<number> {
clear: { type: "boolean" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
let name: string | null;
if (flags["clear"]) {
diff --git a/src/cli/brain/verbs/skill-proposals.ts b/src/cli/brain/verbs/skill-proposals.ts
index 91482500..faad3db2 100644
--- a/src/cli/brain/verbs/skill-proposals.ts
+++ b/src/cli/brain/verbs/skill-proposals.ts
@@ -1,11 +1,10 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import {
acceptSkillProposal,
learnSkillProposals,
listPendingSkillProposals,
rejectSkillProposal,
} from "../../../core/brain/skill-proposals.ts";
-import { CliError, parse, resolveBrainVault } from "../helpers.ts";
+import { CliError, brainVerbContext, parse } from "../helpers.ts";
export async function cmdBrainSkillProposals(argv: string[]): Promise<number> {
const sub = argv[0];
@@ -23,7 +22,7 @@ function learn(argv: string[]): number {
json: { type: "boolean" },
"min-support": { type: "string" },
});
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const minSupportRaw = trim(flags["min-support"]);
const minSupport = minSupportRaw
? parsePositiveInteger(minSupportRaw, "--min-support")
@@ -50,7 +49,7 @@ function list(argv: string[]): number {
vault: { type: "string" },
json: { type: "boolean" },
});
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const pending = listPendingSkillProposals(vault);
if (flags["json"]) {
@@ -75,7 +74,7 @@ function accept(argv: string[]): number {
});
const slug = trim(positional[0]);
if (!slug) throw new CliError("brain skill-proposals accept: slug is required");
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const note = trim(flags["note"]);
const result = note
? acceptSkillProposal(vault, slug, { note })
@@ -100,7 +99,7 @@ function reject(argv: string[]): number {
if (!slug) throw new CliError("brain skill-proposals reject: slug is required");
const note = trim(flags["note"]);
if (!note) throw new CliError("brain skill-proposals reject: --note is required");
- const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = brainVerbContext(flags).vault;
const result = rejectSkillProposal(vault, slug, { note });
if (flags["json"]) {
diff --git a/src/cli/brain/verbs/snapshot.ts b/src/cli/brain/verbs/snapshot.ts
index a992e9a0..2fbd92d8 100644
--- a/src/cli/brain/verbs/snapshot.ts
+++ b/src/cli/brain/verbs/snapshot.ts
@@ -6,16 +6,14 @@ import {
import { diffBrainTrees } from "../../../core/brain/snapshot-diff.ts";
import { renderDiffJson, renderDiffMarkdown } from "../../../core/brain/snapshot-diff-render.ts";
import { brainDirs } from "../../../core/brain/paths.ts";
-import { defaultConfigPath } from "../../../core/config.ts";
-import { parse, fail, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, parse } from "../helpers.ts";
export async function cmdBrainSnapshotDiff(argv: string[]): Promise<number> {
const { flags, positional } = parse(argv, {
vault: { type: "string" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
if (positional.length < 1 || positional.length > 2) {
return fail(
diff --git a/src/cli/brain/verbs/summary.ts b/src/cli/brain/verbs/summary.ts
index 56a2dc79..10d71672 100644
--- a/src/cli/brain/verbs/summary.ts
+++ b/src/cli/brain/verbs/summary.ts
@@ -7,13 +7,12 @@
* their notes; `--json` returns the structured envelope for tooling.
*/
-import { defaultConfigPath } from "../../../core/config.ts";
import { dream } from "../../../core/brain/dream.ts";
import {
buildOperatorSummary,
renderOperatorSummaryMarkdown,
} from "../../../core/brain/trust/operator-summary.ts";
-import { parse, fail, okJson, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, okJson, parse } from "../helpers.ts";
export async function cmdBrainSummary(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
@@ -22,8 +21,7 @@ export async function cmdBrainSummary(argv: string[]): Promise<number> {
"skip-dream": { type: "boolean" },
"top-actions": { type: "string" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
let topActionsN: number | undefined;
const topRaw = flags["top-actions"] as string | undefined;
diff --git a/src/cli/brain/verbs/synthesise.ts b/src/cli/brain/verbs/synthesise.ts
index 313caba4..3cdf3362 100644
--- a/src/cli/brain/verbs/synthesise.ts
+++ b/src/cli/brain/verbs/synthesise.ts
@@ -1,7 +1,6 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import { buildConceptCluster } from "../../../core/brain/link-graph/concept-cluster.ts";
import { normaliseWikilinkTarget } from "../../../core/brain/wikilink.ts";
-import { parse, fail, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, parse } from "../helpers.ts";
/**
* `o2b brain synthesise <id> [--include-unlinked] [--vault PATH] [--json]`
@@ -17,8 +16,7 @@ export async function cmdBrainSynthesise(argv: string[]): Promise<number> {
"include-unlinked": { type: "boolean" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
const id = positional[0];
if (!id) return fail("brain synthesise requires a target id (e.g. pref-foo)");
diff --git a/src/cli/brain/verbs/temporal-daily.ts b/src/cli/brain/verbs/temporal-daily.ts
index b6676934..33661da1 100644
--- a/src/cli/brain/verbs/temporal-daily.ts
+++ b/src/cli/brain/verbs/temporal-daily.ts
@@ -1,8 +1,7 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import { buildTimelineIndex } from "../../../core/brain/temporal/build-index.ts";
import { buildDailyBrief } from "../../../core/brain/temporal/daily-brief.ts";
import { loadTemporalConfigSafe } from "../../../core/brain/policy.ts";
-import { CliError, parse, resolveBrainVault, localTimeFields } from "../helpers.ts";
+import { CliError, brainVerbContext, localTimeFields, parse } from "../helpers.ts";
import { captureReportDelta, renderReportDelta } from "../../../core/brain/report-snapshot.ts";
const ISO_DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
@@ -19,8 +18,7 @@ export async function cmdBrainDaily(argv: string[]): Promise<number> {
date: { type: "string" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
const date = resolveDateArg(flags["date"]);
const cfg = loadTemporalConfigSafe(vault);
const index = buildTimelineIndex(vault, {});
diff --git a/src/cli/brain/verbs/temporal-evolution.ts b/src/cli/brain/verbs/temporal-evolution.ts
index d5d30548..a700ce39 100644
--- a/src/cli/brain/verbs/temporal-evolution.ts
+++ b/src/cli/brain/verbs/temporal-evolution.ts
@@ -1,10 +1,9 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import { buildTimelineIndex } from "../../../core/brain/temporal/build-index.ts";
import {
buildBeliefEvolution,
type BeliefEvolutionTarget,
} from "../../../core/brain/temporal/belief-evolution.ts";
-import { CliError, parse, resolveBrainVault } from "../helpers.ts";
+import { CliError, brainVerbContext, parse } from "../helpers.ts";
/**
* `o2b brain evolution [--vault PATH] (--pref-id ID | --topic SLUG)
@@ -21,8 +20,7 @@ export async function cmdBrainEvolution(argv: string[]): Promise<number> {
topic: { type: "string" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
const prefId = trimOrUndefined(flags["pref-id"]);
const topic = trimOrUndefined(flags["topic"]);
diff --git a/src/cli/brain/verbs/temporal-stale.ts b/src/cli/brain/verbs/temporal-stale.ts
index 1e4841d5..f727603e 100644
--- a/src/cli/brain/verbs/temporal-stale.ts
+++ b/src/cli/brain/verbs/temporal-stale.ts
@@ -1,8 +1,7 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import { buildTimelineIndex } from "../../../core/brain/temporal/build-index.ts";
import { findStaleEntries } from "../../../core/brain/temporal/stale-watch.ts";
import { loadTemporalConfigSafe } from "../../../core/brain/policy.ts";
-import { parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, parse } from "../helpers.ts";
/**
* `o2b brain stale [--vault PATH] [--json]`
@@ -16,8 +15,7 @@ export async function cmdBrainStale(argv: string[]): Promise<number> {
vault: { type: "string" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
const cfg = loadTemporalConfigSafe(vault);
const index = buildTimelineIndex(vault, {});
diff --git a/src/cli/brain/verbs/temporal-timeline.ts b/src/cli/brain/verbs/temporal-timeline.ts
index 31ab3b48..f73729d0 100644
--- a/src/cli/brain/verbs/temporal-timeline.ts
+++ b/src/cli/brain/verbs/temporal-timeline.ts
@@ -1,8 +1,7 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import { isBrainLogEventKind, type BrainLogEventKind } from "../../../core/brain/types.ts";
import { buildTimelineIndex } from "../../../core/brain/temporal/build-index.ts";
import { selectEvents } from "../../../core/brain/temporal/select-events.ts";
-import { CliError, parse, resolveBrainVault, localTimeFields } from "../helpers.ts";
+import { CliError, brainVerbContext, localTimeFields, parse } from "../helpers.ts";
/**
* `o2b brain timeline [--vault PATH] [--pref-id ID] [--topic SLUG]
@@ -24,8 +23,7 @@ export async function cmdBrainTimeline(argv: string[]): Promise<number> {
limit: { type: "string" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
const prefId = trimOrUndefined(flags["pref-id"]);
const topic = trimOrUndefined(flags["topic"]);
diff --git a/src/cli/brain/verbs/temporal-weekly.ts b/src/cli/brain/verbs/temporal-weekly.ts
index 28437ad6..c364b51d 100644
--- a/src/cli/brain/verbs/temporal-weekly.ts
+++ b/src/cli/brain/verbs/temporal-weekly.ts
@@ -1,9 +1,8 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import { captureReportDelta, renderReportDelta } from "../../../core/brain/report-snapshot.ts";
import { buildTimelineIndex } from "../../../core/brain/temporal/build-index.ts";
import { buildWeeklySynthesis } from "../../../core/brain/temporal/weekly-brief.ts";
import { loadTemporalConfigSafe } from "../../../core/brain/policy.ts";
-import { CliError, parse, resolveBrainVault, localTimeFields } from "../helpers.ts";
+import { CliError, brainVerbContext, localTimeFields, parse } from "../helpers.ts";
const ISO_DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
@@ -19,8 +18,7 @@ export async function cmdBrainWeekly(argv: string[]): Promise<number> {
"week-end": { type: "string" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
const weekEnd = resolveWeekEndArg(flags["week-end"]);
const cfg = loadTemporalConfigSafe(vault);
const index = buildTimelineIndex(vault, {});
diff --git a/src/cli/brain/verbs/tiers.ts b/src/cli/brain/verbs/tiers.ts
index 05b89bfb..f7401632 100644
--- a/src/cli/brain/verbs/tiers.ts
+++ b/src/cli/brain/verbs/tiers.ts
@@ -16,9 +16,8 @@ import { existsSync } from "node:fs";
import { resolveSearchConfig } from "../../../core/search/index.ts";
import { Store } from "../../../core/search/store.ts";
import { parseFrontmatter, writeFrontmatterAtomic } from "../../../core/vault.ts";
-import { defaultConfigPath } from "../../../core/config.ts";
import type { FrontmatterMap } from "../../../core/types.ts";
-import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";
const USAGE =
"usage: o2b brain tiers check | " +
@@ -44,8 +43,7 @@ export async function cmdBrainTiers(argv: string[]): Promise<number> {
return 2;
}
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
const searchConfig = resolveSearchConfig({ vault, configPath: config ?? undefined });
const field = (flags["field"] as string | undefined)?.trim();
diff --git a/src/cli/brain/verbs/token-footprint.ts b/src/cli/brain/verbs/token-footprint.ts
index 88a0c9cd..3fad820c 100644
--- a/src/cli/brain/verbs/token-footprint.ts
+++ b/src/cli/brain/verbs/token-footprint.ts
@@ -5,9 +5,8 @@
* for programmatic consumers (cron digests, dashboards).
*/
-import { defaultConfigPath } from "../../../core/config.ts";
import { computeTokenFootprint } from "../../../core/brain/token-footprint.ts";
-import { parse, fail, okJson, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, okJson, parse } from "../helpers.ts";
export async function cmdBrainTokenFootprint(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
@@ -15,8 +14,7 @@ export async function cmdBrainTokenFootprint(argv: string[]): Promise<number> {
json: { type: "boolean" },
"warn-threshold": { type: "string" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
const overrideRaw = flags["warn-threshold"] as string | undefined;
let warnThreshold: number | undefined;
if (overrideRaw !== undefined) {
diff --git a/src/cli/brain/verbs/truth.ts b/src/cli/brain/verbs/truth.ts
index 401b51fc..a805248a 100644
--- a/src/cli/brain/verbs/truth.ts
+++ b/src/cli/brain/verbs/truth.ts
@@ -9,7 +9,6 @@
* errors.
*/
-import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
import { aggregateQuantities } from "../../../core/brain/truth/aggregate.ts";
import { detectAgentCollisions } from "../../../core/brain/truth/collision.ts";
import { computeTruthStateWithConflicts } from "../../../core/brain/truth/conflicts.ts";
@@ -21,7 +20,7 @@ import {
} from "../../../core/brain/truth/store.ts";
import { normalizeEntityName } from "../../../core/brain/entities/canonical.ts";
import { isoSecond } from "../../../core/brain/time.ts";
-import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, ok, okJson, parse, resolveBrainAgent } from "../helpers.ts";
const OPS = ["ingest", "slots", "conflicts", "aggregate", "collisions", "sweep"] as const;
type TruthOp = (typeof OPS)[number];
@@ -71,8 +70,7 @@ export async function cmdBrainTruth(argv: string[]): Promise<number> {
return 2;
}
const asJson = flags["json"] === true;
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
try {
switch (op) {
@@ -101,7 +99,7 @@ export async function cmdBrainTruth(argv: string[]): Promise<number> {
}
const result = appendClaimEvent(vault, {
ts: (flags["ts"] as string | undefined) ?? isoSecond(new Date()),
- agent: (flags["agent"] as string | undefined) ?? resolveAgentName(config),
+ agent: resolveBrainAgent(flags, config),
entity: requireString(flags, "entity"),
aspect: requireString(flags, "aspect"),
value: requireString(flags, "value"),
diff --git a/src/cli/brain/verbs/tune.ts b/src/cli/brain/verbs/tune.ts
index 37535704..cd1b24ae 100644
--- a/src/cli/brain/verbs/tune.ts
+++ b/src/cli/brain/verbs/tune.ts
@@ -18,8 +18,7 @@ import { appendMetric } from "../../../core/brain/metrics.ts";
import { isoSecond } from "../../../core/brain/time.ts";
import { resolveSearchConfig } from "../../../core/search/index.ts";
import { SearchError } from "../../../core/search/types.ts";
-import { defaultConfigPath } from "../../../core/config.ts";
-import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";
const USAGE =
"usage: o2b brain tune run --dataset <path> [--k N] | status | reset [--vault <path>] [--json]";
@@ -42,8 +41,7 @@ export async function cmdBrainTune(argv: string[]): Promise<number> {
return 2;
}
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { config, vault } = brainVerbContext(flags);
try {
if (action === "status") {
diff --git a/src/cli/brain/verbs/unlinked.ts b/src/cli/brain/verbs/unlinked.ts
index 971ae5f0..d005cd8f 100644
--- a/src/cli/brain/verbs/unlinked.ts
+++ b/src/cli/brain/verbs/unlinked.ts
@@ -1,7 +1,6 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import { findUnlinkedMentions } from "../../../core/brain/link-graph/unlinked-mentions.ts";
import { normaliseWikilinkTarget } from "../../../core/brain/wikilink.ts";
-import { parse, fail, resolveBrainVault } from "../helpers.ts";
+import { brainVerbContext, fail, parse } from "../helpers.ts";
/**
* `o2b brain unlinked <target-id> [--limit N] [--vault PATH] [--json]`
@@ -17,8 +16,7 @@ export async function cmdBrainUnlinked(argv: string[]): Promise<number> {
limit: { type: "string" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
const id = positional[0];
if (!id) {
diff --git a/src/cli/brain/verbs/upgrade.ts b/src/cli/brain/verbs/upgrade.ts
index 6573ffe3..2e0ca3c7 100644
--- a/src/cli/brain/verbs/upgrade.ts
+++ b/src/cli/brain/verbs/upgrade.ts
@@ -1,4 +1,3 @@
-import { defaultConfigPath } from "../../../core/config.ts";
import {
planUpgrade,
applyUpgrade,
@@ -6,14 +5,14 @@ import {
type UpgradePlan,
} from "../../../core/brain/upgrade.ts";
import {
- parse,
+ brainVerbContext,
fail,
ok,
okJson,
- resolveBrainVault,
+ parse,
printUpgradePlanText,
- renderUpgradePlanJson,
readSingleLine,
+ renderUpgradePlanJson,
} from "../helpers.ts";
export async function cmdBrainUpgrade(argv: string[]): Promise<number> {
@@ -25,8 +24,7 @@ export async function cmdBrainUpgrade(argv: string[]): Promise<number> {
check: { type: "boolean" },
json: { type: "boolean" },
});
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const { vault } = brainVerbContext(flags);
if (flags["dry-run"] && flags["apply"])
return fail("brain upgrade: --dry-run and --apply are mutually exclusive");
diff --git a/src/core/brain/confidence.ts b/src/core/brain/confidence.ts
new file mode 100644
index 00000000..31c2f25f
--- /dev/null
+++ b/src/core/brain/confidence.ts
@@ -0,0 +1,91 @@
+/**
+ * Deterministic preference-confidence computation for the dream pass.
+ *
+ * Extracted from dream.ts: the Wilson-bound derivation and band
+ * mapping are pure functions of the evidence counters and config, so
+ * they live apart from the orchestration that consumes them.
+ */
+
+import { BRAIN_CONFIDENCE, type BrainConfidence, type BrainConfig } from "./types.ts";
+
+/**
+ * Confidence computation. Returns both the numeric value and the
+ * categorical band derived from it.
+ *
+ * `value = wilson_low(applied, n) * freshness`:
+ *
+ * - `wilson_low(applied, n)` where `n = applied + violated` -
+ * a conservative 95% lower bound on the application rate.
+ * `n == 0` yields `0`.
+ * - `freshness` linearly decays from `1.0` at age 0 to `0.0` at
+ * `retire.stale_evidence_days`. `null` last_evidence_at → `0`.
+ *
+ * Band thresholds (`confidence.medium_min`, `confidence.high_min`)
+ * are applied to `value` directly. The numeric value is what the
+ * digest's drop tracker compares across runs.
+ */
+export interface ConfidenceComputeResult {
+ readonly value: number;
+ readonly band: BrainConfidence;
+}
+
+export const BAND_RANK: Readonly<Record<BrainConfidence, number>> = Object.freeze({
+ low: 0,
+ medium: 1,
+ high: 2,
+});
+
+export function computeConfidence(
+ applied: number,
+ violated: number,
+ lastEvidenceAt: string | null,
+ cfg: BrainConfig,
+ now: Date,
+): ConfidenceComputeResult {
+ const n = applied + violated;
+ let wilsonLow = 0;
+ if (n > 0) {
+ const z = 1.96;
+ const z2 = z * z;
+ const pHat = applied / n;
+ const denom = 1 + z2 / n;
+ const centre = (pHat + z2 / (2 * n)) / denom;
+ const margin = (z * Math.sqrt((pHat * (1 - pHat)) / n + z2 / (4 * n * n))) / denom;
+ wilsonLow = Math.max(0, centre - margin);
+ }
+ let freshness = 0;
+ if (lastEvidenceAt) {
+ const ageMs = now.getTime() - Date.parse(lastEvidenceAt);
+ if (Number.isFinite(ageMs)) {
+ const limitMs = cfg.retire.stale_evidence_days * 24 * 3600 * 1000;
+ if (limitMs > 0) {
+ freshness = Math.max(0, Math.min(1, 1 - ageMs / limitMs));
+ }
+ }
+ }
+ const rawValue = wilsonLow * freshness;
+ const value = Math.round(rawValue * 10000) / 10000;
+
+ let band: BrainConfidence;
+ if (value >= cfg.confidence.high_min) {
+ band = BRAIN_CONFIDENCE.high;
+ } else if (value >= cfg.confidence.medium_min) {
+ band = BRAIN_CONFIDENCE.medium;
+ } else {
+ band = BRAIN_CONFIDENCE.low;
+ }
+ return Object.freeze({ value, band });
+}
+
+/** Re-derive the confidence band for an externally adjusted value. */
+export function rebandConfidence(value: number, cfg: BrainConfig): ConfidenceComputeResult {
+ let band: BrainConfidence;
+ if (value >= cfg.confidence.high_min) {
+ band = BRAIN_CONFIDENCE.high;
+ } else if (value >= cfg.confidence.medium_min) {
+ band = BRAIN_CONFIDENCE.medium;
+ } else {
+ band = BRAIN_CONFIDENCE.low;
+ }
+ return Object.freeze({ value, band });
+}
diff --git a/src/core/brain/dream-plan.ts b/src/core/brain/dream-plan.ts
new file mode 100644
index 00000000..6aa8f6a3
--- /dev/null
+++ b/src/core/brain/dream-plan.ts
@@ -0,0 +1,205 @@
+/**
+ * Shared scan-record and plan-state shapes for the dream pass.
+ *
+ * Extracted from dream.ts so the planning sub-modules
+ * (reconcile-outcomes.ts, dream-refresh.ts) and the orchestrator can
+ * exchange typed state without a single-file dependency knot. Pure
+ * data shapes plus two stateless helpers; no I/O.
+ */
+
+import type { BrainPreference, BrainRetiredReason, BrainSignal, BrainSignalSign } from "./types.ts";
+
+export interface SignalRecord {
+ readonly path: string;
+ readonly signal: BrainSignal;
+ /** True iff the file lives in `inbox/` (not `processed/`). */
+ readonly active: boolean;
+}
+
+export interface PreferenceRecord {
+ readonly path: string;
+ readonly pref: BrainPreference;
+}
+
+export interface RetiredRecord {
+ readonly path: string;
+ readonly topic: string;
+ readonly id: string;
+ readonly principle: string;
+ readonly scope?: string;
+ /**
+ * The free-form user reason passed to `o2b brain reject --reason`.
+ * Presence triggers signal-suppression for future signals on the
+ * same (topic, scope) — see §6 of the OSB features summary.
+ */
+ readonly user_rejected_reason?: string;
+}
+
+export interface CorruptedEntry {
+ readonly path: string;
+}
+
+export interface ScanResult {
+ readonly signals: SignalRecord[];
+ readonly preferences: PreferenceRecord[];
+ readonly retired: RetiredRecord[];
+ readonly corrupted: CorruptedEntry[];
+}
+
+/**
+ * Entry surfacing a signal cluster that the self-approval guardrail
+ * (v0.10.16) held back from promotion because one or more configured
+ * thresholds were not met. Distinct from `suppressed` (which fires
+ * on a user-rejected retired preference); a quarantined cluster
+ * stays inbox-side and may promote on the next dream pass once
+ * more evidence accumulates.
+ */
+export interface DreamQuarantinedEntry {
+ /** Topic slug whose signals are held below the promotion threshold. */
+ readonly topic: string;
+ /** Count of accumulated same-sign signals. */
+ readonly signal_count: number;
+ /** Number of distinct agents that raised same-sign signals. */
+ readonly distinct_agents: number;
+ /** Age (in days) of the earliest signal in the cluster. */
+ readonly age_days: number;
+ /**
+ * Which threshold(s) blocked promotion: any subset of
+ * `min_signals`, `min_distinct_agents`, `min_age_days`.
+ */
+ readonly failed_gates: ReadonlyArray<string>;
+}
+
+export interface PlanState {
+ /** Topic slug → planned new unconfirmed preference. */
+ readonly newUnconfirmed: NewUnconfirmedPlan[];
+ /** Preferences to retire (after refresh). */
+ readonly retires: RetirePlan[];
+ /** Same-sign signals on active prefs → moved + log event. */
+ readonly notedRedundant: NotedRedundantPlan[];
+ /** Pinned prefs that would have retired but stay because pinned. */
+ readonly retainPinned: RetainPinnedPlan[];
+ /** Signal id → record to move out of inbox/. */
+ readonly signalsToMove: Map<string, SignalMovePlan>;
+ /** Topic slugs flagged contradicted but no transition this run. */
+ readonly contradictionTopics: Set<string>;
+ /**
+ * Signals dropped because their (topic, scope) matches a user-rejected
+ * retired pref carrying a `user_rejected_reason`. Each entry produces
+ * one `signal-suppressed` log event AND a move into `processed/` so
+ * the inbox does not accumulate.
+ */
+ readonly signalsSuppressed: SignalSuppressedPlan[];
+ /**
+ * Signal clusters held back from promotion by the self-approval
+ * guardrail (v0.10.16). The cluster passed the existing
+ * `candidate_threshold` but failed one or more configured
+ * thresholds in `BrainGuardrailConfig`. Preserved across the plan
+ * so it surfaces on the DreamRunSummary without affecting the
+ * existing move-to-processed semantics.
+ */
+ readonly quarantined: DreamQuarantinedEntry[];
+}
+
+export interface SignalSuppressedPlan {
+ readonly signal: string;
+ /** Pre-rendered `[[ret-slug|principle]]` wikilink for the suppressor. */
+ readonly retired: string;
+ readonly reason: string;
+ readonly topic: string;
+}
+
+export interface NewUnconfirmedPlan {
+ readonly slug: string;
+ readonly topic: string;
+ readonly scope: string | undefined;
+ readonly principle: string;
+ readonly evidencedBy: ReadonlyArray<string>;
+ readonly sign: BrainSignalSign;
+ /**
+ * Wikilink string (`[[ret-<slug>]]` or `[[pref-<slug>]]`) to the
+ * preference this new entry supersedes, if any. Threaded through to
+ * `writePreference` so the resulting frontmatter carries
+ * `supersedes:` for audit-trail continuity across rebuttals.
+ */
+ readonly supersedes?: string;
+ /**
+ * Brain lifecycle suite (F5). Bi-temporal validity derived from the
+ * source signal at plan time (explicit signal fields preferred, else
+ * extracted from the signal's ISO temporal text). Threaded to the
+ * preference writer on promotion.
+ */
+ readonly valid_from?: string;
+ readonly valid_until?: string;
+}
+
+export interface RetirePlan {
+ readonly slug: string;
+ /**
+ * Principle of the preference being retired, captured at plan time
+ * so the dream summary log payload can render a titled wikilink
+ * (`[[ret-slug|principle]]`) without re-reading the file after move.
+ */
+ readonly principle: string;
+ readonly reason: BrainRetiredReason;
+ readonly supersededBy?: string;
+}
+
+export interface NotedRedundantPlan {
+ /** Pre-rendered `[[pref-id|principle]]` wikilink for the active pref. */
+ readonly preference: string;
+ readonly signal: string;
+}
+
+export interface RetainPinnedPlan {
+ /** Pre-rendered `[[pref-id|principle]]` wikilink for the pinned pref. */
+ readonly preference: string;
+ readonly reason: BrainRetiredReason;
+}
+
+export interface SignalMovePlan {
+ readonly id: string;
+ readonly date: string;
+ readonly slug: string;
+ readonly path: string;
+}
+
+export function emptyPlan(): PlanState {
+ return {
+ newUnconfirmed: [],
+ retires: [],
+ notedRedundant: [],
+ retainPinned: [],
+ signalsToMove: new Map(),
+ contradictionTopics: new Set(),
+ signalsSuppressed: [],
+ quarantined: [],
+ };
+}
+
+export function recordSignalMove(plan: PlanState, rec: SignalRecord): void {
+ if (!rec.active) return;
+ const id = rec.signal.id;
+ if (plan.signalsToMove.has(id)) return;
+ // Derive date + slug from the id (`sig-YYYY-MM-DD-<slug>`).
+ const m = /^sig-(\d{4}-\d{2}-\d{2})-(.+)$/.exec(id);
+ if (!m) return;
+ plan.signalsToMove.set(id, {
+ id,
+ date: m[1]!,
+ slug: m[2]!,
+ path: rec.path,
+ });
+}
+
+export function filterWithinWindow(
+ sigs: SignalRecord[],
+ windowDays: number,
+ now: Date,
+): SignalRecord[] {
+ const minTime = now.getTime() - windowDays * 24 * 3600 * 1000;
+ return sigs.filter((s) => {
+ const t = Date.parse(s.signal.created_at);
+ return Number.isFinite(t) && t >= minTime;
+ });
+}
diff --git a/src/core/brain/dream-refresh.ts b/src/core/brain/dream-refresh.ts
new file mode 100644
index 00000000..4aebfbf9
--- /dev/null
+++ b/src/core/brain/dream-refresh.ts
@@ -0,0 +1,434 @@
+/**
+ * Evidence refresh and promotion planning (dream phase F4).
+ *
+ * Extracted from dream.ts. Scans apply-evidence log events (merge-
+ * alias aware), recomputes per-preference counters, status
+ * transitions (confirm, quarantine, context-driven retire), and
+ * confidence - including the outcome-regression penalty. Pure
+ * planning: callers apply the returned updates.
+ */
+
+import { BAND_RANK, computeConfidence, rebandConfidence } from "./confidence.ts";
+import type { PlanState, ScanResult } from "./dream-plan.ts";
+import { collectEvidenceForSlug } from "./evidence.ts";
+import { listLogDates, readLogDay } from "./log-jsonl.ts";
+import { isPinned } from "./pin.ts";
+import { wouldRewritePreference } from "./preference.ts";
+import { classifyFreshnessTrend } from "./temporal/freshness-trend.ts";
+import { parseWikilink, renderPrefLink } from "./wikilink.ts";
+import {
+ BRAIN_APPLY_RESULT,
+ BRAIN_LOG_EVENT_KIND,
+ BRAIN_PREFERENCE_STATUS,
+ BRAIN_RETIRED_REASON,
+ type BrainConfidence,
+ type BrainConfig,
+} from "./types.ts";
+
+export interface RefreshUpdate {
+ readonly slug: string;
+ readonly topic: string;
+ readonly scope?: string;
+ readonly principle: string;
+ readonly created_at: string;
+ readonly unconfirmed_until: string;
+ readonly status: (typeof BRAIN_PREFERENCE_STATUS)[keyof typeof BRAIN_PREFERENCE_STATUS];
+ readonly evidenced_by: ReadonlyArray<string>;
+ readonly confirmed_at: string | null;
+ readonly applied_count: number;
+ readonly violated_count: number;
+ readonly last_evidence_at: string | null;
+ readonly confidence: BrainConfidence;
+ readonly confidence_value: number;
+ readonly pinned: boolean;
+ /**
+ * Freshness trend (t_ee09a6ce), computed at PLAN time so the no-op
+ * pre-flight (`wouldRewritePreference`) renders the same bytes the
+ * write loop will stamp. Computing it only in the write loop would
+ * make every stamped pref look like "needs rewrite" forever. Absent
+ * when the stamp is withheld: a pref that has never carried the
+ * field and is not being rewritten anyway stays byte-identical, so
+ * legacy vaults keep their no-op dream guarantees.
+ */
+ readonly freshness_trend?: string;
+}
+
+/**
+ * Pref → recorded band drop within the current dream pass. Captured
+ * during refresh so the digest can render a `## Confidence drops`
+ * section without re-deriving transitions from the log.
+ */
+/**
+ * Outcome regression (t_d478df53): minimum applied-with-failure events
+ * before a preference is flagged, and the multiplicative confidence
+ * penalty a flagged preference receives. The penalty is part of the
+ * deterministic confidence derivation, so reruns stay no-ops.
+ */
+export const OUTCOME_REGRESSION_MIN_FAILURES = 2;
+export const OUTCOME_REGRESSION_PENALTY = 0.8;
+
+export interface DreamOutcomeRegression {
+ readonly id: string;
+ readonly principle: string;
+ readonly failures: number;
+ readonly successes: number;
+}
+
+export interface RefreshBandDrop {
+ readonly id: string;
+ readonly principle: string;
+ readonly previous: BrainConfidence;
+ readonly next: BrainConfidence;
+ readonly applied: number;
+ readonly violated: number;
+ readonly previous_value: number | null;
+ readonly next_value: number;
+}
+
+export interface RefreshResult {
+ /** Slugs transitioning unconfirmed → confirmed in THIS run. */
+ readonly confirmed: Set<string>;
+ /** Slug → full updated frontmatter to write. */
+ readonly updated: Map<string, RefreshUpdate>;
+ /**
+ * Preferences whose `confidence` band dropped (e.g. `high → medium`)
+ * during the refresh phase. Newest-first stable order (insertion
+ * order at construction).
+ */
+ readonly bandDrops: RefreshBandDrop[];
+ /** Preferences flagged by the outcome-regression rule (t_d478df53). */
+ readonly outcomeRegressions: DreamOutcomeRegression[];
+}
+
+export interface ApplyEvidenceEntry {
+ readonly pref_slug: string;
+ readonly timestamp: string;
+ readonly result: (typeof BRAIN_APPLY_RESULT)[keyof typeof BRAIN_APPLY_RESULT];
+ /** Downstream outcome when recorded (t_d478df53). */
+ readonly outcome?: "success" | "failure";
+}
+
+export function scanApplyEvidence(vault: string): ApplyEvidenceEntry[] {
+ const out: ApplyEvidenceEntry[] = [];
+ const mergeAliases = new Map<string, string>();
+ // Shard-aware (Memory Integrity Suite): merged per-day reads.
+ for (const date of listLogDates(vault)) {
+ const { entries } = readLogDay(vault, date);
+ for (const e of entries) {
+ if (e.eventType === BRAIN_LOG_EVENT_KIND.merge) {
+ const keep = parseWikilinkFromBodyValue(e.body["keep"]);
+ const drop = parseWikilinkFromBodyValue(e.body["drop"]);
+ if (keep?.startsWith("pref-") && drop?.startsWith("pref-")) {
+ mergeAliases.set(
+ drop.slice("pref-".length),
+ resolveMergeAlias(keep.slice("pref-".length), mergeAliases),
+ );
+ }
+ continue;
+ }
+ if (e.eventType !== BRAIN_LOG_EVENT_KIND.applyEvidence) continue;
+ const prefRaw = e.body["preference"];
+ const result = e.body["result"];
+ if (typeof prefRaw !== "string" || typeof result !== "string") continue;
+ if (
+ result !== BRAIN_APPLY_RESULT.applied &&
+ result !== BRAIN_APPLY_RESULT.violated &&
+ result !== BRAIN_APPLY_RESULT.outdated
+ )
+ continue;
+ // Parse `[[pref-slug]]` → slug.
+ const target = parseWikilink(prefRaw);
+ if (!target || !target.startsWith("pref-")) continue;
+ out.push({
+ pref_slug: target.slice("pref-".length),
+ timestamp: e.timestamp,
+ result: result as ApplyEvidenceEntry["result"],
+ ...(e.body["outcome"] === "success" || e.body["outcome"] === "failure"
+ ? { outcome: e.body["outcome"] as "success" | "failure" }
+ : {}),
+ });
+ }
+ }
+ const resolved = out.map((entry) => ({
+ ...entry,
+ pref_slug: resolveMergeAlias(entry.pref_slug, mergeAliases),
+ }));
+ // Stable order: by timestamp ascending. Multiple entries at the same
+ // second keep their parse order (parseLogDay returns insertion order).
+ resolved.sort((a, b) => Date.parse(a.timestamp) - Date.parse(b.timestamp));
+ return resolved;
+}
+
+function parseWikilinkFromBodyValue(value: unknown): string | null {
+ return typeof value === "string" ? parseWikilink(value) : null;
+}
+
+function resolveMergeAlias(slug: string, aliases: ReadonlyMap<string, string>): string {
+ let current = slug;
+ const seen = new Set<string>();
+ while (!seen.has(current)) {
+ seen.add(current);
+ const next = aliases.get(current);
+ if (!next) return current;
+ current = next;
+ }
+ return current;
+}
+
+export function planRefresh(
+ vault: string,
+ scan: ScanResult,
+ evidence: ApplyEvidenceEntry[],
+ cfg: BrainConfig,
+ now: Date,
+ plan: PlanState,
+): RefreshResult {
+ const confirmed = new Set<string>();
+ const updated = new Map<string, RefreshUpdate>();
+ const bandDrops: RefreshBandDrop[] = [];
+ const outcomeRegressions: DreamOutcomeRegression[] = [];
+
+ // Index evidence by slug.
+ const bySlug = new Map<string, ApplyEvidenceEntry[]>();
+ for (const e of evidence) {
+ const arr = bySlug.get(e.pref_slug);
+ if (arr) arr.push(e);
+ else bySlug.set(e.pref_slug, [e]);
+ }
+
+ // Slugs that will retire this run — we skip refresh for those so the
+ // retired/ snapshot reflects the pre-refresh counters (which is the
+ // existing test expectation in moveToRetired).
+ const retiringSlugs = new Set(plan.retires.map((r) => r.slug));
+
+ for (const rec of scan.preferences) {
+ const slug = rec.pref.id.startsWith("pref-") ? rec.pref.id.slice("pref-".length) : rec.pref.id;
+ if (retiringSlugs.has(slug)) continue;
+
+ const ev = bySlug.get(slug) ?? [];
+ const applied = ev.filter((e) => e.result === BRAIN_APPLY_RESULT.applied).length;
+ const violated = ev.filter((e) => e.result === BRAIN_APPLY_RESULT.violated).length;
+ const outdatedCount = ev.filter((e) => e.result === BRAIN_APPLY_RESULT.outdated).length;
+ const lastEvidence = ev.length > 0 ? ev[ev.length - 1]!.timestamp : null;
+ const firstApplied = ev.find((e) => e.result === BRAIN_APPLY_RESULT.applied);
+
+ // `outdated` is a context-driven retire signal: a single event
+ // means the rule's scope still matches but the artifact shows
+ // the rule itself is obsolete (framework migration, convention
+ // change). Pin protects against decay-based retires but NOT
+ // against context-driven ones — pinning means "I want this
+ // rule"; an `outdated` event means "context says this rule no
+ // longer applies anywhere." Honour the explicit signal.
+ //
+ // Idempotency: once retired, the pref moves to `retired/` and
+ // future dream passes don't re-process it from `preferences/`.
+ if (outdatedCount > 0) {
+ plan.retires.push({
+ slug,
+ principle: rec.pref.principle,
+ reason: BRAIN_RETIRED_REASON.supersededByContext,
+ });
+ continue;
+ }
+
+ let status = rec.pref.status;
+ let confirmedAt = rec.pref.confirmed_at;
+ if (status === BRAIN_PREFERENCE_STATUS.unconfirmed && firstApplied) {
+ status = BRAIN_PREFERENCE_STATUS.confirmed;
+ confirmedAt = firstApplied.timestamp;
+ confirmed.add(slug);
+ }
+
+ // Quarantine transitions — only applicable to already-confirmed
+ // and already-quarantined preferences. An unconfirmed pref still
+ // promotes via the firstApplied branch above; quarantine entry is
+ // measured against `confirmed` counts. Detailed semantics live on
+ // `BRAIN_PREFERENCE_STATUS.quarantine` in `types.ts`.
+ if (
+ status === BRAIN_PREFERENCE_STATUS.confirmed &&
+ violated >= applied &&
+ applied > cfg.confidence.low_max_applied
+ ) {
+ status = BRAIN_PREFERENCE_STATUS.quarantine;
+ } else if (status === BRAIN_PREFERENCE_STATUS.quarantine) {
+ const newViolated = violated > rec.pref.violated_count;
+ if (newViolated) {
+ if (isPinned(rec.pref)) {
+ plan.retainPinned.push({
+ preference: renderPrefLink({
+ id: rec.pref.id,
+ principle: rec.pref.principle,
+ }),
+ reason: BRAIN_RETIRED_REASON.quarantineViolated,
+ });
+ } else {
+ plan.retires.push({
+ slug,
+ principle: rec.pref.principle,
+ reason: BRAIN_RETIRED_REASON.quarantineViolated,
+ });
+ // Skip refresh — moveToRetired will read the on-disk
+ // counters when it builds the retired snapshot.
+ continue;
+ }
+ } else if (applied > violated) {
+ status = BRAIN_PREFERENCE_STATUS.confirmed;
+ }
+ }
+
+ const baseConfidence = computeConfidence(applied, violated, lastEvidence, cfg, now);
+
+ // Outcome regression (t_d478df53): applied events whose downstream
+ // outcome was `failure` outnumbering `success` mean the rule looks
+ // confirmed while actively hurting. The flag stages an explainable
+ // finding and a multiplicative confidence penalty - retirement
+ // still goes through the existing gates, never silently. The
+ // penalty is a pure function of the evidence, so reruns converge.
+ const appliedFailures = ev.filter(
+ (e) => e.result === BRAIN_APPLY_RESULT.applied && e.outcome === "failure",
+ ).length;
+ const appliedSuccesses = ev.filter(
+ (e) => e.result === BRAIN_APPLY_RESULT.applied && e.outcome === "success",
+ ).length;
+ const regressed =
+ appliedFailures >= OUTCOME_REGRESSION_MIN_FAILURES && appliedFailures > appliedSuccesses;
+ const confidence = regressed
+ ? rebandConfidence(
+ Math.round(baseConfidence.value * OUTCOME_REGRESSION_PENALTY * 10000) / 10000,
+ cfg,
+ )
+ : baseConfidence;
+ if (regressed) {
+ outcomeRegressions.push({
+ id: rec.pref.id,
+ principle: rec.pref.principle,
+ failures: appliedFailures,
+ successes: appliedSuccesses,
+ });
+ }
+
+ // Idempotency on a no-op rerun: skip refresh for prefs where
+ // counters AND status are unchanged AND the on-disk body already
+ // matches what we would render with current evidence. The second
+ // half (body comparison) is what carries the v0.10.1 migration
+ // forward — a pref whose counters are stable but whose body
+ // still has the v0.9.x placeholder will fail the body check and
+ // get rewritten on the next pass.
+ const previousValue = rec.pref.confidence_value;
+ // A `null` previous value (file not yet touched by dream) is
+ // treated as "matches whatever we just computed" — the
+ // body-bytes check in `wouldRewritePreference` is what triggers
+ // the write that populates the field.
+ const valueDifferent =
+ previousValue !== null && Math.abs(previousValue - confidence.value) > 1e-6;
+ const countersChanged =
+ applied !== rec.pref.applied_count ||
+ violated !== rec.pref.violated_count ||
+ lastEvidence !== rec.pref.last_evidence_at ||
+ status !== rec.pref.status ||
+ confirmedAt !== rec.pref.confirmed_at ||
+ confidence.band !== rec.pref.confidence ||
+ valueDifferent;
+
+ // Freshness trend (t_ee09a6ce): classified at PLAN time so the
+ // no-op pre-flight below and the write loop render identical
+ // bytes. The stamp is OPPORTUNISTIC: it lands when the pref is
+ // being rewritten anyway (counters changed) or already carries
+ // the field (then it refreshes on every consolidation pass, the
+ // Hindsight contract). A never-stamped pref with unchanged
+ // counters is left byte-identical so legacy vaults keep their
+ // no-op dream guarantees.
+ const stampTrend = countersChanged || rec.pref.freshness_trend !== undefined;
+ let trendLabel: string | undefined;
+ if (stampTrend) {
+ const trendEv = collectEvidenceForSlug(vault, slug, {
+ sinceIso: rec.pref.created_at,
+ maxApplied: 1000,
+ maxViolated: 1000,
+ });
+ trendLabel = classifyFreshnessTrend({
+ createdAt: rec.pref.created_at,
+ events: [...trendEv.applied, ...trendEv.violated].map((r) => ({
+ at: r.timestamp,
+ result: r.result,
+ })),
+ nowMs: now.getTime(),
+ }).trend;
+ }
+
+ const prospective = {
+ slug,
+ topic: rec.pref.topic,
+ ...(rec.pref.scope ? { scope: rec.pref.scope } : {}),
+ principle: rec.pref.principle,
+ created_at: rec.pref.created_at,
+ unconfirmed_until: rec.pref.unconfirmed_until,
+ status,
+ evidenced_by: rec.pref.evidenced_by,
+ confirmed_at: confirmedAt,
+ applied_count: applied,
+ violated_count: violated,
+ last_evidence_at: lastEvidence,
+ confidence: confidence.band,
+ confidence_value: confidence.value,
+ pinned: rec.pref.pinned,
+ ...(trendLabel !== undefined ? { freshness_trend: trendLabel } : {}),
+ };
+
+ if (!countersChanged) {
+ const ev2 = collectEvidenceForSlug(vault, slug, {
+ sinceIso: rec.pref.created_at,
+ });
+ if (
+ !wouldRewritePreference(vault, {
+ ...prospective,
+ recentApplied: ev2.applied,
+ recentViolated: ev2.violated,
+ // v0.12.0 Brain Integrity Suite: feed the existing
+ // _revision and _content_hash into the pre-flight render
+ // so the byte comparison matches the writePreferenceTxn
+ // no-op semantic. Otherwise a refreshed pref written by a
+ // prior pass (with _revision: N stamped) would look like
+ // "needs rewrite" against a prospective render that omits
+ // those fields, flipping changed=false runs into spurious
+ // updates.
+ // parsePreference defaults absent _revision to 0; treat 0
+ // the same as "absent" for the pre-flight render so the
+ // bytes-compare matches existing legacy starter files that
+ // never had the field on disk.
+ ...(rec.pref.revision !== undefined && rec.pref.revision > 0
+ ? { revision: rec.pref.revision }
+ : {}),
+ ...(rec.pref.content_hash !== undefined ? { content_hash: rec.pref.content_hash } : {}),
+ })
+ ) {
+ // Counters and body both unchanged — true no-op for this pref.
+ continue;
+ }
+ }
+
+ updated.set(slug, prospective);
+
+ // Capture band drops for the digest. A drop is any transition
+ // where the new band ranks lower than the previous (high →
+ // medium, medium → low, high → low). Stable across re-runs as
+ // long as the underlying counters do — the digest only renders
+ // it when a real transition occurred in this pass.
+ if (BAND_RANK[confidence.band] < BAND_RANK[rec.pref.confidence]) {
+ bandDrops.push(
+ Object.freeze({
+ id: rec.pref.id,
+ principle: rec.pref.principle,
+ previous: rec.pref.confidence,
+ next: confidence.band,
+ applied,
+ violated,
+ previous_value: rec.pref.confidence_value,
+ next_value: confidence.value,
+ }),
+ );
+ }
+ }
+
+ return { confirmed, updated, bandDrops, outcomeRegressions };
+}
diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.ts
index 1b39209d..479284e8 100644
--- a/src/core/brain/dream.ts
+++ b/src/core/brain/dream.ts
@@ -41,20 +41,13 @@ import { parseFrontmatter } from "../vault.ts";
import { regenerateActiveQuiet } from "./active.ts";
import { openWorkrun, WORKRUN_PHASE, type WorkrunHandle } from "./dream-workrun.ts";
import { DREAM_PHASE, type DreamPhase, type DreamPhaseSummary } from "./dream-phases.ts";
-import {
- resolveContradiction,
- type ContradictionInput,
- type ReconcileSignal,
-} from "./reconcile-domains.ts";
import { extractTemporalConstraints } from "./temporal-extract.ts";
import { runHealEnrichment } from "./heal-run.ts";
import { collectEvidenceForSlug } from "./evidence.ts";
-import { classifyFreshnessTrend } from "./temporal/freshness-trend.ts";
import { buildIntentReview, type BrainIntentReviewEntry } from "./intent-review.ts";
import { writePreferenceTxn } from "./preference-txn.ts";
import { appendLogEvent, type BrainLogEntry } from "./log.ts";
-import { listLogDates, readLogDay } from "./log-jsonl.ts";
-import { moveToRetired, parsePreference, wouldRewritePreference } from "./preference.ts";
+import { moveToRetired, parsePreference } from "./preference.ts";
import { parseSignal } from "./signal.ts";
import { isPinned } from "./pin.ts";
import { createSnapshot, pruneSnapshots } from "./snapshot.ts";
@@ -70,15 +63,31 @@ import {
} from "./paths.ts";
import { countSigns, dominantSignOf } from "./sign.ts";
import { isoDate, isoSecond } from "./time.ts";
-import { parseWikilink, renderPrefLink } from "./wikilink.ts";
import {
- BRAIN_APPLY_RESULT,
- BRAIN_CONFIDENCE,
+ emptyPlan,
+ filterWithinWindow,
+ recordSignalMove,
+ type CorruptedEntry,
+ type PlanState,
+ type PreferenceRecord,
+ type RetiredRecord,
+ type DreamQuarantinedEntry,
+ type ScanResult,
+ type SignalRecord,
+} from "./dream-plan.ts";
+import {
+ planRefresh,
+ scanApplyEvidence,
+ type DreamOutcomeRegression,
+ type RefreshResult,
+} from "./dream-refresh.ts";
+import { buildReconcileOutcomes } from "./reconcile-outcomes.ts";
+import { renderPrefLink } from "./wikilink.ts";
+import {
BRAIN_LOG_EVENT_KIND,
BRAIN_PREFERENCE_STATUS,
BRAIN_RETIRED_REASON,
BRAIN_SIGNAL_SIGN,
- type BrainConfidence,
type BrainConfig,
type BrainPreference,
type BrainRetiredReason,
@@ -115,30 +124,6 @@ export interface DreamUncertainEntry {
readonly message: string;
}
-/**
- * Entry surfacing a signal cluster that the self-approval guardrail
- * (v0.10.16) held back from promotion because one or more configured
- * thresholds were not met. Distinct from `suppressed` (which fires
- * on a user-rejected retired preference); a quarantined cluster
- * stays inbox-side and may promote on the next dream pass once
- * more evidence accumulates.
- */
-export interface DreamQuarantinedEntry {
- /** Topic slug whose signals are held below the promotion threshold. */
- readonly topic: string;
- /** Count of accumulated same-sign signals. */
- readonly signal_count: number;
- /** Number of distinct agents that raised same-sign signals. */
- readonly distinct_agents: number;
- /** Age (in days) of the earliest signal in the cluster. */
- readonly age_days: number;
- /**
- * Which threshold(s) blocked promotion: any subset of
- * `min_signals`, `min_distinct_agents`, `min_age_days`.
- */
- readonly failed_gates: ReadonlyArray<string>;
-}
-
/**
* Brain Integrity Suite (v0.12.0). Entry for a retire that the dream
* pass declined because `retire.confirmed_evidence_min_threshold` was
@@ -273,43 +258,6 @@ export interface DreamOptions {
// ----- Internal scan types ------------------------------------------------
-interface SignalRecord {
- readonly path: string;
- readonly signal: BrainSignal;
- /** True iff the file lives in `inbox/` (not `processed/`). */
- readonly active: boolean;
-}
-
-interface PreferenceRecord {
- readonly path: string;
- readonly pref: BrainPreference;
-}
-
-interface RetiredRecord {
- readonly path: string;
- readonly topic: string;
- readonly id: string;
- readonly principle: string;
- readonly scope?: string;
- /**
- * The free-form user reason passed to `o2b brain reject --reason`.
- * Presence triggers signal-suppression for future signals on the
- * same (topic, scope) — see §6 of the OSB features summary.
- */
- readonly user_rejected_reason?: string;
-}
-
-interface CorruptedEntry {
- readonly path: string;
-}
-
-interface ScanResult {
- readonly signals: SignalRecord[];
- readonly preferences: PreferenceRecord[];
- readonly retired: RetiredRecord[];
- readonly corrupted: CorruptedEntry[];
-}
-
// ----- Main entry ----------------------------------------------------------
export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
@@ -997,113 +945,6 @@ function scanBrain(vault: string): ScanResult {
// ----- Planning -----------------------------------------------------------
-interface PlanState {
- /** Topic slug → planned new unconfirmed preference. */
- readonly newUnconfirmed: NewUnconfirmedPlan[];
- /** Preferences to retire (after refresh). */
- readonly retires: RetirePlan[];
- /** Same-sign signals on active prefs → moved + log event. */
- readonly notedRedundant: NotedRedundantPlan[];
- /** Pinned prefs that would have retired but stay because pinned. */
- readonly retainPinned: RetainPinnedPlan[];
- /** Signal id → record to move out of inbox/. */
- readonly signalsToMove: Map<string, SignalMovePlan>;
- /** Topic slugs flagged contradicted but no transition this run. */
- readonly contradictionTopics: Set<string>;
- /**
- * Signals dropped because their (topic, scope) matches a user-rejected
- * retired pref carrying a `user_rejected_reason`. Each entry produces
- * one `signal-suppressed` log event AND a move into `processed/` so
- * the inbox does not accumulate.
- */
- readonly signalsSuppressed: SignalSuppressedPlan[];
- /**
- * Signal clusters held back from promotion by the self-approval
- * guardrail (v0.10.16). The cluster passed the existing
- * `candidate_threshold` but failed one or more configured
- * thresholds in `BrainGuardrailConfig`. Preserved across the plan
- * so it surfaces on the DreamRunSummary without affecting the
- * existing move-to-processed semantics.
- */
- readonly quarantined: DreamQuarantinedEntry[];
-}
-
-interface SignalSuppressedPlan {
- readonly signal: string;
- /** Pre-rendered `[[ret-slug|principle]]` wikilink for the suppressor. */
- readonly retired: string;
- readonly reason: string;
- readonly topic: string;
-}
-
-interface NewUnconfirmedPlan {
- readonly slug: string;
- readonly topic: string;
- readonly scope: string | undefined;
- readonly principle: string;
- readonly evidencedBy: ReadonlyArray<string>;
- readonly sign: BrainSignalSign;
- /**
- * Wikilink string (`[[ret-<slug>]]` or `[[pref-<slug>]]`) to the
- * preference this new entry supersedes, if any. Threaded through to
- * `writePreference` so the resulting frontmatter carries
- * `supersedes:` for audit-trail continuity across rebuttals.
- */
- readonly supersedes?: string;
- /**
- * Brain lifecycle suite (F5). Bi-temporal validity derived from the
- * source signal at plan time (explicit signal fields preferred, else
- * extracted from the signal's ISO temporal text). Threaded to the
- * preference writer on promotion.
- */
- readonly valid_from?: string;
- readonly valid_until?: string;
-}
-
-interface RetirePlan {
- readonly slug: string;
- /**
- * Principle of the preference being retired, captured at plan time
- * so the dream summary log payload can render a titled wikilink
- * (`[[ret-slug|principle]]`) without re-reading the file after move.
- */
- readonly principle: string;
- readonly reason: BrainRetiredReason;
- readonly supersededBy?: string;
-}
-
-interface NotedRedundantPlan {
- /** Pre-rendered `[[pref-id|principle]]` wikilink for the active pref. */
- readonly preference: string;
- readonly signal: string;
-}
-
-interface RetainPinnedPlan {
- /** Pre-rendered `[[pref-id|principle]]` wikilink for the pinned pref. */
- readonly preference: string;
- readonly reason: BrainRetiredReason;
-}
-
-interface SignalMovePlan {
- readonly id: string;
- readonly date: string;
- readonly slug: string;
- readonly path: string;
-}
-
-function emptyPlan(): PlanState {
- return {
- newUnconfirmed: [],
- retires: [],
- notedRedundant: [],
- retainPinned: [],
- signalsToMove: new Map(),
- contradictionTopics: new Set(),
- signalsSuppressed: [],
- quarantined: [],
- };
-}
-
function planTopics(
scan: ScanResult,
cfg: BrainConfig,
@@ -1449,29 +1290,6 @@ function allocatePreferencePlanSlug(base: string, reserved: Set<string>): string
return candidate;
}
-function recordSignalMove(plan: PlanState, rec: SignalRecord): void {
- if (!rec.active) return;
- const id = rec.signal.id;
- if (plan.signalsToMove.has(id)) return;
- // Derive date + slug from the id (`sig-YYYY-MM-DD-<slug>`).
- const m = /^sig-(\d{4}-\d{2}-\d{2})-(.+)$/.exec(id);
- if (!m) return;
- plan.signalsToMove.set(id, {
- id,
- date: m[1]!,
- slug: m[2]!,
- path: rec.path,
- });
-}
-
-function filterWithinWindow(sigs: SignalRecord[], windowDays: number, now: Date): SignalRecord[] {
- const minTime = now.getTime() - windowDays * 24 * 3600 * 1000;
- return sigs.filter((s) => {
- const t = Date.parse(s.signal.created_at);
- return Number.isFinite(t) && t >= minTime;
- });
-}
-
/**
* Brain lifecycle suite (F5). Derive a preference's bi-temporal validity
* from the source signal: prefer the signal's explicit `valid_from` /
@@ -1498,581 +1316,8 @@ function phaseSummary(phase: DreamPhase, metrics: Record<string, number>): Dream
return { phase, metrics };
}
-/** Project a scanned signal onto the minimal reconcile view. */
-function toReconcileSignal(r: SignalRecord): ReconcileSignal {
- return {
- created_at: r.signal.created_at,
- ...(r.signal.recorded_at ? { recorded_at: r.signal.recorded_at } : {}),
- ...(r.signal.source ? { source: r.signal.source } : {}),
- };
-}
-
-// ----- Reconcile (F3) ------------------------------------------------------
-
-interface ReconcileAutoResolved {
- readonly topic: string;
- readonly domain: "source-freshness";
- readonly winner_sign: "positive" | "negative";
- readonly margin_days: number;
-}
-
-interface ReconcileOutcomes {
- readonly openQuestions: DreamOpenQuestion[];
- readonly autoResolved: ReconcileAutoResolved[];
-}
-
-/**
- * Classify every contradiction topic the plan flagged into a domain and
- * decide its outcome. Source-freshness contradictions where the fresher
- * side leads by at least half the contradiction window auto-resolve
- * (recorded only - never a sub-threshold mutation); the rest become
- * operator-facing open questions. Pure; emits nothing.
- */
-function buildReconcileOutcomes(
- scan: ScanResult,
- plan: PlanState,
- cfg: BrainConfig,
- now: Date,
-): ReconcileOutcomes {
- const openQuestions: DreamOpenQuestion[] = [];
- const autoResolved: ReconcileAutoResolved[] = [];
- if (plan.contradictionTopics.size === 0) return { openQuestions, autoResolved };
-
- const windowDays = cfg.dream.contradiction_window_days;
- // Freshness must be decisive WITHIN the contradiction window, so the
- // margin is half the window (a gap larger than the window would have
- // excluded the older signal from the contradiction in the first place).
- const freshnessMarginDays = Math.max(1, Math.ceil(windowDays / 2));
-
- const byTopic = new Map<string, SignalRecord[]>();
- for (const rec of scan.signals) {
- const arr = byTopic.get(rec.signal.topic);
- if (arr) arr.push(rec);
- else byTopic.set(rec.signal.topic, [rec]);
- }
-
- for (const topic of plan.contradictionTopics) {
- const sigs = filterWithinWindow(byTopic.get(topic) ?? [], windowDays, now);
- const positives = sigs
- .filter((s) => s.signal.signal === BRAIN_SIGNAL_SIGN.positive)
- .map(toReconcileSignal);
- const negatives = sigs
- .filter((s) => s.signal.signal === BRAIN_SIGNAL_SIGN.negative)
- .map(toReconcileSignal);
- const scope = sigs.find((s) => s.signal.scope)?.signal.scope;
- const input: ContradictionInput = {
- topic,
- ...(scope ? { scope } : {}),
- positives,
- negatives,
- };
- const outcome = resolveContradiction(input, { now, freshnessMarginDays });
- if (outcome.kind === "auto-resolved") {
- autoResolved.push({
- topic,
- domain: outcome.domain,
- winner_sign: outcome.winner_sign,
- margin_days: outcome.margin_days,
- });
- } else {
- openQuestions.push(outcome.question);
- }
- }
- return { openQuestions, autoResolved };
-}
-
// ----- Refresh + promote --------------------------------------------------
-interface RefreshUpdate {
- readonly slug: string;
- readonly topic: string;
- readonly scope?: string;
- readonly principle: string;
- readonly created_at: string;
- readonly unconfirmed_until: string;
- readonly status: (typeof BRAIN_PREFERENCE_STATUS)[keyof typeof BRAIN_PREFERENCE_STATUS];
- readonly evidenced_by: ReadonlyArray<string>;
- readonly confirmed_at: string | null;
- readonly applied_count: number;
- readonly violated_count: number;
- readonly last_evidence_at: string | null;
- readonly confidence: BrainConfidence;
- readonly confidence_value: number;
- readonly pinned: boolean;
- /**
- * Freshness trend (t_ee09a6ce), computed at PLAN time so the no-op
- * pre-flight (`wouldRewritePreference`) renders the same bytes the
- * write loop will stamp. Computing it only in the write loop would
- * make every stamped pref look like "needs rewrite" forever. Absent
- * when the stamp is withheld: a pref that has never carried the
- * field and is not being rewritten anyway stays byte-identical, so
- * legacy vaults keep their no-op dream guarantees.
- */
- readonly freshness_trend?: string;
-}
-
-/**
- * Pref → recorded band drop within the current dream pass. Captured
- * during refresh so the digest can render a `## Confidence drops`
- * section without re-deriving transitions from the log.
- */
-/**
- * Outcome regression (t_d478df53): minimum applied-with-failure events
- * before a preference is flagged, and the multiplicative confidence
- * penalty a flagged preference receives. The penalty is part of the
- * deterministic confidence derivation, so reruns stay no-ops.
- */
-export const OUTCOME_REGRESSION_MIN_FAILURES = 2;
-export const OUTCOME_REGRESSION_PENALTY = 0.8;
-
-export interface DreamOutcomeRegression {
- readonly id: string;
- readonly principle: string;
- readonly failures: number;
- readonly successes: number;
-}
-
-export interface RefreshBandDrop {
- readonly id: string;
- readonly principle: string;
- readonly previous: BrainConfidence;
- readonly next: BrainConfidence;
- readonly applied: number;
- readonly violated: number;
- readonly previous_value: number | null;
- readonly next_value: number;
-}
-
-interface RefreshResult {
- /** Slugs transitioning unconfirmed → confirmed in THIS run. */
- readonly confirmed: Set<string>;
- /** Slug → full updated frontmatter to write. */
- readonly updated: Map<string, RefreshUpdate>;
- /**
- * Preferences whose `confidence` band dropped (e.g. `high → medium`)
- * during the refresh phase. Newest-first stable order (insertion
- * order at construction).
- */
- readonly bandDrops: RefreshBandDrop[];
- /** Preferences flagged by the outcome-regression rule (t_d478df53). */
- readonly outcomeRegressions: DreamOutcomeRegression[];
-}
-
-interface ApplyEvidenceEntry {
- readonly pref_slug: string;
- readonly timestamp: string;
- readonly result: (typeof BRAIN_APPLY_RESULT)[keyof typeof BRAIN_APPLY_RESULT];
- /** Downstream outcome when recorded (t_d478df53). */
- readonly outcome?: "success" | "failure";
-}
-
-function scanApplyEvidence(vault: string): ApplyEvidenceEntry[] {
- const out: ApplyEvidenceEntry[] = [];
- const mergeAliases = new Map<string, string>();
- // Shard-aware (Memory Integrity Suite): merged per-day reads.
- for (const date of listLogDates(vault)) {
- const { entries } = readLogDay(vault, date);
- for (const e of entries) {
- if (e.eventType === BRAIN_LOG_EVENT_KIND.merge) {
- const keep = parseWikilinkFromBodyValue(e.body["keep"]);
- const drop = parseWikilinkFromBodyValue(e.body["drop"]);
- if (keep?.startsWith("pref-") && drop?.startsWith("pref-")) {
- mergeAliases.set(
- drop.slice("pref-".length),
- resolveMergeAlias(keep.slice("pref-".length), mergeAliases),
- );
- }
- continue;
- }
- if (e.eventType !== BRAIN_LOG_EVENT_KIND.applyEvidence) continue;
- const prefRaw = e.body["preference"];
- const result = e.body["result"];
- if (typeof prefRaw !== "string" || typeof result !== "string") continue;
- if (
- result !== BRAIN_APPLY_RESULT.applied &&
- result !== BRAIN_APPLY_RESULT.violated &&
- result !== BRAIN_APPLY_RESULT.outdated
- )
- continue;
- // Parse `[[pref-slug]]` → slug.
- const target = parseWikilink(prefRaw);
- if (!target || !target.startsWith("pref-")) continue;
- out.push({
- pref_slug: target.slice("pref-".length),
- timestamp: e.timestamp,
- result: result as ApplyEvidenceEntry["result"],
- ...(e.body["outcome"] === "success" || e.body["outcome"] === "failure"
- ? { outcome: e.body["outcome"] as "success" | "failure" }
- : {}),
- });
- }
- }
- const resolved = out.map((entry) => ({
- ...entry,
- pref_slug: resolveMergeAlias(entry.pref_slug, mergeAliases),
- }));
- // Stable order: by timestamp ascending. Multiple entries at the same
- // second keep their parse order (parseLogDay returns insertion order).
- resolved.sort((a, b) => Date.parse(a.timestamp) - Date.parse(b.timestamp));
- return resolved;
-}
-
-function parseWikilinkFromBodyValue(value: unknown): string | null {
- return typeof value === "string" ? parseWikilink(value) : null;
-}
-
-function resolveMergeAlias(slug: string, aliases: ReadonlyMap<string, string>): string {
- let current = slug;
- const seen = new Set<string>();
- while (!seen.has(current)) {
- seen.add(current);
- const next = aliases.get(current);
- if (!next) return current;
- current = next;
- }
- return current;
-}
-
-function planRefresh(
- vault: string,
- scan: ScanResult,
- evidence: ApplyEvidenceEntry[],
- cfg: BrainConfig,
- now: Date,
- plan: PlanState,
-): RefreshResult {
- const confirmed = new Set<string>();
- const updated = new Map<string, RefreshUpdate>();
- const bandDrops: RefreshBandDrop[] = [];
- const outcomeRegressions: DreamOutcomeRegression[] = [];
-
- // Index evidence by slug.
- const bySlug = new Map<string, ApplyEvidenceEntry[]>();
- for (const e of evidence) {
- const arr = bySlug.get(e.pref_slug);
- if (arr) arr.push(e);
- else bySlug.set(e.pref_slug, [e]);
- }
-
- // Slugs that will retire this run — we skip refresh for those so the
- // retired/ snapshot reflects the pre-refresh counters (which is the
- // existing test expectation in moveToRetired).
- const retiringSlugs = new Set(plan.retires.map((r) => r.slug));
-
- for (const rec of scan.preferences) {
- const slug = rec.pref.id.startsWith("pref-") ? rec.pref.id.slice("pref-".length) : rec.pref.id;
- if (retiringSlugs.has(slug)) continue;
-
- const ev = bySlug.get(slug) ?? [];
- const applied = ev.filter((e) => e.result === BRAIN_APPLY_RESULT.applied).length;
- const violated = ev.filter((e) => e.result === BRAIN_APPLY_RESULT.violated).length;
- const outdatedCount = ev.filter((e) => e.result === BRAIN_APPLY_RESULT.outdated).length;
- const lastEvidence = ev.length > 0 ? ev[ev.length - 1]!.timestamp : null;
- const firstApplied = ev.find((e) => e.result === BRAIN_APPLY_RESULT.applied);
-
- // `outdated` is a context-driven retire signal: a single event
- // means the rule's scope still matches but the artifact shows
- // the rule itself is obsolete (framework migration, convention
- // change). Pin protects against decay-based retires but NOT
- // against context-driven ones — pinning means "I want this
- // rule"; an `outdated` event means "context says this rule no
- // longer applies anywhere." Honour the explicit signal.
- //
- // Idempotency: once retired, the pref moves to `retired/` and
- // future dream passes don't re-process it from `preferences/`.
- if (outdatedCount > 0) {
- plan.retires.push({
- slug,
- principle: rec.pref.principle,
- reason: BRAIN_RETIRED_REASON.supersededByContext,
- });
- continue;
- }
-
- let status = rec.pref.status;
- let confirmedAt = rec.pref.confirmed_at;
- if (status === BRAIN_PREFERENCE_STATUS.unconfirmed && firstApplied) {
- status = BRAIN_PREFERENCE_STATUS.confirmed;
- confirmedAt = firstApplied.timestamp;
- confirmed.add(slug);
- }
-
- // Quarantine transitions — only applicable to already-confirmed
- // and already-quarantined preferences. An unconfirmed pref still
- // promotes via the firstApplied branch above; quarantine entry is
- // measured against `confirmed` counts. Detailed semantics live on
- // `BRAIN_PREFERENCE_STATUS.quarantine` in `types.ts`.
- if (
- status === BRAIN_PREFERENCE_STATUS.confirmed &&
- violated >= applied &&
- applied > cfg.confidence.low_max_applied
- ) {
- status = BRAIN_PREFERENCE_STATUS.quarantine;
- } else if (status === BRAIN_PREFERENCE_STATUS.quarantine) {
- const newViolated = violated > rec.pref.violated_count;
- if (newViolated) {
- if (isPinned(rec.pref)) {
- plan.retainPinned.push({
- preference: renderPrefLink({
- id: rec.pref.id,
- principle: rec.pref.principle,
- }),
- reason: BRAIN_RETIRED_REASON.quarantineViolated,
- });
- } else {
- plan.retires.push({
- slug,
- principle: rec.pref.principle,
- reason: BRAIN_RETIRED_REASON.quarantineViolated,
- });
- // Skip refresh — moveToRetired will read the on-disk
- // counters when it builds the retired snapshot.
- continue;
- }
- } else if (applied > violated) {
- status = BRAIN_PREFERENCE_STATUS.confirmed;
- }
- }
-
- const baseConfidence = computeConfidence(applied, violated, lastEvidence, cfg, now);
-
- // Outcome regression (t_d478df53): applied events whose downstream
- // outcome was `failure` outnumbering `success` mean the rule looks
- // confirmed while actively hurting. The flag stages an explainable
- // finding and a multiplicative confidence penalty - retirement
- // still goes through the existing gates, never silently. The
- // penalty is a pure function of the evidence, so reruns converge.
- const appliedFailures = ev.filter(
- (e) => e.result === BRAIN_APPLY_RESULT.applied && e.outcome === "failure",
- ).length;
- const appliedSuccesses = ev.filter(
- (e) => e.result === BRAIN_APPLY_RESULT.applied && e.outcome === "success",
- ).length;
- const regressed =
- appliedFailures >= OUTCOME_REGRESSION_MIN_FAILURES && appliedFailures > appliedSuccesses;
- const confidence = regressed
- ? rebandConfidence(
- Math.round(baseConfidence.value * OUTCOME_REGRESSION_PENALTY * 10000) / 10000,
- cfg,
- )
- : baseConfidence;
- if (regressed) {
- outcomeRegressions.push({
- id: rec.pref.id,
- principle: rec.pref.principle,
- failures: appliedFailures,
- successes: appliedSuccesses,
- });
- }
-
- // Idempotency on a no-op rerun: skip refresh for prefs where
- // counters AND status are unchanged AND the on-disk body already
- // matches what we would render with current evidence. The second
- // half (body comparison) is what carries the v0.10.1 migration
- // forward — a pref whose counters are stable but whose body
- // still has the v0.9.x placeholder will fail the body check and
- // get rewritten on the next pass.
- const previousValue = rec.pref.confidence_value;
- // A `null` previous value (file not yet touched by dream) is
- // treated as "matches whatever we just computed" — the
- // body-bytes check in `wouldRewritePreference` is what triggers
- // the write that populates the field.
- const valueDifferent =
- previousValue !== null && Math.abs(previousValue - confidence.value) > 1e-6;
- const countersChanged =
- applied !== rec.pref.applied_count ||
- violated !== rec.pref.violated_count ||
- lastEvidence !== rec.pref.last_evidence_at ||
- status !== rec.pref.status ||
- confirmedAt !== rec.pref.confirmed_at ||
- confidence.band !== rec.pref.confidence ||
- valueDifferent;
-
- // Freshness trend (t_ee09a6ce): classified at PLAN time so the
- // no-op pre-flight below and the write loop render identical
- // bytes. The stamp is OPPORTUNISTIC: it lands when the pref is
- // being rewritten anyway (counters changed) or already carries
- // the field (then it refreshes on every consolidation pass, the
- // Hindsight contract). A never-stamped pref with unchanged
- // counters is left byte-identical so legacy vaults keep their
- // no-op dream guarantees.
- const stampTrend = countersChanged || rec.pref.freshness_trend !== undefined;
- let trendLabel: string | undefined;
- if (stampTrend) {
- const trendEv = collectEvidenceForSlug(vault, slug, {
- sinceIso: rec.pref.created_at,
- maxApplied: 1000,
- maxViolated: 1000,
- });
- trendLabel = classifyFreshnessTrend({
- createdAt: rec.pref.created_at,
- events: [...trendEv.applied, ...trendEv.violated].map((r) => ({
- at: r.timestamp,
- result: r.result,
- })),
- nowMs: now.getTime(),
- }).trend;
- }
-
- const prospective = {
- slug,
- topic: rec.pref.topic,
- ...(rec.pref.scope ? { scope: rec.pref.scope } : {}),
- principle: rec.pref.principle,
- created_at: rec.pref.created_at,
- unconfirmed_until: rec.pref.unconfirmed_until,
- status,
- evidenced_by: rec.pref.evidenced_by,
- confirmed_at: confirmedAt,
- applied_count: applied,
- violated_count: violated,
- last_evidence_at: lastEvidence,
- confidence: confidence.band,
- confidence_value: confidence.value,
- pinned: rec.pref.pinned,
- ...(trendLabel !== undefined ? { freshness_trend: trendLabel } : {}),
- };
-
- if (!countersChanged) {
- const ev2 = collectEvidenceForSlug(vault, slug, {
- sinceIso: rec.pref.created_at,
- });
- if (
- !wouldRewritePreference(vault, {
- ...prospective,
- recentApplied: ev2.applied,
- recentViolated: ev2.violated,
- // v0.12.0 Brain Integrity Suite: feed the existing
- // _revision and _content_hash into the pre-flight render
- // so the byte comparison matches the writePreferenceTxn
- // no-op semantic. Otherwise a refreshed pref written by a
- // prior pass (with _revision: N stamped) would look like
- // "needs rewrite" against a prospective render that omits
- // those fields, flipping changed=false runs into spurious
- // updates.
- // parsePreference defaults absent _revision to 0; treat 0
- // the same as "absent" for the pre-flight render so the
- // bytes-compare matches existing legacy starter files that
- // never had the field on disk.
- ...(rec.pref.revision !== undefined && rec.pref.revision > 0
- ? { revision: rec.pref.revision }
- : {}),
- ...(rec.pref.content_hash !== undefined ? { content_hash: rec.pref.content_hash } : {}),
- })
- ) {
- // Counters and body both unchanged — true no-op for this pref.
- continue;
- }
- }
-
- updated.set(slug, prospective);
-
- // Capture band drops for the digest. A drop is any transition
- // where the new band ranks lower than the previous (high →
- // medium, medium → low, high → low). Stable across re-runs as
- // long as the underlying counters do — the digest only renders
- // it when a real transition occurred in this pass.
- if (BAND_RANK[confidence.band] < BAND_RANK[rec.pref.confidence]) {
- bandDrops.push(
- Object.freeze({
- id: rec.pref.id,
- principle: rec.pref.principle,
- previous: rec.pref.confidence,
- next: confidence.band,
- applied,
- violated,
- previous_value: rec.pref.confidence_value,
- next_value: confidence.value,
- }),
- );
- }
- }
-
- return { confirmed, updated, bandDrops, outcomeRegressions };
-}
-
-/**
- * Confidence computation. Returns both the numeric value and the
- * categorical band derived from it.
- *
- * `value = wilson_low(applied, n) * freshness`:
- *
- * - `wilson_low(applied, n)` where `n = applied + violated` -
- * a conservative 95% lower bound on the application rate.
- * `n == 0` yields `0`.
- * - `freshness` linearly decays from `1.0` at age 0 to `0.0` at
- * `retire.stale_evidence_days`. `null` last_evidence_at → `0`.
- *
- * Band thresholds (`confidence.medium_min`, `confidence.high_min`)
- * are applied to `value` directly. The numeric value is what the
- * digest's drop tracker compares across runs.
- */
-export interface ConfidenceComputeResult {
- readonly value: number;
- readonly band: BrainConfidence;
-}
-
-const BAND_RANK: Readonly<Record<BrainConfidence, number>> = Object.freeze({
- low: 0,
- medium: 1,
- high: 2,
-});
-
-export function computeConfidence(
- applied: number,
- violated: number,
- lastEvidenceAt: string | null,
- cfg: BrainConfig,
- now: Date,
-): ConfidenceComputeResult {
- const n = applied + violated;
- let wilsonLow = 0;
- if (n > 0) {
- const z = 1.96;
- const z2 = z * z;
- const pHat = applied / n;
- const denom = 1 + z2 / n;
- const centre = (pHat + z2 / (2 * n)) / denom;
- const margin = (z * Math.sqrt((pHat * (1 - pHat)) / n + z2 / (4 * n * n))) / denom;
- wilsonLow = Math.max(0, centre - margin);
- }
- let freshness = 0;
- if (lastEvidenceAt) {
- const ageMs = now.getTime() - Date.parse(lastEvidenceAt);
- if (Number.isFinite(ageMs)) {
- const limitMs = cfg.retire.stale_evidence_days * 24 * 3600 * 1000;
- if (limitMs > 0) {
- freshness = Math.max(0, Math.min(1, 1 - ageMs / limitMs));
- }
- }
- }
- const rawValue = wilsonLow * freshness;
- const value = Math.round(rawValue * 10000) / 10000;
-
- let band: BrainConfidence;
- if (value >= cfg.confidence.high_min) {
- band = BRAIN_CONFIDENCE.high;
- } else if (value >= cfg.confidence.medium_min) {
- band = BRAIN_CONFIDENCE.medium;
- } else {
- band = BRAIN_CONFIDENCE.low;
- }
- return Object.freeze({ value, band });
-}
-
-/** Re-derive the confidence band for an externally adjusted value. */
-function rebandConfidence(value: number, cfg: BrainConfig): ConfidenceComputeResult {
- let band: BrainConfidence;
- if (value >= cfg.confidence.high_min) {
- band = BRAIN_CONFIDENCE.high;
- } else if (value >= cfg.confidence.medium_min) {
- band = BRAIN_CONFIDENCE.medium;
- } else {
- band = BRAIN_CONFIDENCE.low;
- }
- return Object.freeze({ value, band });
-}
-
// ----- Auto-retires (expired-unconfirmed, stale-no-evidence) --------------
function planAutoRetires(
diff --git a/src/core/brain/index.ts b/src/core/brain/index.ts
index cb4a9bdd..15adb286 100644
--- a/src/core/brain/index.ts
+++ b/src/core/brain/index.ts
@@ -97,8 +97,8 @@ export {
loadBrainConfigDetailed,
validateBrainConfig,
validateBrainConfigDetailed,
- parseBrainYaml,
} from "./policy.ts";
+export { parseBrainYaml } from "./yaml-parse.ts";
export type { BrainConfigLoadWarning, LoadBrainConfigResult, ValidateResult } from "./policy.ts";
diff --git a/src/core/brain/link-graph/format-wikilink.ts b/src/core/brain/link-graph/format-wikilink.ts
index 59315ea8..1acb7b59 100644
--- a/src/core/brain/link-graph/format-wikilink.ts
+++ b/src/core/brain/link-graph/format-wikilink.ts
@@ -35,7 +35,8 @@ export function isWikiLinkFormat(value: string): value is WikiLinkFormat {
/** Mirrors the masks used by the link-graph parser, broadened for the
* rewrite path: backtick fences of any length (3+), tilde fences, and
* inline code spans all stay verbatim. */
-const RICH_WIKILINK_RE = /\[\[([^\]\n]+)\]\]/g;
+import { RICH_WIKILINK_RE } from "../wikilink.ts";
+
const CODE_BLOCK_RE = /(`{3,}|~{3,})[\s\S]*?\1|`[^`]+`/g;
export interface NormalizeResult {
diff --git a/src/core/brain/link-graph/parse-wikilink.ts b/src/core/brain/link-graph/parse-wikilink.ts
index 953e5c6c..4f0bc795 100644
--- a/src/core/brain/link-graph/parse-wikilink.ts
+++ b/src/core/brain/link-graph/parse-wikilink.ts
@@ -29,6 +29,8 @@
import { basename } from "node:path";
+import { ANCHORED_WIKILINK_RE, RICH_WIKILINK_RE } from "../wikilink.ts";
+
/**
* Local regex for the rich extractor. Captures the full bracket
* body (everything between `[[` and `]]`), so anchor / alias / block
@@ -38,7 +40,6 @@ import { basename } from "node:path";
* don't collapse two adjacent wikilinks into one match. Anchored to
* non-newline so a link that spans lines is not silently joined.
*/
-const RICH_WIKILINK_RE = /\[\[([^\]\n]+)\]\]/g;
/**
* Local mask for fenced and inline code spans. Mirrors the constant
@@ -120,7 +121,7 @@ export function parseWikilinkRich(value: string): WikilinkParse {
// Strip surrounding wikilink brackets when present. Bare-text input
// skips this branch and goes straight to the decoration-strip
// pipeline.
- const wm = /^\[\[([^\]]+)\]\]/.exec(s);
+ const wm = ANCHORED_WIKILINK_RE.exec(s);
if (wm) s = wm[1]!.trim();
// Pull alias FIRST. The pipe separator binds tighter than the hash
diff --git a/src/core/brain/lint-consolidate.ts b/src/core/brain/lint-consolidate.ts
index c841f7e4..20dd396b 100644
--- a/src/core/brain/lint-consolidate.ts
+++ b/src/core/brain/lint-consolidate.ts
@@ -23,6 +23,7 @@ import { join } from "node:path";
import { atomicWriteFileSync } from "../fs-atomic.ts";
import { parseFrontmatter } from "../vault.ts";
+import { WIKILINK_TARGET_RE } from "./wikilink.ts";
import { BRAIN_ROOT_REL, brainDirs } from "./paths.ts";
import {
PAGE_LIFECYCLE,
@@ -88,15 +89,13 @@ function buildMergeMap(vault: string): MergeMap {
return Object.freeze({ forward });
}
-const WIKILINK_RE = /\[\[([^\]|#]+)([#|][^\]]*)?\]\]/g;
-
function scanFileForMergedLinks(
path: string,
raw: string,
merge: MergeMap,
): { fixes: LintFix[]; rewritten: string } {
const fixes: LintFix[] = [];
- const rewritten = raw.replace(WIKILINK_RE, (match, target, suffix) => {
+ const rewritten = raw.replace(WIKILINK_TARGET_RE, (match, target, suffix) => {
const canonical = merge.forward.get(target);
if (!canonical) return match;
fixes.push({ kind: "fix-merged-link", path, from: target, to: canonical });
diff --git a/src/core/brain/policy.ts b/src/core/brain/policy.ts
index 29848992..65502e36 100644
--- a/src/core/brain/policy.ts
+++ b/src/core/brain/policy.ts
@@ -20,6 +20,7 @@
*/
import { existsSync, readFileSync } from "node:fs";
+import { parseBrainYaml, type ParsedBlock } from "./yaml-parse.ts";
import type {
BrainActiveConfig,
@@ -1593,279 +1594,3 @@ function describe(value: unknown): string {
if (typeof value === "object") return "object";
return `${typeof value}(${JSON.stringify(value)})`;
}
-
-// ----- Minimal indent-aware YAML parser ------------------------------------
-//
-// The parser handles only the shape used by `_brain.yaml`:
-//
-// - `# comment` lines and blanks
-// - top-level `key: <scalar>`
-// - top-level `key:` followed by an indented block of one indent level
-// - block-level `<indent>key: <scalar>`
-//
-// Scalars are parsed as:
-// - plain integers / floats (no exponents, no leading +)
-// - quoted strings ('..' or "..") — the quotes are stripped and the
-// content is taken as-is (no escape sequences)
-// - the bare words `true`, `false`, `null`
-// - otherwise: the literal string
-//
-// This intentionally rejects nested mappings deeper than two levels,
-// anchors, and aliases — none of which the schema needs.
-
-type ParsedScalar = number | string | boolean | null;
-type ParsedBlockValue =
- | ParsedScalar
- | Record<string, ParsedScalar | ParsedScalar[]>
- | ParsedScalar[];
-type ParsedBlock = Record<string, ParsedBlockValue>;
-
-interface Line {
- readonly raw: string;
- readonly indent: number;
- readonly content: string;
- readonly lineNumber: number;
-}
-
-export function parseBrainYaml(text: string): ParsedBlock {
- const lines = splitLines(text);
- const out: ParsedBlock = {};
- let i = 0;
- while (i < lines.length) {
- const line = lines[i]!;
- if (line.indent !== 0) {
- throw new Error(`line ${line.lineNumber}: unexpected indentation at top level`);
- }
- const kv = splitKeyValue(line);
- if (kv.value === "") {
- // Block header: collect indented children.
- // Each child may be a scalar value (`key: val`) or a list (`key:` followed
- // by deeper-indented `- item` lines). Lists-within-blocks are the only
- // third-level nesting we support — they are required for `discipline_report`.
- const child: Record<string, ParsedScalar | ParsedScalar[]> = {};
- i++;
- const blockIndent = detectBlockIndent(lines, i);
- while (i < lines.length && lines[i]!.indent >= blockIndent && blockIndent > 0) {
- const inner = lines[i]!;
- if (inner.indent !== blockIndent) {
- throw new Error(
- `line ${inner.lineNumber}: inconsistent indentation in block '${kv.key}' ` +
- `(expected ${blockIndent} spaces, got ${inner.indent})`,
- );
- }
- const innerKv = splitKeyValue(inner);
- if (innerKv.value === "") {
- // Child key with no value — expect a list of `- item` lines at a
- // deeper indent level.
- i++;
- const listIndent = detectBlockIndent(lines, i);
- if (listIndent <= blockIndent) {
- // Empty list (next line is at the same or shallower indent).
- if (innerKv.key in child) {
- throw new Error(
- `line ${inner.lineNumber}: duplicate key '${innerKv.key}' in block '${kv.key}'`,
- );
- }
- child[innerKv.key] = [];
- continue;
- }
- const items: ParsedScalar[] = [];
- while (i < lines.length && lines[i]!.indent >= listIndent) {
- const listLine = lines[i]!;
- if (listLine.indent !== listIndent) {
- throw new Error(
- `line ${listLine.lineNumber}: inconsistent indentation in list '${innerKv.key}' ` +
- `(expected ${listIndent} spaces, got ${listLine.indent})`,
- );
- }
- if (!listLine.content.startsWith("- ") && listLine.content !== "-") {
- // If it looks like a `key: value` pair, it's a deeper block — not
- // supported. Preserve the original error message so existing tests
- // that assert on the wording keep passing.
- if (/^[A-Za-z_][A-Za-z0-9_-]*\s*:/.test(listLine.content)) {
- throw new Error(
- `line ${listLine.lineNumber}: nested blocks deeper than one level are not supported`,
- );
- }
- throw new Error(
- `line ${listLine.lineNumber}: expected list item starting with '- ' ` +
- `in '${kv.key}.${innerKv.key}'`,
- );
- }
- const itemText = listLine.content.startsWith("- ")
- ? listLine.content.slice(2).trim()
- : "";
- const item = parseScalar(itemText, listLine.lineNumber);
- if (Array.isArray(item)) {
- throw new Error(
- `line ${listLine.lineNumber}: nested inline arrays are not supported`,
- );
- }
- items.push(item);
- i++;
- }
- if (innerKv.key in child) {
- throw new Error(
- `line ${inner.lineNumber}: duplicate key '${innerKv.key}' in block '${kv.key}'`,
- );
- }
- child[innerKv.key] = items;
- continue;
- }
- if (innerKv.key in child) {
- throw new Error(
- `line ${inner.lineNumber}: duplicate key '${innerKv.key}' in block '${kv.key}'`,
- );
- }
- child[innerKv.key] = parseScalar(innerKv.value, inner.lineNumber);
- i++;
- }
- if (kv.key in out) {
- throw new Error(`duplicate top-level key '${kv.key}'`);
- }
- out[kv.key] = child;
- continue;
- }
- if (kv.key in out) {
- throw new Error(`duplicate top-level key '${kv.key}'`);
- }
- out[kv.key] = parseScalar(kv.value, line.lineNumber);
- i++;
- }
- return out;
-}
-
-function splitLines(text: string): Line[] {
- const out: Line[] = [];
- let lineNumber = 0;
- for (const raw of text.split(/\r?\n/)) {
- lineNumber++;
- // Strip trailing whitespace; leave leading intact for indent detection.
- const stripped = raw.replace(/\s+$/, "");
- // Skip blanks and comment-only lines.
- if (stripped.trim() === "") continue;
- if (stripped.trimStart().startsWith("#")) continue;
- // Strip inline comments only when they are clearly outside a quoted
- // value. Keep this simple: only honour ` #` (space then hash) on
- // unquoted lines. Quoted values keep their content verbatim.
- let content = stripped;
- if (!/['"]/.test(stripped)) {
- const hashIdx = stripped.indexOf(" #");
- if (hashIdx >= 0) content = stripped.slice(0, hashIdx).replace(/\s+$/, "");
- }
- const indent = content.length - content.trimStart().length;
- out.push({
- raw,
- indent,
- content: content.slice(indent),
- lineNumber,
- });
- }
- return out;
-}
-
-interface KeyValue {
- readonly key: string;
- readonly value: string;
-}
-
-function splitKeyValue(line: Line): KeyValue {
- const idx = line.content.indexOf(":");
- if (idx <= 0) {
- throw new Error(
- `line ${line.lineNumber}: expected 'key: value', got: ${JSON.stringify(line.raw)}`,
- );
- }
- const key = line.content.slice(0, idx).trim();
- if (!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(key)) {
- throw new Error(`line ${line.lineNumber}: invalid key name: ${JSON.stringify(key)}`);
- }
- const value = line.content.slice(idx + 1).trim();
- return { key, value };
-}
-
-function detectBlockIndent(lines: Line[], cursor: number): number {
- if (cursor >= lines.length) return 0;
- const first = lines[cursor]!;
- if (first.indent === 0) return 0; // empty block (next top-level key)
- return first.indent;
-}
-
-function parseScalar(text: string, lineNumber: number): ParsedScalar | ParsedScalar[] {
- if (text.startsWith("[") && text.endsWith("]")) {
- return parseInlineArray(text.slice(1, -1), lineNumber);
- }
- if (
- text.length >= 2 &&
- ((text.startsWith('"') && text.endsWith('"')) || (text.startsWith("'") && text.endsWith("'")))
- ) {
- return text.slice(1, -1);
- }
- if (text === "true") return true;
- if (text === "false") return false;
- if (text === "null" || text === "~") return null;
- // Number: integer or finite decimal. Anything else → literal string.
- if (/^-?\d+$/.test(text)) {
- const n = parseInt(text, 10);
- return n;
- }
- if (/^-?\d+\.\d+$/.test(text)) {
- const n = parseFloat(text);
- if (!Number.isFinite(n)) {
- throw new Error(`line ${lineNumber}: non-finite number: ${text}`);
- }
- return n;
- }
- return text;
-}
-
-function parseInlineArray(innerRaw: string, lineNumber: number): ParsedScalar[] {
- const inner = innerRaw.trim();
- if (inner === "") return [];
-
- const out: ParsedScalar[] = [];
- let current = "";
- let inQuote = false;
- let quoteChar: '"' | "'" | "" = "";
-
- for (let i = 0; i < inner.length; i++) {
- const ch = inner[i]!;
- if (inQuote) {
- current += ch;
- if (ch === quoteChar) {
- inQuote = false;
- quoteChar = "";
- }
- continue;
- }
- if (ch === '"' || ch === "'") {
- inQuote = true;
- quoteChar = ch;
- current += ch;
- continue;
- }
- if (ch === ",") {
- out.push(parseInlineArrayItem(current, lineNumber));
- current = "";
- continue;
- }
- current += ch;
- }
- if (inQuote) {
- throw new Error(`line ${lineNumber}: unterminated quoted string in inline array`);
- }
- out.push(parseInlineArrayItem(current, lineNumber));
- return out;
-}
-
-function parseInlineArrayItem(text: string, lineNumber: number): ParsedScalar {
- const trimmed = text.trim();
- if (trimmed === "") {
- throw new Error(`line ${lineNumber}: empty item in inline array`);
- }
- const parsed = parseScalar(trimmed, lineNumber);
- if (Array.isArray(parsed)) {
- throw new Error(`line ${lineNumber}: nested inline arrays are not supported`);
- }
- return parsed;
-}
diff --git a/src/core/brain/reconcile-outcomes.ts b/src/core/brain/reconcile-outcomes.ts
new file mode 100644
index 00000000..50a5ca33
--- /dev/null
+++ b/src/core/brain/reconcile-outcomes.ts
@@ -0,0 +1,103 @@
+/**
+ * Contradiction reconcile outcomes (dream phase F3).
+ *
+ * Extracted from dream.ts. Classifies every contradiction topic the
+ * plan flagged and decides auto-resolution vs operator-facing open
+ * question. Pure; emits nothing.
+ */
+
+import {
+ resolveContradiction,
+ type ContradictionInput,
+ type ReconcileSignal,
+} from "./reconcile-domains.ts";
+import {
+ filterWithinWindow,
+ type PlanState,
+ type ScanResult,
+ type SignalRecord,
+} from "./dream-plan.ts";
+import { BRAIN_SIGNAL_SIGN, type BrainConfig, type DreamOpenQuestion } from "./types.ts";
+
+/** Project a scanned signal onto the minimal reconcile view. */
+function toReconcileSignal(r: SignalRecord): ReconcileSignal {
+ return {
+ created_at: r.signal.created_at,
+ ...(r.signal.recorded_at ? { recorded_at: r.signal.recorded_at } : {}),
+ ...(r.signal.source ? { source: r.signal.source } : {}),
+ };
+}
+
+// ----- Reconcile (F3) ------------------------------------------------------
+
+export interface ReconcileAutoResolved {
+ readonly topic: string;
+ readonly domain: "source-freshness";
+ readonly winner_sign: "positive" | "negative";
+ readonly margin_days: number;
+}
+
+export interface ReconcileOutcomes {
+ readonly openQuestions: DreamOpenQuestion[];
+ readonly autoResolved: ReconcileAutoResolved[];
+}
+
+/**
+ * Classify every contradiction topic the plan flagged into a domain and
+ * decide its outcome. Source-freshness contradictions where the fresher
+ * side leads by at least half the contradiction window auto-resolve
+ * (recorded only - never a sub-threshold mutation); the rest become
+ * operator-facing open questions. Pure; emits nothing.
+ */
+export function buildReconcileOutcomes(
+ scan: ScanResult,
+ plan: PlanState,
+ cfg: BrainConfig,
+ now: Date,
+): ReconcileOutcomes {
+ const openQuestions: DreamOpenQuestion[] = [];
+ const autoResolved: ReconcileAutoResolved[] = [];
+ if (plan.contradictionTopics.size === 0) return { openQuestions, autoResolved };
+
+ const windowDays = cfg.dream.contradiction_window_days;
+ // Freshness must be decisive WITHIN the contradiction window, so the
+ // margin is half the window (a gap larger than the window would have
+ // excluded the older signal from the contradiction in the first place).
+ const freshnessMarginDays = Math.max(1, Math.ceil(windowDays / 2));
+
+ const byTopic = new Map<string, SignalRecord[]>();
+ for (const rec of scan.signals) {
+ const arr = byTopic.get(rec.signal.topic);
+ if (arr) arr.push(rec);
+ else byTopic.set(rec.signal.topic, [rec]);
+ }
+
+ for (const topic of plan.contradictionTopics) {
+ const sigs = filterWithinWindow(byTopic.get(topic) ?? [], windowDays, now);
+ const positives = sigs
+ .filter((s) => s.signal.signal === BRAIN_SIGNAL_SIGN.positive)
+ .map(toReconcileSignal);
+ const negatives = sigs
+ .filter((s) => s.signal.signal === BRAIN_SIGNAL_SIGN.negative)
+ .map(toReconcileSignal);
+ const scope = sigs.find((s) => s.signal.scope)?.signal.scope;
+ const input: ContradictionInput = {
+ topic,
+ ...(scope ? { scope } : {}),
+ positives,
+ negatives,
+ };
+ const outcome = resolveContradiction(input, { now, freshnessMarginDays });
+ if (outcome.kind === "auto-resolved") {
+ autoResolved.push({
+ topic,
+ domain: outcome.domain,
+ winner_sign: outcome.winner_sign,
+ margin_days: outcome.margin_days,
+ });
+ } else {
+ openQuestions.push(outcome.question);
+ }
+ }
+ return { openQuestions, autoResolved };
+}
diff --git a/src/core/brain/schema-mutate.ts b/src/core/brain/schema-mutate.ts
index fe33eaf5..1531b27d 100644
--- a/src/core/brain/schema-mutate.ts
+++ b/src/core/brain/schema-mutate.ts
@@ -2,7 +2,7 @@ import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { appendAuditRecord } from "../reliability/audit.ts";
-import { atomicWriteText } from "../reliability/atomic.ts";
+import { atomicWriteText } from "../fs-atomic.ts";
import { withFileLock } from "../reliability/lock.ts";
import { brainConfigPath, brainDirs } from "./paths.ts";
import {
diff --git a/src/core/brain/set-primary.ts b/src/core/brain/set-primary.ts
index fcd20244..f78338ba 100644
--- a/src/core/brain/set-primary.ts
+++ b/src/core/brain/set-primary.ts
@@ -29,12 +29,8 @@ import { existsSync, readFileSync } from "node:fs";
import { atomicWriteFileSync } from "../fs-atomic.ts";
import { brainConfigPath } from "./paths.ts";
-import {
- BrainConfigError,
- formatPrimaryAgentYamlValue,
- parseBrainYaml,
- validateBrainConfig,
-} from "./policy.ts";
+import { parseBrainYaml } from "./yaml-parse.ts";
+import { BrainConfigError, formatPrimaryAgentYamlValue, validateBrainConfig } from "./policy.ts";
/**
* Result of {@link setPrimaryAgent}. `previous` is the value on disk
diff --git a/src/core/brain/wikilink.ts b/src/core/brain/wikilink.ts
index 3858690c..df5aa015 100644
--- a/src/core/brain/wikilink.ts
+++ b/src/core/brain/wikilink.ts
@@ -30,6 +30,57 @@ import { basename } from "node:path";
import type { LinkOutputFormat } from "../config.ts";
+/*
+ * Canonical wikilink regex variants.
+ *
+ * Exactly one definition of the `[[...]]` syntax exists per contract;
+ * every parser in the codebase imports the variant whose edge-case
+ * behavior it needs instead of declaring a local copy:
+ *
+ * - {@link WIKILINK_TARGET_RE}: target before any `|`/`#` suffix,
+ * suffix captured separately. Tolerates newlines inside the
+ * brackets (historical `vault.ts` behavior). For target extraction
+ * and merged-link rewriting.
+ * - {@link WIKILINK_ALIAS_RE}: target plus optional `|alias`
+ * capture, single-line only, `#` stays inside the target. For the
+ * search link/entity extractors.
+ * - {@link RICH_WIKILINK_RE}: whole bracket body in one capture,
+ * single-line only. For the link-graph parser/formatter which
+ * decomposes the body itself.
+ * - {@link WIKILINK_DETECT_RE}: presence check, no captures.
+ * - {@link ANCHORED_WIKILINK_RE} / {@link EXACT_WIKILINK_RE}:
+ * prefix-strip and whole-string forms used by the normalisers in
+ * this module.
+ *
+ * The `g`-flagged variants are shared module-level instances: use them
+ * with `matchAll`/`replace` (which do not leak `lastIndex` state);
+ * clone via `new RegExp(re)` before calling `exec`/`test` in a loop.
+ */
+
+/** Target capture with separate `[#|]suffix` capture; multi-line tolerant. */
+export const WIKILINK_TARGET_RE = /\[\[([^\]|#]+)([#|][^\]]*)?\]\]/g;
+
+/**
+ * Target plus optional `|alias` capture; single-line, unicode mode.
+ * The `u` flag is inherited from the entity extractor; the link
+ * extractor formerly ran the same pattern without it - equivalent
+ * here because the pattern only uses negated classes over BMP
+ * delimiters.
+ */
+export const WIKILINK_ALIAS_RE = /\[\[([^\]\n|]+?)(?:\|([^\]\n]+))?\]\]/gu;
+
+/** Whole bracket body in one capture; single-line. */
+export const RICH_WIKILINK_RE = /\[\[([^\]\n]+)\]\]/g;
+
+/** Presence check only; no captures, not global. */
+export const WIKILINK_DETECT_RE = /\[\[[^\]\n]+\]\]/u;
+
+/** Leading-wikilink prefix strip; body in one capture. */
+export const ANCHORED_WIKILINK_RE = /^\[\[([^\]]+)\]\]/;
+
+/** Whole-string wikilink form; body in one capture. */
+export const EXACT_WIKILINK_RE = /^\[\[([^\]]+)\]\]$/;
+
/**
* Strip wikilink decoration off `value` and return the bare target id.
*
@@ -46,7 +97,7 @@ import type { LinkOutputFormat } from "../config.ts";
export function normaliseWikilinkTarget(value: string): string {
let s = value.trim();
// Strip surrounding wikilink brackets, retaining only the target.
- const wm = /^\[\[([^\]]+)\]\]/.exec(s);
+ const wm = ANCHORED_WIKILINK_RE.exec(s);
if (wm) s = wm[1]!.trim();
return stripBasenameDecoration(s);
}
@@ -82,7 +133,7 @@ function stripBasenameDecoration(body: string): string {
* get a clean id either way.
*/
export function parseWikilink(value: string): string | null {
- const m = /^\s*\[\[([^\]]+)\]\]\s*$/.exec(value);
+ const m = EXACT_WIKILINK_RE.exec(value.trim());
if (!m) return null;
return normaliseWikilinkTarget(m[1]!);
}
@@ -143,7 +194,7 @@ export function parseArtifactRef(value: string): ArtifactRefParse {
// otherwise has its colon swallowed by `path.basename`.
let body = value.trim();
let wasWikilink = false;
- const wm = /^\[\[([^\]]+)\]\]$/.exec(body);
+ const wm = EXACT_WIKILINK_RE.exec(body);
if (wm) {
body = wm[1]!.trim();
wasWikilink = true;
diff --git a/src/core/brain/yaml-parse.ts b/src/core/brain/yaml-parse.ts
new file mode 100644
index 00000000..00427032
--- /dev/null
+++ b/src/core/brain/yaml-parse.ts
@@ -0,0 +1,281 @@
+/**
+ * Minimal indent-aware parser for the YAML subset used by `_brain.yaml`.
+ *
+ * Extracted from policy.ts so config semantics (validation, defaults,
+ * resolvers) and syntax parsing live in separate modules. The grammar
+ * is unchanged.
+ */
+
+// The parser handles only the shape used by `_brain.yaml`:
+//
+// - `# comment` lines and blanks
+// - top-level `key: <scalar>`
+// - top-level `key:` followed by an indented block of one indent level
+// - block-level `<indent>key: <scalar>`
+//
+// Scalars are parsed as:
+// - plain integers / floats (no exponents, no leading +)
+// - quoted strings ('..' or "..") — the quotes are stripped and the
+// content is taken as-is (no escape sequences)
+// - the bare words `true`, `false`, `null`
+// - otherwise: the literal string
+//
+// This intentionally rejects nested mappings deeper than two levels,
+// anchors, and aliases — none of which the schema needs.
+
+export type ParsedScalar = number | string | boolean | null;
+type ParsedBlockValue =
+ | ParsedScalar
+ | Record<string, ParsedScalar | ParsedScalar[]>
+ | ParsedScalar[];
+export type ParsedBlock = Record<string, ParsedBlockValue>;
+
+interface Line {
+ readonly raw: string;
+ readonly indent: number;
+ readonly content: string;
+ readonly lineNumber: number;
+}
+
+export function parseBrainYaml(text: string): ParsedBlock {
+ const lines = splitLines(text);
+ const out: ParsedBlock = {};
+ let i = 0;
+ while (i < lines.length) {
+ const line = lines[i]!;
+ if (line.indent !== 0) {
+ throw new Error(`line ${line.lineNumber}: unexpected indentation at top level`);
+ }
+ const kv = splitKeyValue(line);
+ if (kv.value === "") {
+ // Block header: collect indented children.
+ // Each child may be a scalar value (`key: val`) or a list (`key:` followed
+ // by deeper-indented `- item` lines). Lists-within-blocks are the only
+ // third-level nesting we support — they are required for `discipline_report`.
+ const child: Record<string, ParsedScalar | ParsedScalar[]> = {};
+ i++;
+ const blockIndent = detectBlockIndent(lines, i);
+ while (i < lines.length && lines[i]!.indent >= blockIndent && blockIndent > 0) {
+ const inner = lines[i]!;
+ if (inner.indent !== blockIndent) {
+ throw new Error(
+ `line ${inner.lineNumber}: inconsistent indentation in block '${kv.key}' ` +
+ `(expected ${blockIndent} spaces, got ${inner.indent})`,
+ );
+ }
+ const innerKv = splitKeyValue(inner);
+ if (innerKv.value === "") {
+ // Child key with no value — expect a list of `- item` lines at a
+ // deeper indent level.
+ i++;
+ const listIndent = detectBlockIndent(lines, i);
+ if (listIndent <= blockIndent) {
+ // Empty list (next line is at the same or shallower indent).
+ if (innerKv.key in child) {
+ throw new Error(
+ `line ${inner.lineNumber}: duplicate key '${innerKv.key}' in block '${kv.key}'`,
+ );
+ }
+ child[innerKv.key] = [];
+ continue;
+ }
+ const items: ParsedScalar[] = [];
+ while (i < lines.length && lines[i]!.indent >= listIndent) {
+ const listLine = lines[i]!;
+ if (listLine.indent !== listIndent) {
+ throw new Error(
+ `line ${listLine.lineNumber}: inconsistent indentation in list '${innerKv.key}' ` +
+ `(expected ${listIndent} spaces, got ${listLine.indent})`,
+ );
+ }
+ if (!listLine.content.startsWith("- ") && listLine.content !== "-") {
+ // If it looks like a `key: value` pair, it's a deeper block — not
+ // supported. Preserve the original error message so existing tests
+ // that assert on the wording keep passing.
+ if (/^[A-Za-z_][A-Za-z0-9_-]*\s*:/.test(listLine.content)) {
+ throw new Error(
+ `line ${listLine.lineNumber}: nested blocks deeper than one level are not supported`,
+ );
+ }
+ throw new Error(
+ `line ${listLine.lineNumber}: expected list item starting with '- ' ` +
+ `in '${kv.key}.${innerKv.key}'`,
+ );
+ }
+ const itemText = listLine.content.startsWith("- ")
+ ? listLine.content.slice(2).trim()
+ : "";
+ const item = parseScalar(itemText, listLine.lineNumber);
+ if (Array.isArray(item)) {
+ throw new Error(
+ `line ${listLine.lineNumber}: nested inline arrays are not supported`,
+ );
+ }
+ items.push(item);
+ i++;
+ }
+ if (innerKv.key in child) {
+ throw new Error(
+ `line ${inner.lineNumber}: duplicate key '${innerKv.key}' in block '${kv.key}'`,
+ );
+ }
+ child[innerKv.key] = items;
+ continue;
+ }
+ if (innerKv.key in child) {
+ throw new Error(
+ `line ${inner.lineNumber}: duplicate key '${innerKv.key}' in block '${kv.key}'`,
+ );
+ }
+ child[innerKv.key] = parseScalar(innerKv.value, inner.lineNumber);
+ i++;
+ }
+ if (kv.key in out) {
+ throw new Error(`duplicate top-level key '${kv.key}'`);
+ }
+ out[kv.key] = child;
+ continue;
+ }
+ if (kv.key in out) {
+ throw new Error(`duplicate top-level key '${kv.key}'`);
+ }
+ out[kv.key] = parseScalar(kv.value, line.lineNumber);
+ i++;
+ }
+ return out;
+}
+
+function splitLines(text: string): Line[] {
+ const out: Line[] = [];
+ let lineNumber = 0;
+ for (const raw of text.split(/\r?\n/)) {
+ lineNumber++;
+ // Strip trailing whitespace; leave leading intact for indent detection.
+ const stripped = raw.replace(/\s+$/, "");
+ // Skip blanks and comment-only lines.
+ if (stripped.trim() === "") continue;
+ if (stripped.trimStart().startsWith("#")) continue;
+ // Strip inline comments only when they are clearly outside a quoted
+ // value. Keep this simple: only honour ` #` (space then hash) on
+ // unquoted lines. Quoted values keep their content verbatim.
+ let content = stripped;
+ if (!/['"]/.test(stripped)) {
+ const hashIdx = stripped.indexOf(" #");
+ if (hashIdx >= 0) content = stripped.slice(0, hashIdx).replace(/\s+$/, "");
+ }
+ const indent = content.length - content.trimStart().length;
+ out.push({
+ raw,
+ indent,
+ content: content.slice(indent),
+ lineNumber,
+ });
+ }
+ return out;
+}
+
+interface KeyValue {
+ readonly key: string;
+ readonly value: string;
+}
+
+function splitKeyValue(line: Line): KeyValue {
+ const idx = line.content.indexOf(":");
+ if (idx <= 0) {
+ throw new Error(
+ `line ${line.lineNumber}: expected 'key: value', got: ${JSON.stringify(line.raw)}`,
+ );
+ }
+ const key = line.content.slice(0, idx).trim();
+ if (!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(key)) {
+ throw new Error(`line ${line.lineNumber}: invalid key name: ${JSON.stringify(key)}`);
+ }
+ const value = line.content.slice(idx + 1).trim();
+ return { key, value };
+}
+
+function detectBlockIndent(lines: Line[], cursor: number): number {
+ if (cursor >= lines.length) return 0;
+ const first = lines[cursor]!;
+ if (first.indent === 0) return 0; // empty block (next top-level key)
+ return first.indent;
+}
+
+function parseScalar(text: string, lineNumber: number): ParsedScalar | ParsedScalar[] {
+ if (text.startsWith("[") && text.endsWith("]")) {
+ return parseInlineArray(text.slice(1, -1), lineNumber);
+ }
+ if (
+ text.length >= 2 &&
+ ((text.startsWith('"') && text.endsWith('"')) || (text.startsWith("'") && text.endsWith("'")))
+ ) {
+ return text.slice(1, -1);
+ }
+ if (text === "true") return true;
+ if (text === "false") return false;
+ if (text === "null" || text === "~") return null;
+ // Number: integer or finite decimal. Anything else → literal string.
+ if (/^-?\d+$/.test(text)) {
+ const n = parseInt(text, 10);
+ return n;
+ }
+ if (/^-?\d+\.\d+$/.test(text)) {
+ const n = parseFloat(text);
+ if (!Number.isFinite(n)) {
+ throw new Error(`line ${lineNumber}: non-finite number: ${text}`);
+ }
+ return n;
+ }
+ return text;
+}
+
+function parseInlineArray(innerRaw: string, lineNumber: number): ParsedScalar[] {
+ const inner = innerRaw.trim();
+ if (inner === "") return [];
+
+ const out: ParsedScalar[] = [];
+ let current = "";
+ let inQuote = false;
+ let quoteChar: '"' | "'" | "" = "";
+
+ for (let i = 0; i < inner.length; i++) {
+ const ch = inner[i]!;
+ if (inQuote) {
+ current += ch;
+ if (ch === quoteChar) {
+ inQuote = false;
+ quoteChar = "";
+ }
+ continue;
+ }
+ if (ch === '"' || ch === "'") {
+ inQuote = true;
+ quoteChar = ch;
+ current += ch;
+ continue;
+ }
+ if (ch === ",") {
+ out.push(parseInlineArrayItem(current, lineNumber));
+ current = "";
+ continue;
+ }
+ current += ch;
+ }
+ if (inQuote) {
+ throw new Error(`line ${lineNumber}: unterminated quoted string in inline array`);
+ }
+ out.push(parseInlineArrayItem(current, lineNumber));
+ return out;
+}
+
+function parseInlineArrayItem(text: string, lineNumber: number): ParsedScalar {
+ const trimmed = text.trim();
+ if (trimmed === "") {
+ throw new Error(`line ${lineNumber}: empty item in inline array`);
+ }
+ const parsed = parseScalar(trimmed, lineNumber);
+ if (Array.isArray(parsed)) {
+ throw new Error(`line ${lineNumber}: nested inline arrays are not supported`);
+ }
+ return parsed;
+}
diff --git a/src/core/fs-atomic.ts b/src/core/fs-atomic.ts
index e61ed71b..6672b96e 100644
--- a/src/core/fs-atomic.ts
+++ b/src/core/fs-atomic.ts
@@ -31,6 +31,40 @@ export function atomicWriteFileSync(target: string, contents: string): void {
});
}
+export interface AtomicWriteTextOptions {
+ /** File mode for the new inode. Defaults to private `0o600`. */
+ readonly mode?: number;
+ /**
+ * Pre-write gate: runs against the candidate text BEFORE anything
+ * touches the filesystem. A throw aborts the write and leaves the
+ * existing target untouched — used by config writers that must never
+ * persist a payload their own parser would reject.
+ */
+ readonly validate?: (candidate: string) => void;
+}
+
+/**
+ * Validated atomic overwrite for sensitive text files (configs,
+ * schema documents). Same temp-file + fsync + rename pipeline as
+ * {@link atomicWriteFileSync}, plus a validation hook and a private
+ * default mode.
+ */
+export function atomicWriteText(
+ targetPath: string,
+ candidate: string,
+ opts: AtomicWriteTextOptions = {},
+): void {
+ opts.validate?.(candidate);
+ withTempFile(
+ targetPath,
+ candidate,
+ (tmpPath) => {
+ renameSync(tmpPath, targetPath);
+ },
+ opts.mode ?? 0o600,
+ );
+}
+
/**
* Like {@link atomicWriteFileSync} but fails with `EEXIST` if `target`
* already exists, atomically. Implemented via `link(2)` instead of
@@ -68,7 +102,12 @@ export function atomicCreateFileSyncExclusive(target: string, contents: string):
* file is unlinked on any failure; durability fsync of the parent directory
* is best-effort after a successful commit.
*/
-function withTempFile(target: string, contents: string, commit: (tmpPath: string) => void): void {
+function withTempFile(
+ target: string,
+ contents: string,
+ commit: (tmpPath: string) => void,
+ mode: number = 0o644,
+): void {
const dir = dirname(target);
mkdirSync(dir, { recursive: true });
@@ -84,7 +123,7 @@ function withTempFile(target: string, contents: string, commit: (tmpPath: string
let fd: number | null = null;
let committed = false;
try {
- fd = openSync(tmpPath, "wx", 0o644);
+ fd = openSync(tmpPath, "wx", mode);
const buf = Buffer.from(contents, "utf8");
let written = 0;
while (written < buf.byteLength) {
diff --git a/src/core/reliability/atomic.ts b/src/core/reliability/atomic.ts
deleted file mode 100644
index e595a1e0..00000000
--- a/src/core/reliability/atomic.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-import {
- closeSync,
- existsSync,
- fsyncSync,
- mkdirSync,
- openSync,
- renameSync,
- unlinkSync,
- writeFileSync,
-} from "node:fs";
-import { basename, dirname, join } from "node:path";
-
-export interface AtomicWriteTextOptions {
- readonly mode?: number;
- readonly validate?: (candidate: string) => void;
-}
-
-export function atomicWriteText(
- targetPath: string,
- candidate: string,
- opts: AtomicWriteTextOptions = {},
-): void {
- opts.validate?.(candidate);
-
- const parent = dirname(targetPath);
- mkdirSync(parent, { recursive: true });
- const tempPath = join(
- parent,
- `.${basename(targetPath)}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,
- );
-
- let fileDescriptor: number | null = null;
- try {
- fileDescriptor = openSync(tempPath, "wx", opts.mode ?? 0o600);
- writeFileSync(fileDescriptor, candidate, "utf8");
- fsyncSync(fileDescriptor);
- closeSync(fileDescriptor);
- fileDescriptor = null;
- renameSync(tempPath, targetPath);
- fsyncDirectoryBestEffort(parent);
- } catch (error) {
- if (fileDescriptor !== null) {
- try {
- closeSync(fileDescriptor);
- } catch {
- // Best-effort cleanup; preserve the original write error.
- }
- }
- if (existsSync(tempPath)) {
- try {
- unlinkSync(tempPath);
- } catch {
- // Best-effort cleanup; preserve the original write error.
- }
- }
- throw error;
- }
-}
-
-function fsyncDirectoryBestEffort(path: string): void {
- let directoryDescriptor: number | null = null;
- try {
- directoryDescriptor = openSync(path, "r");
- fsyncSync(directoryDescriptor);
- } catch {
- // Some platforms/filesystems reject directory fsync. The file fsync
- // and atomic rename have already happened, so degrade quietly.
- } finally {
- if (directoryDescriptor !== null) {
- try {
- closeSync(directoryDescriptor);
- } catch {
- // Ignore close failures on a best-effort durability flush.
- }
- }
- }
-}
diff --git a/src/core/search/entities.ts b/src/core/search/entities.ts
index a2cd823e..b8a50802 100644
--- a/src/core/search/entities.ts
+++ b/src/core/search/entities.ts
@@ -20,7 +20,8 @@
* normalised (lowercased, whitespace-collapsed, deduped) and frozen.
*/
-const WIKILINK_RE = /\[\[([^\]\n|]+?)(?:\|([^\]\n]+))?\]\]/gu;
+import { WIKILINK_ALIAS_RE } from "../brain/wikilink.ts";
+
const QUOTED_RE = /"([^"\n]{2,})"/gu;
// One or more consecutive uppercase-initial tokens (covers "Sergey" and
// "Open Second Brain"). Tokens may carry trailing letters/numbers.
@@ -56,7 +57,7 @@ export function extractEntities(text: string): ReadonlyArray<string> {
out.push(n);
};
- for (const m of text.matchAll(WIKILINK_RE)) {
+ for (const m of text.matchAll(WIKILINK_ALIAS_RE)) {
const target = m[1] ?? "";
const alias = m[2];
if (alias) add(alias);
diff --git a/src/core/search/links.ts b/src/core/search/links.ts
index 3acfebf0..13bfdf48 100644
--- a/src/core/search/links.ts
+++ b/src/core/search/links.ts
@@ -12,6 +12,8 @@
* on the side of stripping too much rather than capturing junk links.
*/
+import { WIKILINK_ALIAS_RE } from "../brain/wikilink.ts";
+
export type LinkType = "wikilink" | "markdown_link" | "tag";
export interface ExtractedLink {
@@ -22,7 +24,6 @@ export interface ExtractedLink {
const CODE_FENCE_RE = /(^|\n)(```|~~~)[^\n]*\n[\s\S]*?(?:\n(?:```|~~~)[^\n]*|$)/g;
const INLINE_CODE_RE = /`[^`\n]*`/g;
-const WIKILINK_RE = /\[\[([^\]\n|]+?)(?:\|([^\]\n]+))?\]\]/g;
// Negative lookbehind so `![alt](url)` image embeds are NOT captured as
// markdown_link. CodeRabbit caught this regression on PR #15.
const MD_LINK_RE = /(?<!!)\[([^\]\n]*)\]\(([^)\n\s]+)(?:\s+"[^"\n]*")?\)/g;
@@ -60,7 +61,7 @@ export function extractLinks(content: string): ExtractedLink[] {
const cleaned = stripCode(content);
const out: ExtractedLink[] = [];
- for (const m of cleaned.matchAll(WIKILINK_RE)) {
+ for (const m of cleaned.matchAll(WIKILINK_ALIAS_RE)) {
const target = (m[1] ?? "").trim();
const alt = m[2] ? m[2].trim() : null;
if (target === "") continue;
diff --git a/src/core/search/query-plan.ts b/src/core/search/query-plan.ts
index e35c523f..b8de1c30 100644
--- a/src/core/search/query-plan.ts
+++ b/src/core/search/query-plan.ts
@@ -16,6 +16,7 @@
* out, with no I/O and no clock/random source.
*/
+import { WIKILINK_DETECT_RE } from "../brain/wikilink.ts";
import { extractEntities } from "./entities.ts";
import type { QueryIntent, QueryPlan, WeightProfile } from "./types.ts";
@@ -59,7 +60,6 @@ const PROFILES: Record<QueryIntent, WeightProfile> = Object.freeze({
const QUOTED_PHRASE_RE = /"[^"\n]{2,}"/u;
const WILDCARD_RE = /\*/u;
-const WIKILINK_RE = /\[\[[^\]\n]+\]\]/u;
/** Lowercase + trim + collapse internal whitespace. No word lists. */
function normalize(query: string): string {
@@ -96,7 +96,7 @@ function classify(query: string, normalized: string): QueryIntent {
// Rule 2: explicit wikilinks or a query dominated by entity-like
// tokens is a proper-noun lookup.
- if (WIKILINK_RE.test(query) || entityShare >= 0.5) return "entity";
+ if (WIKILINK_DETECT_RE.test(query) || entityShare >= 0.5) return "entity";
// Rule 3: a long query with few entities reads as open-ended.
if (tokens >= 6 && entityShare < 0.2) return "broad";
diff --git a/src/core/vault.ts b/src/core/vault.ts
index 712c315c..82214ef9 100644
--- a/src/core/vault.ts
+++ b/src/core/vault.ts
@@ -10,6 +10,7 @@
import { mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
import { dirname, join, relative } from "node:path";
+import { WIKILINK_TARGET_RE } from "./brain/wikilink.ts";
import { atomicCreateFileSyncExclusive, atomicWriteFileSync } from "./fs-atomic.ts";
import { stem } from "./fs-utils.ts";
import type { FrontmatterMap, FrontmatterValue, VaultPage } from "./types.ts";
@@ -17,7 +18,6 @@ import type { FrontmatterMap, FrontmatterValue, VaultPage } from "./types.ts";
const FRONTMATTER_RE = /^---\s*\n([\s\S]*?)\n---\s*\n?/;
const KEY_VALUE_RE = /^([a-zA-Z_][a-zA-Z0-9_-]*)\s*:\s*(.*?)\s*$/;
const PLAIN_SCALAR_RE = /^[A-Za-z0-9_./-](?:[A-Za-z0-9_./ -]*[A-Za-z0-9_./-])?$/;
-const WIKILINK_RE = /\[\[([^\]|#]+)(?:[|#][^\]]*)?\]\]/g;
const CODE_BLOCK_RE = /```[\s\S]*?```|`[^`]+`/g;
const SLUG_INVALID_RE = /[^a-z0-9]+/g;
const SLUG_MAX_LEN = 64;
@@ -217,7 +217,7 @@ export function extractWikilinks(content: string): string[] {
const masked = content.replace(CODE_BLOCK_RE, " ");
const seen = new Set<string>();
const result: string[] = [];
- for (const m of masked.matchAll(WIKILINK_RE)) {
+ for (const m of masked.matchAll(WIKILINK_TARGET_RE)) {
const target = m[1]!;
const dot = target.lastIndexOf(".");
const ext = dot >= 0 ? target.slice(dot).toLowerCase() : "";
diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.ts
index b7f05b1c..4351d11a 100644
--- a/src/mcp/brain-tools.ts
+++ b/src/mcp/brain-tools.ts
@@ -1,5614 +1,48 @@
/**
- * MCP tool registrations for the Brain layer.
+ * Aggregation seam for the Brain MCP tool surface.
*
- * Exposes the Brain operations that are safe to invoke from an agent
- * harness:
- *
- * - `brain_feedback` — record a single taste signal (or a
- * directly-confirmed preference when
- * `force_confirmed: true`).
- * - `brain_dream` — run the deterministic learning pass.
- * - `brain_apply_evidence` — record whether a preference was applied
- * or violated on a freshly-produced
- * artifact.
- * - `brain_digest` — render a human-readable summary of the
- * last activity window.
- * - `brain_query` — read-only aggregation by preference id,
- * topic, or time window.
- * - `brain_agent_query` — read-only aggregation by source agent.
- * - `brain_agent_diff` — read-only comparison between source agents.
- * - `brain_doctor` — invariant / schema health check.
- * - `brain_backlinks` — read-only inbound reference lookup.
- * - `brain_pinned_context` — current-task scratchpad read/write/clear.
- * - `brain_context` — pull-bootstrap of `Brain/active.md`.
- *
- * The five Brain commands that remain CLI-only on purpose
- * (`init`, `reject`, `pin`, `unpin`, `rollback`) deliberately do *not*
- * have MCP wrappers — see design doc §9.1 "absence from MCP protects
- * against autonomous mistakes". Their handler functions live in
- * `src/core/brain/*` and `src/cli/*` for shell-side use.
- *
- * Each handler delegates to the corresponding `src/core/brain/*`
- * function so the contract stays byte-identical to the CLI. Arguments
- * are coerced/validated locally with the same helpers the legacy tools
- * use; we re-implement the small ones here rather than re-exporting
- * private functions from `tools.ts` to keep the dependency direction
- * one-way (Brain tools may grow their own coercion rules later).
- */
-
-import { isAbsolute, join, relative, resolve } from "node:path";
-
-import { existsSync, readdirSync, readFileSync } from "node:fs";
-
-import {
- resolveAgentName,
- resolveLinkOutputFormat,
- resolveSearchFocusContextPack,
- resolveTimezone,
- resolveTriggerCooldownDays,
-} from "../core/config.ts";
-import { indexVault, resolveSearchConfig } from "../core/search/index.ts";
-import { Store } from "../core/search/store.ts";
-import {
- assignNoteLabel,
- LabelVocabularyError,
- readLabels,
- removeNoteLabel,
-} from "../core/brain/labels.ts";
-import { loadSchemaPack } from "../core/brain/schema-pack.ts";
-import { listSecrets } from "../core/brain/secrets/store.ts";
-import { runWithSecret, SecretExecDeniedError } from "../core/brain/secrets/exec.ts";
-import {
- acceptBridge,
- bridgePairKey,
- discoverBridges,
- dismissBridge,
- readDismissedBridges,
- writeBridgeProposals,
-} from "../core/brain/link-graph/bridge-discovery.ts";
-import {
- detectCommunities,
- materializeClusterNotes,
-} from "../core/brain/link-graph/communities.ts";
-import { appendMetric } from "../core/brain/metrics.ts";
-import { createSafeguard, resolveSafeguardTimeoutMs } from "../core/brain/safeguard.ts";
-import { parseRecallBenchmarkDataset, runRecallBenchmark } from "../core/search/benchmark.ts";
-import { loadTunedParameters, resetTuning, tuneRecall } from "../core/search/tuning.ts";
-import { currentLease } from "../core/brain/maintenance/lease.ts";
-import { listJournal } from "../core/brain/maintenance/journal.ts";
-import { runMaintenance, type DailyWindow } from "../core/brain/maintenance/lane.ts";
-import { writeFrontmatterAtomic } from "../core/vault.ts";
-import { resolveNotePath } from "../core/brain/note-path.ts";
-import type { FrontmatterMap } from "../core/types.ts";
-import { readActiveSessionFocus } from "../core/search/session-focus.ts";
-import { brainActivePath, brainDirs } from "../core/brain/paths.ts";
-import { regenerateActive, type RegenerateActiveResult } from "../core/brain/active.ts";
-import { parseFrontmatter } from "../core/vault.ts";
-import {
- appendApplyEvidence,
- BrainPreferenceNotFoundError,
- type AppendApplyEvidenceInput,
-} from "../core/brain/apply-evidence.ts";
-import { buildBacklinkIndex } from "../core/brain/backlinks.ts";
-import { EntityAmbiguityError, getEntity, listEntities } from "../core/brain/entities/registry.ts";
-import { validateEntityCategory } from "../core/brain/entities/canonical.ts";
-import { readPrefAudit } from "../core/brain/pref-audit.ts";
-import { buildMorningBrief } from "../core/brain/morning-brief.ts";
-import { deliverBriefTriggers, renderTriggerBriefSection } from "../core/brain/triggers/brief.ts";
-import { scanTriggers } from "../core/brain/triggers/scan.ts";
-import { createTriggers, listTriggers, transitionTrigger } from "../core/brain/triggers/store.ts";
-import { deepSynthesis, synthesisCandidates } from "../core/brain/deep-synthesis.ts";
-import { discoverIdeas, ideaCandidates } from "../core/brain/idea-discovery.ts";
-import { listGateTelemetry, summarizeGateTelemetry } from "../core/brain/gate-telemetry.ts";
-import { isTriggerStatus, type TriggerRecord } from "../core/brain/triggers/types.ts";
-import { aggregateSources } from "../core/brain/portability/sources.ts";
-import { switchProfile, listProfiles } from "../core/brain/portability/profiles.ts";
-import { defaultConfigPath } from "../core/config.ts";
-import { findUnlinkedMentions } from "../core/brain/link-graph/unlinked-mentions.ts";
-import { buildConceptCluster } from "../core/brain/link-graph/concept-cluster.ts";
-import { auditMoc, MocAuditError } from "../core/brain/link-graph/moc-audit.ts";
-import { readVaultInstructionFile } from "../core/brain/vault-instruction-file.ts";
-import { buildTimelineIndex } from "../core/brain/temporal/build-index.ts";
-import { selectEvents } from "../core/brain/temporal/select-events.ts";
-import { buildBeliefEvolution } from "../core/brain/temporal/belief-evolution.ts";
-import { findStaleEntries } from "../core/brain/temporal/stale-watch.ts";
-import { buildDailyBrief } from "../core/brain/temporal/daily-brief.ts";
-import { buildWeeklySynthesis } from "../core/brain/temporal/weekly-brief.ts";
-import { loadTemporalConfigSafe } from "../core/brain/policy.ts";
-import { isBrainLogEventKind, type BrainLogEventKind } from "../core/brain/types.ts";
-import { packContext } from "../core/brain/context-pack.ts";
-import {
- listIntentions,
- moveIntentionToHistory,
- setIntention,
- showIntention,
-} from "../core/brain/intentions.ts";
-import { buildPreCompressPack } from "../core/brain/pre-compress-pack.ts";
-import {
- getContextReceipt,
- isContextReceiptTrigger,
- listContextReceipts,
- summarizeContextReceipt,
- type ContextReceiptOptions,
-} from "../core/brain/context-receipts.ts";
-import {
- isRecallTelemetryMode,
- isRecallTelemetryStatus,
- listRecallTelemetry,
- summarizeRecallTelemetry,
- type RecallTelemetryFilter,
- type RecallTelemetryMode,
- type RecallTelemetryOptions,
- type RecallTelemetryStatus,
-} from "../core/brain/recall-telemetry.ts";
-import {
- diffContextPreset,
- getContextPreset,
- listContextPresets,
- suggestContextPreset,
- type ContextPresetCurrentConfig,
-} from "../core/brain/context-presets.ts";
-import { extractPreCompactRecords } from "../core/brain/pre-compact-extract.ts";
-import {
- describeSessionRecall,
- expandSessionRecall,
- searchSessionRecall,
-} from "../core/brain/session-recall.ts";
-import {
- acceptSkillProposal,
- learnSkillProposals,
- listPendingSkillProposals,
- rejectSkillProposal,
-} from "../core/brain/skill-proposals.ts";
-import {
- listProceduralMemory,
- markProceduralMemoryUsed,
- reconcileProceduralMemory,
-} from "../core/brain/procedural-memory.ts";
-import { readProceduralGraph, rebuildProceduralGraph } from "../core/brain/procedural-graph.ts";
-import { readProceduralHints, rebuildProceduralHints } from "../core/brain/procedural-hints.ts";
-import {
- applyRecurrenceEvidence,
- getRecurrenceEntry,
- listRecurrenceEntries,
- purgeRecurrenceSource,
-} from "../core/brain/recurrence.ts";
-import {
- evaluateAttentionFlow,
- listAttentionFlows,
- renderAttentionFlow,
-} from "../core/brain/attention-flows.ts";
-import { collectMaintenanceActions } from "../core/brain/maintenance/collect.ts";
-import { normaliseWikilinkTarget } from "../core/brain/wikilink.ts";
-import { renderDigest, type DigestFormat } from "../core/brain/digest.ts";
-import { dream } from "../core/brain/dream.ts";
-import {
- applyDreamBundle,
- discardDreamBundle,
- listDreamBundles,
- stageDream,
- validateDreamBundle,
-} from "../core/brain/dream-stage.ts";
-import { buildIntentReview } from "../core/brain/intent-review.ts";
-import { buildRetentionReview } from "../core/brain/retention.ts";
-import { buildMonthlyReview, normalizeMonthlyReviewMonth } from "../core/brain/monthly-review.ts";
-import { buildReviewCandidates } from "../core/brain/review-candidates.ts";
-import { runDoctor } from "../core/brain/doctor.ts";
-import { buildOperatorSummary } from "../core/brain/trust/operator-summary.ts";
-import { BRAIN_ROLES } from "../core/brain/trust/role.ts";
-import {
- BrainNotFoundError,
- queryByLogSince,
- queryByPreference,
- queryByTopic,
-} from "../core/brain/query.ts";
-import { diffAgentSources, type AgentSourceDiffMode } from "../core/brain/agent-source/diff.ts";
-import { queryAgentSources } from "../core/brain/agent-source/query.ts";
-import type { AgentSourceContributionKind } from "../core/brain/agent-source/types.ts";
-import { writeSignal } from "../core/brain/signal.ts";
-import { writePreference } from "../core/brain/preference.ts";
-import { validateBrainFeedbackInput } from "../core/brain/sessions/validate-feedback.ts";
-import { isoDate, isoSecond } from "../core/brain/time.ts";
-import { formatLocalTimestamp } from "../core/brain/present-time.ts";
-import { captureReportDelta } from "../core/brain/report-snapshot.ts";
-import { slugify } from "../core/vault.ts";
-import { normalizeAgentArgument } from "../core/agent-identity.ts";
-import {
- BRAIN_LOG_EVENT_KIND,
- BRAIN_PREFERENCE_STATUS,
- BRAIN_APPLY_RESULT,
- type BrainApplyResult,
- type BrainPreference,
- type BrainRetired,
- type BrainSignal,
- type BrainSignalSign,
-} from "../core/brain/types.ts";
-import { normalizeEntityName } from "../core/brain/entities/canonical.ts";
-import { listDeadEnds, recordDeadEnd } from "../core/brain/dead-ends.ts";
-import { buildForesight, FORESIGHT_HORIZON_DAYS } from "../core/brain/temporal/foresight.ts";
-import { aggregateQuantities } from "../core/brain/truth/aggregate.ts";
-import { detectAgentCollisions } from "../core/brain/truth/collision.ts";
-import { computeTruthStateWithConflicts } from "../core/brain/truth/conflicts.ts";
-import { appendClaimEvent, readClaimEvents } from "../core/brain/truth/store.ts";
-import { appendLogEvent } from "../core/brain/log.ts";
-import type { BrainLogEntry } from "../core/brain/log.ts";
-import { appendBrainNote } from "../core/brain/note.ts";
-import { mirrorSignal, resolveSharedNamespace } from "../core/brain/shared-namespace.ts";
-import {
- WriteSessionRequestError,
- abandonSession,
- approveSession,
- openArtifactSession,
- sessionEnvelope,
-} from "../core/brain/write-session/engine.ts";
-import { dispatchSubmit, openPanelSession } from "../core/brain/write-session/panel.ts";
-import { listWriteSessions, readWriteSession } from "../core/brain/write-session/store.ts";
-import type { WriteSessionEnvelope } from "../core/brain/write-session/types.ts";
-import { buildMcpLandscape } from "../core/graph/mcp-config.ts";
-import {
- appendPinnedContext,
- clearPinnedContext,
- readPinnedContext,
- writePinnedContext,
- type PinnedContext,
-} from "../core/brain/pinned.ts";
-
-import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "./protocol.ts";
-import type { ServerContext, ToolDefinition } from "./tools.ts";
-import { MCP_PREVIEW_BUDGET } from "./preview-budget.ts";
-import {
- coerceStr,
- coerceStrList,
- coerceBool,
- coerceBoolOptional,
- coerceIsoDate,
- coerceFormat,
- coerceInt,
- coerceStringOptional,
-} from "./coerce.ts";
-import { emitGatedTelemetry } from "../core/brain/continuity/emit.ts";
-import { emitRecallTelemetry } from "../core/brain/recall-telemetry.ts";
-
-// ----- brain_feedback ------------------------------------------------------
-
-/**
- * Build the slug used in the signal / preference filename. We never let
- * the agent decide the slug directly — taking `topic` as the slug stem
- * is what the design doc §9.2 prescribes (slugs are deterministic from
- * topic). The slug is run through `slugify` defensively so a slightly
- * mis-shaped topic still yields a filesystem-safe basename.
- */
-function deriveSlug(topic: string): string {
- return slugify(topic);
-}
-
-async function toolBrainFeedback(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- // Single source of truth for the brain_feedback payload contract —
- // session-replay (sessions/import.ts) and the MCP live path now go
- // through the same validator so rule shape cannot drift between the
- // two surfaces.
- const validated = validateBrainFeedbackInput(args);
- if (!validated.ok) {
- throw new MCPError(INVALID_PARAMS, validated.reason);
- }
- const {
- topic,
- signal: signalRaw,
- principle,
- scope,
- raw,
- source,
- force_confirmed,
- } = validated.value;
- const forceConfirmed = force_confirmed ?? false;
-
- // Agent-fallback stays MCP-side: validator just hands back the user-
- // supplied value (or undefined); the live path resolves via config
- // when absent.
- const agent =
- normalizeAgentArgument(validated.value.agent ?? null) ??
- resolveAgentName(ctx.configPath ?? undefined);
- const now = new Date();
- const date = isoDate(now);
- const createdAt = isoSecond(now);
- const slug = deriveSlug(topic);
-
- // 1. Always write the signal to inbox/. Mirrors the CLI handler so the
- // audit trail in `Brain/log/` and `inbox/processed/` stays consistent
- // across CLI and MCP entry points. `--force-confirmed` ADDITIONALLY
- // creates a confirmed pref below.
- const signalInput = {
- topic,
- signal: signalRaw as BrainSignalSign,
- agent,
- principle,
- created_at: createdAt,
- date,
- slug,
- ...(scope ? { scope } : {}),
- ...(source && source.length > 0 ? { source: [...source] } : {}),
- ...(raw ? { raw } : {}),
- };
- const sigResult = writeSignal(ctx.vault, signalInput);
- // t_936a1a61: fail-soft mirror into the shared namespace AFTER the
- // primary write; `mirror` is reported only when the key is configured.
- const sharedNamespace = resolveSharedNamespace(ctx.configPath);
- const mirror =
- sharedNamespace === null ? undefined : mirrorSignal(sharedNamespace, ctx.vault, signalInput);
-
- try {
- appendLogEvent(ctx.vault, {
- timestamp: createdAt,
- eventType: BRAIN_LOG_EVENT_KIND.feedback,
- body: {
- signal: `[[${sigResult.id}]]`,
- topic: topic.trim(),
- sign: signalRaw,
- agent,
- },
- });
- } catch (err) {
- process.stderr.write(`warning: append feedback log failed: ${(err as Error).message}\n`);
- }
-
- let prefResult: { path: string; id: string } | null = null;
- if (forceConfirmed) {
- // Escape hatch: skip the dream pass and create the confirmed rule now.
- // `confirmed_at` is now; `unconfirmed_until` is also now so the trial
- // window collapses on inspection. The just-written signal is recorded
- // as the rule's origin under `evidenced_by`.
- prefResult = writePreference(ctx.vault, {
- slug,
- topic: topic.trim(),
- principle: principle.trim(),
- created_at: createdAt,
- unconfirmed_until: createdAt,
- status: BRAIN_PREFERENCE_STATUS.confirmed,
- evidenced_by: [`[[${sigResult.id}]]`],
- confirmed_at: createdAt,
- ...(scope ? { scope } : {}),
- });
- try {
- // Offset by 1s so the force-confirmed event sorts after the feedback
- // event on the same UTC second (parseLogDay is stable on ties, but a
- // visible chronology reads cleaner).
- appendLogEvent(ctx.vault, {
- timestamp: isoSecond(new Date(now.getTime() + 1000)),
- eventType: BRAIN_LOG_EVENT_KIND.forceConfirmed,
- body: {
- preference: `[[${prefResult.id}]]`,
- agent,
- },
- });
- } catch (err) {
- process.stderr.write(
- `warning: append force-confirmed log failed: ${(err as Error).message}\n`,
- );
- }
- }
-
- return {
- kind: prefResult ? "preference" : "signal",
- ...(mirror !== undefined ? { mirror } : {}),
- signal_path: vaultRelativeSafe(ctx.vault, sigResult.path),
- signal_absolute_path: resolve(sigResult.path),
- signal_id: sigResult.id,
- ...(prefResult
- ? {
- preference_path: vaultRelativeSafe(ctx.vault, prefResult.path),
- preference_absolute_path: resolve(prefResult.path),
- preference_id: prefResult.id,
- // Back-compat: top-level `path`/`id` previously pointed at the
- // pref on the force-confirmed branch. Keep them aligned for
- // callers that look at the bare fields.
- path: vaultRelativeSafe(ctx.vault, prefResult.path),
- absolute_path: resolve(prefResult.path),
- id: prefResult.id,
- }
- : {
- path: vaultRelativeSafe(ctx.vault, sigResult.path),
- absolute_path: resolve(sigResult.path),
- id: sigResult.id,
- }),
- agent,
- };
-}
-
-// ----- brain_dream ---------------------------------------------------------
-
-async function toolBrainDream(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const action = args["action"] ?? "run";
- if (
- action !== "run" &&
- action !== "stage" &&
- action !== "validate" &&
- action !== "apply" &&
- action !== "discard" &&
- action !== "list"
- ) {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_dream: action must be run|stage|validate|apply|discard|list",
- );
- }
- const dryRun = coerceBool(args, "dry_run");
- const nowDate = coerceIsoDate(args, "now");
- const agentArg = coerceStr(args, "agent", false);
- const agent = normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);
-
- if (action !== "run") {
- // Staged lifecycle (t_ae8a8ec0): stage -> validate -> apply over a
- // persisted bundle; dream() stays the only promotion engine.
- const runIdArg = coerceStr(args, "run_id", false);
- if ((action === "validate" || action === "apply" || action === "discard") && !runIdArg) {
- throw new MCPError(INVALID_PARAMS, `brain_dream action=${action}: run_id is required`);
- }
- const now = nowDate ?? new Date();
- const stageOpts = { now, ...(agent ? { agentName: agent } : {}) };
- switch (action) {
- case "stage": {
- const bundle = stageDream(ctx.vault, stageOpts);
- return {
- action,
- run_id: bundle.runId,
- plan: bundle.plan,
- sources: bundle.sources.length,
- dir: `Brain/dream/staged/${bundle.runId}`,
- };
- }
- case "validate": {
- const verdict = validateDreamBundle(ctx.vault, runIdArg!, stageOpts);
- return { action, run_id: runIdArg, valid: verdict.valid, drift: [...verdict.drift] };
- }
- case "apply": {
- const outcome = applyDreamBundle(ctx.vault, runIdArg!, stageOpts);
- return {
- action,
- run_id: runIdArg,
- applied: outcome.applied,
- drift: [...outcome.validation.drift],
- ...(outcome.summary !== undefined
- ? {
- changed: outcome.summary.changed,
- new_unconfirmed: [...outcome.summary.new_unconfirmed],
- confirmed: [...outcome.summary.confirmed],
- retired: outcome.summary.retired.map((r) => ({ id: r.id, reason: r.reason })),
- }
- : {}),
- };
- }
- case "discard": {
- return { action, run_id: runIdArg, removed: discardDreamBundle(ctx.vault, runIdArg!) };
- }
- default: {
- return {
- action,
- bundles: listDreamBundles(ctx.vault).map((b) => ({
- run_id: b.runId,
- status: b.status,
- staged_at: b.stagedAt,
- proposals: b.proposals,
- sources: b.sources,
- })),
- };
- }
- }
- }
-
- const summary = dream(ctx.vault, {
- dryRun,
- ...(nowDate ? { now: nowDate } : {}),
- ...(agent ? { agentName: agent } : {}),
- });
-
- // The summary is already a Plain Old Frozen Object — JSON-serialise
- // verbatim. We surface `snapshot_path` / `log_path` as vault-relative
- // for caller convenience while preserving the absolute path as well.
- return {
- run_id: summary.run_id,
- changed: summary.changed,
- dry_run: dryRun,
- new_unconfirmed: [...summary.new_unconfirmed],
- confirmed: [...summary.confirmed],
- retired: summary.retired.map((r) => ({ id: r.id, reason: r.reason })),
- contradictions: [...summary.contradictions],
- moved_to_processed: [...summary.moved_to_processed],
- suppressed: [...summary.suppressed],
- warnings: summary.warnings.map((w) => ({
- code: w.code,
- message: w.message,
- })),
- uncertain: summary.uncertain.map((u) => ({
- code: u.code,
- ...(u.topic !== undefined ? { topic: u.topic } : {}),
- message: u.message,
- })),
- quarantined: summary.quarantined.map((q) => ({
- topic: q.topic,
- signal_count: q.signal_count,
- distinct_agents: q.distinct_agents,
- age_days: q.age_days,
- failed_gates: [...q.failed_gates],
- })),
- snapshot_path: summary.snapshot_path
- ? vaultRelativeSafe(ctx.vault, summary.snapshot_path)
- : null,
- log_path: summary.log_path ? vaultRelativeSafe(ctx.vault, summary.log_path) : null,
- };
-}
-
-// ----- brain_review_candidates --------------------------------------------
-
-async function toolBrainIntentReview(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const nowDate = coerceIsoDate(args, "now");
- const report = buildIntentReview(ctx.vault, nowDate ? { now: nowDate } : {});
- return {
- schema_version: report.schema_version,
- generated_at: report.generated_at,
- reviews: report.reviews.map((review) => ({
- topic: review.topic,
- decision: review.decision,
- signal_count: review.signal_count,
- risk_band: review.risk_band,
- risk_score: review.risk_score,
- reasons: [...review.reasons],
- })),
- };
-}
-
-async function toolBrainRetention(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const nowDate = coerceIsoDate(args, "now");
- const report = buildRetentionReview(ctx.vault, nowDate ? { now: nowDate } : {});
- return {
- schema_version: report.schema_version,
- generated_at: report.generated_at,
- summary: report.summary,
- recommendations: report.recommendations.map((recommendation) => ({
- id: recommendation.id,
- artifact_type: recommendation.artifact_type,
- action: recommendation.action,
- reason: recommendation.reason,
- path: recommendation.path,
- })),
- };
-}
-
-async function toolBrainMonthlyReview(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const monthRaw = args["month"];
- let month: string | undefined;
- if (monthRaw !== undefined && monthRaw !== null) {
- if (typeof monthRaw !== "string") {
- throw new MCPError(INVALID_PARAMS, "brain_brief view=monthly: month must be YYYY-MM");
- }
- try {
- month = normalizeMonthlyReviewMonth(monthRaw);
- } catch {
- throw new MCPError(INVALID_PARAMS, "brain_brief view=monthly: month must be YYYY-MM");
- }
- }
- const report = buildMonthlyReview(ctx.vault, month ? { month } : {});
- return {
- schema_version: report.schema_version,
- generated_at: report.generated_at,
- month: report.month,
- window: report.window,
- summary: report.summary,
- };
-}
-
-async function toolBrainReviewCandidates(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const nowDate = coerceIsoDate(args, "now");
- // Surprisal annotation (t_fddfe64a) is best-effort: a resolvable
- // search config adds novelty ranking, anything else degrades to the
- // plain report.
- let searchConfig: ReturnType<typeof resolveSearchConfig> | undefined;
- try {
- searchConfig = resolveSearchConfig({
- vault: ctx.vault,
- configPath: ctx.configPath ?? undefined,
- });
- } catch {
- searchConfig = undefined;
- }
- const report = await buildReviewCandidates(ctx.vault, {
- ...(nowDate ? { now: nowDate } : {}),
- ...(searchConfig !== undefined ? { searchConfig } : {}),
- });
- return {
- ...(report.signal_novelty !== undefined ? { signal_novelty: report.signal_novelty } : {}),
- would_create: [...report.would_create],
- would_promote: [...report.would_promote],
- would_retire: report.would_retire.map((r) => ({
- id: r.id,
- reason: r.reason,
- })),
- would_supersede: report.would_supersede.map((r) => ({
- id: r.id,
- reason: r.reason,
- })),
- clusters_below_threshold: report.clusters_below_threshold.map((c) => ({
- topic: c.topic,
- signal_count: c.signal_count,
- distinct_agents: c.distinct_agents,
- age_days: c.age_days,
- failed_gates: [...c.failed_gates],
- })),
- gated_retires: report.gated_retires.map((g) => ({
- pref_id: g.pref_id,
- topic: g.topic,
- applied_count: g.applied_count,
- violated_count: g.violated_count,
- threshold: g.threshold,
- attempted_reason: g.attempted_reason,
- })),
- intent_reviews: report.intent_reviews.map((review) => ({
- topic: review.topic,
- decision: review.decision,
- signal_count: review.signal_count,
- risk_band: review.risk_band,
- risk_score: review.risk_score,
- reasons: [...review.reasons],
- })),
- };
-}
-
-// ----- brain_apply_evidence ------------------------------------------------
-
-async function toolBrainApplyEvidence(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const prefId = coerceStr(args, "pref_id", true)!;
- const artifact = coerceStr(args, "artifact", true)!;
- const resultRaw = coerceStr(args, "result", true)!;
- if (
- resultRaw !== BRAIN_APPLY_RESULT.applied &&
- resultRaw !== BRAIN_APPLY_RESULT.violated &&
- resultRaw !== BRAIN_APPLY_RESULT.outdated
- ) {
- throw new MCPError(
- INVALID_PARAMS,
- `argument 'result' must be 'applied', 'violated', or 'outdated'`,
- );
- }
- const agentArg = coerceStr(args, "agent", false);
- const note = coerceStr(args, "note", false);
- const outcomeRaw = coerceStr(args, "outcome", false);
- if (
- outcomeRaw !== null &&
- outcomeRaw !== "success" &&
- outcomeRaw !== "failure" &&
- outcomeRaw !== "unknown"
- ) {
- throw new MCPError(
- INVALID_PARAMS,
- `argument 'outcome' must be 'success', 'failure', or 'unknown'`,
- );
- }
-
- const agent = normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);
-
- const input: AppendApplyEvidenceInput = {
- pref_id: prefId,
- artifact,
- result: resultRaw as BrainApplyResult,
- agent,
- ...(outcomeRaw !== null ? { outcome: outcomeRaw } : {}),
- ...(note ? { note } : {}),
- };
-
- // Surface BrainPreferenceNotFoundError as a tool-level error envelope
- // (isError: true) rather than an MCP protocol error. The design doc
- // says "not an error condition" — the agent should see an informative
- // payload that explains what to do next, not a JSON-RPC error frame.
- // v0.10.16: assert applier role at the MCP boundary so the structural
- // permission gate fires before any I/O.
- try {
- const res = appendApplyEvidence(ctx.vault, input, {
- role: BRAIN_ROLES.applier,
- });
- return {
- logged_at: res.logged_at,
- log_path: vaultRelativeSafe(ctx.vault, res.log_path),
- absolute_log_path: resolve(res.log_path),
- agent,
- };
- } catch (exc) {
- if (exc instanceof BrainPreferenceNotFoundError) {
- // Re-throw as a non-MCPError so `server.handleToolsCall` packs it
- // into a `toolError` envelope (isError: true, single-text content).
- throw new Error(exc.message, { cause: exc });
- }
- throw exc;
- }
-}
-
-// ----- brain_note (§32B, v0.10.8) ------------------------------------------
-
-/**
- * Append one narrative-milestone line to today's Brain log. Agents
- * record release / merged-PR / discovered-fact lines under the `note`
- * event kind in `Brain/log/<today>.md` (and the JSONL sidecar).
- *
- * The body lives in `appendBrainNote` so the CLI verb (`o2b brain
- * note`) and this MCP handler share one code path. Validation errors
- * land in MCP's `INVALID_PARAMS` envelope here; the CLI wrapper
- * pre-validates usage shape and surfaces the same condition as exit 2.
- */
-async function toolBrainNote(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const rawText = coerceStr(args, "text", true)!;
- const agentArg = coerceStr(args, "agent", false);
-
- let res;
- try {
- res = appendBrainNote({
- vault: ctx.vault,
- text: rawText,
- ...(agentArg ? { agent: agentArg } : {}),
- ...(ctx.configPath ? { configPath: ctx.configPath } : {}),
- });
- } catch (err) {
- // `appendBrainNote` throws one validation error ("text is required");
- // any other failure is an I/O / filesystem fault from `appendLogEvent`
- // and must not be reported as a client-side INVALID_PARAMS.
- const message = (err as Error).message ?? String(err);
- const code = message.startsWith("brain_note:") ? INVALID_PARAMS : INTERNAL_ERROR;
- throw new MCPError(code, message);
- }
- return {
- logged_at: res.logged_at,
- log_path: res.log_path,
- absolute_log_path: res.absolute_log_path,
- agent: res.agent,
- };
-}
-
-// ----- brain_write_session (Agent Write Contract Suite, v0.41.0) ------------
-
-/**
- * One agent-facing surface for the write-session kernel: `op`
- * discriminates the lifecycle operation, `kind` (open only) picks
- * artifact vs panel. Envelopes are the same JSON the CLI prints -
- * status, step, prompt, errors, attempts_left, expires_at, target.
- * Structured request failures surface as INVALID_PARAMS with the
- * machine-readable error list in the message.
- */
-async function toolBrainWriteSession(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const op = coerceStr(args, "op", true)!;
- const sessionId = coerceStr(args, "session_id", false);
- const requireSessionId = (): string => {
- if (!sessionId) {
- throw new MCPError(INVALID_PARAMS, `brain_write_session: op '${op}' requires session_id`);
- }
- return sessionId;
- };
- try {
- switch (op) {
- case "open": {
- const kind = coerceStr(args, "kind", false) ?? "artifact";
- const agent =
- normalizeAgentArgument(coerceStr(args, "agent", false) ?? null) ??
- resolveAgentName(ctx.configPath ?? undefined);
- const requireReview = args["require_review"] === true;
- if (kind === "panel") {
- const topic = coerceStr(args, "topic", true)!;
- const personasRaw = args["personas"];
- const personas = Array.isArray(personasRaw)
- ? personasRaw.filter((x): x is string => typeof x === "string")
- : undefined;
- const target = coerceStr(args, "target", false);
- return asRecord(
- openPanelSession(ctx.vault, {
- agent,
- topic,
- requireReview,
- ...(personas && personas.length > 0 ? { personas } : {}),
- ...(target ? { targetPath: target } : {}),
- }),
- );
- }
- if (kind !== "artifact") {
- throw new MCPError(
- INVALID_PARAMS,
- `brain_write_session: kind must be 'artifact' or 'panel', got '${kind}'`,
- );
- }
- const target = coerceStr(args, "target", true)!;
- const intent = coerceStr(args, "intent", false) ?? "create";
- if (intent !== "create" && intent !== "overwrite" && intent !== "merge") {
- throw new MCPError(
- INVALID_PARAMS,
- `brain_write_session: intent must be create|overwrite|merge, got '${intent}'`,
- );
- }
- const schemaType = coerceStr(args, "schema_type", false);
- const prompt = coerceStr(args, "prompt", false);
- const retryCap = args["retry_cap"];
- return asRecord(
- openArtifactSession(ctx.vault, {
- agent,
- targetPath: target,
- intent,
- requireReview,
- ...(schemaType ? { schemaType } : {}),
- ...(prompt ? { prompt } : {}),
- ...(typeof retryCap === "number" ? { retryCap } : {}),
- }),
- );
- }
- case "submit": {
- const id = requireSessionId();
- const text = coerceStr(args, "text", true)!;
- return asRecord(dispatchSubmit(ctx.vault, { sessionId: id, text }));
- }
- case "approve":
- return asRecord(approveSession(ctx.vault, { sessionId: requireSessionId() }));
- case "abandon":
- return asRecord(abandonSession(ctx.vault, { sessionId: requireSessionId() }));
- case "status": {
- const id = requireSessionId();
- const probe = readWriteSession(ctx.vault, id, new Date().toISOString());
- if (probe.error !== null) throw new MCPError(INVALID_PARAMS, probe.error);
- if (probe.session === null) {
- throw new MCPError(INVALID_PARAMS, `unknown write-session: ${id}`);
- }
- return asRecord(sessionEnvelope(probe.session));
- }
- case "list": {
- const limit = coerceInt(args, "limit", 100, 1, 500);
- const sessions = listWriteSessions(ctx.vault, new Date().toISOString());
- return {
- total: sessions.length,
- sessions: sessions.slice(0, limit).map((rec) => asRecord(sessionEnvelope(rec))),
- };
- }
- default:
- throw new MCPError(
- INVALID_PARAMS,
- `brain_write_session: op must be open|submit|approve|abandon|status|list, got '${op}'`,
- );
- }
- } catch (err) {
- if (err instanceof WriteSessionRequestError) {
- // Preserve the {code, path, message} boundary contract: the
- // structured list rides MCPError's data slot, the message stays
- // human-readable prose.
- throw new MCPError(
- INVALID_PARAMS,
- err.message,
- err.errors.length > 0 ? { errors: err.errors } : undefined,
- );
- }
- throw err;
- }
-}
-
-function asRecord(envelope: WriteSessionEnvelope): Record<string, unknown> {
- return { ...envelope };
-}
-
-// ----- brain_context (v0.10.10) --------------------------------------------
-
-type PinnedContextOperation = "read" | "write" | "append" | "clear";
-
-function coercePinnedContextOperation(args: Record<string, unknown>): PinnedContextOperation {
- const operation = coerceStr(args, "operation", false) ?? "read";
- if (
- operation !== "read" &&
- operation !== "write" &&
- operation !== "append" &&
- operation !== "clear"
- ) {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_pinned_context operation must be one of: read, write, append, clear",
- );
- }
- return operation;
-}
-
-function serializePinnedContext(
- ctx: ServerContext,
- pinned: PinnedContext,
- operation?: PinnedContextOperation,
-): Record<string, unknown> {
- return {
- ...(operation ? { operation } : {}),
- present: pinned.present,
- path: vaultRelativeSafe(ctx.vault, pinned.path),
- absolute_path: pinned.path,
- content: pinned.content,
- };
-}
-
-async function toolBrainPinnedContext(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const operation = coercePinnedContextOperation(args);
- let pinned: PinnedContext;
- if (operation === "read") {
- pinned = readPinnedContext(ctx.vault);
- } else if (operation === "write") {
- pinned = writePinnedContext(ctx.vault, coerceStr(args, "content", true)!);
- } else if (operation === "append") {
- pinned = appendPinnedContext(ctx.vault, coerceStr(args, "content", true)!);
- } else {
- pinned = clearPinnedContext(ctx.vault);
- }
- return serializePinnedContext(ctx, pinned, operation);
-}
-
-function appendPinnedToContextContent(activeContent: string, pinnedContent: string): string {
- if (pinnedContent.length === 0) return activeContent;
- const pinnedBlock = `## Pinned context\n\n${pinnedContent}`;
- const trimmedActive = activeContent.trimEnd();
- if (trimmedActive.length === 0) return `${pinnedBlock}\n`;
- return `${trimmedActive}\n\n${pinnedBlock}\n`;
-}
-
-type BrainContextCounts = RegenerateActiveResult["counts"];
-
-const EMPTY_CONTEXT_COUNTS: BrainContextCounts = {
- confirmed: 0,
- quarantine: 0,
- retired_recent: 0,
- most_applied_30d: 0,
-};
-
-/**
- * Read-only pull-bootstrap of `Brain/active.md` + the active-preference
- * counts. Built for runtimes that have no `SessionStart` hook (Cursor,
- * Aider, raw Claude API): one tool call gives the agent the same
- * shortcut card the SessionStart-aware runtimes get injected
- * automatically.
- *
- * Behaviour matrix:
- * - Brain/ absent → present:false, content:"", zero counts.
- * - Brain/ present, active.md absent → call regenerateActive (idempotent)
- * and read the regenerated file.
- * - Brain/ present, active.md fresh → idempotent regenerate is a no-op
- * rewrite; the on-disk body is
- * returned verbatim.
- */
-async function toolBrainContext(ctx: ServerContext): Promise<Record<string, unknown>> {
- const dirs = brainDirs(ctx.vault);
- const activePath = brainActivePath(ctx.vault);
- const pinned = readPinnedContext(ctx.vault);
- if (!existsSync(dirs.brain)) {
- return {
- vault_path: ctx.vault,
- present: false,
- active_path: activePath,
- content: "",
- counts: EMPTY_CONTEXT_COUNTS,
- generated_at: null,
- pinned: serializePinnedContext(ctx, pinned),
- };
- }
-
- let counts: BrainContextCounts = EMPTY_CONTEXT_COUNTS;
- let error: string | undefined;
- try {
- counts = regenerateActive(ctx.vault).counts;
- } catch (err) {
- error = (err as Error)?.message ?? String(err);
- }
-
- // After a successful regenerateActive, active.md is guaranteed to
- // exist (the function either wrote it or confirmed an equal body
- // already on disk). A read failure here is an unrelated filesystem
- // race, not a missing-file branch — handle it in the same `error`
- // slot the regenerate failure uses.
- let content = "";
- let generatedAt: string | null = null;
- if (!error) {
- try {
- content = readFileSync(activePath, "utf8");
- const [meta] = parseFrontmatter(activePath);
- const v = meta["generated_at"];
- if (typeof v === "string" && v.trim().length > 0) {
- generatedAt = v;
- }
- } catch (err) {
- error = (err as Error)?.message ?? String(err);
- content = "";
- generatedAt = null;
- }
- }
- content = appendPinnedToContextContent(content, pinned.content);
-
- // Optional vault-root instruction file (v0.10.17). Absent file =
- // field omitted so hosts that strip unknown fields stay
- // byte-identical. Read errors are silently swallowed - this is a
- // best-effort enrichment, not a hard contract.
- let vaultInstruction: ReturnType<typeof readVaultInstructionFile> = null;
- try {
- vaultInstruction = readVaultInstructionFile(ctx.vault);
- } catch {
- vaultInstruction = null;
- }
-
- return {
- vault_path: ctx.vault,
- present: true,
- active_path: activePath,
- content,
- counts,
- generated_at: generatedAt,
- pinned: serializePinnedContext(ctx, pinned),
- ...(error ? { error } : {}),
- ...(vaultInstruction
- ? {
- vault_instruction: {
- path: vaultInstruction.path,
- content: vaultInstruction.content,
- lines: vaultInstruction.lines,
- },
- }
- : {}),
- };
-}
-
-// ----- brain_digest --------------------------------------------------------
-
-async function toolBrainDigest(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const since = coerceIsoDate(args, "since");
- const until = coerceIsoDate(args, "until");
- const format = coerceFormat(args) satisfies DigestFormat;
-
- // Pin ONE effective until instant so the rendered content, the
- // snapshot render, and the snapshot date key all describe the same
- // window even when the caller omitted `until`.
- const effectiveUntil = until ?? new Date();
- const result = renderDigest(ctx.vault, {
- ...(since ? { since } : {}),
- until: effectiveUntil,
- format,
- linkOutputFormat: resolveLinkOutputFormat(ctx.configPath ?? undefined),
- });
-
- const envelope: Record<string, unknown> = {
- format,
- empty: result.empty,
- content: result.content,
- };
- // Snapshot the structured summary, not the rendered string: render
- // a JSON digest for the snapshot regardless of the caller's format
- // so the run-over-run diff keys on data.
- const digestDate = isoDate(effectiveUntil);
- const snapshotSource =
- format === "json"
- ? result.content
- : renderDigest(ctx.vault, {
- ...(since ? { since } : {}),
- until: effectiveUntil,
- format: "json",
- linkOutputFormat: resolveLinkOutputFormat(ctx.configPath ?? undefined),
- }).content;
- let parsedSnapshot: unknown = null;
- try {
- parsedSnapshot = JSON.parse(snapshotSource);
- } catch {
- parsedSnapshot = null;
- }
- const delta =
- parsedSnapshot !== null
- ? captureReportDelta(
- ctx.vault,
- "digest",
- digestDate,
- parsedSnapshot,
- ctx.configPath ? { configPath: ctx.configPath } : {},
- )
- : null;
- return delta !== null ? { ...envelope, delta } : envelope;
-}
-
-// ----- brain_query ---------------------------------------------------------
-
-async function toolBrainQuery(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const preference = coerceStr(args, "preference", false);
- const topic = coerceStr(args, "topic", false);
- const since = coerceIsoDate(args, "since");
- // `format` is accepted for forward-compat (design doc §9.2 names it),
- // but the structured response shape is identical regardless — the
- // caller serialises however they want. We validate the value to catch
- // typos early.
- coerceFormat(args);
-
- const supplied = [preference, topic, since].filter((v) => v !== null).length;
- if (supplied === 0) {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_query requires exactly one of: preference, topic, since",
- );
- }
- if (supplied > 1) {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_query accepts at most one of: preference, topic, since",
- );
- }
-
- // Recall telemetry (t_405b8053): per-call opt-in mirroring
- // brain_search. The payload carries the query KIND only - never the
- // supplied preference id / topic slug / timestamp value.
- const telemetry = coerceBoolOptional(args, "telemetry") ?? false;
- const telemetryHost = coerceStringOptional(args, "telemetry_host", 200) ?? "mcp";
- const telemetrySessionId = coerceStringOptional(args, "session_id", 512);
- const telemetryTurnId = coerceStringOptional(args, "turn_id", 512);
- const queryKind = preference !== null ? "preference" : topic !== null ? "topic" : "since";
- const startedAtMs = Date.now();
- const emitQueryTelemetry = (status: "ok" | "empty" | "error", resultCount: number): void => {
- // Lazy emit kernel (t_5d7aa7c5): gate off = thunk never runs; a
- // throwing continuity write can never fail the query itself.
- emitGatedTelemetry(telemetry || undefined, () =>
- emitRecallTelemetry(ctx.vault, {
- host: telemetryHost,
- ...(telemetrySessionId !== undefined ? { sessionId: telemetrySessionId } : {}),
- ...(telemetryTurnId !== undefined ? { turnId: telemetryTurnId } : {}),
- mode: "query",
- status,
- durationMs: Date.now() - startedAtMs,
- resultCount,
- gaps:
- status === "error" ? ["query_error"] : status === "empty" ? ["no_matching_context"] : [],
- metadata: { query_kind: queryKind },
- }),
- );
- };
-
- try {
- if (preference !== null) {
- try {
- const res = queryByPreference(ctx.vault, preference);
- emitQueryTelemetry(res.evidence.length > 0 ? "ok" : "empty", res.evidence.length);
- return {
- mode: "preference",
- preference: serializePreference(res.preference),
- evidence: res.evidence.map(serializeLogEntry),
- };
- } catch (exc) {
- if (exc instanceof BrainNotFoundError) {
- throw new Error(exc.message, { cause: exc });
- }
- throw exc;
- }
- }
-
- if (topic !== null) {
- const res = queryByTopic(ctx.vault, topic);
- const resultCount = res.signals.length + res.all_log_events.length;
- emitQueryTelemetry(resultCount > 0 ? "ok" : "empty", resultCount);
- return {
- mode: "topic",
- topic,
- signals: res.signals.map(serializeSignal),
- preference: res.preference ? serializePreference(res.preference) : null,
- all_log_events: res.all_log_events.map(serializeLogEntry),
- };
- }
-
- // since
- const res = queryByLogSince(ctx.vault, since!);
- emitQueryTelemetry(res.length > 0 ? "ok" : "empty", res.length);
- return {
- mode: "since",
- since: since!.toISOString(),
- events: res.map(serializeLogEntry),
- };
- } catch (exc) {
- emitQueryTelemetry("error", 0);
- throw exc;
- }
-}
-
-// ----- brain_agent_query / brain_agent_diff --------------------------------
-
-async function toolBrainAgentQuery(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const topic = coerceStr(args, "topic", false);
- const query = coerceStr(args, "query", false);
- const kind = coerceAgentContributionKind(args, "kind");
- return queryAgentSources(ctx.vault, {
- agents: coerceStrList(args, "agents"),
- ...(topic !== null ? { topic } : {}),
- ...(query !== null ? { query } : {}),
- ...(kind !== null ? { kind } : {}),
- limit: coerceInt(args, "limit", 50, 1, 500),
- }) as unknown as Record<string, unknown>;
-}
-
-async function toolBrainAgentDiff(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const mode = coerceAgentDiffMode(args, "mode");
- const topic = coerceStr(args, "topic", false);
- const query = coerceStr(args, "query", false);
- const kind = coerceAgentContributionKind(args, "kind");
- return diffAgentSources(ctx.vault, {
- ...(mode !== null ? { mode } : {}),
- agents: coerceStrList(args, "agents"),
- ...(topic !== null ? { topic } : {}),
- ...(query !== null ? { query } : {}),
- ...(kind !== null ? { kind } : {}),
- limit: coerceInt(args, "limit", 50, 1, 500),
- }) as unknown as Record<string, unknown>;
-}
-
-function coerceAgentContributionKind(
- args: Record<string, unknown>,
- key: string,
-): AgentSourceContributionKind | null {
- const raw = coerceStr(args, key, false);
- if (raw === null) return null;
- if (raw !== "signal" && raw !== "preference" && raw !== "log") {
- throw new MCPError(
- INVALID_PARAMS,
- `argument '${key}' must be 'signal', 'preference', or 'log'`,
- );
- }
- return raw;
-}
-
-function coerceAgentDiffMode(
- args: Record<string, unknown>,
- key: string,
-): AgentSourceDiffMode | null {
- const raw = coerceStr(args, key, false);
- if (raw === null) return null;
- if (raw !== "browse" && raw !== "search" && raw !== "diff" && raw !== "map") {
- throw new MCPError(
- INVALID_PARAMS,
- `argument '${key}' must be 'browse', 'search', 'diff', or 'map'`,
- );
- }
- return raw;
-}
-
-// ----- brain_backlinks -----------------------------------------------------
-
-/** Serialize one entity for the MCP payload (no absolute paths). */
-function entityToPayload(
- entity: import("../core/brain/entities/types.ts").BrainEntity,
-): Record<string, unknown> {
- return {
- id: entity.id,
- category: entity.category,
- name: entity.name,
- aliases: [...entity.aliases],
- status: entity.status,
- ...(entity.source_agent !== undefined ? { source_agent: entity.source_agent } : {}),
- ...(entity.confidence !== undefined ? { confidence: entity.confidence } : {}),
- created_at: entity.created_at,
- updated_at: entity.updated_at,
- ...(entity.archived_at !== undefined ? { archived_at: entity.archived_at } : {}),
- relations: entity.relations.map((r) => ({ relation: r.relation, target: r.target })),
- body: entity.body,
- };
-}
-
-async function toolBrainEntity(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- // Argument validation happens at the boundary so INVALID_PARAMS is
- // reserved for genuine client-input errors; unexpected registry
- // failures (malformed entity file, I/O) surface as INTERNAL_ERROR.
- const view = coerceStr(args, "view", true)!;
- if (view !== "get" && view !== "list") {
- throw new MCPError(INVALID_PARAMS, `brain_entity: unknown view '${view}' (get | list)`);
- }
- const category = coerceStr(args, "category", false);
- if (category !== null) {
- try {
- validateEntityCategory(category);
- } catch (err) {
- throw new MCPError(INVALID_PARAMS, `brain_entity: ${(err as Error).message}`);
- }
- }
- const status = coerceStr(args, "status", false);
- if (status !== null && status !== "active" && status !== "archived") {
- throw new MCPError(INVALID_PARAMS, "brain_entity: status must be 'active' or 'archived'");
- }
- const query = view === "get" ? coerceStr(args, "query", true)! : null;
-
- try {
- if (view === "get") {
- const entity = getEntity(ctx.vault, {
- query: query!,
- ...(category !== null ? { category } : {}),
- });
- if (entity === null) return { found: false, query: query! };
- return { found: true, ...entityToPayload(entity) };
- }
- const entities = listEntities(ctx.vault, {
- ...(category !== null ? { category } : {}),
- ...(status !== null ? { status } : {}),
- });
- return { entities: entities.map(entityToPayload), total: entities.length };
- } catch (err) {
- if (err instanceof MCPError) throw err;
- if (err instanceof EntityAmbiguityError) {
- // A category-less query hitting several categories is a
- // client-resolvable input problem, not a server fault.
- throw new MCPError(INVALID_PARAMS, `brain_entity: ${err.message}`);
- }
- throw new MCPError(INTERNAL_ERROR, `brain_entity: ${(err as Error).message}`);
- }
-}
-
-async function toolBrainBacklinks(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const id = coerceStr(args, "id", true)!;
- // The index is keyed by normalised wikilink targets. Run callers'
- // input through the same normaliser so `pref-foo`, `[[pref-foo]]`,
- // `[[pref-foo|Alias]]`, and `Brain/preferences/pref-foo.md` all
- // resolve to the same lookup.
- const target = normaliseWikilinkTarget(id);
- const index = buildBacklinkIndex(ctx.vault);
- const refs = index.get(target) ?? [];
- return {
- id: target,
- count: refs.length,
- refs: refs.map((r) => ({
- source: r.source,
- source_kind: r.sourceKind,
- field: r.field,
- ...(r.timestamp !== undefined ? { timestamp: r.timestamp } : {}),
- })),
- };
-}
-
-async function toolBrainAudit(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const raw = coerceStr(args, "pref_id", true)!;
- // The trail is keyed by the original `pref-<slug>` id. Run the input
- // through the shared wikilink normaliser first (handles `[[id]]`,
- // `[[id|Alias]]`, and `Brain/.../id.md` forms), then strip the
- // pref-/ret- prefix so every reference resolves to one trail.
- const slug = normaliseWikilinkTarget(raw)
- .replace(/^(?:pref-|ret-)/, "")
- .trim();
- if (slug.length === 0) {
- throw new Error(`brain_audit: empty preference slug after normalising '${raw}'`);
- }
- const prefId = `pref-${slug}`;
- const { records, warnings } = readPrefAudit(ctx.vault, prefId);
- return {
- pref_id: prefId,
- count: records.length,
- records,
- warnings: warnings.map((w) => w.message),
- };
-}
-
-async function toolBrainMorningBrief(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const topK = optionalPositiveInt(args, "top_k", "brain_brief view=morning") ?? 10;
- const lookbackDays = optionalPositiveInt(args, "lookback_days", "brain_brief view=morning") ?? 7;
- const maxCharsPerMemory = optionalPositiveInt(
- args,
- "max_chars_per_memory",
- "brain_brief view=morning",
- );
- const maxTotalChars = optionalPositiveInt(args, "max_total_chars", "brain_brief view=morning");
- const now = new Date();
- const brief = buildMorningBrief(ctx.vault, {
- now,
- topK,
- lookbackDays,
- ...(maxCharsPerMemory !== undefined ? { maxCharsPerMemory } : {}),
- ...(maxTotalChars !== undefined ? { maxTotalChars } : {}),
- });
- // Pending-trigger section (t_cd1fee79): renders only when a trigger
- // scan persisted surfaceable triggers; included triggers are marked
- // delivered so a prompt shows once per cooldown window. Fail-soft -
- // a broken queue never breaks the brief.
- let triggerSection: ReturnType<typeof renderTriggerBriefSection> | null = null;
- try {
- triggerSection = renderTriggerBriefSection(ctx.vault, {
- now,
- cooldownDays: resolveTriggerCooldownDays(ctx.configPath ?? undefined),
- });
- if (triggerSection.triggers.length > 0) deliverBriefTriggers(ctx.vault, triggerSection, now);
- } catch {
- triggerSection = null;
- }
- const text =
- triggerSection !== null && triggerSection.text !== ""
- ? `${brief.text}${brief.text.length > 0 ? "\n\n" : ""}${triggerSection.text}`
- : brief.text;
- return {
- text,
- preferences: brief.preferences,
- open_questions: brief.openQuestions,
- recent_notes: brief.recentNotes,
- total_chars: brief.totalChars,
- ...(triggerSection !== null && triggerSection.triggers.length > 0
- ? {
- triggers: triggerSection.triggers.map((t) => ({
- id: t.id,
- kind: t.kind,
- urgency: t.urgency,
- reason: t.reason,
- })),
- }
- : {}),
- };
-}
-
-async function toolBrainSources(
- ctx: ServerContext,
- _args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- void _args;
- const report = aggregateSources(ctx.vault);
- return {
- sources: report.sources,
- total_active: report.total_active,
- total_processed: report.total_processed,
- };
-}
-
-async function toolBrainSwitchVault(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const name = coerceStr(args, "name", true)!;
- const configPath = ctx.configPath ?? defaultConfigPath();
- try {
- switchProfile(configPath, name);
- } catch (err) {
- throw new Error(`brain_switch_vault: ${(err as Error).message ?? String(err)}`, {
- cause: err,
- });
- }
- // The running server keeps its already-resolved vault; the switch
- // takes effect for the next server launch / CLI invocation.
- return {
- active: name,
- profiles: listProfiles(configPath).profiles,
- note: "active profile updated; takes effect on next server launch",
- };
-}
-
-// ----- brain_doctor --------------------------------------------------------
-
-async function toolBrainDoctor(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const strict = coerceBool(args, "strict");
- const format = coerceFormat(args);
-
- const result = runDoctor(ctx.vault, {
- strict,
- dbPath: resolveSearchConfig({ vault: ctx.vault, configPath: ctx.configPath ?? undefined })
- .dbPath,
- });
-
- // Decide a single ok flag — `strict` only changes the CLI exit code,
- // so we mirror that semantic here: with `strict`, warnings demote ok
- // to false. Errors always do.
- const ok = result.errors.length === 0 && (!strict || result.warnings.length === 0);
-
- return {
- format,
- ok,
- strict,
- errors: result.errors.map((i) => ({
- severity: i.severity,
- code: i.code,
- message: i.message,
- ...(i.path !== undefined ? { path: vaultRelativeSafe(ctx.vault, i.path) } : {}),
- })),
- warnings: result.warnings.map((i) => ({
- severity: i.severity,
- code: i.code,
- message: i.message,
- ...(i.path !== undefined ? { path: vaultRelativeSafe(ctx.vault, i.path) } : {}),
- })),
- // v0.10.15: ranked maintenance actions surfaced as a parallel
- // signal to errors/warnings. The list is independent of `strict`
- // because nothing here downgrades the `ok` flag - actions are
- // suggestions, not invariant violations.
- suggested_actions: collectMaintenanceActions(ctx.vault).map((a) => ({
- id: a.id,
- category: a.category,
- title: a.title,
- impact: a.impact,
- ...(a.target !== undefined ? { target: a.target } : {}),
- })),
- // v0.10.16: trust-layer fields. `trust_verdict` is always populated
- // by runDoctor; `verification_delta_summary` only when the caller
- // threads a dream summary through (not exposed via this tool's
- // surface, so it stays absent here). `instruction_file_warnings`
- // surfaces vault-root instruction files exceeding the configured
- // ceiling.
- ...(result.trust_verdict !== undefined ? { trust_verdict: result.trust_verdict } : {}),
- instruction_file_warnings: (result.instruction_file_warnings ?? []).map((w) => ({
- path: w.path,
- lines: w.lines,
- ceiling: w.ceiling,
- })),
- };
-}
-
-// ----- brain_health --------------------------------------------------------
-
-async function toolBrainHealth(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const format = coerceFormat(args);
- const result = runDoctor(ctx.vault);
- const sh = result.semantic_health;
- return {
- format,
- verdict: sh?.verdict ?? "clean",
- contradictions: (sh?.contradictions ?? []).map((c) => ({
- a: c.aId,
- b: c.bId,
- ...(c.scope !== null ? { scope: c.scope } : {}),
- jaccard: c.jaccard,
- a_sign: c.aSign,
- b_sign: c.bSign,
- })),
- concept_gaps: (sh?.conceptGaps ?? []).map((g) => ({
- term: g.term,
- frequency: g.frequency,
- })),
- stale_claims: (sh?.staleClaims ?? []).map((s) => ({
- id: s.id,
- last_evidence_at: s.lastEvidenceAt,
- age_days: s.ageDays,
- })),
- };
-}
-
-// ----- Serializers ---------------------------------------------------------
-
-function serializeSignal(s: BrainSignal): Record<string, unknown> {
- return {
- kind: s.kind,
- id: s.id,
- created_at: s.created_at,
- topic: s.topic,
- signal: s.signal,
- agent: s.agent,
- principle: s.principle,
- tags: [...s.tags],
- ...(s.scope !== undefined ? { scope: s.scope } : {}),
- ...(s.source !== undefined ? { source: [...s.source] } : {}),
- ...(s.raw !== undefined ? { raw: s.raw } : {}),
- };
-}
-
-function serializePreference(p: BrainPreference | BrainRetired): Record<string, unknown> {
- if (p.kind === "brain-retired") {
- return {
- kind: p.kind,
- id: p.id,
- status: p.status,
- retired_at: p.retired_at,
- retired_reason: p.retired_reason,
- retired_by: p.retired_by,
- ...(p.superseded_by !== undefined ? { superseded_by: p.superseded_by } : {}),
- created_at: p.created_at,
- topic: p.topic,
- ...(p.scope !== undefined ? { scope: p.scope } : {}),
- principle: p.principle,
- evidenced_by: [...p.evidenced_by],
- applied_count: p.applied_count,
- violated_count: p.violated_count,
- last_evidence_at: p.last_evidence_at,
- confidence: p.confidence,
- confidence_value: p.confidence_value,
- pinned: p.pinned,
- tags: [...p.tags],
- ...(p.aliases !== undefined ? { aliases: [...p.aliases] } : {}),
- };
- }
- return {
- kind: p.kind,
- id: p.id,
- created_at: p.created_at,
- confirmed_at: p.confirmed_at,
- unconfirmed_until: p.unconfirmed_until,
- topic: p.topic,
- ...(p.scope !== undefined ? { scope: p.scope } : {}),
- status: p.status,
- principle: p.principle,
- evidenced_by: [...p.evidenced_by],
- applied_count: p.applied_count,
- violated_count: p.violated_count,
- last_evidence_at: p.last_evidence_at,
- confidence: p.confidence,
- confidence_value: p.confidence_value,
- pinned: p.pinned,
- tags: [...p.tags],
- ...(p.supersedes !== undefined ? { supersedes: p.supersedes } : {}),
- ...(p.aliases !== undefined ? { aliases: [...p.aliases] } : {}),
- };
-}
-
-function serializeLogEntry(e: BrainLogEntry): Record<string, unknown> {
- // Preserve the structured payload verbatim (array values stay arrays).
- // JSON.stringify handles `ReadonlyArray<string>` and string values
- // identically. `Object.entries` widens the value type to `unknown` for
- // generic-keyed records under `verbatimModuleSyntax`; narrow explicitly.
- const body: Record<string, string | ReadonlyArray<string>> = {};
- for (const [k, v] of Object.entries(e.body) as ReadonlyArray<
- readonly [string, string | ReadonlyArray<string>]
- >) {
- body[k] = Array.isArray(v) ? [...v] : v;
- }
- return {
- timestamp: e.timestamp,
- event_type: e.eventType,
- body,
- };
-}
-
-// ----- Misc ----------------------------------------------------------------
-
-/**
- * Produce a vault-relative path, swallowing errors (a defensive pattern
- * for output rendering). Exported for unit tests
- * — internal callers stay inside this module.
- *
- * @internal
- */
-export function vaultRelativeSafe(vault: string, target: string): string {
- const absVault = resolve(vault);
- const absTarget = resolve(target);
- // Use Node's path.relative so the separator handling matches the host
- // OS (forward-slashes on POSIX, back-slashes on Windows). The prior
- // implementation hard-coded `"/"` and silently broke on Windows when
- // the vault sat under e.g. `C:\Users\...`.
- const rel = relative(absVault, absTarget);
- if (rel === "") return "";
- // `relative()` returns a path starting with `..` (or, in rare drive-
- // mismatch cases on Windows, an absolute path) when the target sits
- // outside the vault. In both situations we return the original target
- // unchanged — callers treat that as "not under vault" and render it
- // as-is.
- if (rel.startsWith("..") || isAbsolute(rel)) return target;
- return rel;
-}
-
-// ----- Tool registration ---------------------------------------------------
-
-const PINNED_CONTEXT_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {
- type: "object",
- required: ["present", "path", "absolute_path", "content"],
- properties: {
- operation: { type: "string", enum: ["read", "write", "append", "clear"] },
- present: { type: "boolean" },
- path: { type: "string" },
- absolute_path: { type: "string" },
- content: { type: "string" },
- },
- additionalProperties: false,
-};
-
-const BRAIN_CONTEXT_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {
- type: "object",
- required: ["vault_path", "present", "active_path", "content", "counts", "generated_at", "pinned"],
- properties: {
- vault_path: { type: "string" },
- present: { type: "boolean" },
- active_path: { type: "string" },
- content: { type: "string" },
- counts: {
- type: "object",
- required: ["confirmed", "quarantine", "retired_recent", "most_applied_30d"],
- properties: {
- confirmed: { type: "integer" },
- quarantine: { type: "integer" },
- retired_recent: { type: "integer" },
- most_applied_30d: { type: "integer" },
- },
- additionalProperties: false,
- },
- generated_at: {},
- pinned: PINNED_CONTEXT_OUTPUT_SCHEMA,
- },
-};
-
-const BRAIN_QUERY_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {
- type: "object",
- required: ["mode"],
- properties: {
- mode: { type: "string", enum: ["preference", "topic", "since"] },
- },
-};
-
-// ----- brain_operator_summary (v0.10.16) -----------------------------------
-
-/**
- * Aggregate operator dashboard: trust verdict, doctor / dream
- * counts, verification delta summary, ranked maintenance actions,
- * and instruction-file ceiling warnings - one read-only call so an
- * operator does not run `brain_digest` + `brain_doctor` separately.
- */
-async function toolBrainOperatorSummary(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const topRaw = args["top_actions"];
- let topActionsN: number | undefined;
- if (topRaw !== undefined && topRaw !== null) {
- // Strict integer coercion: reject `"3abc"`, `"2.5"`, and other
- // shapes `Number.parseInt` would silently accept. Only a pure
- // integer literal is allowed.
- if (typeof topRaw === "number") {
- if (!Number.isInteger(topRaw) || topRaw < 0) {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_brief view=operator: top_actions must be a non-negative integer",
- );
- }
- topActionsN = topRaw;
- } else if (typeof topRaw === "string") {
- const trimmed = topRaw.trim();
- if (trimmed === "" || !/^[0-9]+$/.test(trimmed)) {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_brief view=operator: top_actions must be a non-negative integer",
- );
- }
- topActionsN = Number.parseInt(trimmed, 10);
- } else {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_brief view=operator: top_actions must be a non-negative integer",
- );
- }
- }
-
- const includeDreamRaw = args["include_dream"];
- let includeDream: boolean;
- if (includeDreamRaw === undefined || includeDreamRaw === null) {
- includeDream = true;
- } else if (typeof includeDreamRaw === "boolean") {
- includeDream = includeDreamRaw;
- } else {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_brief view=operator: include_dream must be a boolean",
- );
- }
-
- let dreamSummary;
- let dreamError: string | undefined;
- if (includeDream) {
- try {
- dreamSummary = dream(ctx.vault, { dryRun: true });
- } catch (err) {
- // Surface the failure so callers know the dashboard is missing
- // verification + dream signals; do not silently produce a
- // partial envelope.
- dreamError = (err as Error).message ?? String(err);
- }
- }
- const summary = buildOperatorSummary(ctx.vault, {
- ...(dreamSummary ? { dreamSummary } : {}),
- ...(topActionsN !== undefined ? { topActionsN } : {}),
- });
- return {
- vault_path: ctx.vault,
- trust_verdict: summary.trust_verdict,
- digest_summary: summary.digest_summary,
- doctor_summary: {
- warning_count: summary.doctor_summary.warning_count,
- error_count: summary.doctor_summary.error_count,
- },
- dream_summary: summary.dream_summary,
- verification_delta: {
- summary: summary.verification_delta.summary,
- entries: summary.verification_delta.entries,
- },
- top_actions: summary.top_actions,
- instruction_file_warnings: summary.instruction_file_warnings,
- ...(dreamError !== undefined ? { dream_error: dreamError } : {}),
- };
-}
-
-// ----- brain_unlinked_mentions (v0.10.17) ----------------------------------
-
-/**
- * Raw-text mentions of a target's title / aliases that are NOT
- * already inside `[[...]]` wikilinks. Read-only walker over
- * `Brain/preferences/` and `Brain/retired/`. Match boundary is
- * Unicode-aware (`\p{L}`, `\p{N}`), language-agnostic.
- */
-async function toolBrainUnlinkedMentions(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const idRaw = args["id"];
- if (typeof idRaw !== "string" || idRaw.trim().length === 0) {
- throw new MCPError(INVALID_PARAMS, "brain_unlinked_mentions: id must be a non-empty string");
- }
- const targetId = normaliseWikilinkTarget(idRaw);
- // Limit coercion mirrors the v0.10.16 `brain_operator_summary`
- // precedent: accept either a number or a strict integer-literal
- // string (`"5"` ok; `"abc"`, `"3abc"`, `"2.5"` rejected). This
- // keeps the MCP boundary uniform across new tools.
- const limitRaw = args["limit"];
- let limit: number | undefined;
- if (limitRaw !== undefined && limitRaw !== null) {
- if (typeof limitRaw === "number") {
- if (!Number.isInteger(limitRaw) || limitRaw < 1) {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_unlinked_mentions: limit must be a positive integer",
- );
- }
- limit = limitRaw;
- } else if (typeof limitRaw === "string") {
- const trimmed = limitRaw.trim();
- if (trimmed === "" || !/^[0-9]+$/.test(trimmed)) {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_unlinked_mentions: limit must be a positive integer",
- );
- }
- const parsed = Number.parseInt(trimmed, 10);
- if (parsed < 1) {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_unlinked_mentions: limit must be a positive integer",
- );
- }
- limit = parsed;
- } else {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_unlinked_mentions: limit must be a positive integer",
- );
- }
- }
- const mentions = findUnlinkedMentions(ctx.vault, targetId, limit !== undefined ? { limit } : {});
- return {
- vault_path: ctx.vault,
- target_id: targetId,
- mentions: mentions.map((m) => ({
- source: m.source,
- line: m.line,
- term: m.term,
- context: m.contextSnippet,
- })),
- };
-}
-
-// ----- brain_foresight (t_08a79c81) -----------------------------------------
-
-/** Forward-looking projection envelope; read-only fold. */
-function toolBrainForesight(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Record<string, unknown> {
- const horizonRaw = args["horizon_days"];
- let horizonDays = FORESIGHT_HORIZON_DAYS;
- if (horizonRaw !== undefined && horizonRaw !== null) {
- if (typeof horizonRaw !== "number" || !Number.isInteger(horizonRaw) || horizonRaw < 1) {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_foresight: horizon_days must be a positive integer",
- );
- }
- horizonDays = horizonRaw;
- }
- return { ...buildForesight(ctx.vault, { now: new Date(), horizonDays }) };
-}
-
-// ----- brain_labels (t_7a41f42d) ---------------------------------------------
-
-/** Controlled-vocabulary classification over the schema pack's labels. */
-function toolBrainLabels(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Record<string, unknown> {
- const op = args["operation"];
- if (op !== "assign" && op !== "remove" && op !== "show") {
- throw new MCPError(INVALID_PARAMS, "brain_labels: operation must be assign|remove|show");
- }
- const path = args["path"];
- if (typeof path !== "string" || path.trim() === "") {
- throw new MCPError(INVALID_PARAMS, "brain_labels: path must be a vault-relative string");
- }
- if (op === "show") {
- const [metadata] = parseFrontmatter(vaultContainedPath(ctx.vault, path, "brain_labels show"));
- return { path, labels: readLabels(metadata) };
- }
- const pack = loadSchemaPack(ctx.vault);
- const dimension = args["dimension"];
- if (typeof dimension !== "string" || dimension.trim() === "") {
- throw new MCPError(INVALID_PARAMS, `brain_labels ${op}: dimension must be non-empty`);
- }
- try {
- if (op === "remove") {
- return { ...removeNoteLabel(ctx.vault, path, { dimension, pack }) };
- }
- const value = args["value"];
- if (typeof value !== "string" || value.trim() === "") {
- throw new MCPError(INVALID_PARAMS, "brain_labels assign: value must be non-empty");
- }
- const agentArg = args["agent"];
- const agent =
- normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??
- resolveAgentName(ctx.configPath ?? undefined);
- return {
- ...assignNoteLabel(ctx.vault, path, { dimension, value, pack, agent, now: new Date() }),
- };
- } catch (exc) {
- if (exc instanceof LabelVocabularyError) {
- throw new MCPError(INVALID_PARAMS, `brain_labels ${op}: ${exc.message}`);
- }
- throw exc;
- }
-}
-
-// ----- brain_tiers (t_3f92d3f1) ----------------------------------------------
-
-/** Staged repair surface for identity-tier frontmatter hand-edits. */
-async function toolBrainTiers(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const op = args["operation"];
- if (op !== "check" && op !== "restore" && op !== "accept") {
- throw new MCPError(INVALID_PARAMS, "brain_tiers: operation must be check|restore|accept");
- }
- const searchConfig = resolveSearchConfig({
- vault: ctx.vault,
- configPath: ctx.configPath ?? undefined,
- });
- if (op === "check") {
- // Fail-soft: a vault that was never indexed has no snapshots and
- // therefore no drift - not an error.
- if (!existsSync(searchConfig.dbPath)) return { findings: [] };
- const store = await Store.open(searchConfig, { mode: "read" });
- try {
- return { findings: store.listTierDrift() };
- } finally {
- await store.close();
- }
- }
- const path = args["path"];
- if (typeof path !== "string" || path.trim() === "") {
- throw new MCPError(INVALID_PARAMS, `brain_tiers ${op}: path must be a vault-relative string`);
- }
- if (op === "restore" && args["apply"] !== true) {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_tiers restore: pass apply=true - restore writes the file",
- );
- }
- const field = typeof args["field"] === "string" ? (args["field"] as string) : undefined;
- if (!existsSync(searchConfig.dbPath)) {
- throw new MCPError(INVALID_PARAMS, `brain_tiers ${op}: the vault has no search index yet`);
- }
- const store = await Store.open(searchConfig, { mode: "write" });
- try {
- const docId = store.getDocumentIdByPath(path);
- if (docId === null) {
- throw new MCPError(INVALID_PARAMS, `brain_tiers ${op}: not indexed: ${path}`);
- }
- const rows = store
- .listTierDrift()
- .filter((r) => r.documentId === docId && (field === undefined || r.field === field));
- if (rows.length === 0) {
- throw new MCPError(INVALID_PARAMS, `brain_tiers ${op}: no open drift for ${path}`);
- }
- if (op === "restore") {
- const absolute = vaultContainedPath(ctx.vault, path, "brain_tiers restore");
- const [metadata, body] = parseFrontmatter(absolute);
- const next = { ...metadata };
- for (const r of rows) {
- next[r.field] = frontmatterValueFromSnapshot(r.expected, r.field);
- }
- writeFrontmatterAtomic(absolute, next, body, { overwrite: true });
- for (const r of rows) store.clearTierDrift(docId, r.field);
- return { restored: rows.map((r) => r.field), path };
- }
- const snapshot: Record<string, unknown> = { ...store.getTierSnapshot(docId) };
- for (const r of rows) {
- snapshot[r.field] = r.actual;
- store.clearTierDrift(docId, r.field);
- }
- store.setTierSnapshot(docId, snapshot);
- return { accepted: rows.map((r) => r.field), path };
- } finally {
- await store.close();
- }
-}
-
-/** Resolve a vault-relative path, refusing traversal and symlink escapes. */
-function vaultContainedPath(vault: string, relPath: string, label: string): string {
- try {
- return resolveNotePath(vault, relPath);
- } catch (exc) {
- throw new MCPError(INVALID_PARAMS, `${label}: ${(exc as Error).message}`);
- }
-}
-
-/** Narrow a snapshot value to the shapes frontmatter can carry. */
-function frontmatterValueFromSnapshot(value: unknown, field: string): FrontmatterMap[string] {
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
- return value;
- }
- if (Array.isArray(value) && value.every((v): v is string => typeof v === "string")) {
- return value;
- }
- throw new MCPError(
- INVALID_PARAMS,
- `brain_tiers restore: snapshot value for "${field}" is not a frontmatter scalar or string array`,
- );
-}
-
-// ----- brain_secrets (t_0b134404) ---------------------------------------------
-
-/**
- * Capability-gated custody, agent-facing subset: list metadata and
- * run an allowlisted command. Deliberately NO set/get over MCP - the
- * material enters via the operator's CLI and leaves only into a
- * subprocess env.
- */
-async function toolBrainSecrets(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const op = args["operation"];
- if (op !== "list" && op !== "run") {
- throw new MCPError(INVALID_PARAMS, "brain_secrets: operation must be list|run");
- }
- if (op === "list") {
- return { secrets: listSecrets(ctx.vault) };
- }
- const name = args["name"];
- if (typeof name !== "string" || name.trim() === "") {
- throw new MCPError(INVALID_PARAMS, "brain_secrets run: name must be non-empty");
- }
- const command = args["command"];
- if (
- !Array.isArray(command) ||
- command.length === 0 ||
- !command.every((part): part is string => typeof part === "string")
- ) {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_secrets run: command must be a non-empty array of strings",
- );
- }
- const agentArg = args["agent"];
- const agent =
- normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??
- resolveAgentName(ctx.configPath ?? undefined);
- try {
- const result = await runWithSecret(ctx.vault, name, command, { agent, now: new Date() });
- return { exit_code: result.exitCode, stdout: result.stdout, stderr: result.stderr };
- } catch (exc) {
- if (exc instanceof SecretExecDeniedError) {
- throw new MCPError(INVALID_PARAMS, `brain_secrets run: ${exc.message}`);
- }
- throw exc;
- }
-}
-
-// ----- brain_maintenance (t_166d1226) ------------------------------------------
-
-/** Quiet-window, lease-guarded heavy maintenance lane. */
-async function toolBrainMaintenance(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const op = args["operation"];
- if (op !== "run" && op !== "status") {
- throw new MCPError(INVALID_PARAMS, "brain_maintenance: operation must be run|status");
- }
- const now = new Date();
- if (op === "status") {
- return {
- lease: currentLease(ctx.vault, { now }),
- journal: listJournal(ctx.vault, 10),
- };
- }
- let window: DailyWindow | undefined;
- const startHour = args["window_start_hour"];
- const endHour = args["window_end_hour"];
- if (startHour !== undefined || endHour !== undefined) {
- if (
- typeof startHour !== "number" ||
- typeof endHour !== "number" ||
- !Number.isInteger(startHour) ||
- !Number.isInteger(endHour) ||
- startHour < 0 ||
- startHour > 23 ||
- endHour < 0 ||
- endHour > 23
- ) {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_maintenance run: window_start_hour/window_end_hour must be integers 0..23",
- );
- }
- const tz = typeof args["tz"] === "string" ? (args["tz"] as string) : "UTC";
- window = { startHour, endHour, tz };
- }
- const agentArg = args["agent"];
- const agent =
- normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??
- resolveAgentName(ctx.configPath ?? undefined);
- const searchConfig = resolveSearchConfig({
- vault: ctx.vault,
- configPath: ctx.configPath ?? undefined,
- });
- // Same per-task deadlines as the CLI lane (t_06784b8d): one fresh
- // cooperative safeguard per task, budget resolved per-op -> global
- // -> default.
- const laneSafeguard = (operation: "dream" | "reindex" | "bridges" | "clusters") =>
- createSafeguard({
- operation,
- timeoutMs: resolveSafeguardTimeoutMs(operation, ctx.configPath ?? undefined),
- });
- const result = await runMaintenance(ctx.vault, {
- now,
- holder: `${agent}@${process.pid}`,
- force: args["force"] === true,
- ...(window !== undefined ? { window } : {}),
- tasks: [
- {
- name: "dream",
- run: async () => {
- dream(ctx.vault, { now, safeguard: laneSafeguard("dream") });
- },
- },
- {
- name: "reindex",
- run: async () => {
- await indexVault(searchConfig, { safeguard: laneSafeguard("reindex") });
- },
- },
- // Same lane contract as the CLI verb (link-recall-intelligence):
- // bridges and clusters run after reindex so they see fresh
- // edges; both are fail-soft without embeddings, and a metrics
- // write failure never fails the task.
- {
- name: "bridges",
- run: async () => {
- const store = await Store.open(searchConfig, { mode: "read" });
- try {
- const report = discoverBridges(store, {
- dismissed: readDismissedBridges(ctx.vault),
- safeguard: laneSafeguard("bridges"),
- });
- writeBridgeProposals(ctx.vault, report, { now });
- try {
- appendMetric(ctx.vault, {
- surface: "bridge_discovery",
- runAt: isoSecond(now),
- payload: {
- proposals: report.proposals.length,
- scanned_candidates: report.scannedCandidates,
- vec_available: report.vecAvailable,
- lane: true,
- },
- });
- } catch {
- // Metrics are observability, not correctness.
- }
- } finally {
- await store.close();
- }
- },
- },
- {
- name: "clusters",
- run: async () => {
- const store = await Store.open(searchConfig, { mode: "read" });
- try {
- const communities = detectCommunities(store, { safeguard: laneSafeguard("clusters") });
- const materialized = materializeClusterNotes(ctx.vault, communities, { store, now });
- try {
- appendMetric(ctx.vault, {
- surface: "communities",
- runAt: isoSecond(now),
- payload: {
- communities: communities.length,
- sizes: communities.map((c) => c.size),
- written: materialized.written.length,
- removed: materialized.removed.length,
- lane: true,
- },
- });
- } catch {
- // Metrics are observability, not correctness.
- }
- } finally {
- await store.close();
- }
- },
- },
- ],
- });
- return { verdict: result.verdict, tasks: result.tasks };
-}
-
-// ----- brain_bridges (t_ab540afe) --------------------------------------------
-
-/**
- * Bridge discovery over the vec index: discover regenerates the
- * reviewable proposals artifact, accept writes one related wikilink,
- * dismiss persists a pair suppression, list reads the artifact back.
- */
-async function toolBrainBridges(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const op = args["operation"];
- if (op !== "discover" && op !== "list" && op !== "accept" && op !== "dismiss") {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_bridges: operation must be discover|list|accept|dismiss",
- );
- }
- if (op === "accept" || op === "dismiss") {
- const source = args["source"];
- const target = args["target"];
- if (typeof source !== "string" || source.trim() === "") {
- throw new MCPError(
- INVALID_PARAMS,
- `brain_bridges ${op}: source must be a vault-relative path`,
- );
- }
- if (typeof target !== "string" || target.trim() === "") {
- throw new MCPError(
- INVALID_PARAMS,
- `brain_bridges ${op}: target must be a vault-relative path`,
- );
- }
- if (op === "dismiss") {
- return {
- dismissed: bridgePairKey(source, target),
- added: dismissBridge(ctx.vault, source, target),
- };
- }
- try {
- const pack = loadSchemaPack(ctx.vault);
- return { ...acceptBridge(ctx.vault, source, target, { pack }), source, target };
- } catch (exc) {
- const message = (exc as Error).message ?? String(exc);
- if (/outside the vault|does not exist|link constraint/.test(message)) {
- throw new MCPError(INVALID_PARAMS, `brain_bridges accept: ${message}`);
- }
- throw exc;
- }
- }
- if (op === "list") {
- const path = join(ctx.vault, "Brain", "proposals", "bridges.md");
- if (!existsSync(path)) return { exists: false, proposals: 0 };
- const [meta] = parseFrontmatter(path);
- return {
- exists: true,
- path: "Brain/proposals/bridges.md",
- generated_at: meta["generated_at"] ?? null,
- proposals: Number(meta["proposals"] ?? 0),
- };
- }
- // discover
- const max = args["max"];
- if (max !== undefined && (!Number.isInteger(max) || (max as number) < 1)) {
- throw new MCPError(INVALID_PARAMS, "brain_bridges discover: max must be a positive integer");
- }
- const minSimilarity = args["min_similarity"];
- if (
- minSimilarity !== undefined &&
- (typeof minSimilarity !== "number" || minSimilarity <= 0 || minSimilarity > 1)
- ) {
- throw new MCPError(INVALID_PARAMS, "brain_bridges discover: min_similarity must be in (0, 1]");
- }
- const searchConfig = resolveSearchConfig({
- vault: ctx.vault,
- configPath: ctx.configPath ?? undefined,
- });
- if (!existsSync(searchConfig.dbPath)) {
- return { vec_available: false, proposals: [], reason: "index not built" };
- }
- const store = await Store.open(searchConfig, { mode: "read" });
- const now = new Date();
- try {
- const dismissed = readDismissedBridges(ctx.vault);
- const report = discoverBridges(store, {
- ...(max !== undefined ? { maxProposals: max as number } : {}),
- ...(minSimilarity !== undefined ? { minSimilarity } : {}),
- dismissed,
- });
- writeBridgeProposals(ctx.vault, report, { now });
- try {
- appendMetric(ctx.vault, {
- surface: "bridge_discovery",
- runAt: isoSecond(now),
- payload: {
- proposals: report.proposals.length,
- scanned_candidates: report.scannedCandidates,
- vec_available: report.vecAvailable,
- dismissed_total: dismissed.size,
- },
- });
- } catch {
- // Metrics are observability, not correctness.
- }
- return {
- vec_available: report.vecAvailable,
- ...(report.reason !== undefined ? { reason: report.reason } : {}),
- scanned_candidates: report.scannedCandidates,
- proposals: report.proposals,
- artifact: "Brain/proposals/bridges.md",
- };
- } finally {
- await store.close();
- }
-}
-
-// ----- brain_clusters (t_4ba927ec) --------------------------------------------
-
-/** Graph-wide community detection with materialized cluster notes. */
-async function toolBrainClusters(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const op = args["operation"];
- if (op !== "run" && op !== "list") {
- throw new MCPError(INVALID_PARAMS, "brain_clusters: operation must be run|list");
- }
- if (op === "list") {
- const dir = join(ctx.vault, "Brain", "clusters");
- if (!existsSync(dir)) return { clusters: [] };
- const clusters = readdirSync(dir)
- .filter((f) => f.endsWith(".md"))
- .toSorted()
- .map((f) => {
- const [meta] = parseFrontmatter(join(dir, f));
- return meta["kind"] === "brain-cluster"
- ? {
- path: `Brain/clusters/${f}`,
- cluster: String(meta["cluster"] ?? ""),
- size: Number(meta["size"] ?? 0),
- density: Number(meta["density"] ?? 0),
- generated_at: String(meta["generated_at"] ?? ""),
- }
- : null;
- })
- .filter((c) => c !== null);
- return { clusters };
- }
- const minSize = args["min_size"];
- if (minSize !== undefined && (!Number.isInteger(minSize) || (minSize as number) < 2)) {
- throw new MCPError(INVALID_PARAMS, "brain_clusters run: min_size must be an integer >= 2");
- }
- const searchConfig = resolveSearchConfig({
- vault: ctx.vault,
- configPath: ctx.configPath ?? undefined,
- });
- if (!existsSync(searchConfig.dbPath)) {
- return { communities: [], reason: "index not built" };
- }
- const store = await Store.open(searchConfig, { mode: "read" });
- const now = new Date();
- try {
- const communities = detectCommunities(
- store,
- minSize !== undefined ? { minSize: minSize as number } : {},
- );
- const materialized = materializeClusterNotes(ctx.vault, communities, { store, now });
- try {
- appendMetric(ctx.vault, {
- surface: "communities",
- runAt: isoSecond(now),
- payload: {
- communities: communities.length,
- sizes: communities.map((c) => c.size),
- written: materialized.written.length,
- removed: materialized.removed.length,
- },
- });
- } catch {
- // Metrics are observability, not correctness.
- }
- return {
- communities: communities.map((c) => ({
- id: c.id,
- size: c.size,
- density: c.density,
- members: c.members.map((m) => m.path),
- })),
- written: materialized.written,
- removed: materialized.removed,
- };
- } finally {
- await store.close();
- }
-}
-
-// ----- brain_benchmark (t_e2215d49) -------------------------------------------
-
-/** Recall-quality benchmark over an inline dataset. */
-async function toolBrainBenchmark(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const op = args["operation"];
- if (op !== "run") {
- throw new MCPError(INVALID_PARAMS, "brain_benchmark: operation must be run");
- }
- const k = args["k"];
- if (k !== undefined && (!Number.isInteger(k) || (k as number) < 1)) {
- throw new MCPError(INVALID_PARAMS, "brain_benchmark run: k must be a positive integer");
- }
- let dataset;
- try {
- dataset = parseRecallBenchmarkDataset(args["dataset"]);
- } catch (exc) {
- throw new MCPError(INVALID_PARAMS, `brain_benchmark run: ${(exc as Error).message}`);
- }
- const searchConfig = resolveSearchConfig({
- vault: ctx.vault,
- configPath: ctx.configPath ?? undefined,
- });
- const now = new Date();
- const report = await runRecallBenchmark(searchConfig, dataset, {
- ...(k !== undefined ? { k: k as number } : {}),
- expand: args["expand"] === true,
- });
- try {
- appendMetric(ctx.vault, {
- surface: "recall_benchmark",
- runAt: isoSecond(now),
- payload: {
- total: report.total,
- k: report.k,
- expand: report.expand,
- hit_at_k: report.hitAtK,
- mrr: report.mrr,
- misses: report.perQuery.filter((q) => !q.hit).map((q) => q.id),
- },
- });
- } catch {
- // Metrics are observability, not correctness.
- }
- return {
- total: report.total,
- k: report.k,
- expand: report.expand,
- hit_at_k: report.hitAtK,
- mrr: report.mrr,
- per_query: report.perQuery,
- };
-}
-
-// ----- brain_tune (t_ae973491) -------------------------------------------------
-
-/** Opt-in self-tuning recall: run the grid, inspect, or reset. */
-async function toolBrainTune(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const op = args["operation"];
- if (op !== "run" && op !== "status" && op !== "reset") {
- throw new MCPError(INVALID_PARAMS, "brain_tune: operation must be run|status|reset");
- }
- const searchConfig = resolveSearchConfig({
- vault: ctx.vault,
- configPath: ctx.configPath ?? undefined,
- });
- if (op === "status") {
- return {
- enabled: searchConfig.recall.selfTuningEnabled,
- tuned: loadTunedParameters(ctx.vault),
- };
- }
- if (op === "reset") {
- return { removed: resetTuning(ctx.vault) };
- }
- const k = args["k"];
- if (k !== undefined && (!Number.isInteger(k) || (k as number) < 1)) {
- throw new MCPError(INVALID_PARAMS, "brain_tune run: k must be a positive integer");
- }
- let dataset;
- try {
- dataset = parseRecallBenchmarkDataset(args["dataset"]);
- } catch (exc) {
- throw new MCPError(INVALID_PARAMS, `brain_tune run: ${(exc as Error).message}`);
- }
- const now = new Date();
- const report = await tuneRecall(searchConfig, dataset, {
- ...(k !== undefined ? { k: k as number } : {}),
- now,
- });
- try {
- appendMetric(ctx.vault, {
- surface: "self_tuning",
- runAt: isoSecond(now),
- payload: {
- chosen: report.chosen,
- evaluated: report.evaluated.length,
- best_mrr: Math.max(...report.evaluated.map((e) => e.mrr)),
- dataset_hash: report.datasetHash,
- },
- });
- } catch {
- // Metrics are observability, not correctness.
- }
- return {
- chosen: report.chosen,
- evaluated: report.evaluated.map((e) => ({ params: e.params, mrr: e.mrr, hit_at_k: e.hitAtK })),
- dataset_hash: report.datasetHash,
- };
-}
-
-// ----- brain_dead_ends (t_be62c62d) -----------------------------------------
-
-/**
- * Negative-knowledge registry: record one tried-and-failed approach
- * or list the bounded active set, newest first.
- */
-function toolBrainDeadEnds(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Record<string, unknown> {
- const op = args["operation"];
- if (op !== "record" && op !== "list") {
- throw new MCPError(INVALID_PARAMS, "brain_dead_ends: operation must be record|list");
- }
- if (op === "list") {
- const { entries, warnings } = listDeadEnds(ctx.vault);
- return { entries, warnings };
- }
- const approach = args["approach"];
- const reason = args["reason"];
- if (typeof approach !== "string" || approach.trim() === "") {
- throw new MCPError(INVALID_PARAMS, "brain_dead_ends record: approach must be non-empty");
- }
- if (typeof reason !== "string" || reason.trim() === "") {
- throw new MCPError(INVALID_PARAMS, "brain_dead_ends record: reason must be non-empty");
- }
- const agentArg = args["agent"];
- const agent =
- normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??
- resolveAgentName(ctx.configPath ?? undefined);
- const result = recordDeadEnd(ctx.vault, {
- approach,
- reason,
- ...(typeof args["context"] === "string" ? { context: args["context"] as string } : {}),
- agent,
- now: new Date(),
- });
- return { ok: true, id: result.entry.id, path: result.entry.path, archived: result.archived };
-}
-
-// ----- brain_truth (Entity Truth & Self-Improving Dream Suite) ---------------
-
-/**
- * Operator/agent surface over the entity claim ledger: ingest one
- * claim, render slots/conflicts from the fold, aggregate exact-match
- * quantities, report cross-agent collisions. Read ops are pure folds
- * over the append-only ledger.
- */
-function toolBrainTruth(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Record<string, unknown> {
- const op = args["operation"];
- if (
- op !== "ingest" &&
- op !== "slots" &&
- op !== "conflicts" &&
- op !== "aggregate" &&
- op !== "collisions"
- ) {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_truth: operation must be ingest|slots|conflicts|aggregate|collisions",
- );
- }
- const requireStr = (name: string): string => {
- const value = args[name];
- if (typeof value !== "string" || value.trim() === "") {
- throw new MCPError(INVALID_PARAMS, `brain_truth ${op}: ${name} must be a non-empty string`);
- }
- return value;
- };
-
- if (op === "ingest") {
- const quantityValue = args["quantity_value"];
- if (
- (quantityValue === undefined || quantityValue === null) &&
- (typeof args["quantity_unit"] === "string" || typeof args["quantity_action"] === "string")
- ) {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_truth ingest: quantity_value is required when quantity_unit or quantity_action is provided",
- );
- }
- let quantity: { value: number; unit: string | null; action: string | null } | undefined;
- if (quantityValue !== undefined && quantityValue !== null) {
- if (typeof quantityValue !== "number" || !Number.isFinite(quantityValue)) {
- throw new MCPError(INVALID_PARAMS, "brain_truth ingest: quantity_value must be a number");
- }
- quantity = {
- value: quantityValue,
- unit: typeof args["quantity_unit"] === "string" ? (args["quantity_unit"] as string) : null,
- action:
- typeof args["quantity_action"] === "string" ? (args["quantity_action"] as string) : null,
- };
- }
- const agentArg = args["agent"];
- const agent =
- normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??
- resolveAgentName(ctx.configPath ?? undefined);
- const result = appendClaimEvent(ctx.vault, {
- ts: isoSecond(new Date()),
- agent,
- entity: requireStr("entity"),
- aspect: requireStr("aspect"),
- value: requireStr("value"),
- ...(quantity !== undefined ? { valueKind: "quantity" as const, quantity } : {}),
- source: requireStr("source"),
- });
- return {
- ok: true,
- entity: result.event.entity,
- aspect: result.event.aspect,
- path: result.path,
- };
- }
-
- const events = readClaimEvents(ctx.vault).events;
- if (op === "slots" || op === "conflicts") {
- const state = computeTruthStateWithConflicts(events);
- if (op === "conflicts") return { events: state.events, conflicts: state.conflicts };
- const entityFilter = args["entity"];
- const slots =
- typeof entityFilter === "string" && entityFilter.trim() !== ""
- ? state.slots.filter((s) => s.entity === normalizeEntityName(entityFilter))
- : state.slots;
- return { events: state.events, slots };
- }
- if (op === "aggregate") {
- const state = computeTruthStateWithConflicts(events);
- return {
- ...aggregateQuantities(state.slots, {
- ...(typeof args["action"] === "string" ? { action: args["action"] as string } : {}),
- unit: typeof args["unit"] === "string" ? (args["unit"] as string) : null,
- ...(typeof args["entity"] === "string" ? { entity: args["entity"] as string } : {}),
- }),
- };
- }
- return {
- collisions: detectAgentCollisions(events, { now: new Date() }),
- };
-}
-
-// ----- brain_concept_synthesis (v0.10.17) ----------------------------------
-
-/**
- * Concept-scoped cluster envelope: target + all linkers (depth-1)
- * plus optionally unlinked mentions. Pure assembler; no LLM call.
- */
-async function toolBrainConceptSynthesis(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const idRaw = args["id"];
- if (typeof idRaw !== "string" || idRaw.trim().length === 0) {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_analytics view=concept_synthesis: id must be a non-empty string",
- );
- }
- const includeUnlinkedRaw = args["include_unlinked"];
- let includeUnlinked = false;
- if (includeUnlinkedRaw !== undefined && includeUnlinkedRaw !== null) {
- if (typeof includeUnlinkedRaw !== "boolean") {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_analytics view=concept_synthesis: include_unlinked must be a boolean",
- );
- }
- includeUnlinked = includeUnlinkedRaw;
- }
- const targetId = normaliseWikilinkTarget(idRaw);
- const cluster = buildConceptCluster(ctx.vault, targetId, {
- includeUnlinked,
- });
- return {
- vault_path: ctx.vault,
- target_id: cluster.targetId,
- target_title: cluster.targetTitle,
- linkers: cluster.linkers,
- unlinked_mentions: cluster.unlinkedMentions,
- generated_at: cluster.generatedAt,
- };
-}
-
-// ----- brain_moc_audit (v0.10.17) ------------------------------------------
-
-/**
- * Per-MOC coverage audit. Classifies cluster members into
- * `wellCovered` / `fragile` / `candidateMissing` and surfaces a
- * `suggestedNext` candidate. MOC detection is purely structural -
- * outbound link count + link density.
- */
-async function toolBrainMocAudit(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const idRaw = args["id"];
- if (typeof idRaw !== "string" || idRaw.trim().length === 0) {
- throw new MCPError(INVALID_PARAMS, "brain_moc_audit: id must be a non-empty string");
- }
- const targetId = normaliseWikilinkTarget(idRaw);
- try {
- const report = auditMoc(ctx.vault, targetId);
- return {
- vault_path: ctx.vault,
- hub_id: report.hubId,
- outbound_count: report.outboundCount,
- well_covered: report.wellCovered,
- fragile: report.fragile,
- candidate_missing: report.candidateMissing,
- ...(report.suggestedNext ? { suggested_next: report.suggestedNext } : {}),
- };
- } catch (err) {
- if (err instanceof MocAuditError) {
- throw new MCPError(INVALID_PARAMS, `brain_moc_audit: ${err.message}`);
- }
- throw err;
- }
-}
-
-// ----- Temporal subsystem MCP wrappers (v0.10.18) --------------------------
-
-function coercePositiveInteger(tool: string, field: string, raw: unknown): number | undefined {
- if (raw === undefined || raw === null) return undefined;
- if (typeof raw === "number") {
- if (!Number.isInteger(raw) || raw < 1) {
- throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a positive integer`);
- }
- return raw;
- }
- if (typeof raw === "string") {
- const trimmed = raw.trim();
- if (trimmed === "" || !/^[0-9]+$/.test(trimmed)) {
- throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a positive integer`);
- }
- const parsed = Number.parseInt(trimmed, 10);
- if (parsed < 1) {
- throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a positive integer`);
- }
- return parsed;
- }
- throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a positive integer`);
-}
-
-const ISO_DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
-
-function coerceIsoTimestampOrDate(
- tool: string,
- field: string,
- raw: unknown,
- shape: "date-only" | "date-or-timestamp" = "date-or-timestamp",
-): string | undefined {
- if (raw === undefined || raw === null) return undefined;
- if (typeof raw !== "string" || raw.trim().length === 0) {
- throw new MCPError(
- INVALID_PARAMS,
- `${tool}: ${field} must be an ISO date${shape === "date-or-timestamp" ? " or ISO timestamp" : " (YYYY-MM-DD)"}`,
- );
- }
- const v = raw.trim();
- if (shape === "date-only" && !ISO_DATE_ONLY_RE.test(v)) {
- throw new MCPError(
- INVALID_PARAMS,
- `${tool}: ${field} must be an ISO date (YYYY-MM-DD); got ${JSON.stringify(v)}`,
- );
- }
- // Validate by parsing - rejects "2026-13-99" / "garbage" / etc.
- const ms = Date.parse(v);
- if (!Number.isFinite(ms)) {
- throw new MCPError(
- INVALID_PARAMS,
- `${tool}: ${field} must be a parseable ISO date${shape === "date-or-timestamp" ? " or timestamp" : ""}; got ${JSON.stringify(v)}`,
- );
- }
- return v;
-}
-
-function coerceEventKind(tool: string, raw: unknown): BrainLogEventKind | undefined {
- if (raw === undefined || raw === null) return undefined;
- if (typeof raw !== "string") {
- throw new MCPError(INVALID_PARAMS, `${tool}: kind must be a string`);
- }
- if (!isBrainLogEventKind(raw)) {
- throw new MCPError(INVALID_PARAMS, `${tool}: kind must be a known BrainLogEventKind`);
- }
- return raw;
-}
-
-/**
- * `brain_timeline` - frozen chronological list of events filtered by
- * any combination of `pref_id`, `topic`, `kind`, `since`, `until`,
- * `limit`. Pure read.
- */
-async function toolBrainTimeline(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const prefId = typeof args["pref_id"] === "string" ? args["pref_id"] : undefined;
- const topic = typeof args["topic"] === "string" ? args["topic"] : undefined;
- const kind = coerceEventKind("brain_timeline", args["kind"]);
- const since = coerceIsoTimestampOrDate("brain_timeline", "since", args["since"]);
- const until = coerceIsoTimestampOrDate("brain_timeline", "until", args["until"]);
- const limit = coercePositiveInteger("brain_timeline", "limit", args["limit"]);
-
- const index = buildTimelineIndex(ctx.vault, {
- ...(since !== undefined ? { since } : {}),
- ...(until !== undefined ? { until } : {}),
- });
- const events = selectEvents(index, {
- ...(prefId !== undefined ? { prefId } : {}),
- ...(topic !== undefined ? { topic } : {}),
- ...(kind !== undefined ? { kind } : {}),
- ...(since !== undefined ? { since } : {}),
- ...(until !== undefined ? { until } : {}),
- });
- const sliced = limit !== undefined ? events.slice(0, limit) : events;
- return {
- vault_path: ctx.vault,
- window: index.window,
- total: events.length,
- events: sliced.map((ev) => ({
- at: ev.at,
- kind: ev.kind,
- source: ev.source,
- ...(ev.prefId !== undefined ? { pref_id: ev.prefId } : {}),
- ...(ev.topic !== undefined ? { topic: ev.topic } : {}),
- ...(ev.result !== undefined ? { result: ev.result } : {}),
- ...(ev.artifact !== undefined ? { artifact: ev.artifact } : {}),
- ...(ev.reason !== undefined ? { reason: ev.reason } : {}),
- ...(ev.text !== undefined ? { text: ev.text } : {}),
- })),
- };
-}
-
-/**
- * `brain_belief_evolution` - per-pref / per-topic chronological story:
- * status transitions, evidence rollup with running counts, and
- * retirement chain.
- */
-async function toolBrainBeliefEvolution(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const prefIdRaw = args["pref_id"];
- const topicRaw = args["topic"];
- const hasPref = typeof prefIdRaw === "string" && prefIdRaw.trim().length > 0;
- const hasTopic = typeof topicRaw === "string" && topicRaw.trim().length > 0;
- if (hasPref === hasTopic) {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_analytics view=belief_evolution: exactly one of pref_id or topic is required",
- );
- }
- const target = hasPref
- ? { prefId: (prefIdRaw as string).trim() }
- : { topic: (topicRaw as string).trim() };
- const index = buildTimelineIndex(ctx.vault, {});
- const evo = buildBeliefEvolution(index, ctx.vault, target);
- return {
- vault_path: ctx.vault,
- target: evo.target,
- transitions: evo.transitions,
- evidence: evo.evidence,
- retirements: evo.retirements,
- generated_at: evo.generatedAt,
- };
-}
-
-/**
- * `brain_stale_scan` - structural staleness report for preferences,
- * signals, and log files. Thresholds come from the `temporal:` config
- * block.
- */
-async function toolBrainStaleScan(
- ctx: ServerContext,
- _args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- void _args;
- const cfg = loadTemporalConfigSafe(ctx.vault);
- const index = buildTimelineIndex(ctx.vault, {});
- const report = findStaleEntries(index, ctx.vault, cfg);
- return {
- vault_path: ctx.vault,
- thresholds: report.thresholds,
- stale_preferences: report.stalePreferences,
- stale_signals: report.staleSignals,
- stale_log_files: report.staleLogFiles,
- generated_at: report.generatedAt,
- };
-}
-
-/**
- * `brain_daily_brief` - structured counters + transitions + source
- * pointers for one day. Defaults `date` to today UTC when omitted.
- */
-async function toolBrainDailyBrief(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const dateRaw = args["date"];
- const dateCoerced = coerceIsoTimestampOrDate("brain_daily_brief", "date", dateRaw, "date-only");
- const date = dateCoerced ?? new Date().toISOString().slice(0, 10);
- const cfg = loadTemporalConfigSafe(ctx.vault);
- const index = buildTimelineIndex(ctx.vault, {});
- const brief = buildDailyBrief(index, ctx.vault, date, {
- offsetHours: cfg.daily_window_offset_hours,
- });
- const envelope: Record<string, unknown> = {
- vault_path: ctx.vault,
- date: brief.date,
- window: brief.window,
- events_by_kind: brief.eventsByKind,
- status_transitions: brief.statusTransitions,
- vault_delta: brief.vaultDelta,
- source_pointers: brief.sourcePointers,
- generated_at: brief.generatedAt,
- };
- // Dual-output (t_00eece5d): persist a machine snapshot and report
- // the run-over-run delta when report snapshots are enabled.
- const delta = captureReportDelta(
- ctx.vault,
- "daily",
- brief.date,
- envelope,
- ctx.configPath ? { configPath: ctx.configPath } : {},
- );
- return delta !== null ? { ...envelope, delta } : envelope;
-}
-
-/**
- * `brain_weekly_synthesis` - 7-day deterministic summary plus retired
- * and contradictions lists.
- */
-async function toolBrainWeeklySynthesis(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const weekEndRaw = args["week_end"];
- const weekEndCoerced = coerceIsoTimestampOrDate(
- "brain_weekly_synthesis",
- "week_end",
- weekEndRaw,
- "date-only",
- );
- const weekEnd = weekEndCoerced ?? new Date().toISOString().slice(0, 10);
- const cfg = loadTemporalConfigSafe(ctx.vault);
- const index = buildTimelineIndex(ctx.vault, {});
- const synth = buildWeeklySynthesis(index, ctx.vault, weekEnd, cfg);
- const envelope: Record<string, unknown> = {
- vault_path: ctx.vault,
- window_start: synth.windowStart,
- window_end: synth.windowEnd,
- events_by_kind: synth.eventsByKind,
- status_transitions: synth.statusTransitions,
- retired: synth.retired,
- contradictions: synth.contradictions,
- vault_delta: synth.vaultDelta,
- source_pointers: synth.sourcePointers,
- generated_at: synth.generatedAt,
- };
- const delta = captureReportDelta(
- ctx.vault,
- "weekly",
- weekEnd,
- envelope,
- ctx.configPath ? { configPath: ctx.configPath } : {},
- );
- return delta !== null ? { ...envelope, delta } : envelope;
-}
-
-// ----- brain_intention (Agent Surface Suite) --------------------------------
-
-function toolBrainIntention(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Record<string, unknown> {
- const operation = coerceStr(args, "operation", true)!;
- if (operation === "list") {
- return {
- intentions: listIntentions(ctx.vault).map((chain) => ({
- scope: chain.scope,
- version: chain.version,
- updated_at: chain.updatedAt,
- text: chain.text,
- })),
- };
- }
- const scope = coerceStr(args, "scope", true)!;
- if (operation === "set") {
- const text = coerceStr(args, "text", true)!;
- const chain = setIntention(ctx.vault, {
- scope,
- text,
- agent: resolveAgentName(ctx.configPath ?? undefined),
- });
- return { operation, scope: chain.scope, version: chain.version, path: chain.path };
- }
- if (operation === "show") {
- const chain = showIntention(ctx.vault, scope);
- if (chain === null) return { operation, scope, present: false };
- return {
- operation,
- scope: chain.scope,
- present: true,
- version: chain.version,
- updated_at: chain.updatedAt,
- text: chain.text,
- history: chain.history,
- path: chain.path,
- };
- }
- if (operation === "move") {
- const moved = moveIntentionToHistory(ctx.vault, { scope });
- return { operation, scope: moved.scope, archive_path: moved.archivePath };
- }
- throw new MCPError(
- INVALID_PARAMS,
- "brain_intention operation must be one of: set, show, list, move",
- );
-}
-
-// ----- brain_trigger (Workspace Insight Suite) ------------------------------
-
-function triggerToJson(record: TriggerRecord): Record<string, unknown> {
- return {
- id: record.id,
- kind: record.kind,
- status: record.effectiveStatus,
- urgency: record.urgency,
- reason: record.reason,
- suggested_action: record.suggestedAction,
- source_artifacts: record.sourceArtifacts,
- cooldown_key: record.cooldownKey,
- created_at: record.createdAt,
- expires_at: record.expiresAt,
- delivered_at: record.deliveredAt,
- resolved_at: record.resolvedAt,
- };
-}
-
-const TRIGGER_TERMINAL = new Set(["acted", "dismissed", "expired"]);
-
-function toolBrainTrigger(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Record<string, unknown> {
- const operation = coerceStr(args, "operation", true)!;
- const now = new Date();
- if (operation === "scan") {
- const cooldownDays = resolveTriggerCooldownDays(ctx.configPath ?? undefined);
- const result = scanTriggers(ctx.vault, { now, cooldownDays });
- return {
- operation,
- candidates: result.candidates,
- created: result.created.map(triggerToJson),
- skipped: result.skipped.map((skip) => ({
- cooldown_key: skip.cooldownKey,
- reason: skip.reason,
- })),
- };
- }
- if (operation === "list" || operation === "history") {
- const statusRaw = coerceStr(args, "status", false);
- if (statusRaw !== null && statusRaw !== undefined && !isTriggerStatus(statusRaw)) {
- throw new MCPError(INVALID_PARAMS, `brain_trigger: unknown status '${statusRaw}'`);
- }
- let records = listTriggers(ctx.vault, {
- now,
- ...(statusRaw ? { status: statusRaw } : {}),
- });
- if (operation === "history") {
- records = records.filter((record) => TRIGGER_TERMINAL.has(record.effectiveStatus));
- } else if (!statusRaw) {
- records = records.filter((record) => !TRIGGER_TERMINAL.has(record.effectiveStatus));
- }
- return { operation, triggers: records.map(triggerToJson) };
- }
- if (operation === "acknowledge" || operation === "dismiss" || operation === "act") {
- const id = coerceStr(args, "id", true)!;
- try {
- return {
- operation,
- trigger: triggerToJson(transitionTrigger(ctx.vault, id, operation, { now })),
- };
- } catch (err) {
- throw new MCPError(INVALID_PARAMS, `brain_trigger: ${(err as Error).message}`);
- }
- }
- throw new MCPError(
- INVALID_PARAMS,
- "brain_trigger operation must be one of: scan, list, history, acknowledge, dismiss, act",
- );
-}
-
-// ----- brain_deep_synthesis (Workspace Insight Suite) -----------------------
-
-async function toolBrainDeepSynthesis(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const topic = coerceStr(args, "topic", true)!;
- const limit = optionalPositiveInt(args, "limit", "brain_deep_synthesis") ?? 30;
- if (limit > 100) {
- throw new MCPError(INVALID_PARAMS, "brain_deep_synthesis: limit must be at most 100");
- }
- const enqueue = coerceBool(args, "triggers");
- const now = new Date();
- const searchConfig = resolveSearchConfig({
- vault: ctx.vault,
- configPath: ctx.configPath ?? undefined,
- });
- const report = await deepSynthesis(searchConfig, topic, { now, limit });
- let triggersCreated: number | undefined;
- if (enqueue) {
- const result = createTriggers(ctx.vault, synthesisCandidates(report), {
- now,
- cooldownDays: resolveTriggerCooldownDays(ctx.configPath ?? undefined),
- });
- triggersCreated = result.created.length;
- }
- return {
- topic: report.topic,
- generated_at: report.generatedAt,
- checked: report.checked,
- notes: report.notes,
- agreements: report.agreements,
- contradictions: report.contradictions,
- stale_claims: report.staleClaims.map((s) => ({
- path: s.path,
- age_days: s.ageDays,
- superseded_by: s.supersededBy,
- })),
- gaps: report.gaps,
- contaminated: report.contaminated,
- ...(triggersCreated !== undefined ? { triggers_created: triggersCreated } : {}),
- };
-}
-
-// ----- brain_idea_discovery (Workspace Insight Suite) ------------------------
-
-function toolBrainIdeaDiscovery(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Record<string, unknown> {
- const cap = optionalPositiveInt(args, "cap", "brain_idea_discovery") ?? 5;
- if (cap > 50) {
- throw new MCPError(INVALID_PARAMS, "brain_idea_discovery: cap must be at most 50");
- }
- const enqueue = coerceBool(args, "triggers");
- const now = new Date();
- const ideas = discoverIdeas(ctx.vault, { now, cap });
- let triggersCreated: number | undefined;
- if (enqueue) {
- const result = createTriggers(ctx.vault, ideaCandidates(ideas), {
- now,
- cooldownDays: resolveTriggerCooldownDays(ctx.configPath ?? undefined),
- });
- triggersCreated = result.created.length;
- }
- return {
- ideas: ideas.map((idea) => ({
- kind: idea.kind,
- title: idea.title,
- reason: idea.reason,
- score: idea.score,
- source_artifacts: idea.sourceArtifacts,
- })),
- ...(triggersCreated !== undefined ? { triggers_created: triggersCreated } : {}),
- };
-}
-
-// ----- brain_context_pack (v0.10.15) ---------------------------------------
-
-/**
- * Bounded-token vault slice ordered by importance tier then recency.
- * Lets an agent prime its context window under a strict budget.
- */
-async function toolBrainContextPack(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const maxRaw = args["max_tokens"];
- const maxTokens =
- typeof maxRaw === "number"
- ? maxRaw
- : typeof maxRaw === "string" && /^[0-9]+$/.test(maxRaw.trim())
- ? Number.parseInt(maxRaw.trim(), 10)
- : Number.NaN;
- if (!Number.isInteger(maxTokens) || maxTokens <= 0) {
- throw new MCPError(INVALID_PARAMS, "brain_context_pack: max_tokens must be a positive integer");
- }
- const query = typeof args["query"] === "string" ? (args["query"] as string) : undefined;
- const includeLanes = coerceBool(args, "lanes");
- const cacheStable = coerceBool(args, "cache_stable");
- const dedupRepeated = coerceBool(args, "dedup_repeated");
- const attentionFlowIds = coerceStrList(args, "attention_flow_ids");
- const maxCharsPerMemory = optionalPositiveInt(args, "max_chars_per_memory", "brain_context_pack");
- const maxTotalChars = optionalPositiveInt(args, "max_total_chars", "brain_context_pack");
- const receipt = receiptOptionsFromArgs("brain_context_pack", args, "context_pack", "mcp");
- const telemetry = telemetryOptionsFromArgs("brain_context_pack", args, "mcp");
- // Focus wiring (Agent Surface Suite, t_5b478e47): gated on the
- // search_focus_context_pack config key (default off) so the default
- // pack stays byte-identical. Fail-soft - a broken search config
- // never breaks the pack.
- let sessionFocus: ReturnType<typeof readActiveSessionFocus> = null;
- if (resolveSearchFocusContextPack(ctx.configPath ?? undefined)) {
- // Argument validation stays OUTSIDE the fail-soft block: an invalid
- // focus_session is a caller error (INVALID_PARAMS), not a config
- // read to swallow.
- const focusSession = coerceStr(args, "focus_session", false) ?? undefined;
- try {
- const searchConfig = resolveSearchConfig({
- vault: ctx.vault,
- configPath: ctx.configPath ?? undefined,
- });
- sessionFocus = readActiveSessionFocus(searchConfig, focusSession);
- } catch {
- sessionFocus = null;
- }
- }
- const report = packContext(ctx.vault, {
- maxTokens,
- ...(sessionFocus !== null ? { sessionFocus } : {}),
- ...(query ? { query } : {}),
- ...(includeLanes ? { includeLanes: true } : {}),
- ...(receipt !== undefined ? { receipt } : {}),
- ...(cacheStable || dedupRepeated
- ? {
- transforms: {
- ...(cacheStable ? { cacheStableOrdering: true } : {}),
- ...(dedupRepeated ? { deduplicateRepeatedContext: true } : {}),
- },
- }
- : {}),
- ...(maxCharsPerMemory !== undefined ? { maxCharsPerMemory } : {}),
- ...(maxTotalChars !== undefined ? { maxTotalChars } : {}),
- ...(telemetry !== undefined ? { telemetry } : {}),
- ...(attentionFlowIds.length > 0 ? { attentionFlowIds } : {}),
- });
- return {
- vault_path: ctx.vault,
- max_tokens: report.maxTokens,
- tokens_used: report.tokensUsed,
- items: report.items.map((i) => ({
- id: i.id,
- path: i.path,
- tier: i.tier,
- tokens: i.tokens,
- body: i.body,
- trimmed: i.trimmed,
- ...(i.originalRank !== undefined ? { original_rank: i.originalRank } : {}),
- ...(i.stableRank !== undefined ? { stable_rank: i.stableRank } : {}),
- ...(i.dedupedFrom !== undefined ? { deduped_from: i.dedupedFrom } : {}),
- ...(i.referenceHint !== undefined ? { reference_hint: i.referenceHint } : {}),
- ...(i.safety ? { safety: i.safety } : {}),
- })),
- skipped: report.skipped.map((s) => ({
- id: s.id,
- tokens: s.tokens,
- reason: s.reason,
- })),
- ...(report.receiptId ? { receipt_id: report.receiptId } : {}),
- ...(report.telemetryId ? { telemetry_id: report.telemetryId } : {}),
- ...(report.lanes ? { lanes: report.lanes } : {}),
- };
-}
-
-// ----- brain_context_receipts ---------------------------------------------
-
-async function toolBrainContextReceipts(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const operation = optionalStringArg("brain_context_receipts", args, "operation");
- if (operation === "list") {
- const trigger = optionalStringArg("brain_context_receipts", args, "trigger");
- if (trigger !== undefined && !isContextReceiptTrigger(trigger)) {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_context_receipts: trigger must be context_pack or pre_compress",
- );
- }
- const host = optionalStringArg("brain_context_receipts", args, "host");
- const sessionId = optionalStringArg("brain_context_receipts", args, "session_id");
- const limit = coercePositiveInteger("brain_context_receipts", "limit", args["limit"]);
- const receipts = listContextReceipts(ctx.vault, {
- ...(trigger !== undefined ? { trigger } : {}),
- ...(host !== undefined ? { host } : {}),
- ...(sessionId !== undefined ? { sessionId } : {}),
- ...(limit !== undefined ? { limit } : {}),
- });
- const summaries = receipts.map(summarizeContextReceipt);
- return {
- vault_path: ctx.vault,
- total: summaries.length,
- receipts: summaries,
- };
- }
-
- if (operation === "show") {
- const id = optionalStringArg("brain_context_receipts", args, "id");
- if (id === undefined) {
- throw new MCPError(INVALID_PARAMS, "brain_context_receipts: id is required for show");
- }
- const receipt = getContextReceipt(ctx.vault, id);
- if (receipt === null) {
- throw new MCPError(INVALID_PARAMS, `brain_context_receipts: receipt not found: ${id}`);
- }
- return {
- id: receipt.id,
- kind: receipt.kind,
- createdAt: receipt.createdAt,
- sourceRefs: receipt.sourceRefs,
- payload: receipt.payload,
- private: receipt.private,
- redacted: receipt.redacted,
- };
- }
-
- throw new MCPError(INVALID_PARAMS, "brain_context_receipts: operation must be list or show");
-}
-
-function optionalStringArg(
- tool: string,
- args: Record<string, unknown>,
- key: string,
-): string | undefined {
- const raw = args[key];
- if (raw === undefined || raw === null) return undefined;
- if (typeof raw !== "string" || raw.trim().length === 0) {
- throw new MCPError(INVALID_PARAMS, `${tool}: ${key} must be a non-empty string`);
- }
- return raw.trim();
-}
-
-function requiredStringArg(tool: string, args: Record<string, unknown>, key: string): string {
- const value = optionalStringArg(tool, args, key);
- if (value === undefined) throw new MCPError(INVALID_PARAMS, `${tool}: ${key} is required`);
- return value;
-}
-
-// ----- brain_recall_telemetry ---------------------------------------------
-
-async function toolBrainRecallTelemetry(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const operation = optionalStringArg("brain_recall_telemetry", args, "operation");
- const filter = recallTelemetryFilter(args);
-
- if (operation === "list") {
- const records = listRecallTelemetry(ctx.vault, filter);
- return { vault_path: ctx.vault, total: records.length, records };
- }
- if (operation === "summary") {
- const summary = summarizeRecallTelemetry(ctx.vault, filter);
- return { ...summary };
- }
- // Gate-decision telemetry (Workspace Insight Suite, t_65036e02):
- // records emitted by brain_recall_gate when recall_gate_telemetry is on.
- if (operation === "gate_list") {
- const records = listGateTelemetry(ctx.vault, {
- ...(filter.host !== undefined ? { host: filter.host } : {}),
- ...(filter.since !== undefined ? { since: filter.since } : {}),
- ...(filter.until !== undefined ? { until: filter.until } : {}),
- ...(filter.limit !== undefined ? { limit: filter.limit } : {}),
- });
- return { vault_path: ctx.vault, total: records.length, records };
- }
- if (operation === "gate_summary") {
- const summary = summarizeGateTelemetry(ctx.vault, {
- ...(filter.host !== undefined ? { host: filter.host } : {}),
- ...(filter.since !== undefined ? { since: filter.since } : {}),
- ...(filter.until !== undefined ? { until: filter.until } : {}),
- });
- return { ...summary };
- }
- throw new MCPError(
- INVALID_PARAMS,
- "brain_recall_telemetry: operation must be list, summary, gate_list, or gate_summary",
- );
-}
-
-function recallTelemetryFilter(args: Record<string, unknown>): RecallTelemetryFilter {
- const mode = coerceRecallTelemetryMode(args["mode"]);
- const status = coerceRecallTelemetryStatus(args["status"]);
- const host = optionalStringArg("brain_recall_telemetry", args, "host");
- const since = optionalStringArg("brain_recall_telemetry", args, "since");
- const until = optionalStringArg("brain_recall_telemetry", args, "until");
- const limit = coercePositiveInteger("brain_recall_telemetry", "limit", args["limit"]);
- return {
- ...(mode !== undefined ? { mode } : {}),
- ...(status !== undefined ? { status } : {}),
- ...(host !== undefined ? { host } : {}),
- ...(since !== undefined ? { since } : {}),
- ...(until !== undefined ? { until } : {}),
- ...(limit !== undefined ? { limit } : {}),
- };
-}
-
-function coerceRecallTelemetryMode(raw: unknown): RecallTelemetryMode | undefined {
- if (raw === undefined || raw === null) return undefined;
- const trimmed = typeof raw === "string" ? raw.trim() : raw;
- if (!isRecallTelemetryMode(trimmed)) {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_recall_telemetry: mode must be search, context_pack, or pre_compress",
- );
- }
- return trimmed;
-}
-
-function coerceRecallTelemetryStatus(raw: unknown): RecallTelemetryStatus | undefined {
- if (raw === undefined || raw === null) return undefined;
- const trimmed = typeof raw === "string" ? raw.trim() : raw;
- if (!isRecallTelemetryStatus(trimmed)) {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_recall_telemetry: status must be ok, empty, error, or timeout",
- );
- }
- return trimmed;
-}
-
-// ----- brain_context_presets ----------------------------------------------
-
-async function toolBrainContextPresets(
- _ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const operation = optionalStringArg("brain_context_presets", args, "operation");
- if (operation === "show") {
- const presetId = optionalStringArg("brain_context_presets", args, "preset_id");
- const result =
- presetId === undefined ? { presets: listContextPresets() } : getContextPreset(presetId);
- if (result === null) {
- throw new MCPError(INVALID_PARAMS, `brain_context_presets: unknown preset ${presetId}`);
- }
- return Array.isArray(result) ? { presets: result } : { ...result };
- }
- if (operation === "suggest") {
- const model = optionalStringArg("brain_context_presets", args, "model");
- const window = coercePositiveInteger(
- "brain_context_presets",
- "context_window_tokens",
- args["context_window_tokens"],
- );
- return {
- ...suggestContextPreset({
- ...(model !== undefined ? { model } : {}),
- ...(window !== undefined ? { contextWindowTokens: window } : {}),
- }),
- };
- }
- if (operation === "diff") {
- const presetId = optionalStringArg("brain_context_presets", args, "preset_id");
- if (presetId === undefined) {
- throw new MCPError(INVALID_PARAMS, "brain_context_presets: preset_id is required for diff");
- }
- return {
- ...diffContextPreset(presetId, contextPresetCurrentConfig(args["current"])),
- };
- }
- throw new MCPError(
- INVALID_PARAMS,
- "brain_context_presets: operation must be show, suggest, or diff",
- );
-}
-
-function contextPresetCurrentConfig(raw: unknown): ContextPresetCurrentConfig {
- if (raw === undefined || raw === null) return {};
- if (typeof raw !== "object" || Array.isArray(raw)) {
- throw new MCPError(INVALID_PARAMS, "brain_context_presets: current must be an object");
- }
- return raw as ContextPresetCurrentConfig;
-}
-
-// ----- brain_pre_compact_extract ------------------------------------------
-
-async function toolBrainPreCompactExtract(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const sessionId = requiredStringArg("brain_pre_compact_extract", args, "session_id");
- const turnStart = requiredStringArg("brain_pre_compact_extract", args, "turn_start");
- const turnEnd = requiredStringArg("brain_pre_compact_extract", args, "turn_end");
- const text = requiredStringArg("brain_pre_compact_extract", args, "text");
- const maxChars = coercePositiveInteger(
- "brain_pre_compact_extract",
- "max_chars",
- args["max_chars"],
- );
- const result = extractPreCompactRecords(ctx.vault, {
- sessionId,
- turnStart,
- turnEnd,
- text,
- ...(optionalStringArg("brain_pre_compact_extract", args, "host") !== undefined
- ? { host: optionalStringArg("brain_pre_compact_extract", args, "host") }
- : {}),
- ...(maxChars !== undefined ? { maxChars } : {}),
- });
- return { count: result.records.length, ...result };
-}
-
-// ----- session recall DAG --------------------------------------------------
-
-async function toolBrainSessionGrep(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const limit = coercePositiveInteger("brain_session_grep", "limit", args["limit"]);
- const snippetChars = coercePositiveInteger(
- "brain_session_grep",
- "snippet_chars",
- args["snippet_chars"],
- );
- return {
- ...searchSessionRecall(ctx.vault, {
- query: requiredStringArg("brain_session_grep", args, "query"),
- ...(optionalStringArg("brain_session_grep", args, "session_id") !== undefined
- ? {
- sessionId: optionalStringArg("brain_session_grep", args, "session_id"),
- }
- : {}),
- ...(limit !== undefined ? { limit } : {}),
- ...(snippetChars !== undefined ? { snippetChars } : {}),
- }),
- };
-}
-
-async function toolBrainSessionDescribe(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- return {
- ...describeSessionRecall(ctx.vault, {
- sessionId: requiredStringArg("brain_session_describe", args, "session_id"),
- }),
- };
-}
-
-async function toolBrainSessionExpand(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const rawLimit = coercePositiveInteger("brain_session_expand", "raw_limit", args["raw_limit"]);
- return {
- ...expandSessionRecall(ctx.vault, {
- id: requiredStringArg("brain_session_expand", args, "id"),
- ...(rawLimit !== undefined ? { rawLimit } : {}),
- ...(optionalStringArg("brain_session_expand", args, "cursor") !== undefined
- ? { cursor: optionalStringArg("brain_session_expand", args, "cursor") }
- : {}),
- }),
- };
-}
-
-// ----- brain_pre_compress_pack (v0.20.0) -----------------------------------
-
-/** Parse an optional positive-integer arg, throwing INVALID_PARAMS otherwise. */
-function optionalPositiveInt(
- args: Record<string, unknown>,
- key: string,
- tool: string,
-): number | undefined {
- const raw = args[key];
- if (raw === undefined) return undefined;
- const n =
- typeof raw === "number"
- ? raw
- : typeof raw === "string" && /^[0-9]+$/.test(raw.trim())
- ? Number.parseInt(raw.trim(), 10)
- : Number.NaN;
- if (!Number.isInteger(n) || n <= 0) {
- throw new MCPError(INVALID_PARAMS, `${tool}: ${key} must be a positive integer`);
- }
- return n;
-}
-
-/**
- * Read-only bundle of the highest-confidence confirmed preferences plus
- * the head of active.md, rendered as a system-prompt addendum for a host
- * runtime to inject just before a context-compression event.
- */
-async function toolBrainPreCompressPack(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const topK = optionalPositiveInt(args, "top_k", "brain_pre_compress_pack") ?? 10;
- const maxCharsPerMemory = optionalPositiveInt(
- args,
- "max_chars_per_memory",
- "brain_pre_compress_pack",
- );
- const maxTotalChars = optionalPositiveInt(args, "max_total_chars", "brain_pre_compress_pack");
- const receipt = receiptOptionsFromArgs("brain_pre_compress_pack", args, "pre_compress", "mcp");
- const telemetry = telemetryOptionsFromArgs("brain_pre_compress_pack", args, "mcp");
- const pack = buildPreCompressPack(ctx.vault, {
- topK,
- ...(maxCharsPerMemory !== undefined ? { maxCharsPerMemory } : {}),
- ...(maxTotalChars !== undefined ? { maxTotalChars } : {}),
- ...(receipt !== undefined ? { receipt } : {}),
- ...(telemetry !== undefined ? { telemetry } : {}),
- });
- return {
- vault_path: ctx.vault,
- text: pack.text,
- active_head_included: pack.activeHeadIncluded,
- ...(pack.activeHeadSafety ? { active_head_safety: pack.activeHeadSafety } : {}),
- total_chars: pack.totalChars,
- ...(pack.receiptId ? { receipt_id: pack.receiptId } : {}),
- ...(pack.telemetryId ? { telemetry_id: pack.telemetryId } : {}),
- items: pack.items.map((i) => ({
- id: i.id,
- principle: i.principle,
- trimmed: i.trimmed,
- ...(i.safety ? { safety: i.safety } : {}),
- })),
- };
-}
-
-function receiptOptionsFromArgs(
- tool: string,
- args: Record<string, unknown>,
- trigger: "context_pack" | "pre_compress",
- defaultHost: string,
-): ContextReceiptOptions | undefined {
- if (!coerceBool(args, "receipt")) return undefined;
- return {
- host: optionalStringArg(tool, args, "receipt_host") ?? defaultHost,
- trigger,
- ...(optionalStringArg(tool, args, "session_id") !== undefined
- ? { sessionId: optionalStringArg(tool, args, "session_id") }
- : {}),
- ...(optionalStringArg(tool, args, "turn_id") !== undefined
- ? { turnId: optionalStringArg(tool, args, "turn_id") }
- : {}),
- };
-}
-
-function telemetryOptionsFromArgs(
- tool: string,
- args: Record<string, unknown>,
- defaultHost: string,
-): RecallTelemetryOptions | undefined {
- if (!coerceBool(args, "telemetry")) return undefined;
- return {
- host: optionalStringArg(tool, args, "telemetry_host") ?? defaultHost,
- ...(optionalStringArg(tool, args, "session_id") !== undefined
- ? { sessionId: optionalStringArg(tool, args, "session_id") }
- : {}),
- ...(optionalStringArg(tool, args, "turn_id") !== undefined
- ? { turnId: optionalStringArg(tool, args, "turn_id") }
- : {}),
- };
-}
-
-async function toolBrainSkillProposals(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const operation = requiredStringArg("brain_skill_proposals", args, "operation");
- if (operation === "learn") {
- const minSupport = optionalPositiveInt(args, "min_support", "brain_skill_proposals");
- const result =
- minSupport !== undefined
- ? learnSkillProposals(ctx.vault, { minSupport })
- : learnSkillProposals(ctx.vault);
- return { ...result };
- }
- if (operation === "list") {
- const proposals = listPendingSkillProposals(ctx.vault);
- return { total: proposals.length, proposals };
- }
- if (operation === "accept") {
- const slug = requiredStringArg("brain_skill_proposals", args, "slug");
- const note = optionalStringArg("brain_skill_proposals", args, "note");
- const reviewed = note
- ? acceptSkillProposal(ctx.vault, slug, { note })
- : acceptSkillProposal(ctx.vault, slug);
- return { ...reviewed };
- }
- if (operation === "reject") {
- const slug = requiredStringArg("brain_skill_proposals", args, "slug");
- const note = requiredStringArg("brain_skill_proposals", args, "note");
- const reviewed = rejectSkillProposal(ctx.vault, slug, { note });
- return { ...reviewed };
- }
- throw new MCPError(
- INVALID_PARAMS,
- "brain_skill_proposals: operation must be one of learn|list|accept|reject",
- );
-}
-
-async function toolBrainProceduralMemory(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const operation = requiredStringArg("brain_procedural_memory", args, "operation");
- if (operation === "reconcile") {
- const roots = coerceStrList(args, "roots");
- const effectiveRoots =
- roots.length > 0
- ? roots
- : [
- join(ctx.vault, "Brain", "procedures"),
- join(ctx.vault, "skills"),
- join(ctx.vault, "runbooks"),
- ];
- return {
- ...reconcileProceduralMemory(ctx.vault, { roots: effectiveRoots }),
- };
- }
- if (operation === "list") {
- const entries = listProceduralMemory(ctx.vault);
- return { total: entries.length, entries };
- }
- if (operation === "mark_used") {
- const id = requiredStringArg("brain_procedural_memory", args, "id");
- const updated = markProceduralMemoryUsed(ctx.vault, id);
- if (!updated) {
- throw new MCPError(INVALID_PARAMS, `brain_procedural_memory: unknown entry id: ${id}`);
- }
- return { ...updated };
- }
- throw new MCPError(
- INVALID_PARAMS,
- "brain_procedural_memory: operation must be one of reconcile|list|mark_used",
- );
-}
-
-async function toolBrainRecurrence(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const operation = requiredStringArg("brain_recurrence", args, "operation");
- if (operation === "list") {
- const entries = listRecurrenceEntries(ctx.vault);
- return { total: entries.length, entries };
- }
- if (operation === "show") {
- const contentHash = requiredStringArg("brain_recurrence", args, "content_hash");
- const entry = getRecurrenceEntry(ctx.vault, contentHash);
- if (!entry) {
- throw new MCPError(INVALID_PARAMS, `brain_recurrence: unknown content hash: ${contentHash}`);
- }
- return { ...entry };
- }
- if (operation === "learn" || operation === "forget") {
- const contentHash = requiredStringArg("brain_recurrence", args, "content_hash");
- const scope = requiredStringArg("brain_recurrence", args, "scope");
- const sourceId = requiredStringArg("brain_recurrence", args, "source_id");
- const entry = applyRecurrenceEvidence(ctx.vault, {
- contentHash,
- scope,
- sourceId,
- action: operation,
- });
- return { operation, entry };
- }
- if (operation === "purge_source") {
- const sourceId = requiredStringArg("brain_recurrence", args, "source_id");
- purgeRecurrenceSource(ctx.vault, sourceId);
- return { ok: true, source_id: sourceId };
- }
- throw new MCPError(
- INVALID_PARAMS,
- "brain_recurrence: operation must be one of list|show|learn|forget|purge_source",
- );
-}
-
-async function toolBrainProceduralGraph(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const operation = requiredStringArg("brain_procedural_graph", args, "operation");
- if (operation === "rebuild") {
- const graph = rebuildProceduralGraph(ctx.vault);
- const hints = rebuildProceduralHints(ctx.vault, { graph });
- return {
- operation,
- graph: {
- nodes: graph.nodes.length,
- edges: graph.edges.length,
- generated_at: graph.generated_at,
- },
- hints: {
- entries: hints.entries.length,
- generated_at: hints.generated_at,
- },
- };
- }
- if (operation === "show") {
- const graph = readProceduralGraph(ctx.vault);
- if (!graph) {
- throw new MCPError(INVALID_PARAMS, "brain_procedural_graph: graph projection not found");
- }
- return { ...graph };
- }
- if (operation === "hints") {
- const hints = readProceduralHints(ctx.vault);
- if (!hints) {
- throw new MCPError(INVALID_PARAMS, "brain_procedural_graph: hints projection not found");
- }
- return { ...hints };
- }
- throw new MCPError(
- INVALID_PARAMS,
- "brain_procedural_graph: operation must be one of rebuild|show|hints",
- );
-}
-
-async function toolBrainAttentionFlows(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const operation = requiredStringArg("brain_attention_flows", args, "operation");
- if (operation === "list") {
- const flows = listAttentionFlows(ctx.vault);
- return { total: flows.length, flows };
- }
- if (operation === "evaluate") {
- const flowId = requiredStringArg("brain_attention_flows", args, "flow_id");
- const report = evaluateAttentionFlow(ctx.vault, flowId);
- return { ...report };
- }
- if (operation === "render") {
- const flowId = requiredStringArg("brain_attention_flows", args, "flow_id");
- return {
- flow_id: flowId,
- text: renderAttentionFlow(ctx.vault, flowId),
- };
- }
- throw new MCPError(
- INVALID_PARAMS,
- "brain_analytics view=attention_flows: operation must be one of list|evaluate|render",
- );
-}
-
-async function toolMcpLandscape(ctx: ServerContext): Promise<Record<string, unknown>> {
- const landscape = buildMcpLandscape(ctx.vault);
- return {
- vault_path: ctx.vault,
- servers: landscape.servers.map((s) => ({
- name: s.name,
- source: s.source,
- packages: s.packages,
- env: s.env,
- })),
- };
-}
-
-// ----- 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);
-}
-
-/**
- * Timezone presentation (t_2ccadc6a): when the operator configured an
- * IANA zone, brief/analytics envelopes gain two ADDITIVE fields - a
- * `timezone` echo and `local_time` (the render instant in that zone).
- * Stored timestamps inside the envelope stay canonical UTC; with no
- * timezone configured the envelope is byte-identical to 0.45.0.
- */
-function localizeEnvelope(ctx: ServerContext, result: unknown): unknown {
- if (result === null || typeof result !== "object" || Array.isArray(result)) return result;
- const tz = resolveTimezone(ctx.configPath ?? undefined);
- if (tz === null) return result;
- return {
- ...(result as Record<string, unknown>),
- timezone: tz,
- local_time: formatLocalTimestamp(isoSecond(new Date()), tz),
- };
-}
-
-async function toolBrainBrief(ctx: ServerContext, args: Record<string, unknown>): Promise<unknown> {
- return localizeEnvelope(ctx, 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 localizeEnvelope(ctx, await dispatchByView(ANALYTICS_VIEW_HANDLERS, ctx, withDefaults));
-}
+ * The handlers live in per-domain modules under `./brain/` (one
+ * module per concern, mirroring the sibling search-tools.ts /
+ * schema-tools.ts split). This file only concatenates their tool
+ * arrays in a stable order; `tools.ts` and the test suite import
+ * `BRAIN_TOOLS` from here, so the registration point is unchanged.
+ * The tests/mcp/brain-tools-parity.test.ts guard pins the frozen
+ * v1.x tool-name set.
+ */
+
+import { FEEDBACK_TOOLS } from "./brain/feedback-tools.ts";
+import { REVIEW_TOOLS } from "./brain/review-tools.ts";
+import { CONTEXT_TOOLS } from "./brain/context-tools.ts";
+import { PACK_TOOLS } from "./brain/pack-tools.ts";
+import { QUERY_TOOLS } from "./brain/query-tools.ts";
+import { ENTITY_TOOLS } from "./brain/entity-tools.ts";
+import { HEALTH_TOOLS } from "./brain/health-tools.ts";
+import { BRIEF_TOOLS } from "./brain/brief-tools.ts";
+import { ANALYTICS_TOOLS } from "./brain/analytics-tools.ts";
+import { KNOWLEDGE_TOOLS } from "./brain/knowledge-tools.ts";
+import { ADMIN_TOOLS } from "./brain/admin-tools.ts";
+import { RECALL_TOOLS } from "./brain/recall-tools.ts";
+import { WORKSPACE_TOOLS } from "./brain/workspace-tools.ts";
+import { PROCEDURE_TOOLS } from "./brain/procedure-tools.ts";
+import { LANDSCAPE_TOOLS } from "./brain/landscape-tools.ts";
+import type { ToolDefinition } from "./tools.ts";
+
+export { vaultRelativeSafe } from "./brain/shared.ts";
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:
- "Record one Brain taste signal in `Brain/inbox/sig-*.md`. With `force_confirmed: true`, create the preference directly (skips the dream trial window).",
- inputSchema: {
- type: "object",
- properties: {
- topic: {
- type: "string",
- description: "Stable kebab-slug for the rule, e.g. `no-internal-abbrev`.",
- },
- signal: {
- type: "string",
- enum: ["positive", "negative"],
- description:
- "`positive` when the principle is the rule to follow, `negative` when it's what to avoid.",
- },
- principle: {
- type: "string",
- description: "One-line, agent-readable formulation of the rule (imperative voice).",
- },
- scope: {
- type: "string",
- description:
- "Optional soft category for later application-scope matching, e.g. `writing`, `coding`.",
- },
- source: {
- type: "array",
- items: { type: "string" },
- description: "Optional wikilinks to the artifacts or notes that triggered the signal.",
- },
- agent: {
- type: "string",
- description: "Optional agent identity override; defaults to the server-resolved name.",
- },
- raw: {
- type: "string",
- description: "Optional free-form raw quote (rendered under `## Raw` in the signal file).",
- },
- force_confirmed: {
- type: "boolean",
- description:
- "When true, also creates an immediately-active confirmed `pref-*` alongside the inbox signal, skipping the dream-pass promotion step.",
- },
- },
- required: ["topic", "signal", "principle"],
- additionalProperties: false,
- },
- handler: toolBrainFeedback,
- },
- {
- name: "brain_dream",
- description:
- "Deterministic learning pass over `Brain/inbox/`. action=run (default) promotes inline; the staged lifecycle persists a reviewable bundle: stage -> validate -> apply (or discard), plus list. Typically scheduled via cron.",
- inputSchema: {
- type: "object",
- properties: {
- action: {
- type: "string",
- enum: ["run", "stage", "validate", "apply", "discard", "list"],
- description:
- "run executes inline; stage persists a proposal bundle; validate/apply/discard manage one bundle by run_id; list shows bundles.",
- },
- run_id: {
- type: "string",
- description: "Bundle id for validate/apply/discard (from action=stage or list).",
- },
- dry_run: {
- type: "boolean",
- description: "action=run only: compute the plan without writing any files.",
- },
- now: {
- type: "string",
- description:
- "Optional ISO-8601 timestamp used as the wall clock for the run (testing / replay).",
- },
- agent: {
- type: "string",
- description:
- "Optional caller identity; a mismatch with the configured primary agent emits a warning. Defaults to the server-resolved name.",
- },
- },
- additionalProperties: false,
- },
- handler: toolBrainDream,
- },
- {
- name: "brain_intent_review",
- description:
- "Read-only pre-dream intent review over active signal clusters. Returns each topic's decision, signal count, risk band, risk score, and reasons without mutating files.",
- inputSchema: {
- type: "object",
- properties: {
- now: {
- type: "string",
- description:
- "Optional ISO-8601 timestamp used as the wall clock for the review (testing / replay).",
- },
- },
- additionalProperties: false,
- },
- handler: toolBrainIntentReview,
- },
- {
- name: "brain_retention",
- description:
- "Recommendation-only lifecycle review over retired preferences and processed signals. Returns keep/improve/park/prune candidates and never deletes or moves artifacts.",
- inputSchema: {
- type: "object",
- properties: {
- now: {
- type: "string",
- description:
- "Optional ISO-8601 timestamp used as the wall clock for the review (testing / replay).",
- },
- },
- additionalProperties: false,
- },
- handler: toolBrainRetention,
- },
- {
- name: "brain_review_candidates",
- description:
- "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: {
- now: {
- type: "string",
- description:
- "Optional ISO-8601 timestamp used as the wall clock for the dry-run (testing / replay).",
- },
- },
- additionalProperties: false,
- },
- handler: toolBrainReviewCandidates,
- },
- {
- name: "brain_apply_evidence",
- description:
- "Record whether an active preference was applied, violated, or marked outdated against a freshly-produced durable artifact. Appends one event to `Brain/log/<today>.md`. A single `outdated` event triggers retire on the next dream pass.",
- inputSchema: {
- type: "object",
- properties: {
- pref_id: {
- type: "string",
- description: "Preference id (`pref-<slug>` or bare `<slug>`).",
- },
- artifact: {
- type: "string",
- description:
- "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, `violated` if broken, `outdated` if the artifact shows the rule itself is obsolete.",
- },
- agent: {
- type: "string",
- description: "Optional agent identity override; defaults to the server-resolved name.",
- },
- outcome: {
- type: "string",
- enum: ["success", "failure", "unknown"],
- description:
- "Optional downstream outcome of the artifact (t_d478df53): did the work the rule was applied to actually succeed? `unknown` is treated like an absent outcome.",
- },
- note: {
- type: "string",
- description: "Optional one-line context.",
- },
- },
- required: ["pref_id", "artifact", "result"],
- additionalProperties: false,
- },
- handler: toolBrainApplyEvidence,
- },
- {
- name: "brain_note",
- description:
- "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: {
- text: {
- type: "string",
- description:
- "One-line narrative description. Newlines collapse to single spaces; the shared redactor strips secret-shaped tokens.",
- },
- agent: {
- type: "string",
- description: "Optional agent identity override; defaults to the server-resolved name.",
- },
- },
- required: ["text"],
- additionalProperties: false,
- },
- handler: toolBrainNote,
- },
- {
- name: "brain_pinned_context",
- description:
- "Read, write, append, or clear the transient current-task scratchpad at `Brain/pinned.md`. Use for facts that should survive context rotation but should not become permanent preferences.",
- inputSchema: {
- type: "object",
- properties: {
- operation: {
- type: "string",
- enum: ["read", "write", "append", "clear"],
- description: "Operation to perform. Defaults to read.",
- },
- content: {
- type: "string",
- description: "Pinned context body for write/append operations.",
- },
- },
- additionalProperties: false,
- },
- outputSchema: PINNED_CONTEXT_OUTPUT_SCHEMA,
- handler: toolBrainPinnedContext,
- },
- {
- name: "brain_write_session",
- description:
- "Provider-agnostic Brain write sessions (artifact and decision-panel kinds): open returns a generation prompt, submit validates the text, only clean artifacts commit. Correction loop, retry cap, collision guard, optional operator review. The calling agent generates; the Brain never does.",
- inputSchema: {
- type: "object",
- properties: {
- op: {
- type: "string",
- enum: ["open", "submit", "approve", "abandon", "status", "list"],
- description: "Lifecycle operation.",
- },
- kind: {
- type: "string",
- enum: ["artifact", "panel"],
- description: "Session kind for op=open. Defaults to artifact.",
- },
- session_id: {
- type: "string",
- description: "Session id (`ws-...`) for submit/approve/abandon/status.",
- },
- target: {
- type: "string",
- description:
- "Vault-relative commit target under Brain/ (artifact open; optional panel override). Reserved namespaces are refused.",
- },
- text: {
- type: "string",
- description:
- "Generated text for op=submit: the full artifact, a persona answer, or the synthesis.",
- },
- topic: { type: "string", description: "Decision topic (panel open)." },
- personas: {
- type: "array",
- items: { type: "string" },
- description:
- "Persona slugs to convene in order (panel open). Defaults to every loaded persona.",
- },
- schema_type: {
- type: "string",
- description: "Schema-pack page type the artifact must declare (artifact open).",
- },
- intent: {
- type: "string",
- enum: ["create", "overwrite", "merge"],
- description:
- "Commit intent against an existing target (artifact open). Default create - never overwrites.",
- },
- prompt: { type: "string", description: "Custom generation instruction (artifact open)." },
- require_review: {
- type: "boolean",
- description: "Park the validated artifact at needs-review until an operator approves.",
- },
- retry_cap: { type: "number", description: "Failed submits allowed per step (default 3)." },
- limit: {
- type: "number",
- description: "Max sessions returned by op=list (default 100, cap 500).",
- },
- agent: { type: "string", description: "Agent identity override (open)." },
- },
- required: ["op"],
- additionalProperties: false,
- },
- handler: toolBrainWriteSession,
- },
- {
- name: "brain_intention",
- description:
- "Scoped current-intention chains under Brain/intentions/: set updates a workstream's now-document (prior text lands in its history trail), show/list read, move retires the chain into history/.",
- inputSchema: {
- type: "object",
- properties: {
- operation: {
- type: "string",
- enum: ["set", "show", "list", "move"],
- description: "Operation to perform.",
- },
- scope: {
- type: "string",
- minLength: 1,
- maxLength: 128,
- description: "Workstream or session label (normalised to a scope slug).",
- },
- text: {
- type: "string",
- minLength: 1,
- maxLength: 4000,
- description: "Intention text for the set operation.",
- },
- },
- required: ["operation"],
- additionalProperties: false,
- },
- previewBudget: MCP_PREVIEW_BUDGET,
- handler: toolBrainIntention,
- },
- {
- name: "brain_trigger",
- description:
- "Grounded proactive trigger queue under Brain/triggers/: scan generates deduped triggers from health/retention data, list/history read by lifecycle status, acknowledge/dismiss/act transition one trigger. Anti-nag: cooldown keys keep the same issue from reappearing every run.",
- inputSchema: {
- type: "object",
- properties: {
- operation: {
- type: "string",
- enum: ["scan", "list", "history", "acknowledge", "dismiss", "act"],
- description: "Operation to perform.",
- },
- id: {
- type: "string",
- minLength: 1,
- maxLength: 128,
- description: "Trigger id for acknowledge/dismiss/act.",
- },
- status: {
- type: "string",
- enum: ["pending", "delivered", "acknowledged", "acted", "dismissed", "expired"],
- description: "Effective-status filter for list.",
- },
- },
- required: ["operation"],
- additionalProperties: false,
- },
- previewBudget: MCP_PREVIEW_BUDGET,
- handler: toolBrainTrigger,
- },
- {
- name: "brain_deep_synthesis",
- description:
- "Topic-scoped deterministic dossier: matched notes, agreements (positive typed relations), contradictions, stale claims, and knowledge gaps (dangling wikilinks). Evidence assembly only - prose synthesis stays with the caller. Optional triggers=true enqueues findings.",
- inputSchema: {
- type: "object",
- properties: {
- topic: { type: "string", minLength: 1, maxLength: 500 },
- limit: { type: "integer", minimum: 1, maximum: 100 },
- triggers: {
- type: "boolean",
- description: "Enqueue contradiction/gap findings into the trigger queue.",
- },
- },
- required: ["topic"],
- additionalProperties: false,
- },
- previewBudget: MCP_PREVIEW_BUDGET,
- handler: toolBrainDeepSynthesis,
- },
- {
- name: "brain_idea_discovery",
- description:
- "Ranked next-direction candidates from the vault's open loops: unanswered open questions, orphan research notes (no inbound links), and aging unresolved inbox signals. Deterministic scoring; triggers=true enqueues the ranked ideas.",
- inputSchema: {
- type: "object",
- properties: {
- cap: { type: "integer", minimum: 1, maximum: 50 },
- triggers: {
- type: "boolean",
- description: "Enqueue the ranked ideas into the trigger queue.",
- },
- },
- additionalProperties: false,
- },
- previewBudget: MCP_PREVIEW_BUDGET,
- handler: toolBrainIdeaDiscovery,
- },
- {
- name: "brain_context",
- description:
- "Pull the current Brain/active.md body, pinned current-task context, and active-preference counts. Use at session start when SessionStart hook is unavailable (Cursor, Aider, raw Claude API). Read-only.",
- inputSchema: {
- type: "object",
- properties: {},
- additionalProperties: false,
- },
- outputSchema: BRAIN_CONTEXT_OUTPUT_SCHEMA,
- handler: toolBrainContext,
- },
- {
- 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: {
- type: "object",
- properties: {
- preference: {
- type: "string",
- description:
- "Preference id (`pref-...` or `ret-...`) to look up with its evidence trail.",
- },
- topic: {
- type: "string",
- description: "Topic slug to aggregate signals + active/retired preference + log events.",
- },
- since: {
- type: "string",
- description: "ISO-8601 timestamp; returns every Brain log event with timestamp >= since.",
- },
- format: {
- type: "string",
- enum: ["markdown", "json"],
- description:
- "Reserved for forward-compat; the structured response is the same regardless.",
- },
- telemetry: {
- type: "boolean",
- description:
- "Opt-in recall telemetry: emit one continuity record (mode 'query', kind-only payload) for this call.",
- },
- telemetry_host: { type: "string", maxLength: 200 },
- session_id: { type: "string", maxLength: 512 },
- turn_id: { type: "string", maxLength: 512 },
- },
- additionalProperties: false,
- },
- outputSchema: BRAIN_QUERY_OUTPUT_SCHEMA,
- handler: toolBrainQuery,
- },
- {
- 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: {
- type: "object",
- properties: {
- agents: {
- type: "array",
- items: { type: "string" },
- description: "Agent ids to query. Omit or pass [] to query all known agents.",
- },
- topic: {
- type: "string",
- description: "Exact Brain topic filter.",
- },
- query: {
- type: "string",
- description:
- "Case-insensitive substring matched against deterministic contribution text.",
- },
- kind: {
- type: "string",
- enum: ["signal", "preference", "log"],
- description: "Contribution kind filter.",
- },
- limit: {
- type: "integer",
- minimum: 1,
- maximum: 500,
- description: "Maximum contributions returned. Defaults to 50.",
- },
- },
- additionalProperties: false,
- },
- handler: toolBrainAgentQuery,
- },
- {
- name: "brain_agent_diff",
- description:
- "Read-only comparison between source agents using the same provenance foundation as brain_agent_query. Supports browse, search, diff, and map modes.",
- inputSchema: {
- type: "object",
- properties: {
- mode: {
- type: "string",
- enum: ["browse", "search", "diff", "map"],
- description:
- "Comparison mode. Defaults to search when query is supplied, otherwise browse.",
- },
- agents: {
- type: "array",
- items: { type: "string" },
- description: "Agent ids to compare. Omit or pass [] to compare all known agents.",
- },
- topic: {
- type: "string",
- description: "Exact Brain topic filter.",
- },
- query: {
- type: "string",
- description:
- "Case-insensitive substring matched against deterministic contribution text.",
- },
- kind: {
- type: "string",
- enum: ["signal", "preference", "log"],
- description: "Contribution kind filter.",
- },
- limit: {
- type: "integer",
- minimum: 1,
- maximum: 500,
- description: "Maximum contributions returned before comparison. Defaults to 50.",
- },
- },
- additionalProperties: false,
- },
- handler: toolBrainAgentDiff,
- },
- {
- name: "brain_doctor",
- description:
- "Validate `Brain/` invariants: status-vs-folder consistency, frontmatter validity, duplicate ids, ISO parsing, log header parsing. Read-only.",
- inputSchema: {
- type: "object",
- properties: {
- strict: {
- type: "boolean",
- description: "When true, warnings demote `ok` to false (CLI exit-code parity).",
- },
- format: {
- type: "string",
- enum: ["markdown", "json"],
- description:
- "Output format hint. Structured result is identical; caller decides rendering.",
- },
- },
- additionalProperties: false,
- },
- handler: toolBrainDoctor,
- },
- {
- name: "brain_health",
- description:
- "Semantic-health report: contradictory confirmed preferences (opposite sign of record, same subject), recurring concepts with no dedicated preference, and confirmed preferences running on stale evidence. Returns the per-domain findings plus a clean/watch/investigate verdict. Read-only.",
- inputSchema: {
- type: "object",
- properties: {
- format: {
- type: "string",
- enum: ["markdown", "json"],
- description:
- "Output format hint. Structured result is identical; caller decides rendering.",
- },
- },
- additionalProperties: false,
- },
- handler: toolBrainHealth,
- },
- {
- name: "brain_mcp_landscape",
- description:
- "List the Model Context Protocol servers configured across the vault: each server's name, the config file that declares it, the packages it pulls, and the env-var NAMES it requires. Environment values are never read. Discovery is vault-relative. Read-only.",
- inputSchema: {
- type: "object",
- properties: {},
- additionalProperties: false,
- },
- outputSchema: {
- type: "object",
- required: ["vault_path", "servers"],
- properties: {
- vault_path: { type: "string" },
- servers: {
- type: "array",
- items: {
- type: "object",
- required: ["name", "source", "packages", "env"],
- properties: {
- name: { type: "string" },
- source: { type: "string" },
- packages: { type: "array", items: { type: "string" } },
- env: { type: "array", items: { type: "string" } },
- },
- },
- },
- },
- },
- handler: toolMcpLandscape,
- },
- {
- name: "brain_entity",
- previewBudget: MCP_PREVIEW_BUDGET,
- description:
- "Look up (view: get) or list (view: list) canonical entities from the Brain/entities/ registry. Aliases resolve to the canonical record. Read-only; writes go through the o2b CLI.",
- inputSchema: {
- type: "object",
- properties: {
- view: {
- type: "string",
- enum: ["get", "list"],
- description: "get: resolve one entity by name or alias. list: enumerate the registry.",
- },
- query: {
- type: "string",
- description: "Name or alias to resolve (required for view: get).",
- },
- category: {
- type: "string",
- description: "Optional category filter (slug, e.g. `people`).",
- },
- status: {
- type: "string",
- enum: ["active", "archived"],
- description: "Optional status filter for view: list.",
- },
- },
- required: ["view"],
- additionalProperties: false,
- },
- handler: toolBrainEntity,
- },
- {
- 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: {
- type: "object",
- properties: {
- id: {
- type: "string",
- description:
- "Target id (e.g. `pref-foo`, `ret-bar`, `sig-2026-05-14-baz`). Wikilink decoration is stripped if present.",
- },
- },
- required: ["id"],
- additionalProperties: false,
- },
- handler: toolBrainBacklinks,
- },
- {
- 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 revisions. Accepts pref-/ret-/bare/wikilink ids. Read-only.",
- inputSchema: {
- type: "object",
- properties: {
- pref_id: {
- type: "string",
- description:
- "Preference id (e.g. `pref-foo`). `ret-foo`, bare `foo`, and `[[pref-foo]]` all resolve to the same trail.",
- },
- },
- required: ["pref_id"],
- additionalProperties: false,
- },
- handler: toolBrainAudit,
- },
- {
- name: "brain_sources",
- description:
- "Read-only dashboard of the brain's signals grouped by (agent, source_type) with active/processed and distinct-topic counts plus totals.",
- inputSchema: {
- type: "object",
- properties: {},
- additionalProperties: false,
- },
- handler: toolBrainSources,
- },
- {
- name: "brain_switch_vault",
- description:
- "Activate a named vault profile (from the profiles registry). Updates the active pointer; the change takes effect on the next server launch - the running server keeps its already-resolved vault.",
- inputSchema: {
- type: "object",
- properties: {
- name: { type: "string", description: "Profile name to activate." },
- },
- required: ["name"],
- additionalProperties: false,
- },
- handler: toolBrainSwitchVault,
- },
- {
- name: "brain_context_pack",
- previewBudget: MCP_PREVIEW_BUDGET,
- description:
- "Return the highest-tier, most recent vault slice that fits under `max_tokens`. Ordered core → supporting → peripheral, newest first; stops adding pages when the next page would exceed the budget. Read-only.",
- inputSchema: {
- type: "object",
- properties: {
- max_tokens: {
- type: "integer",
- minimum: 1,
- description: "Strict upper bound on the returned slice's token count.",
- },
- query: {
- type: "string",
- description: "Optional case/Unicode-insensitive substring filter on topic + principle.",
- },
- focus_session: {
- type: "string",
- minLength: 1,
- maxLength: 128,
- description:
- "Session id whose bound search focus boosts matching memories (requires search_focus_context_pack).",
- },
- max_chars_per_memory: {
- type: "integer",
- minimum: 1,
- description:
- "Optional per-page character cap so one huge page cannot crowd out the rest; trimmed pages carry `trimmed: true`.",
- },
- max_total_chars: {
- type: "integer",
- minimum: 1,
- description:
- "Optional second ceiling (code points) on the cumulative size of the returned slice. Lowest-priority overflow is dropped with an `over-char-budget` skip reason.",
- },
- lanes: {
- type: "boolean",
- description:
- "When true, also return polarity-aware directives, constraints, and consider lanes. Legacy flat `items` remains present.",
- },
- cache_stable: {
- type: "boolean",
- description:
- "When true, reorder the selected items by stable id and annotate their original rank.",
- },
- dedup_repeated: {
- type: "boolean",
- description:
- "When true, replace repeated context bodies with reference hints to an earlier emitted item.",
- },
- attention_flow_ids: {
- type: "array",
- items: { type: "string" },
- description:
- "Optional declarative attention flow ids to inject as a synthetic context block.",
- },
- receipt: {
- type: "boolean",
- description: "When true, emit an opt-in context receipt for this context-pack run.",
- },
- receipt_host: {
- type: "string",
- description: "Optional host/runtime name for emitted receipts; defaults to `mcp`.",
- },
- telemetry: {
- type: "boolean",
- description:
- "When true, emit an opt-in recall telemetry record for this context-pack run.",
- },
- telemetry_host: {
- type: "string",
- description: "Optional host/runtime name for emitted telemetry; defaults to `mcp`.",
- },
- session_id: {
- type: "string",
- description: "Optional session id recorded on emitted telemetry.",
- },
- turn_id: {
- type: "string",
- description: "Optional turn id recorded on emitted telemetry.",
- },
- },
- required: ["max_tokens"],
- additionalProperties: false,
- },
- handler: toolBrainContextPack,
- },
- {
- name: "brain_context_receipts",
- description:
- "List context receipt summaries or show one full receipt by id. Receipts are append-only continuity records emitted by opt-in context injection callers. Read-only.",
- inputSchema: {
- type: "object",
- properties: {
- operation: {
- type: "string",
- enum: ["list", "show"],
- description: "Use list for summaries, show for one full receipt by id.",
- },
- id: {
- type: "string",
- description: "Receipt id required when operation is show.",
- },
- trigger: {
- type: "string",
- enum: ["context_pack", "pre_compress"],
- description: "Optional list filter by injection trigger.",
- },
- host: {
- type: "string",
- description: "Optional list filter by host/runtime name.",
- },
- session_id: {
- type: "string",
- description: "Optional list filter by recorded session id.",
- },
- limit: {
- type: "integer",
- minimum: 1,
- description: "Optional maximum number of summaries to return.",
- },
- },
- required: ["operation"],
- additionalProperties: false,
- },
- handler: toolBrainContextReceipts,
- },
- {
- name: "brain_recall_telemetry",
- 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: {
- type: "object",
- properties: {
- operation: {
- type: "string",
- enum: ["list", "summary", "gate_list", "gate_summary"],
- description:
- "list/summary for recall telemetry; gate_list/gate_summary for recall-gate decisions.",
- },
- mode: {
- type: "string",
- enum: ["search", "context_pack", "pre_compress"],
- description: "Optional filter by recall mode.",
- },
- status: {
- type: "string",
- enum: ["ok", "empty", "error", "timeout"],
- description: "Optional filter by telemetry status.",
- },
- host: {
- type: "string",
- description: "Optional filter by host/runtime name.",
- },
- since: {
- type: "string",
- description: "Optional inclusive lower timestamp bound.",
- },
- until: {
- type: "string",
- description: "Optional inclusive upper timestamp bound.",
- },
- limit: {
- type: "integer",
- minimum: 1,
- description: "Optional maximum record count for list.",
- },
- },
- required: ["operation"],
- additionalProperties: false,
- },
- handler: toolBrainRecallTelemetry,
- },
- {
- name: "brain_context_presets",
- description:
- "Show, suggest, or diff read-only context budget presets. Diagnostics only; never writes configuration.",
- inputSchema: {
- type: "object",
- properties: {
- operation: {
- type: "string",
- enum: ["show", "suggest", "diff"],
- description:
- "show returns presets, suggest chooses by model/window, diff compares current values.",
- },
- preset_id: {
- type: "string",
- description: "Preset id for show/diff, e.g. tight-context or long-context.",
- },
- model: {
- type: "string",
- description: "Optional model name hint for suggest.",
- },
- context_window_tokens: {
- type: "integer",
- minimum: 1,
- description: "Optional context-window size hint for suggest.",
- },
- current: {
- type: "object",
- description:
- "Optional current values for diff: { context_pack, pre_compress, overrides }. Overrides preserve caller-managed paths.",
- },
- },
- required: ["operation"],
- additionalProperties: false,
- },
- handler: toolBrainContextPresets,
- },
- {
- name: "brain_skill_proposals",
- description:
- "Learn/list/review deterministic skill proposals from continuity records (learn, list, accept, reject).",
- inputSchema: {
- type: "object",
- properties: {
- operation: {
- type: "string",
- enum: ["learn", "list", "accept", "reject"],
- description: "Tool operation.",
- },
- min_support: {
- type: "integer",
- minimum: 1,
- description: "Optional minimum evidence support for learn.",
- },
- slug: {
- type: "string",
- description: "Proposal slug for accept/reject.",
- },
- note: {
- type: "string",
- description: "Optional review note; required for reject.",
- },
- },
- required: ["operation"],
- additionalProperties: false,
- },
- handler: toolBrainSkillProposals,
- },
- {
- name: "brain_procedural_memory",
- description:
- "Reconcile/list procedural memory index and update usage sidecar (reconcile, list, mark_used).",
- inputSchema: {
- type: "object",
- properties: {
- operation: {
- type: "string",
- enum: ["reconcile", "list", "mark_used"],
- description: "Tool operation.",
- },
- roots: {
- type: "array",
- items: { type: "string" },
- description: "Optional root directories for reconcile.",
- },
- id: {
- type: "string",
- description: "Procedural entry id for mark_used.",
- },
- },
- required: ["operation"],
- additionalProperties: false,
- },
- handler: toolBrainProceduralMemory,
- },
- {
- name: "brain_recurrence",
- description:
- "Inspect and update recurrence/support diagnostics (list, show, learn, forget, purge_source).",
- inputSchema: {
- type: "object",
- properties: {
- operation: {
- type: "string",
- enum: ["list", "show", "learn", "forget", "purge_source"],
- description: "Tool operation.",
- },
- content_hash: {
- type: "string",
- description: "Content hash for show/learn/forget.",
- },
- scope: {
- type: "string",
- description: "Scope for learn/forget.",
- },
- source_id: {
- type: "string",
- description: "Source id for learn/forget/purge_source.",
- },
- },
- required: ["operation"],
- additionalProperties: false,
- },
- handler: toolBrainRecurrence,
- },
- {
- name: "brain_truth",
- description:
- "Entity claim ledger: ingest a claim, render current-truth slots with superseded history, list contested conflicts (ask_user), aggregate exact-match quantities, report cross-agent collisions.",
- inputSchema: {
- type: "object",
- properties: {
- operation: {
- type: "string",
- enum: ["ingest", "slots", "conflicts", "aggregate", "collisions"],
- description: "Tool operation.",
- },
- entity: {
- type: "string",
- description: "Entity name (ingest, slots filter, aggregate filter).",
- },
- aspect: { type: "string", description: "Aspect slot for ingest." },
- value: { type: "string", description: "Claim value for ingest." },
- source: { type: "string", description: "Provenance wikilink/path for ingest." },
- agent: { type: "string", description: "Agent identity override for ingest." },
- quantity_value: { type: "number", description: "Numeric value for quantity claims." },
- quantity_unit: { type: "string", description: "Unit token for quantity claims." },
- quantity_action: { type: "string", description: "Measured action for quantity claims." },
- action: { type: "string", description: "Measured action for aggregate." },
- unit: { type: "string", description: "Unit token for aggregate (omit for unitless)." },
- },
- required: ["operation"],
- additionalProperties: false,
- },
- handler: toolBrainTruth,
- previewBudget: MCP_PREVIEW_BUDGET,
- },
- {
- name: "brain_dead_ends",
- description:
- "Negative-knowledge registry (Brain/dead-ends/): record one tried-and-failed approach with why it failed, or list the bounded active set so recall surfaces avoid-X alongside prefer-Y.",
- inputSchema: {
- type: "object",
- properties: {
- operation: {
- type: "string",
- enum: ["record", "list"],
- description: "Tool operation.",
- },
- approach: { type: "string", description: "What was tried (record)." },
- reason: { type: "string", description: "Why it failed or was set aside (record)." },
- context: { type: "string", description: "Optional context (record)." },
- agent: { type: "string", description: "Agent identity override (record)." },
- },
- required: ["operation"],
- additionalProperties: false,
- },
- handler: toolBrainDeadEnds,
- previewBudget: MCP_PREVIEW_BUDGET,
- },
- {
- name: "brain_foresight",
- description:
- "Forward-looking projection (Brain's only anticipatory surface): recurring routines coming due within the horizon via cadence arithmetic, recent open commitments, and open questions - deterministic, every item carries sources.",
- inputSchema: {
- type: "object",
- properties: {
- horizon_days: {
- type: "integer",
- minimum: 1,
- description: "Forward horizon in days (default 14).",
- },
- },
- additionalProperties: false,
- },
- handler: toolBrainForesight,
- previewBudget: MCP_PREVIEW_BUDGET,
- },
- {
- name: "brain_labels",
- description:
- "Controlled-vocabulary classification against the schema pack's labels field: assign (fail-closed - unknown dimensions/values rejected with the declared vocabulary), remove, or show a note's labels. Single-choice per dimension; persists as a labels frontmatter array plus a canonical label entity.",
- inputSchema: {
- type: "object",
- properties: {
- operation: {
- type: "string",
- enum: ["assign", "remove", "show"],
- description: "Tool operation.",
- },
- path: { type: "string", description: "Vault-relative note path." },
- dimension: { type: "string", description: "Label dimension (assign/remove)." },
- value: { type: "string", description: "Label value (assign)." },
- agent: { type: "string", description: "Agent identity override (assign)." },
- },
- required: ["operation", "path"],
- additionalProperties: false,
- },
- handler: toolBrainLabels,
- previewBudget: MCP_PREVIEW_BUDGET,
- },
- {
- name: "brain_tiers",
- description:
- "Frontmatter tier guard: check lists staged identity-field hand-edits the index post-pass detected, restore (apply=true required) writes the expected value back into the file, accept adopts the hand-edit as the new snapshot baseline. Nothing auto-resolves.",
- inputSchema: {
- type: "object",
- properties: {
- operation: {
- type: "string",
- enum: ["check", "restore", "accept"],
- description: "Tool operation.",
- },
- path: { type: "string", description: "Vault-relative path (restore/accept)." },
- field: { type: "string", description: "Restrict to one field (restore/accept)." },
- apply: { type: "boolean", description: "Required true for restore - it writes the file." },
- },
- required: ["operation"],
- additionalProperties: false,
- },
- handler: toolBrainTiers,
- previewBudget: MCP_PREVIEW_BUDGET,
- },
- {
- name: "brain_secrets",
- description:
- "Capability-gated secret custody, agent-facing subset: list stored secret metadata (never values) or run an allowlisted command with the secret injected as its declared env var - output comes back redacted. Storing and removing secrets stays on the operator's CLI (o2b brain secret).",
- inputSchema: {
- type: "object",
- properties: {
- operation: { type: "string", enum: ["list", "run"], description: "Tool operation." },
- name: { type: "string", description: "Secret name (run)." },
- command: {
- type: "array",
- items: { type: "string" },
- description: "Command argv to execute (run); must match the secret's allowlist.",
- },
- agent: { type: "string", description: "Agent identity override (run)." },
- },
- required: ["operation"],
- additionalProperties: false,
- },
- handler: toolBrainSecrets,
- previewBudget: MCP_PREVIEW_BUDGET,
- },
- {
- name: "brain_maintenance",
- description:
- "Quiet-window, lease-guarded heavy maintenance lane: run executes dream, reindex, bridges, and clusters stale-first behind the local-time window, busy gate, and an expiring lease (force bypasses the soft gates, never the lease); status renders the lease holder and recent journal.",
- inputSchema: {
- type: "object",
- properties: {
- operation: { type: "string", enum: ["run", "status"], description: "Tool operation." },
- force: { type: "boolean", description: "Bypass window and busy gates (run)." },
- window_start_hour: {
- type: "integer",
- minimum: 0,
- maximum: 23,
- description: "Local hour the window opens, inclusive (run).",
- },
- window_end_hour: {
- type: "integer",
- minimum: 0,
- maximum: 23,
- description: "Local hour the window closes, exclusive (run).",
- },
- tz: { type: "string", description: "IANA timezone for the window (default UTC)." },
- agent: { type: "string", description: "Agent identity override (run)." },
- },
- required: ["operation"],
- additionalProperties: false,
- },
- handler: toolBrainMaintenance,
- previewBudget: MCP_PREVIEW_BUDGET,
- },
- {
- name: "brain_bridges",
- description:
- "Bridge discovery over the vec index: discover proposes links between embedding-near notes that share no edge (orphan-first, regenerates Brain/proposals/bridges.md, records a metric); accept writes one related wikilink into the source note; dismiss silences a pair; list reads the artifact back.",
- inputSchema: {
- type: "object",
- properties: {
- operation: {
- type: "string",
- enum: ["discover", "list", "accept", "dismiss"],
- description: "Tool operation.",
- },
- source: { type: "string", description: "Vault-relative source note (accept/dismiss)." },
- target: { type: "string", description: "Vault-relative target note (accept/dismiss)." },
- max: { type: "integer", minimum: 1, description: "Proposal cap (discover)." },
- min_similarity: {
- type: "number",
- exclusiveMinimum: 0,
- maximum: 1,
- description: "Cosine similarity threshold (discover, default 0.8).",
- },
- },
- required: ["operation"],
- additionalProperties: false,
- },
- handler: toolBrainBridges,
- previewBudget: MCP_PREVIEW_BUDGET,
- },
- {
- name: "brain_clusters",
- description:
- "Graph-wide community detection: run applies deterministic label propagation over the resolved link graph, materializes one derived note per community of size >= min_size under Brain/clusters/, removes stale generated notes, and records a metric; list reads the generated notes back.",
- inputSchema: {
- type: "object",
- properties: {
- operation: { type: "string", enum: ["run", "list"], description: "Tool operation." },
- min_size: {
- type: "integer",
- minimum: 2,
- description: "Smallest community that materializes (run, default 4).",
- },
- },
- required: ["operation"],
- additionalProperties: false,
- },
- handler: toolBrainClusters,
- previewBudget: MCP_PREVIEW_BUDGET,
- },
- {
- name: "brain_benchmark",
- description:
- "Recall-quality benchmark: score the vault's live hybrid recall against a fixed dataset ({queries: [{id, query, expected: [paths]}]}) - hit@k and MRR per query and aggregate - and record one recall_benchmark metric so quality is chartable over time.",
- inputSchema: {
- type: "object",
- properties: {
- operation: { type: "string", enum: ["run"], description: "Tool operation." },
- dataset: {
- type: "object",
- description: "Benchmark dataset: {queries: [{id, query, expected, k?}]}.",
- },
- k: { type: "integer", minimum: 1, description: "Rank depth (default 5)." },
- expand: { type: "boolean", description: "Route queries through deterministic expansion." },
- },
- required: ["operation", "dataset"],
- additionalProperties: false,
- },
- handler: toolBrainBenchmark,
- previewBudget: MCP_PREVIEW_BUDGET,
- },
- {
- name: "brain_tune",
- description:
- "Opt-in self-tuning recall: run grid-evaluates bounded parameters (pool multiplier, traversal depth, learned weights, expansion) against a benchmark dataset and persists the winner to Brain/search/tuning.json; status shows the validated state; reset deletes it. Search honors it only when enabled.",
- inputSchema: {
- type: "object",
- properties: {
- operation: {
- type: "string",
- enum: ["run", "status", "reset"],
- description: "Tool operation.",
- },
- dataset: { type: "object", description: "Benchmark dataset (run)." },
- k: { type: "integer", minimum: 1, description: "Rank depth (run, default 5)." },
- },
- required: ["operation"],
- additionalProperties: false,
- },
- handler: toolBrainTune,
- previewBudget: MCP_PREVIEW_BUDGET,
- },
- {
- name: "brain_procedural_graph",
- description:
- "Rebuild/show procedural graph projection and prospective hint projection (rebuild, show, hints).",
- inputSchema: {
- type: "object",
- properties: {
- operation: {
- type: "string",
- enum: ["rebuild", "show", "hints"],
- description: "Tool operation.",
- },
- },
- required: ["operation"],
- additionalProperties: false,
- },
- handler: toolBrainProceduralGraph,
- },
- {
- name: "brain_pre_compact_extract",
- description:
- "Extract typed Decision/Commitment/Outcome/Rule/Open question records from bounded text into continuity storage.",
- inputSchema: {
- type: "object",
- properties: {
- session_id: {
- type: "string",
- description: "Session identifier used for idempotency and source refs.",
- },
- turn_start: {
- type: "string",
- description: "First source turn id in the extracted segment.",
- },
- turn_end: {
- type: "string",
- description: "Last source turn id in the extracted segment.",
- },
- text: {
- type: "string",
- description: "Bounded text segment to scan for labeled extraction lines.",
- },
- host: { type: "string", description: "Optional host/client label." },
- max_chars: {
- type: "integer",
- minimum: 1,
- description: "Optional maximum input characters to scan before extracting.",
- },
- },
- required: ["session_id", "turn_start", "turn_end", "text"],
- additionalProperties: false,
- },
- handler: toolBrainPreCompactExtract,
- },
- {
- name: "brain_session_grep",
- previewBudget: MCP_PREVIEW_BUDGET,
- description: "Search imported session recall raw turns and summary nodes.",
- inputSchema: {
- type: "object",
- properties: {
- query: { type: "string", description: "Search text." },
- session_id: {
- type: "string",
- description: "Optional session id filter.",
- },
- limit: {
- type: "integer",
- minimum: 1,
- description: "Maximum hits to return.",
- },
- snippet_chars: {
- type: "integer",
- minimum: 1,
- description: "Maximum chars per hit snippet.",
- },
- },
- required: ["query"],
- additionalProperties: false,
- },
- handler: toolBrainSessionGrep,
- },
- {
- name: "brain_session_describe",
- description: "Describe counts and summary depths for an imported session recall DAG.",
- inputSchema: {
- type: "object",
- properties: {
- session_id: { type: "string", description: "Session id to describe." },
- },
- required: ["session_id"],
- additionalProperties: false,
- },
- handler: toolBrainSessionDescribe,
- },
- {
- name: "brain_session_expand",
- previewBudget: MCP_PREVIEW_BUDGET,
- description:
- "Expand a session recall raw or summary node to immediate sources and paginated exact raw turn content.",
- inputSchema: {
- type: "object",
- properties: {
- id: { type: "string", description: "Session recall record id." },
- raw_limit: {
- type: "integer",
- minimum: 1,
- description: "Maximum raw turn items to return.",
- },
- cursor: {
- type: "string",
- description: "Raw turn pagination cursor from a previous response.",
- },
- },
- required: ["id"],
- additionalProperties: false,
- },
- handler: toolBrainSessionExpand,
- },
- {
- // No preview budget: the addendum is meant to be injected whole and
- // is already bounded by its own per-entry / total character caps.
- name: "brain_pre_compress_pack",
- description:
- "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: {
- top_k: {
- type: "integer",
- minimum: 1,
- description:
- "Maximum number of preferences to include, highest-confidence first (default 10).",
- },
- max_chars_per_memory: {
- type: "integer",
- minimum: 1,
- description:
- "Optional per-entry character cap (code points); trimmed entries carry `trimmed: true`.",
- },
- max_total_chars: {
- type: "integer",
- minimum: 1,
- description:
- "Optional total character cap (code points) across the addendum; lowest-priority overflow is dropped.",
- },
- receipt: {
- type: "boolean",
- description: "When true, emit an opt-in context receipt for this pre-compress run.",
- },
- receipt_host: {
- type: "string",
- description: "Optional host/runtime name for emitted receipts; defaults to `mcp`.",
- },
- telemetry: {
- type: "boolean",
- description:
- "When true, emit an opt-in recall telemetry record for this pre-compress run.",
- },
- telemetry_host: {
- type: "string",
- description: "Optional host/runtime name for emitted telemetry; defaults to `mcp`.",
- },
- session_id: {
- type: "string",
- description: "Optional session id recorded on emitted telemetry.",
- },
- turn_id: {
- type: "string",
- description: "Optional turn id recorded on emitted telemetry.",
- },
- },
- additionalProperties: false,
- },
- handler: toolBrainPreCompressPack,
- },
- {
- 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: {
- type: "object",
- properties: {
- id: {
- type: "string",
- description:
- "Target id (e.g. `pref-foo`, `ret-bar`). Wikilink decoration is stripped if present.",
- },
- limit: {
- type: "integer",
- minimum: 1,
- description:
- "Maximum number of mentions to return. Defaults to 100; the scanner stops as soon as the cap is hit.",
- },
- },
- required: ["id"],
- additionalProperties: false,
- },
- handler: toolBrainUnlinkedMentions,
- },
- {
- name: "brain_moc_audit",
- description:
- "Per-MOC coverage audit. Given a hub note id, classifies its outbound cluster into well-covered / fragile / candidate-missing and surfaces a suggested-next candidate. MOC detection is purely structural (outbound link count + link density). Read-only.",
- inputSchema: {
- type: "object",
- properties: {
- id: {
- type: "string",
- description: "Hub note id (e.g. `pref-foo`). Wikilink decoration is stripped if present.",
- },
- },
- required: ["id"],
- additionalProperties: false,
- },
- handler: toolBrainMocAudit,
- },
- {
- name: "brain_stale_scan",
- description:
- "Structural staleness report: preferences, signals, and Brain/log files inactive longer than the configured `temporal:` thresholds (stale_pref_days / stale_signal_days / stale_log_days). Read-only.",
- inputSchema: {
- type: "object",
- properties: {},
- additionalProperties: false,
- },
- handler: toolBrainStaleScan,
- },
+ ...FEEDBACK_TOOLS,
+ ...REVIEW_TOOLS,
+ ...CONTEXT_TOOLS,
+ ...PACK_TOOLS,
+ ...QUERY_TOOLS,
+ ...ENTITY_TOOLS,
+ ...HEALTH_TOOLS,
+ ...BRIEF_TOOLS,
+ ...ANALYTICS_TOOLS,
+ ...KNOWLEDGE_TOOLS,
+ ...ADMIN_TOOLS,
+ ...RECALL_TOOLS,
+ ...WORKSPACE_TOOLS,
+ ...PROCEDURE_TOOLS,
+ ...LANDSCAPE_TOOLS,
]);
diff --git a/src/mcp/brain/admin-tools.ts b/src/mcp/brain/admin-tools.ts
new file mode 100644
index 00000000..f7822519
--- /dev/null
+++ b/src/mcp/brain/admin-tools.ts
@@ -0,0 +1,478 @@
+/**
+ * Administration: label vocabulary, frontmatter tier guard, secret custody, and the quiet-window maintenance lane.
+ *
+ * Extracted from the former brain-tools.ts monolith; registration
+ * happens through the aggregator, which preserves the public
+ * BRAIN_TOOLS surface.
+ */
+
+import { existsSync } from "node:fs";
+import { resolveAgentName } from "../../core/config.ts";
+import { indexVault, resolveSearchConfig } from "../../core/search/index.ts";
+import { Store } from "../../core/search/store.ts";
+import {
+ assignNoteLabel,
+ LabelVocabularyError,
+ readLabels,
+ removeNoteLabel,
+} from "../../core/brain/labels.ts";
+import { loadSchemaPack } from "../../core/brain/schema-pack.ts";
+import { listSecrets } from "../../core/brain/secrets/store.ts";
+import { runWithSecret, SecretExecDeniedError } from "../../core/brain/secrets/exec.ts";
+import {
+ discoverBridges,
+ readDismissedBridges,
+ writeBridgeProposals,
+} from "../../core/brain/link-graph/bridge-discovery.ts";
+import {
+ detectCommunities,
+ materializeClusterNotes,
+} from "../../core/brain/link-graph/communities.ts";
+import { appendMetric } from "../../core/brain/metrics.ts";
+import { createSafeguard, resolveSafeguardTimeoutMs } from "../../core/brain/safeguard.ts";
+import { currentLease } from "../../core/brain/maintenance/lease.ts";
+import { listJournal } from "../../core/brain/maintenance/journal.ts";
+import { runMaintenance, type DailyWindow } from "../../core/brain/maintenance/lane.ts";
+import { writeFrontmatterAtomic } from "../../core/vault.ts";
+import { resolveNotePath } from "../../core/brain/note-path.ts";
+import type { FrontmatterMap } from "../../core/types.ts";
+import { parseFrontmatter } from "../../core/vault.ts";
+import { dream } from "../../core/brain/dream.ts";
+import { isoSecond } from "../../core/brain/time.ts";
+import { normalizeAgentArgument } from "../../core/agent-identity.ts";
+import { INVALID_PARAMS, MCPError } from "../protocol.ts";
+import type { ServerContext, ToolDefinition } from "../tools.ts";
+import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
+
+/** Controlled-vocabulary classification over the schema pack's labels. */
+function toolBrainLabels(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Record<string, unknown> {
+ const op = args["operation"];
+ if (op !== "assign" && op !== "remove" && op !== "show") {
+ throw new MCPError(INVALID_PARAMS, "brain_labels: operation must be assign|remove|show");
+ }
+ const path = args["path"];
+ if (typeof path !== "string" || path.trim() === "") {
+ throw new MCPError(INVALID_PARAMS, "brain_labels: path must be a vault-relative string");
+ }
+ if (op === "show") {
+ const [metadata] = parseFrontmatter(vaultContainedPath(ctx.vault, path, "brain_labels show"));
+ return { path, labels: readLabels(metadata) };
+ }
+ const pack = loadSchemaPack(ctx.vault);
+ const dimension = args["dimension"];
+ if (typeof dimension !== "string" || dimension.trim() === "") {
+ throw new MCPError(INVALID_PARAMS, `brain_labels ${op}: dimension must be non-empty`);
+ }
+ try {
+ if (op === "remove") {
+ return { ...removeNoteLabel(ctx.vault, path, { dimension, pack }) };
+ }
+ const value = args["value"];
+ if (typeof value !== "string" || value.trim() === "") {
+ throw new MCPError(INVALID_PARAMS, "brain_labels assign: value must be non-empty");
+ }
+ const agentArg = args["agent"];
+ const agent =
+ normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??
+ resolveAgentName(ctx.configPath ?? undefined);
+ return {
+ ...assignNoteLabel(ctx.vault, path, { dimension, value, pack, agent, now: new Date() }),
+ };
+ } catch (exc) {
+ if (exc instanceof LabelVocabularyError) {
+ throw new MCPError(INVALID_PARAMS, `brain_labels ${op}: ${exc.message}`);
+ }
+ throw exc;
+ }
+}
+
+// ----- brain_tiers (t_3f92d3f1) ----------------------------------------------
+
+/** Staged repair surface for identity-tier frontmatter hand-edits. */
+async function toolBrainTiers(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const op = args["operation"];
+ if (op !== "check" && op !== "restore" && op !== "accept") {
+ throw new MCPError(INVALID_PARAMS, "brain_tiers: operation must be check|restore|accept");
+ }
+ const searchConfig = resolveSearchConfig({
+ vault: ctx.vault,
+ configPath: ctx.configPath ?? undefined,
+ });
+ if (op === "check") {
+ // Fail-soft: a vault that was never indexed has no snapshots and
+ // therefore no drift - not an error.
+ if (!existsSync(searchConfig.dbPath)) return { findings: [] };
+ const store = await Store.open(searchConfig, { mode: "read" });
+ try {
+ return { findings: store.listTierDrift() };
+ } finally {
+ await store.close();
+ }
+ }
+ const path = args["path"];
+ if (typeof path !== "string" || path.trim() === "") {
+ throw new MCPError(INVALID_PARAMS, `brain_tiers ${op}: path must be a vault-relative string`);
+ }
+ if (op === "restore" && args["apply"] !== true) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_tiers restore: pass apply=true - restore writes the file",
+ );
+ }
+ const field = typeof args["field"] === "string" ? (args["field"] as string) : undefined;
+ if (!existsSync(searchConfig.dbPath)) {
+ throw new MCPError(INVALID_PARAMS, `brain_tiers ${op}: the vault has no search index yet`);
+ }
+ const store = await Store.open(searchConfig, { mode: "write" });
+ try {
+ const docId = store.getDocumentIdByPath(path);
+ if (docId === null) {
+ throw new MCPError(INVALID_PARAMS, `brain_tiers ${op}: not indexed: ${path}`);
+ }
+ const rows = store
+ .listTierDrift()
+ .filter((r) => r.documentId === docId && (field === undefined || r.field === field));
+ if (rows.length === 0) {
+ throw new MCPError(INVALID_PARAMS, `brain_tiers ${op}: no open drift for ${path}`);
+ }
+ if (op === "restore") {
+ const absolute = vaultContainedPath(ctx.vault, path, "brain_tiers restore");
+ const [metadata, body] = parseFrontmatter(absolute);
+ const next = { ...metadata };
+ for (const r of rows) {
+ next[r.field] = frontmatterValueFromSnapshot(r.expected, r.field);
+ }
+ writeFrontmatterAtomic(absolute, next, body, { overwrite: true });
+ for (const r of rows) store.clearTierDrift(docId, r.field);
+ return { restored: rows.map((r) => r.field), path };
+ }
+ const snapshot: Record<string, unknown> = { ...store.getTierSnapshot(docId) };
+ for (const r of rows) {
+ snapshot[r.field] = r.actual;
+ store.clearTierDrift(docId, r.field);
+ }
+ store.setTierSnapshot(docId, snapshot);
+ return { accepted: rows.map((r) => r.field), path };
+ } finally {
+ await store.close();
+ }
+}
+
+/** Resolve a vault-relative path, refusing traversal and symlink escapes. */
+function vaultContainedPath(vault: string, relPath: string, label: string): string {
+ try {
+ return resolveNotePath(vault, relPath);
+ } catch (exc) {
+ throw new MCPError(INVALID_PARAMS, `${label}: ${(exc as Error).message}`);
+ }
+}
+
+/** Narrow a snapshot value to the shapes frontmatter can carry. */
+function frontmatterValueFromSnapshot(value: unknown, field: string): FrontmatterMap[string] {
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
+ return value;
+ }
+ if (Array.isArray(value) && value.every((v): v is string => typeof v === "string")) {
+ return value;
+ }
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_tiers restore: snapshot value for "${field}" is not a frontmatter scalar or string array`,
+ );
+}
+
+// ----- brain_secrets (t_0b134404) ---------------------------------------------
+
+/**
+ * Capability-gated custody, agent-facing subset: list metadata and
+ * run an allowlisted command. Deliberately NO set/get over MCP - the
+ * material enters via the operator's CLI and leaves only into a
+ * subprocess env.
+ */
+async function toolBrainSecrets(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const op = args["operation"];
+ if (op !== "list" && op !== "run") {
+ throw new MCPError(INVALID_PARAMS, "brain_secrets: operation must be list|run");
+ }
+ if (op === "list") {
+ return { secrets: listSecrets(ctx.vault) };
+ }
+ const name = args["name"];
+ if (typeof name !== "string" || name.trim() === "") {
+ throw new MCPError(INVALID_PARAMS, "brain_secrets run: name must be non-empty");
+ }
+ const command = args["command"];
+ if (
+ !Array.isArray(command) ||
+ command.length === 0 ||
+ !command.every((part): part is string => typeof part === "string")
+ ) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_secrets run: command must be a non-empty array of strings",
+ );
+ }
+ const agentArg = args["agent"];
+ const agent =
+ normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??
+ resolveAgentName(ctx.configPath ?? undefined);
+ try {
+ const result = await runWithSecret(ctx.vault, name, command, { agent, now: new Date() });
+ return { exit_code: result.exitCode, stdout: result.stdout, stderr: result.stderr };
+ } catch (exc) {
+ if (exc instanceof SecretExecDeniedError) {
+ throw new MCPError(INVALID_PARAMS, `brain_secrets run: ${exc.message}`);
+ }
+ throw exc;
+ }
+}
+
+// ----- brain_maintenance (t_166d1226) ------------------------------------------
+
+/** Quiet-window, lease-guarded heavy maintenance lane. */
+async function toolBrainMaintenance(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const op = args["operation"];
+ if (op !== "run" && op !== "status") {
+ throw new MCPError(INVALID_PARAMS, "brain_maintenance: operation must be run|status");
+ }
+ const now = new Date();
+ if (op === "status") {
+ return {
+ lease: currentLease(ctx.vault, { now }),
+ journal: listJournal(ctx.vault, 10),
+ };
+ }
+ let window: DailyWindow | undefined;
+ const startHour = args["window_start_hour"];
+ const endHour = args["window_end_hour"];
+ if (startHour !== undefined || endHour !== undefined) {
+ if (
+ typeof startHour !== "number" ||
+ typeof endHour !== "number" ||
+ !Number.isInteger(startHour) ||
+ !Number.isInteger(endHour) ||
+ startHour < 0 ||
+ startHour > 23 ||
+ endHour < 0 ||
+ endHour > 23
+ ) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_maintenance run: window_start_hour/window_end_hour must be integers 0..23",
+ );
+ }
+ const tz = typeof args["tz"] === "string" ? (args["tz"] as string) : "UTC";
+ window = { startHour, endHour, tz };
+ }
+ const agentArg = args["agent"];
+ const agent =
+ normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??
+ resolveAgentName(ctx.configPath ?? undefined);
+ const searchConfig = resolveSearchConfig({
+ vault: ctx.vault,
+ configPath: ctx.configPath ?? undefined,
+ });
+ // Same per-task deadlines as the CLI lane (t_06784b8d): one fresh
+ // cooperative safeguard per task, budget resolved per-op -> global
+ // -> default.
+ const laneSafeguard = (operation: "dream" | "reindex" | "bridges" | "clusters") =>
+ createSafeguard({
+ operation,
+ timeoutMs: resolveSafeguardTimeoutMs(operation, ctx.configPath ?? undefined),
+ });
+ const result = await runMaintenance(ctx.vault, {
+ now,
+ holder: `${agent}@${process.pid}`,
+ force: args["force"] === true,
+ ...(window !== undefined ? { window } : {}),
+ tasks: [
+ {
+ name: "dream",
+ run: async () => {
+ dream(ctx.vault, { now, safeguard: laneSafeguard("dream") });
+ },
+ },
+ {
+ name: "reindex",
+ run: async () => {
+ await indexVault(searchConfig, { safeguard: laneSafeguard("reindex") });
+ },
+ },
+ // Same lane contract as the CLI verb (link-recall-intelligence):
+ // bridges and clusters run after reindex so they see fresh
+ // edges; both are fail-soft without embeddings, and a metrics
+ // write failure never fails the task.
+ {
+ name: "bridges",
+ run: async () => {
+ const store = await Store.open(searchConfig, { mode: "read" });
+ try {
+ const report = discoverBridges(store, {
+ dismissed: readDismissedBridges(ctx.vault),
+ safeguard: laneSafeguard("bridges"),
+ });
+ writeBridgeProposals(ctx.vault, report, { now });
+ try {
+ appendMetric(ctx.vault, {
+ surface: "bridge_discovery",
+ runAt: isoSecond(now),
+ payload: {
+ proposals: report.proposals.length,
+ scanned_candidates: report.scannedCandidates,
+ vec_available: report.vecAvailable,
+ lane: true,
+ },
+ });
+ } catch {
+ // Metrics are observability, not correctness.
+ }
+ } finally {
+ await store.close();
+ }
+ },
+ },
+ {
+ name: "clusters",
+ run: async () => {
+ const store = await Store.open(searchConfig, { mode: "read" });
+ try {
+ const communities = detectCommunities(store, { safeguard: laneSafeguard("clusters") });
+ const materialized = materializeClusterNotes(ctx.vault, communities, { store, now });
+ try {
+ appendMetric(ctx.vault, {
+ surface: "communities",
+ runAt: isoSecond(now),
+ payload: {
+ communities: communities.length,
+ sizes: communities.map((c) => c.size),
+ written: materialized.written.length,
+ removed: materialized.removed.length,
+ lane: true,
+ },
+ });
+ } catch {
+ // Metrics are observability, not correctness.
+ }
+ } finally {
+ await store.close();
+ }
+ },
+ },
+ ],
+ });
+ return { verdict: result.verdict, tasks: result.tasks };
+}
+
+// ----- brain_bridges (t_ab540afe) --------------------------------------------
+
+export const ADMIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
+ {
+ name: "brain_labels",
+ description:
+ "Controlled-vocabulary classification against the schema pack's labels field: assign (fail-closed - unknown dimensions/values rejected with the declared vocabulary), remove, or show a note's labels. Single-choice per dimension; persists as a labels frontmatter array plus a canonical label entity.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["assign", "remove", "show"],
+ description: "Tool operation.",
+ },
+ path: { type: "string", description: "Vault-relative note path." },
+ dimension: { type: "string", description: "Label dimension (assign/remove)." },
+ value: { type: "string", description: "Label value (assign)." },
+ agent: { type: "string", description: "Agent identity override (assign)." },
+ },
+ required: ["operation", "path"],
+ additionalProperties: false,
+ },
+ handler: toolBrainLabels,
+ previewBudget: MCP_PREVIEW_BUDGET,
+ },
+ {
+ name: "brain_tiers",
+ description:
+ "Frontmatter tier guard: check lists staged identity-field hand-edits the index post-pass detected, restore (apply=true required) writes the expected value back into the file, accept adopts the hand-edit as the new snapshot baseline. Nothing auto-resolves.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["check", "restore", "accept"],
+ description: "Tool operation.",
+ },
+ path: { type: "string", description: "Vault-relative path (restore/accept)." },
+ field: { type: "string", description: "Restrict to one field (restore/accept)." },
+ apply: { type: "boolean", description: "Required true for restore - it writes the file." },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainTiers,
+ previewBudget: MCP_PREVIEW_BUDGET,
+ },
+ {
+ name: "brain_secrets",
+ description:
+ "Capability-gated secret custody, agent-facing subset: list stored secret metadata (never values) or run an allowlisted command with the secret injected as its declared env var - output comes back redacted. Storing and removing secrets stays on the operator's CLI (o2b brain secret).",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: { type: "string", enum: ["list", "run"], description: "Tool operation." },
+ name: { type: "string", description: "Secret name (run)." },
+ command: {
+ type: "array",
+ items: { type: "string" },
+ description: "Command argv to execute (run); must match the secret's allowlist.",
+ },
+ agent: { type: "string", description: "Agent identity override (run)." },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainSecrets,
+ previewBudget: MCP_PREVIEW_BUDGET,
+ },
+ {
+ name: "brain_maintenance",
+ description:
+ "Quiet-window, lease-guarded heavy maintenance lane: run executes dream, reindex, bridges, and clusters stale-first behind the local-time window, busy gate, and an expiring lease (force bypasses the soft gates, never the lease); status renders the lease holder and recent journal.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: { type: "string", enum: ["run", "status"], description: "Tool operation." },
+ force: { type: "boolean", description: "Bypass window and busy gates (run)." },
+ window_start_hour: {
+ type: "integer",
+ minimum: 0,
+ maximum: 23,
+ description: "Local hour the window opens, inclusive (run).",
+ },
+ window_end_hour: {
+ type: "integer",
+ minimum: 0,
+ maximum: 23,
+ description: "Local hour the window closes, exclusive (run).",
+ },
+ tz: { type: "string", description: "IANA timezone for the window (default UTC)." },
+ agent: { type: "string", description: "Agent identity override (run)." },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainMaintenance,
+ previewBudget: MCP_PREVIEW_BUDGET,
+ },
+]);
diff --git a/src/mcp/brain/analytics-tools.ts b/src/mcp/brain/analytics-tools.ts
new file mode 100644
index 00000000..bb277e0d
--- /dev/null
+++ b/src/mcp/brain/analytics-tools.ts
@@ -0,0 +1,253 @@
+/**
+ * Consolidated analytics dispatcher: timeline, belief evolution, concept synthesis, and attention flows behind the brain_analytics view parameter.
+ *
+ * Extracted from the former brain-tools.ts monolith; registration
+ * happens through the aggregator, which preserves the public
+ * BRAIN_TOOLS surface.
+ */
+
+import { buildConceptCluster } from "../../core/brain/link-graph/concept-cluster.ts";
+import { buildTimelineIndex } from "../../core/brain/temporal/build-index.ts";
+import { selectEvents } from "../../core/brain/temporal/select-events.ts";
+import { buildBeliefEvolution } from "../../core/brain/temporal/belief-evolution.ts";
+import { isBrainLogEventKind, type BrainLogEventKind } from "../../core/brain/types.ts";
+import {
+ evaluateAttentionFlow,
+ listAttentionFlows,
+ renderAttentionFlow,
+} from "../../core/brain/attention-flows.ts";
+import { normaliseWikilinkTarget } from "../../core/brain/wikilink.ts";
+import { INVALID_PARAMS, MCPError } from "../protocol.ts";
+import type { ServerContext, ToolDefinition } from "../tools.ts";
+import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
+import {
+ coerceIsoTimestampOrDate,
+ coercePositiveInteger,
+ dispatchByView,
+ localizeEnvelope,
+ requiredStringArg,
+} from "./shared.ts";
+
+function coerceEventKind(tool: string, raw: unknown): BrainLogEventKind | undefined {
+ if (raw === undefined || raw === null) return undefined;
+ if (typeof raw !== "string") {
+ throw new MCPError(INVALID_PARAMS, `${tool}: kind must be a string`);
+ }
+ if (!isBrainLogEventKind(raw)) {
+ throw new MCPError(INVALID_PARAMS, `${tool}: kind must be a known BrainLogEventKind`);
+ }
+ return raw;
+}
+
+/**
+ * `brain_timeline` - frozen chronological list of events filtered by
+ * any combination of `pref_id`, `topic`, `kind`, `since`, `until`,
+ * `limit`. Pure read.
+ */
+async function toolBrainTimeline(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const prefId = typeof args["pref_id"] === "string" ? args["pref_id"] : undefined;
+ const topic = typeof args["topic"] === "string" ? args["topic"] : undefined;
+ const kind = coerceEventKind("brain_timeline", args["kind"]);
+ const since = coerceIsoTimestampOrDate("brain_timeline", "since", args["since"]);
+ const until = coerceIsoTimestampOrDate("brain_timeline", "until", args["until"]);
+ const limit = coercePositiveInteger("brain_timeline", "limit", args["limit"]);
+
+ const index = buildTimelineIndex(ctx.vault, {
+ ...(since !== undefined ? { since } : {}),
+ ...(until !== undefined ? { until } : {}),
+ });
+ const events = selectEvents(index, {
+ ...(prefId !== undefined ? { prefId } : {}),
+ ...(topic !== undefined ? { topic } : {}),
+ ...(kind !== undefined ? { kind } : {}),
+ ...(since !== undefined ? { since } : {}),
+ ...(until !== undefined ? { until } : {}),
+ });
+ const sliced = limit !== undefined ? events.slice(0, limit) : events;
+ return {
+ vault_path: ctx.vault,
+ window: index.window,
+ total: events.length,
+ events: sliced.map((ev) => ({
+ at: ev.at,
+ kind: ev.kind,
+ source: ev.source,
+ ...(ev.prefId !== undefined ? { pref_id: ev.prefId } : {}),
+ ...(ev.topic !== undefined ? { topic: ev.topic } : {}),
+ ...(ev.result !== undefined ? { result: ev.result } : {}),
+ ...(ev.artifact !== undefined ? { artifact: ev.artifact } : {}),
+ ...(ev.reason !== undefined ? { reason: ev.reason } : {}),
+ ...(ev.text !== undefined ? { text: ev.text } : {}),
+ })),
+ };
+}
+
+/**
+ * `brain_belief_evolution` - per-pref / per-topic chronological story:
+ * status transitions, evidence rollup with running counts, and
+ * retirement chain.
+ */
+async function toolBrainBeliefEvolution(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const prefIdRaw = args["pref_id"];
+ const topicRaw = args["topic"];
+ const hasPref = typeof prefIdRaw === "string" && prefIdRaw.trim().length > 0;
+ const hasTopic = typeof topicRaw === "string" && topicRaw.trim().length > 0;
+ if (hasPref === hasTopic) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_analytics view=belief_evolution: exactly one of pref_id or topic is required",
+ );
+ }
+ const target = hasPref
+ ? { prefId: (prefIdRaw as string).trim() }
+ : { topic: (topicRaw as string).trim() };
+ const index = buildTimelineIndex(ctx.vault, {});
+ const evo = buildBeliefEvolution(index, ctx.vault, target);
+ return {
+ vault_path: ctx.vault,
+ target: evo.target,
+ transitions: evo.transitions,
+ evidence: evo.evidence,
+ retirements: evo.retirements,
+ generated_at: evo.generatedAt,
+ };
+}
+
+/**
+ * Concept-scoped cluster envelope: target + all linkers (depth-1)
+ * plus optionally unlinked mentions. Pure assembler; no LLM call.
+ */
+async function toolBrainConceptSynthesis(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const idRaw = args["id"];
+ if (typeof idRaw !== "string" || idRaw.trim().length === 0) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_analytics view=concept_synthesis: id must be a non-empty string",
+ );
+ }
+ const includeUnlinkedRaw = args["include_unlinked"];
+ let includeUnlinked = false;
+ if (includeUnlinkedRaw !== undefined && includeUnlinkedRaw !== null) {
+ if (typeof includeUnlinkedRaw !== "boolean") {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_analytics view=concept_synthesis: include_unlinked must be a boolean",
+ );
+ }
+ includeUnlinked = includeUnlinkedRaw;
+ }
+ const targetId = normaliseWikilinkTarget(idRaw);
+ const cluster = buildConceptCluster(ctx.vault, targetId, {
+ includeUnlinked,
+ });
+ return {
+ vault_path: ctx.vault,
+ target_id: cluster.targetId,
+ target_title: cluster.targetTitle,
+ linkers: cluster.linkers,
+ unlinked_mentions: cluster.unlinkedMentions,
+ generated_at: cluster.generatedAt,
+ };
+}
+
+// ----- brain_moc_audit (v0.10.17) ------------------------------------------
+
+async function toolBrainAttentionFlows(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const operation = requiredStringArg("brain_attention_flows", args, "operation");
+ if (operation === "list") {
+ const flows = listAttentionFlows(ctx.vault);
+ return { total: flows.length, flows };
+ }
+ if (operation === "evaluate") {
+ const flowId = requiredStringArg("brain_attention_flows", args, "flow_id");
+ const report = evaluateAttentionFlow(ctx.vault, flowId);
+ return { ...report };
+ }
+ if (operation === "render") {
+ const flowId = requiredStringArg("brain_attention_flows", args, "flow_id");
+ return {
+ flow_id: flowId,
+ text: renderAttentionFlow(ctx.vault, flowId),
+ };
+ }
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_analytics view=attention_flows: operation must be one of list|evaluate|render",
+ );
+}
+
+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,
+});
+
+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 localizeEnvelope(ctx, await dispatchByView(ANALYTICS_VIEW_HANDLERS, ctx, withDefaults));
+}
+
+export const ANALYTICS_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
+ {
+ 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,
+ },
+]);
diff --git a/src/mcp/brain/brief-tools.ts b/src/mcp/brain/brief-tools.ts
new file mode 100644
index 00000000..3cda958d
--- /dev/null
+++ b/src/mcp/brain/brief-tools.ts
@@ -0,0 +1,441 @@
+/**
+ * Consolidated brief dispatcher: morning/daily/weekly/monthly views, digest, and the operator summary behind the brain_brief view parameter.
+ *
+ * Extracted from the former brain-tools.ts monolith; registration
+ * happens through the aggregator, which preserves the public
+ * BRAIN_TOOLS surface.
+ */
+
+import { resolveLinkOutputFormat, resolveTriggerCooldownDays } from "../../core/config.ts";
+import { buildMorningBrief } from "../../core/brain/morning-brief.ts";
+import {
+ deliverBriefTriggers,
+ renderTriggerBriefSection,
+} from "../../core/brain/triggers/brief.ts";
+import { buildTimelineIndex } from "../../core/brain/temporal/build-index.ts";
+import { buildDailyBrief } from "../../core/brain/temporal/daily-brief.ts";
+import { buildWeeklySynthesis } from "../../core/brain/temporal/weekly-brief.ts";
+import { loadTemporalConfigSafe } from "../../core/brain/policy.ts";
+import { renderDigest, type DigestFormat } from "../../core/brain/digest.ts";
+import { dream } from "../../core/brain/dream.ts";
+import {
+ buildMonthlyReview,
+ normalizeMonthlyReviewMonth,
+} from "../../core/brain/monthly-review.ts";
+import { buildOperatorSummary } from "../../core/brain/trust/operator-summary.ts";
+import { isoDate } from "../../core/brain/time.ts";
+import { captureReportDelta } from "../../core/brain/report-snapshot.ts";
+import { INVALID_PARAMS, MCPError } from "../protocol.ts";
+import type { ServerContext, ToolDefinition } from "../tools.ts";
+import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
+import { coerceIsoDate, coerceFormat } from "../coerce.ts";
+import {
+ coerceIsoTimestampOrDate,
+ dispatchByView,
+ localizeEnvelope,
+ optionalPositiveInt,
+} from "./shared.ts";
+
+async function toolBrainMorningBrief(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const topK = optionalPositiveInt(args, "top_k", "brain_brief view=morning") ?? 10;
+ const lookbackDays = optionalPositiveInt(args, "lookback_days", "brain_brief view=morning") ?? 7;
+ const maxCharsPerMemory = optionalPositiveInt(
+ args,
+ "max_chars_per_memory",
+ "brain_brief view=morning",
+ );
+ const maxTotalChars = optionalPositiveInt(args, "max_total_chars", "brain_brief view=morning");
+ const now = new Date();
+ const brief = buildMorningBrief(ctx.vault, {
+ now,
+ topK,
+ lookbackDays,
+ ...(maxCharsPerMemory !== undefined ? { maxCharsPerMemory } : {}),
+ ...(maxTotalChars !== undefined ? { maxTotalChars } : {}),
+ });
+ // Pending-trigger section (t_cd1fee79): renders only when a trigger
+ // scan persisted surfaceable triggers; included triggers are marked
+ // delivered so a prompt shows once per cooldown window. Fail-soft -
+ // a broken queue never breaks the brief.
+ let triggerSection: ReturnType<typeof renderTriggerBriefSection> | null = null;
+ try {
+ triggerSection = renderTriggerBriefSection(ctx.vault, {
+ now,
+ cooldownDays: resolveTriggerCooldownDays(ctx.configPath ?? undefined),
+ });
+ if (triggerSection.triggers.length > 0) deliverBriefTriggers(ctx.vault, triggerSection, now);
+ } catch {
+ triggerSection = null;
+ }
+ const text =
+ triggerSection !== null && triggerSection.text !== ""
+ ? `${brief.text}${brief.text.length > 0 ? "\n\n" : ""}${triggerSection.text}`
+ : brief.text;
+ return {
+ text,
+ preferences: brief.preferences,
+ open_questions: brief.openQuestions,
+ recent_notes: brief.recentNotes,
+ total_chars: brief.totalChars,
+ ...(triggerSection !== null && triggerSection.triggers.length > 0
+ ? {
+ triggers: triggerSection.triggers.map((t) => ({
+ id: t.id,
+ kind: t.kind,
+ urgency: t.urgency,
+ reason: t.reason,
+ })),
+ }
+ : {}),
+ };
+}
+
+async function toolBrainDigest(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const since = coerceIsoDate(args, "since");
+ const until = coerceIsoDate(args, "until");
+ const format = coerceFormat(args) satisfies DigestFormat;
+
+ // Pin ONE effective until instant so the rendered content, the
+ // snapshot render, and the snapshot date key all describe the same
+ // window even when the caller omitted `until`.
+ const effectiveUntil = until ?? new Date();
+ const result = renderDigest(ctx.vault, {
+ ...(since ? { since } : {}),
+ until: effectiveUntil,
+ format,
+ linkOutputFormat: resolveLinkOutputFormat(ctx.configPath ?? undefined),
+ });
+
+ const envelope: Record<string, unknown> = {
+ format,
+ empty: result.empty,
+ content: result.content,
+ };
+ // Snapshot the structured summary, not the rendered string: render
+ // a JSON digest for the snapshot regardless of the caller's format
+ // so the run-over-run diff keys on data.
+ const digestDate = isoDate(effectiveUntil);
+ const snapshotSource =
+ format === "json"
+ ? result.content
+ : renderDigest(ctx.vault, {
+ ...(since ? { since } : {}),
+ until: effectiveUntil,
+ format: "json",
+ linkOutputFormat: resolveLinkOutputFormat(ctx.configPath ?? undefined),
+ }).content;
+ let parsedSnapshot: unknown = null;
+ try {
+ parsedSnapshot = JSON.parse(snapshotSource);
+ } catch {
+ parsedSnapshot = null;
+ }
+ const delta =
+ parsedSnapshot !== null
+ ? captureReportDelta(
+ ctx.vault,
+ "digest",
+ digestDate,
+ parsedSnapshot,
+ ctx.configPath ? { configPath: ctx.configPath } : {},
+ )
+ : null;
+ return delta !== null ? { ...envelope, delta } : envelope;
+}
+
+// ----- brain_query ---------------------------------------------------------
+
+/**
+ * `brain_daily_brief` - structured counters + transitions + source
+ * pointers for one day. Defaults `date` to today UTC when omitted.
+ */
+async function toolBrainDailyBrief(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const dateRaw = args["date"];
+ const dateCoerced = coerceIsoTimestampOrDate("brain_daily_brief", "date", dateRaw, "date-only");
+ const date = dateCoerced ?? new Date().toISOString().slice(0, 10);
+ const cfg = loadTemporalConfigSafe(ctx.vault);
+ const index = buildTimelineIndex(ctx.vault, {});
+ const brief = buildDailyBrief(index, ctx.vault, date, {
+ offsetHours: cfg.daily_window_offset_hours,
+ });
+ const envelope: Record<string, unknown> = {
+ vault_path: ctx.vault,
+ date: brief.date,
+ window: brief.window,
+ events_by_kind: brief.eventsByKind,
+ status_transitions: brief.statusTransitions,
+ vault_delta: brief.vaultDelta,
+ source_pointers: brief.sourcePointers,
+ generated_at: brief.generatedAt,
+ };
+ // Dual-output (t_00eece5d): persist a machine snapshot and report
+ // the run-over-run delta when report snapshots are enabled.
+ const delta = captureReportDelta(
+ ctx.vault,
+ "daily",
+ brief.date,
+ envelope,
+ ctx.configPath ? { configPath: ctx.configPath } : {},
+ );
+ return delta !== null ? { ...envelope, delta } : envelope;
+}
+
+/**
+ * `brain_weekly_synthesis` - 7-day deterministic summary plus retired
+ * and contradictions lists.
+ */
+async function toolBrainWeeklySynthesis(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const weekEndRaw = args["week_end"];
+ const weekEndCoerced = coerceIsoTimestampOrDate(
+ "brain_weekly_synthesis",
+ "week_end",
+ weekEndRaw,
+ "date-only",
+ );
+ const weekEnd = weekEndCoerced ?? new Date().toISOString().slice(0, 10);
+ const cfg = loadTemporalConfigSafe(ctx.vault);
+ const index = buildTimelineIndex(ctx.vault, {});
+ const synth = buildWeeklySynthesis(index, ctx.vault, weekEnd, cfg);
+ const envelope: Record<string, unknown> = {
+ vault_path: ctx.vault,
+ window_start: synth.windowStart,
+ window_end: synth.windowEnd,
+ events_by_kind: synth.eventsByKind,
+ status_transitions: synth.statusTransitions,
+ retired: synth.retired,
+ contradictions: synth.contradictions,
+ vault_delta: synth.vaultDelta,
+ source_pointers: synth.sourcePointers,
+ generated_at: synth.generatedAt,
+ };
+ const delta = captureReportDelta(
+ ctx.vault,
+ "weekly",
+ weekEnd,
+ envelope,
+ ctx.configPath ? { configPath: ctx.configPath } : {},
+ );
+ return delta !== null ? { ...envelope, delta } : envelope;
+}
+
+// ----- brain_intention (Agent Surface Suite) --------------------------------
+
+async function toolBrainMonthlyReview(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const monthRaw = args["month"];
+ let month: string | undefined;
+ if (monthRaw !== undefined && monthRaw !== null) {
+ if (typeof monthRaw !== "string") {
+ throw new MCPError(INVALID_PARAMS, "brain_brief view=monthly: month must be YYYY-MM");
+ }
+ try {
+ month = normalizeMonthlyReviewMonth(monthRaw);
+ } catch {
+ throw new MCPError(INVALID_PARAMS, "brain_brief view=monthly: month must be YYYY-MM");
+ }
+ }
+ const report = buildMonthlyReview(ctx.vault, month ? { month } : {});
+ return {
+ schema_version: report.schema_version,
+ generated_at: report.generated_at,
+ month: report.month,
+ window: report.window,
+ summary: report.summary,
+ };
+}
+
+/**
+ * Aggregate operator dashboard: trust verdict, doctor / dream
+ * counts, verification delta summary, ranked maintenance actions,
+ * and instruction-file ceiling warnings - one read-only call so an
+ * operator does not run `brain_digest` + `brain_doctor` separately.
+ */
+async function toolBrainOperatorSummary(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const topRaw = args["top_actions"];
+ let topActionsN: number | undefined;
+ if (topRaw !== undefined && topRaw !== null) {
+ // Strict integer coercion: reject `"3abc"`, `"2.5"`, and other
+ // shapes `Number.parseInt` would silently accept. Only a pure
+ // integer literal is allowed.
+ if (typeof topRaw === "number") {
+ if (!Number.isInteger(topRaw) || topRaw < 0) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_brief view=operator: top_actions must be a non-negative integer",
+ );
+ }
+ topActionsN = topRaw;
+ } else if (typeof topRaw === "string") {
+ const trimmed = topRaw.trim();
+ if (trimmed === "" || !/^[0-9]+$/.test(trimmed)) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_brief view=operator: top_actions must be a non-negative integer",
+ );
+ }
+ topActionsN = Number.parseInt(trimmed, 10);
+ } else {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_brief view=operator: top_actions must be a non-negative integer",
+ );
+ }
+ }
+
+ const includeDreamRaw = args["include_dream"];
+ let includeDream: boolean;
+ if (includeDreamRaw === undefined || includeDreamRaw === null) {
+ includeDream = true;
+ } else if (typeof includeDreamRaw === "boolean") {
+ includeDream = includeDreamRaw;
+ } else {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_brief view=operator: include_dream must be a boolean",
+ );
+ }
+
+ let dreamSummary;
+ let dreamError: string | undefined;
+ if (includeDream) {
+ try {
+ dreamSummary = dream(ctx.vault, { dryRun: true });
+ } catch (err) {
+ // Surface the failure so callers know the dashboard is missing
+ // verification + dream signals; do not silently produce a
+ // partial envelope.
+ dreamError = (err as Error).message ?? String(err);
+ }
+ }
+ const summary = buildOperatorSummary(ctx.vault, {
+ ...(dreamSummary ? { dreamSummary } : {}),
+ ...(topActionsN !== undefined ? { topActionsN } : {}),
+ });
+ return {
+ vault_path: ctx.vault,
+ trust_verdict: summary.trust_verdict,
+ digest_summary: summary.digest_summary,
+ doctor_summary: {
+ warning_count: summary.doctor_summary.warning_count,
+ error_count: summary.doctor_summary.error_count,
+ },
+ dream_summary: summary.dream_summary,
+ verification_delta: {
+ summary: summary.verification_delta.summary,
+ entries: summary.verification_delta.entries,
+ },
+ top_actions: summary.top_actions,
+ instruction_file_warnings: summary.instruction_file_warnings,
+ ...(dreamError !== undefined ? { dream_error: dreamError } : {}),
+ };
+}
+
+// ----- brain_unlinked_mentions (v0.10.17) ----------------------------------
+
+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,
+});
+
+async function toolBrainBrief(ctx: ServerContext, args: Record<string, unknown>): Promise<unknown> {
+ return localizeEnvelope(ctx, await dispatchByView(BRIEF_VIEW_HANDLERS, ctx, args));
+}
+
+export const BRIEF_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,
+ },
+]);
diff --git a/src/mcp/brain/context-tools.ts b/src/mcp/brain/context-tools.ts
new file mode 100644
index 00000000..80c6b10d
--- /dev/null
+++ b/src/mcp/brain/context-tools.ts
@@ -0,0 +1,465 @@
+/**
+ * Context assembly: write sessions, pinned scratchpad, session bootstrap, context packing, receipts, presets, and pre-compress/pre-compact surfaces.
+ *
+ * Extracted from the former brain-tools.ts monolith; registration
+ * happens through the aggregator, which preserves the public
+ * BRAIN_TOOLS surface.
+ */
+
+import { existsSync, readFileSync } from "node:fs";
+import { resolveAgentName } from "../../core/config.ts";
+import { brainActivePath, brainDirs } from "../../core/brain/paths.ts";
+import { regenerateActive, type RegenerateActiveResult } from "../../core/brain/active.ts";
+import { parseFrontmatter } from "../../core/vault.ts";
+import { readVaultInstructionFile } from "../../core/brain/vault-instruction-file.ts";
+import { normalizeAgentArgument } from "../../core/agent-identity.ts";
+import {
+ WriteSessionRequestError,
+ abandonSession,
+ approveSession,
+ openArtifactSession,
+ sessionEnvelope,
+} from "../../core/brain/write-session/engine.ts";
+import { dispatchSubmit, openPanelSession } from "../../core/brain/write-session/panel.ts";
+import { listWriteSessions, readWriteSession } from "../../core/brain/write-session/store.ts";
+import type { WriteSessionEnvelope } from "../../core/brain/write-session/types.ts";
+import {
+ appendPinnedContext,
+ clearPinnedContext,
+ readPinnedContext,
+ writePinnedContext,
+ type PinnedContext,
+} from "../../core/brain/pinned.ts";
+import { INVALID_PARAMS, MCPError } from "../protocol.ts";
+import type { ServerContext, ToolDefinition } from "../tools.ts";
+import { coerceStr, coerceInt } from "../coerce.ts";
+import { vaultRelativeSafe } from "./shared.ts";
+
+/**
+ * One agent-facing surface for the write-session kernel: `op`
+ * discriminates the lifecycle operation, `kind` (open only) picks
+ * artifact vs panel. Envelopes are the same JSON the CLI prints -
+ * status, step, prompt, errors, attempts_left, expires_at, target.
+ * Structured request failures surface as INVALID_PARAMS with the
+ * machine-readable error list in the message.
+ */
+async function toolBrainWriteSession(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const op = coerceStr(args, "op", true)!;
+ const sessionId = coerceStr(args, "session_id", false);
+ const requireSessionId = (): string => {
+ if (!sessionId) {
+ throw new MCPError(INVALID_PARAMS, `brain_write_session: op '${op}' requires session_id`);
+ }
+ return sessionId;
+ };
+ try {
+ switch (op) {
+ case "open": {
+ const kind = coerceStr(args, "kind", false) ?? "artifact";
+ const agent =
+ normalizeAgentArgument(coerceStr(args, "agent", false) ?? null) ??
+ resolveAgentName(ctx.configPath ?? undefined);
+ const requireReview = args["require_review"] === true;
+ if (kind === "panel") {
+ const topic = coerceStr(args, "topic", true)!;
+ const personasRaw = args["personas"];
+ const personas = Array.isArray(personasRaw)
+ ? personasRaw.filter((x): x is string => typeof x === "string")
+ : undefined;
+ const target = coerceStr(args, "target", false);
+ return asRecord(
+ openPanelSession(ctx.vault, {
+ agent,
+ topic,
+ requireReview,
+ ...(personas && personas.length > 0 ? { personas } : {}),
+ ...(target ? { targetPath: target } : {}),
+ }),
+ );
+ }
+ if (kind !== "artifact") {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_write_session: kind must be 'artifact' or 'panel', got '${kind}'`,
+ );
+ }
+ const target = coerceStr(args, "target", true)!;
+ const intent = coerceStr(args, "intent", false) ?? "create";
+ if (intent !== "create" && intent !== "overwrite" && intent !== "merge") {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_write_session: intent must be create|overwrite|merge, got '${intent}'`,
+ );
+ }
+ const schemaType = coerceStr(args, "schema_type", false);
+ const prompt = coerceStr(args, "prompt", false);
+ const retryCap = args["retry_cap"];
+ return asRecord(
+ openArtifactSession(ctx.vault, {
+ agent,
+ targetPath: target,
+ intent,
+ requireReview,
+ ...(schemaType ? { schemaType } : {}),
+ ...(prompt ? { prompt } : {}),
+ ...(typeof retryCap === "number" ? { retryCap } : {}),
+ }),
+ );
+ }
+ case "submit": {
+ const id = requireSessionId();
+ const text = coerceStr(args, "text", true)!;
+ return asRecord(dispatchSubmit(ctx.vault, { sessionId: id, text }));
+ }
+ case "approve":
+ return asRecord(approveSession(ctx.vault, { sessionId: requireSessionId() }));
+ case "abandon":
+ return asRecord(abandonSession(ctx.vault, { sessionId: requireSessionId() }));
+ case "status": {
+ const id = requireSessionId();
+ const probe = readWriteSession(ctx.vault, id, new Date().toISOString());
+ if (probe.error !== null) throw new MCPError(INVALID_PARAMS, probe.error);
+ if (probe.session === null) {
+ throw new MCPError(INVALID_PARAMS, `unknown write-session: ${id}`);
+ }
+ return asRecord(sessionEnvelope(probe.session));
+ }
+ case "list": {
+ const limit = coerceInt(args, "limit", 100, 1, 500);
+ const sessions = listWriteSessions(ctx.vault, new Date().toISOString());
+ return {
+ total: sessions.length,
+ sessions: sessions.slice(0, limit).map((rec) => asRecord(sessionEnvelope(rec))),
+ };
+ }
+ default:
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_write_session: op must be open|submit|approve|abandon|status|list, got '${op}'`,
+ );
+ }
+ } catch (err) {
+ if (err instanceof WriteSessionRequestError) {
+ // Preserve the {code, path, message} boundary contract: the
+ // structured list rides MCPError's data slot, the message stays
+ // human-readable prose.
+ throw new MCPError(
+ INVALID_PARAMS,
+ err.message,
+ err.errors.length > 0 ? { errors: err.errors } : undefined,
+ );
+ }
+ throw err;
+ }
+}
+
+function asRecord(envelope: WriteSessionEnvelope): Record<string, unknown> {
+ return { ...envelope };
+}
+
+// ----- brain_context (v0.10.10) --------------------------------------------
+
+type PinnedContextOperation = "read" | "write" | "append" | "clear";
+
+function coercePinnedContextOperation(args: Record<string, unknown>): PinnedContextOperation {
+ const operation = coerceStr(args, "operation", false) ?? "read";
+ if (
+ operation !== "read" &&
+ operation !== "write" &&
+ operation !== "append" &&
+ operation !== "clear"
+ ) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_pinned_context operation must be one of: read, write, append, clear",
+ );
+ }
+ return operation;
+}
+
+function serializePinnedContext(
+ ctx: ServerContext,
+ pinned: PinnedContext,
+ operation?: PinnedContextOperation,
+): Record<string, unknown> {
+ return {
+ ...(operation ? { operation } : {}),
+ present: pinned.present,
+ path: vaultRelativeSafe(ctx.vault, pinned.path),
+ absolute_path: pinned.path,
+ content: pinned.content,
+ };
+}
+
+async function toolBrainPinnedContext(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const operation = coercePinnedContextOperation(args);
+ let pinned: PinnedContext;
+ if (operation === "read") {
+ pinned = readPinnedContext(ctx.vault);
+ } else if (operation === "write") {
+ pinned = writePinnedContext(ctx.vault, coerceStr(args, "content", true)!);
+ } else if (operation === "append") {
+ pinned = appendPinnedContext(ctx.vault, coerceStr(args, "content", true)!);
+ } else {
+ pinned = clearPinnedContext(ctx.vault);
+ }
+ return serializePinnedContext(ctx, pinned, operation);
+}
+
+function appendPinnedToContextContent(activeContent: string, pinnedContent: string): string {
+ if (pinnedContent.length === 0) return activeContent;
+ const pinnedBlock = `## Pinned context\n\n${pinnedContent}`;
+ const trimmedActive = activeContent.trimEnd();
+ if (trimmedActive.length === 0) return `${pinnedBlock}\n`;
+ return `${trimmedActive}\n\n${pinnedBlock}\n`;
+}
+
+type BrainContextCounts = RegenerateActiveResult["counts"];
+
+const EMPTY_CONTEXT_COUNTS: BrainContextCounts = {
+ confirmed: 0,
+ quarantine: 0,
+ retired_recent: 0,
+ most_applied_30d: 0,
+};
+
+/**
+ * Read-only pull-bootstrap of `Brain/active.md` + the active-preference
+ * counts. Built for runtimes that have no `SessionStart` hook (Cursor,
+ * Aider, raw Claude API): one tool call gives the agent the same
+ * shortcut card the SessionStart-aware runtimes get injected
+ * automatically.
+ *
+ * Behaviour matrix:
+ * - Brain/ absent → present:false, content:"", zero counts.
+ * - Brain/ present, active.md absent → call regenerateActive (idempotent)
+ * and read the regenerated file.
+ * - Brain/ present, active.md fresh → idempotent regenerate is a no-op
+ * rewrite; the on-disk body is
+ * returned verbatim.
+ */
+async function toolBrainContext(ctx: ServerContext): Promise<Record<string, unknown>> {
+ const dirs = brainDirs(ctx.vault);
+ const activePath = brainActivePath(ctx.vault);
+ const pinned = readPinnedContext(ctx.vault);
+ if (!existsSync(dirs.brain)) {
+ return {
+ vault_path: ctx.vault,
+ present: false,
+ active_path: activePath,
+ content: "",
+ counts: EMPTY_CONTEXT_COUNTS,
+ generated_at: null,
+ pinned: serializePinnedContext(ctx, pinned),
+ };
+ }
+
+ let counts: BrainContextCounts = EMPTY_CONTEXT_COUNTS;
+ let error: string | undefined;
+ try {
+ counts = regenerateActive(ctx.vault).counts;
+ } catch (err) {
+ error = (err as Error)?.message ?? String(err);
+ }
+
+ // After a successful regenerateActive, active.md is guaranteed to
+ // exist (the function either wrote it or confirmed an equal body
+ // already on disk). A read failure here is an unrelated filesystem
+ // race, not a missing-file branch — handle it in the same `error`
+ // slot the regenerate failure uses.
+ let content = "";
+ let generatedAt: string | null = null;
+ if (!error) {
+ try {
+ content = readFileSync(activePath, "utf8");
+ const [meta] = parseFrontmatter(activePath);
+ const v = meta["generated_at"];
+ if (typeof v === "string" && v.trim().length > 0) {
+ generatedAt = v;
+ }
+ } catch (err) {
+ error = (err as Error)?.message ?? String(err);
+ content = "";
+ generatedAt = null;
+ }
+ }
+ content = appendPinnedToContextContent(content, pinned.content);
+
+ // Optional vault-root instruction file (v0.10.17). Absent file =
+ // field omitted so hosts that strip unknown fields stay
+ // byte-identical. Read errors are silently swallowed - this is a
+ // best-effort enrichment, not a hard contract.
+ let vaultInstruction: ReturnType<typeof readVaultInstructionFile> = null;
+ try {
+ vaultInstruction = readVaultInstructionFile(ctx.vault);
+ } catch {
+ vaultInstruction = null;
+ }
+
+ return {
+ vault_path: ctx.vault,
+ present: true,
+ active_path: activePath,
+ content,
+ counts,
+ generated_at: generatedAt,
+ pinned: serializePinnedContext(ctx, pinned),
+ ...(error ? { error } : {}),
+ ...(vaultInstruction
+ ? {
+ vault_instruction: {
+ path: vaultInstruction.path,
+ content: vaultInstruction.content,
+ lines: vaultInstruction.lines,
+ },
+ }
+ : {}),
+ };
+}
+
+// ----- brain_digest --------------------------------------------------------
+
+const PINNED_CONTEXT_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {
+ type: "object",
+ required: ["present", "path", "absolute_path", "content"],
+ properties: {
+ operation: { type: "string", enum: ["read", "write", "append", "clear"] },
+ present: { type: "boolean" },
+ path: { type: "string" },
+ absolute_path: { type: "string" },
+ content: { type: "string" },
+ },
+ additionalProperties: false,
+};
+
+const BRAIN_CONTEXT_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {
+ type: "object",
+ required: ["vault_path", "present", "active_path", "content", "counts", "generated_at", "pinned"],
+ properties: {
+ vault_path: { type: "string" },
+ present: { type: "boolean" },
+ active_path: { type: "string" },
+ content: { type: "string" },
+ counts: {
+ type: "object",
+ required: ["confirmed", "quarantine", "retired_recent", "most_applied_30d"],
+ properties: {
+ confirmed: { type: "integer" },
+ quarantine: { type: "integer" },
+ retired_recent: { type: "integer" },
+ most_applied_30d: { type: "integer" },
+ },
+ additionalProperties: false,
+ },
+ generated_at: {},
+ pinned: PINNED_CONTEXT_OUTPUT_SCHEMA,
+ },
+};
+
+export const CONTEXT_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
+ {
+ name: "brain_write_session",
+ description:
+ "Provider-agnostic Brain write sessions (artifact and decision-panel kinds): open returns a generation prompt, submit validates the text, only clean artifacts commit. Correction loop, retry cap, collision guard, optional operator review. The calling agent generates; the Brain never does.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ op: {
+ type: "string",
+ enum: ["open", "submit", "approve", "abandon", "status", "list"],
+ description: "Lifecycle operation.",
+ },
+ kind: {
+ type: "string",
+ enum: ["artifact", "panel"],
+ description: "Session kind for op=open. Defaults to artifact.",
+ },
+ session_id: {
+ type: "string",
+ description: "Session id (`ws-...`) for submit/approve/abandon/status.",
+ },
+ target: {
+ type: "string",
+ description:
+ "Vault-relative commit target under Brain/ (artifact open; optional panel override). Reserved namespaces are refused.",
+ },
+ text: {
+ type: "string",
+ description:
+ "Generated text for op=submit: the full artifact, a persona answer, or the synthesis.",
+ },
+ topic: { type: "string", description: "Decision topic (panel open)." },
+ personas: {
+ type: "array",
+ items: { type: "string" },
+ description:
+ "Persona slugs to convene in order (panel open). Defaults to every loaded persona.",
+ },
+ schema_type: {
+ type: "string",
+ description: "Schema-pack page type the artifact must declare (artifact open).",
+ },
+ intent: {
+ type: "string",
+ enum: ["create", "overwrite", "merge"],
+ description:
+ "Commit intent against an existing target (artifact open). Default create - never overwrites.",
+ },
+ prompt: { type: "string", description: "Custom generation instruction (artifact open)." },
+ require_review: {
+ type: "boolean",
+ description: "Park the validated artifact at needs-review until an operator approves.",
+ },
+ retry_cap: { type: "number", description: "Failed submits allowed per step (default 3)." },
+ limit: {
+ type: "number",
+ description: "Max sessions returned by op=list (default 100, cap 500).",
+ },
+ agent: { type: "string", description: "Agent identity override (open)." },
+ },
+ required: ["op"],
+ additionalProperties: false,
+ },
+ handler: toolBrainWriteSession,
+ },
+ {
+ name: "brain_pinned_context",
+ description:
+ "Read, write, append, or clear the transient current-task scratchpad at `Brain/pinned.md`. Use for facts that should survive context rotation but should not become permanent preferences.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["read", "write", "append", "clear"],
+ description: "Operation to perform. Defaults to read.",
+ },
+ content: {
+ type: "string",
+ description: "Pinned context body for write/append operations.",
+ },
+ },
+ additionalProperties: false,
+ },
+ outputSchema: PINNED_CONTEXT_OUTPUT_SCHEMA,
+ handler: toolBrainPinnedContext,
+ },
+ {
+ name: "brain_context",
+ description:
+ "Pull the current Brain/active.md body, pinned current-task context, and active-preference counts. Use at session start when SessionStart hook is unavailable (Cursor, Aider, raw Claude API). Read-only.",
+ inputSchema: {
+ type: "object",
+ properties: {},
+ additionalProperties: false,
+ },
+ outputSchema: BRAIN_CONTEXT_OUTPUT_SCHEMA,
+ handler: toolBrainContext,
+ },
+]);
diff --git a/src/mcp/brain/entity-tools.ts b/src/mcp/brain/entity-tools.ts
new file mode 100644
index 00000000..c66c10d7
--- /dev/null
+++ b/src/mcp/brain/entity-tools.ts
@@ -0,0 +1,163 @@
+/**
+ * Canonical entity registry lookups and vault profile switching.
+ *
+ * Extracted from the former brain-tools.ts monolith; registration
+ * happens through the aggregator, which preserves the public
+ * BRAIN_TOOLS surface.
+ */
+
+import {
+ EntityAmbiguityError,
+ getEntity,
+ listEntities,
+} from "../../core/brain/entities/registry.ts";
+import { validateEntityCategory } from "../../core/brain/entities/canonical.ts";
+import { switchProfile, listProfiles } from "../../core/brain/portability/profiles.ts";
+import { defaultConfigPath } from "../../core/config.ts";
+import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";
+import type { ServerContext, ToolDefinition } from "../tools.ts";
+import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
+import { coerceStr } from "../coerce.ts";
+
+/** Serialize one entity for the MCP payload (no absolute paths). */
+function entityToPayload(
+ entity: import("../../core/brain/entities/types.ts").BrainEntity,
+): Record<string, unknown> {
+ return {
+ id: entity.id,
+ category: entity.category,
+ name: entity.name,
+ aliases: [...entity.aliases],
+ status: entity.status,
+ ...(entity.source_agent !== undefined ? { source_agent: entity.source_agent } : {}),
+ ...(entity.confidence !== undefined ? { confidence: entity.confidence } : {}),
+ created_at: entity.created_at,
+ updated_at: entity.updated_at,
+ ...(entity.archived_at !== undefined ? { archived_at: entity.archived_at } : {}),
+ relations: entity.relations.map((r) => ({ relation: r.relation, target: r.target })),
+ body: entity.body,
+ };
+}
+
+async function toolBrainEntity(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ // Argument validation happens at the boundary so INVALID_PARAMS is
+ // reserved for genuine client-input errors; unexpected registry
+ // failures (malformed entity file, I/O) surface as INTERNAL_ERROR.
+ const view = coerceStr(args, "view", true)!;
+ if (view !== "get" && view !== "list") {
+ throw new MCPError(INVALID_PARAMS, `brain_entity: unknown view '${view}' (get | list)`);
+ }
+ const category = coerceStr(args, "category", false);
+ if (category !== null) {
+ try {
+ validateEntityCategory(category);
+ } catch (err) {
+ throw new MCPError(INVALID_PARAMS, `brain_entity: ${(err as Error).message}`);
+ }
+ }
+ const status = coerceStr(args, "status", false);
+ if (status !== null && status !== "active" && status !== "archived") {
+ throw new MCPError(INVALID_PARAMS, "brain_entity: status must be 'active' or 'archived'");
+ }
+ const query = view === "get" ? coerceStr(args, "query", true)! : null;
+
+ try {
+ if (view === "get") {
+ const entity = getEntity(ctx.vault, {
+ query: query!,
+ ...(category !== null ? { category } : {}),
+ });
+ if (entity === null) return { found: false, query: query! };
+ return { found: true, ...entityToPayload(entity) };
+ }
+ const entities = listEntities(ctx.vault, {
+ ...(category !== null ? { category } : {}),
+ ...(status !== null ? { status } : {}),
+ });
+ return { entities: entities.map(entityToPayload), total: entities.length };
+ } catch (err) {
+ if (err instanceof MCPError) throw err;
+ if (err instanceof EntityAmbiguityError) {
+ // A category-less query hitting several categories is a
+ // client-resolvable input problem, not a server fault.
+ throw new MCPError(INVALID_PARAMS, `brain_entity: ${err.message}`);
+ }
+ throw new MCPError(INTERNAL_ERROR, `brain_entity: ${(err as Error).message}`);
+ }
+}
+
+async function toolBrainSwitchVault(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const name = coerceStr(args, "name", true)!;
+ const configPath = ctx.configPath ?? defaultConfigPath();
+ try {
+ switchProfile(configPath, name);
+ } catch (err) {
+ throw new Error(`brain_switch_vault: ${(err as Error).message ?? String(err)}`, {
+ cause: err,
+ });
+ }
+ // The running server keeps its already-resolved vault; the switch
+ // takes effect for the next server launch / CLI invocation.
+ return {
+ active: name,
+ profiles: listProfiles(configPath).profiles,
+ note: "active profile updated; takes effect on next server launch",
+ };
+}
+
+// ----- brain_doctor --------------------------------------------------------
+
+export const ENTITY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
+ {
+ name: "brain_entity",
+ previewBudget: MCP_PREVIEW_BUDGET,
+ description:
+ "Look up (view: get) or list (view: list) canonical entities from the Brain/entities/ registry. Aliases resolve to the canonical record. Read-only; writes go through the o2b CLI.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ view: {
+ type: "string",
+ enum: ["get", "list"],
+ description: "get: resolve one entity by name or alias. list: enumerate the registry.",
+ },
+ query: {
+ type: "string",
+ description: "Name or alias to resolve (required for view: get).",
+ },
+ category: {
+ type: "string",
+ description: "Optional category filter (slug, e.g. `people`).",
+ },
+ status: {
+ type: "string",
+ enum: ["active", "archived"],
+ description: "Optional status filter for view: list.",
+ },
+ },
+ required: ["view"],
+ additionalProperties: false,
+ },
+ handler: toolBrainEntity,
+ },
+ {
+ name: "brain_switch_vault",
+ description:
+ "Activate a named vault profile (from the profiles registry). Updates the active pointer; the change takes effect on the next server launch - the running server keeps its already-resolved vault.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ name: { type: "string", description: "Profile name to activate." },
+ },
+ required: ["name"],
+ additionalProperties: false,
+ },
+ handler: toolBrainSwitchVault,
+ },
+]);
diff --git a/src/mcp/brain/feedback-tools.ts b/src/mcp/brain/feedback-tools.ts
new file mode 100644
index 00000000..29f37aec
--- /dev/null
+++ b/src/mcp/brain/feedback-tools.ts
@@ -0,0 +1,585 @@
+/**
+ * Brain write surface: taste signals, the dream learning pass, apply-evidence records, and narrative notes.
+ *
+ * Extracted from the former brain-tools.ts monolith; registration
+ * happens through the aggregator, which preserves the public
+ * BRAIN_TOOLS surface.
+ */
+
+import { resolve } from "node:path";
+import { resolveAgentName } from "../../core/config.ts";
+import {
+ appendApplyEvidence,
+ BrainPreferenceNotFoundError,
+ type AppendApplyEvidenceInput,
+} from "../../core/brain/apply-evidence.ts";
+import { dream } from "../../core/brain/dream.ts";
+import {
+ applyDreamBundle,
+ discardDreamBundle,
+ listDreamBundles,
+ stageDream,
+ validateDreamBundle,
+} from "../../core/brain/dream-stage.ts";
+import { BRAIN_ROLES } from "../../core/brain/trust/role.ts";
+import { writeSignal } from "../../core/brain/signal.ts";
+import { writePreference } from "../../core/brain/preference.ts";
+import { validateBrainFeedbackInput } from "../../core/brain/sessions/validate-feedback.ts";
+import { isoDate, isoSecond } from "../../core/brain/time.ts";
+import { slugify } from "../../core/vault.ts";
+import { normalizeAgentArgument } from "../../core/agent-identity.ts";
+import {
+ BRAIN_LOG_EVENT_KIND,
+ BRAIN_PREFERENCE_STATUS,
+ BRAIN_APPLY_RESULT,
+ type BrainApplyResult,
+ type BrainSignalSign,
+} from "../../core/brain/types.ts";
+import { appendLogEvent } from "../../core/brain/log.ts";
+import { appendBrainNote } from "../../core/brain/note.ts";
+import { mirrorSignal, resolveSharedNamespace } from "../../core/brain/shared-namespace.ts";
+import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";
+import type { ServerContext, ToolDefinition } from "../tools.ts";
+import { coerceStr, coerceBool, coerceIsoDate } from "../coerce.ts";
+import { vaultRelativeSafe } from "./shared.ts";
+
+/**
+ * Build the slug used in the signal / preference filename. We never let
+ * the agent decide the slug directly — taking `topic` as the slug stem
+ * is what the design doc §9.2 prescribes (slugs are deterministic from
+ * topic). The slug is run through `slugify` defensively so a slightly
+ * mis-shaped topic still yields a filesystem-safe basename.
+ */
+function deriveSlug(topic: string): string {
+ return slugify(topic);
+}
+
+async function toolBrainFeedback(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ // Single source of truth for the brain_feedback payload contract —
+ // session-replay (sessions/import.ts) and the MCP live path now go
+ // through the same validator so rule shape cannot drift between the
+ // two surfaces.
+ const validated = validateBrainFeedbackInput(args);
+ if (!validated.ok) {
+ throw new MCPError(INVALID_PARAMS, validated.reason);
+ }
+ const {
+ topic,
+ signal: signalRaw,
+ principle,
+ scope,
+ raw,
+ source,
+ force_confirmed,
+ } = validated.value;
+ const forceConfirmed = force_confirmed ?? false;
+
+ // Agent-fallback stays MCP-side: validator just hands back the user-
+ // supplied value (or undefined); the live path resolves via config
+ // when absent.
+ const agent =
+ normalizeAgentArgument(validated.value.agent ?? null) ??
+ resolveAgentName(ctx.configPath ?? undefined);
+ const now = new Date();
+ const date = isoDate(now);
+ const createdAt = isoSecond(now);
+ const slug = deriveSlug(topic);
+
+ // 1. Always write the signal to inbox/. Mirrors the CLI handler so the
+ // audit trail in `Brain/log/` and `inbox/processed/` stays consistent
+ // across CLI and MCP entry points. `--force-confirmed` ADDITIONALLY
+ // creates a confirmed pref below.
+ const signalInput = {
+ topic,
+ signal: signalRaw as BrainSignalSign,
+ agent,
+ principle,
+ created_at: createdAt,
+ date,
+ slug,
+ ...(scope ? { scope } : {}),
+ ...(source && source.length > 0 ? { source: [...source] } : {}),
+ ...(raw ? { raw } : {}),
+ };
+ const sigResult = writeSignal(ctx.vault, signalInput);
+ // t_936a1a61: fail-soft mirror into the shared namespace AFTER the
+ // primary write; `mirror` is reported only when the key is configured.
+ const sharedNamespace = resolveSharedNamespace(ctx.configPath);
+ const mirror =
+ sharedNamespace === null ? undefined : mirrorSignal(sharedNamespace, ctx.vault, signalInput);
+
+ try {
+ appendLogEvent(ctx.vault, {
+ timestamp: createdAt,
+ eventType: BRAIN_LOG_EVENT_KIND.feedback,
+ body: {
+ signal: `[[${sigResult.id}]]`,
+ topic: topic.trim(),
+ sign: signalRaw,
+ agent,
+ },
+ });
+ } catch (err) {
+ process.stderr.write(`warning: append feedback log failed: ${(err as Error).message}\n`);
+ }
+
+ let prefResult: { path: string; id: string } | null = null;
+ if (forceConfirmed) {
+ // Escape hatch: skip the dream pass and create the confirmed rule now.
+ // `confirmed_at` is now; `unconfirmed_until` is also now so the trial
+ // window collapses on inspection. The just-written signal is recorded
+ // as the rule's origin under `evidenced_by`.
+ prefResult = writePreference(ctx.vault, {
+ slug,
+ topic: topic.trim(),
+ principle: principle.trim(),
+ created_at: createdAt,
+ unconfirmed_until: createdAt,
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ evidenced_by: [`[[${sigResult.id}]]`],
+ confirmed_at: createdAt,
+ ...(scope ? { scope } : {}),
+ });
+ try {
+ // Offset by 1s so the force-confirmed event sorts after the feedback
+ // event on the same UTC second (parseLogDay is stable on ties, but a
+ // visible chronology reads cleaner).
+ appendLogEvent(ctx.vault, {
+ timestamp: isoSecond(new Date(now.getTime() + 1000)),
+ eventType: BRAIN_LOG_EVENT_KIND.forceConfirmed,
+ body: {
+ preference: `[[${prefResult.id}]]`,
+ agent,
+ },
+ });
+ } catch (err) {
+ process.stderr.write(
+ `warning: append force-confirmed log failed: ${(err as Error).message}\n`,
+ );
+ }
+ }
+
+ return {
+ kind: prefResult ? "preference" : "signal",
+ ...(mirror !== undefined ? { mirror } : {}),
+ signal_path: vaultRelativeSafe(ctx.vault, sigResult.path),
+ signal_absolute_path: resolve(sigResult.path),
+ signal_id: sigResult.id,
+ ...(prefResult
+ ? {
+ preference_path: vaultRelativeSafe(ctx.vault, prefResult.path),
+ preference_absolute_path: resolve(prefResult.path),
+ preference_id: prefResult.id,
+ // Back-compat: top-level `path`/`id` previously pointed at the
+ // pref on the force-confirmed branch. Keep them aligned for
+ // callers that look at the bare fields.
+ path: vaultRelativeSafe(ctx.vault, prefResult.path),
+ absolute_path: resolve(prefResult.path),
+ id: prefResult.id,
+ }
+ : {
+ path: vaultRelativeSafe(ctx.vault, sigResult.path),
+ absolute_path: resolve(sigResult.path),
+ id: sigResult.id,
+ }),
+ agent,
+ };
+}
+
+// ----- brain_dream ---------------------------------------------------------
+
+async function toolBrainDream(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const action = args["action"] ?? "run";
+ if (
+ action !== "run" &&
+ action !== "stage" &&
+ action !== "validate" &&
+ action !== "apply" &&
+ action !== "discard" &&
+ action !== "list"
+ ) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_dream: action must be run|stage|validate|apply|discard|list",
+ );
+ }
+ const dryRun = coerceBool(args, "dry_run");
+ const nowDate = coerceIsoDate(args, "now");
+ const agentArg = coerceStr(args, "agent", false);
+ const agent = normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);
+
+ if (action !== "run") {
+ // Staged lifecycle (t_ae8a8ec0): stage -> validate -> apply over a
+ // persisted bundle; dream() stays the only promotion engine.
+ const runIdArg = coerceStr(args, "run_id", false);
+ if ((action === "validate" || action === "apply" || action === "discard") && !runIdArg) {
+ throw new MCPError(INVALID_PARAMS, `brain_dream action=${action}: run_id is required`);
+ }
+ const now = nowDate ?? new Date();
+ const stageOpts = { now, ...(agent ? { agentName: agent } : {}) };
+ switch (action) {
+ case "stage": {
+ const bundle = stageDream(ctx.vault, stageOpts);
+ return {
+ action,
+ run_id: bundle.runId,
+ plan: bundle.plan,
+ sources: bundle.sources.length,
+ dir: `Brain/dream/staged/${bundle.runId}`,
+ };
+ }
+ case "validate": {
+ const verdict = validateDreamBundle(ctx.vault, runIdArg!, stageOpts);
+ return { action, run_id: runIdArg, valid: verdict.valid, drift: [...verdict.drift] };
+ }
+ case "apply": {
+ const outcome = applyDreamBundle(ctx.vault, runIdArg!, stageOpts);
+ return {
+ action,
+ run_id: runIdArg,
+ applied: outcome.applied,
+ drift: [...outcome.validation.drift],
+ ...(outcome.summary !== undefined
+ ? {
+ changed: outcome.summary.changed,
+ new_unconfirmed: [...outcome.summary.new_unconfirmed],
+ confirmed: [...outcome.summary.confirmed],
+ retired: outcome.summary.retired.map((r) => ({ id: r.id, reason: r.reason })),
+ }
+ : {}),
+ };
+ }
+ case "discard": {
+ return { action, run_id: runIdArg, removed: discardDreamBundle(ctx.vault, runIdArg!) };
+ }
+ default: {
+ return {
+ action,
+ bundles: listDreamBundles(ctx.vault).map((b) => ({
+ run_id: b.runId,
+ status: b.status,
+ staged_at: b.stagedAt,
+ proposals: b.proposals,
+ sources: b.sources,
+ })),
+ };
+ }
+ }
+ }
+
+ const summary = dream(ctx.vault, {
+ dryRun,
+ ...(nowDate ? { now: nowDate } : {}),
+ ...(agent ? { agentName: agent } : {}),
+ });
+
+ // The summary is already a Plain Old Frozen Object — JSON-serialise
+ // verbatim. We surface `snapshot_path` / `log_path` as vault-relative
+ // for caller convenience while preserving the absolute path as well.
+ return {
+ run_id: summary.run_id,
+ changed: summary.changed,
+ dry_run: dryRun,
+ new_unconfirmed: [...summary.new_unconfirmed],
+ confirmed: [...summary.confirmed],
+ retired: summary.retired.map((r) => ({ id: r.id, reason: r.reason })),
+ contradictions: [...summary.contradictions],
+ moved_to_processed: [...summary.moved_to_processed],
+ suppressed: [...summary.suppressed],
+ warnings: summary.warnings.map((w) => ({
+ code: w.code,
+ message: w.message,
+ })),
+ uncertain: summary.uncertain.map((u) => ({
+ code: u.code,
+ ...(u.topic !== undefined ? { topic: u.topic } : {}),
+ message: u.message,
+ })),
+ quarantined: summary.quarantined.map((q) => ({
+ topic: q.topic,
+ signal_count: q.signal_count,
+ distinct_agents: q.distinct_agents,
+ age_days: q.age_days,
+ failed_gates: [...q.failed_gates],
+ })),
+ snapshot_path: summary.snapshot_path
+ ? vaultRelativeSafe(ctx.vault, summary.snapshot_path)
+ : null,
+ log_path: summary.log_path ? vaultRelativeSafe(ctx.vault, summary.log_path) : null,
+ };
+}
+
+// ----- brain_review_candidates --------------------------------------------
+
+async function toolBrainApplyEvidence(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const prefId = coerceStr(args, "pref_id", true)!;
+ const artifact = coerceStr(args, "artifact", true)!;
+ const resultRaw = coerceStr(args, "result", true)!;
+ if (
+ resultRaw !== BRAIN_APPLY_RESULT.applied &&
+ resultRaw !== BRAIN_APPLY_RESULT.violated &&
+ resultRaw !== BRAIN_APPLY_RESULT.outdated
+ ) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `argument 'result' must be 'applied', 'violated', or 'outdated'`,
+ );
+ }
+ const agentArg = coerceStr(args, "agent", false);
+ const note = coerceStr(args, "note", false);
+ const outcomeRaw = coerceStr(args, "outcome", false);
+ if (
+ outcomeRaw !== null &&
+ outcomeRaw !== "success" &&
+ outcomeRaw !== "failure" &&
+ outcomeRaw !== "unknown"
+ ) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `argument 'outcome' must be 'success', 'failure', or 'unknown'`,
+ );
+ }
+
+ const agent = normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);
+
+ const input: AppendApplyEvidenceInput = {
+ pref_id: prefId,
+ artifact,
+ result: resultRaw as BrainApplyResult,
+ agent,
+ ...(outcomeRaw !== null ? { outcome: outcomeRaw } : {}),
+ ...(note ? { note } : {}),
+ };
+
+ // Surface BrainPreferenceNotFoundError as a tool-level error envelope
+ // (isError: true) rather than an MCP protocol error. The design doc
+ // says "not an error condition" — the agent should see an informative
+ // payload that explains what to do next, not a JSON-RPC error frame.
+ // v0.10.16: assert applier role at the MCP boundary so the structural
+ // permission gate fires before any I/O.
+ try {
+ const res = appendApplyEvidence(ctx.vault, input, {
+ role: BRAIN_ROLES.applier,
+ });
+ return {
+ logged_at: res.logged_at,
+ log_path: vaultRelativeSafe(ctx.vault, res.log_path),
+ absolute_log_path: resolve(res.log_path),
+ agent,
+ };
+ } catch (exc) {
+ if (exc instanceof BrainPreferenceNotFoundError) {
+ // Re-throw as a non-MCPError so `server.handleToolsCall` packs it
+ // into a `toolError` envelope (isError: true, single-text content).
+ throw new Error(exc.message, { cause: exc });
+ }
+ throw exc;
+ }
+}
+
+// ----- brain_note (§32B, v0.10.8) ------------------------------------------
+
+/**
+ * Append one narrative-milestone line to today's Brain log. Agents
+ * record release / merged-PR / discovered-fact lines under the `note`
+ * event kind in `Brain/log/<today>.md` (and the JSONL sidecar).
+ *
+ * The body lives in `appendBrainNote` so the CLI verb (`o2b brain
+ * note`) and this MCP handler share one code path. Validation errors
+ * land in MCP's `INVALID_PARAMS` envelope here; the CLI wrapper
+ * pre-validates usage shape and surfaces the same condition as exit 2.
+ */
+async function toolBrainNote(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const rawText = coerceStr(args, "text", true)!;
+ const agentArg = coerceStr(args, "agent", false);
+
+ let res;
+ try {
+ res = appendBrainNote({
+ vault: ctx.vault,
+ text: rawText,
+ ...(agentArg ? { agent: agentArg } : {}),
+ ...(ctx.configPath ? { configPath: ctx.configPath } : {}),
+ });
+ } catch (err) {
+ // `appendBrainNote` throws one validation error ("text is required");
+ // any other failure is an I/O / filesystem fault from `appendLogEvent`
+ // and must not be reported as a client-side INVALID_PARAMS.
+ const message = (err as Error).message ?? String(err);
+ const code = message.startsWith("brain_note:") ? INVALID_PARAMS : INTERNAL_ERROR;
+ throw new MCPError(code, message);
+ }
+ return {
+ logged_at: res.logged_at,
+ log_path: res.log_path,
+ absolute_log_path: res.absolute_log_path,
+ agent: res.agent,
+ };
+}
+
+// ----- brain_write_session (Agent Write Contract Suite, v0.41.0) ------------
+
+export const FEEDBACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
+ {
+ name: "brain_feedback",
+ description:
+ "Record one Brain taste signal in `Brain/inbox/sig-*.md`. With `force_confirmed: true`, create the preference directly (skips the dream trial window).",
+ inputSchema: {
+ type: "object",
+ properties: {
+ topic: {
+ type: "string",
+ description: "Stable kebab-slug for the rule, e.g. `no-internal-abbrev`.",
+ },
+ signal: {
+ type: "string",
+ enum: ["positive", "negative"],
+ description:
+ "`positive` when the principle is the rule to follow, `negative` when it's what to avoid.",
+ },
+ principle: {
+ type: "string",
+ description: "One-line, agent-readable formulation of the rule (imperative voice).",
+ },
+ scope: {
+ type: "string",
+ description:
+ "Optional soft category for later application-scope matching, e.g. `writing`, `coding`.",
+ },
+ source: {
+ type: "array",
+ items: { type: "string" },
+ description: "Optional wikilinks to the artifacts or notes that triggered the signal.",
+ },
+ agent: {
+ type: "string",
+ description: "Optional agent identity override; defaults to the server-resolved name.",
+ },
+ raw: {
+ type: "string",
+ description: "Optional free-form raw quote (rendered under `## Raw` in the signal file).",
+ },
+ force_confirmed: {
+ type: "boolean",
+ description:
+ "When true, also creates an immediately-active confirmed `pref-*` alongside the inbox signal, skipping the dream-pass promotion step.",
+ },
+ },
+ required: ["topic", "signal", "principle"],
+ additionalProperties: false,
+ },
+ handler: toolBrainFeedback,
+ },
+ {
+ name: "brain_dream",
+ description:
+ "Deterministic learning pass over `Brain/inbox/`. action=run (default) promotes inline; the staged lifecycle persists a reviewable bundle: stage -> validate -> apply (or discard), plus list. Typically scheduled via cron.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ action: {
+ type: "string",
+ enum: ["run", "stage", "validate", "apply", "discard", "list"],
+ description:
+ "run executes inline; stage persists a proposal bundle; validate/apply/discard manage one bundle by run_id; list shows bundles.",
+ },
+ run_id: {
+ type: "string",
+ description: "Bundle id for validate/apply/discard (from action=stage or list).",
+ },
+ dry_run: {
+ type: "boolean",
+ description: "action=run only: compute the plan without writing any files.",
+ },
+ now: {
+ type: "string",
+ description:
+ "Optional ISO-8601 timestamp used as the wall clock for the run (testing / replay).",
+ },
+ agent: {
+ type: "string",
+ description:
+ "Optional caller identity; a mismatch with the configured primary agent emits a warning. Defaults to the server-resolved name.",
+ },
+ },
+ additionalProperties: false,
+ },
+ handler: toolBrainDream,
+ },
+ {
+ name: "brain_apply_evidence",
+ description:
+ "Record whether an active preference was applied, violated, or marked outdated against a freshly-produced durable artifact. Appends one event to `Brain/log/<today>.md`. A single `outdated` event triggers retire on the next dream pass.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ pref_id: {
+ type: "string",
+ description: "Preference id (`pref-<slug>` or bare `<slug>`).",
+ },
+ artifact: {
+ type: "string",
+ description:
+ "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, `violated` if broken, `outdated` if the artifact shows the rule itself is obsolete.",
+ },
+ agent: {
+ type: "string",
+ description: "Optional agent identity override; defaults to the server-resolved name.",
+ },
+ outcome: {
+ type: "string",
+ enum: ["success", "failure", "unknown"],
+ description:
+ "Optional downstream outcome of the artifact (t_d478df53): did the work the rule was applied to actually succeed? `unknown` is treated like an absent outcome.",
+ },
+ note: {
+ type: "string",
+ description: "Optional one-line context.",
+ },
+ },
+ required: ["pref_id", "artifact", "result"],
+ additionalProperties: false,
+ },
+ handler: toolBrainApplyEvidence,
+ },
+ {
+ name: "brain_note",
+ description:
+ "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: {
+ text: {
+ type: "string",
+ description:
+ "One-line narrative description. Newlines collapse to single spaces; the shared redactor strips secret-shaped tokens.",
+ },
+ agent: {
+ type: "string",
+ description: "Optional agent identity override; defaults to the server-resolved name.",
+ },
+ },
+ required: ["text"],
+ additionalProperties: false,
+ },
+ handler: toolBrainNote,
+ },
+]);
diff --git a/src/mcp/brain/health-tools.ts b/src/mcp/brain/health-tools.ts
new file mode 100644
index 00000000..d5baf40e
--- /dev/null
+++ b/src/mcp/brain/health-tools.ts
@@ -0,0 +1,151 @@
+/**
+ * Diagnostics: Brain invariant checks and the semantic-health report.
+ *
+ * Extracted from the former brain-tools.ts monolith; registration
+ * happens through the aggregator, which preserves the public
+ * BRAIN_TOOLS surface.
+ */
+
+import { resolveSearchConfig } from "../../core/search/index.ts";
+import { collectMaintenanceActions } from "../../core/brain/maintenance/collect.ts";
+import { runDoctor } from "../../core/brain/doctor.ts";
+import type { ServerContext, ToolDefinition } from "../tools.ts";
+import { coerceBool, coerceFormat } from "../coerce.ts";
+import { vaultRelativeSafe } from "./shared.ts";
+
+async function toolBrainDoctor(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const strict = coerceBool(args, "strict");
+ const format = coerceFormat(args);
+
+ const result = runDoctor(ctx.vault, {
+ strict,
+ dbPath: resolveSearchConfig({ vault: ctx.vault, configPath: ctx.configPath ?? undefined })
+ .dbPath,
+ });
+
+ // Decide a single ok flag — `strict` only changes the CLI exit code,
+ // so we mirror that semantic here: with `strict`, warnings demote ok
+ // to false. Errors always do.
+ const ok = result.errors.length === 0 && (!strict || result.warnings.length === 0);
+
+ return {
+ format,
+ ok,
+ strict,
+ errors: result.errors.map((i) => ({
+ severity: i.severity,
+ code: i.code,
+ message: i.message,
+ ...(i.path !== undefined ? { path: vaultRelativeSafe(ctx.vault, i.path) } : {}),
+ })),
+ warnings: result.warnings.map((i) => ({
+ severity: i.severity,
+ code: i.code,
+ message: i.message,
+ ...(i.path !== undefined ? { path: vaultRelativeSafe(ctx.vault, i.path) } : {}),
+ })),
+ // v0.10.15: ranked maintenance actions surfaced as a parallel
+ // signal to errors/warnings. The list is independent of `strict`
+ // because nothing here downgrades the `ok` flag - actions are
+ // suggestions, not invariant violations.
+ suggested_actions: collectMaintenanceActions(ctx.vault).map((a) => ({
+ id: a.id,
+ category: a.category,
+ title: a.title,
+ impact: a.impact,
+ ...(a.target !== undefined ? { target: a.target } : {}),
+ })),
+ // v0.10.16: trust-layer fields. `trust_verdict` is always populated
+ // by runDoctor; `verification_delta_summary` only when the caller
+ // threads a dream summary through (not exposed via this tool's
+ // surface, so it stays absent here). `instruction_file_warnings`
+ // surfaces vault-root instruction files exceeding the configured
+ // ceiling.
+ ...(result.trust_verdict !== undefined ? { trust_verdict: result.trust_verdict } : {}),
+ instruction_file_warnings: (result.instruction_file_warnings ?? []).map((w) => ({
+ path: w.path,
+ lines: w.lines,
+ ceiling: w.ceiling,
+ })),
+ };
+}
+
+// ----- brain_health --------------------------------------------------------
+
+async function toolBrainHealth(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const format = coerceFormat(args);
+ const result = runDoctor(ctx.vault);
+ const sh = result.semantic_health;
+ return {
+ format,
+ verdict: sh?.verdict ?? "clean",
+ contradictions: (sh?.contradictions ?? []).map((c) => ({
+ a: c.aId,
+ b: c.bId,
+ ...(c.scope !== null ? { scope: c.scope } : {}),
+ jaccard: c.jaccard,
+ a_sign: c.aSign,
+ b_sign: c.bSign,
+ })),
+ concept_gaps: (sh?.conceptGaps ?? []).map((g) => ({
+ term: g.term,
+ frequency: g.frequency,
+ })),
+ stale_claims: (sh?.staleClaims ?? []).map((s) => ({
+ id: s.id,
+ last_evidence_at: s.lastEvidenceAt,
+ age_days: s.ageDays,
+ })),
+ };
+}
+
+// ----- Serializers ---------------------------------------------------------
+
+export const HEALTH_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
+ {
+ name: "brain_doctor",
+ description:
+ "Validate `Brain/` invariants: status-vs-folder consistency, frontmatter validity, duplicate ids, ISO parsing, log header parsing. Read-only.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ strict: {
+ type: "boolean",
+ description: "When true, warnings demote `ok` to false (CLI exit-code parity).",
+ },
+ format: {
+ type: "string",
+ enum: ["markdown", "json"],
+ description:
+ "Output format hint. Structured result is identical; caller decides rendering.",
+ },
+ },
+ additionalProperties: false,
+ },
+ handler: toolBrainDoctor,
+ },
+ {
+ name: "brain_health",
+ description:
+ "Semantic-health report: contradictory confirmed preferences (opposite sign of record, same subject), recurring concepts with no dedicated preference, and confirmed preferences running on stale evidence. Returns the per-domain findings plus a clean/watch/investigate verdict. Read-only.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ format: {
+ type: "string",
+ enum: ["markdown", "json"],
+ description:
+ "Output format hint. Structured result is identical; caller decides rendering.",
+ },
+ },
+ additionalProperties: false,
+ },
+ handler: toolBrainHealth,
+ },
+]);
diff --git a/src/mcp/brain/knowledge-tools.ts b/src/mcp/brain/knowledge-tools.ts
new file mode 100644
index 00000000..fc9d7191
--- /dev/null
+++ b/src/mcp/brain/knowledge-tools.ts
@@ -0,0 +1,699 @@
+/**
+ * Knowledge graph: foresight, bridge discovery, community clusters, MOC audit, deep synthesis, idea discovery, the claim ledger, and dead ends.
+ *
+ * Extracted from the former brain-tools.ts monolith; registration
+ * happens through the aggregator, which preserves the public
+ * BRAIN_TOOLS surface.
+ */
+
+import { join } from "node:path";
+import { existsSync, readdirSync } from "node:fs";
+import { resolveAgentName, resolveTriggerCooldownDays } from "../../core/config.ts";
+import { resolveSearchConfig } from "../../core/search/index.ts";
+import { Store } from "../../core/search/store.ts";
+import { loadSchemaPack } from "../../core/brain/schema-pack.ts";
+import {
+ acceptBridge,
+ bridgePairKey,
+ discoverBridges,
+ dismissBridge,
+ readDismissedBridges,
+ writeBridgeProposals,
+} from "../../core/brain/link-graph/bridge-discovery.ts";
+import {
+ detectCommunities,
+ materializeClusterNotes,
+} from "../../core/brain/link-graph/communities.ts";
+import { appendMetric } from "../../core/brain/metrics.ts";
+import { parseFrontmatter } from "../../core/vault.ts";
+import { createTriggers } from "../../core/brain/triggers/store.ts";
+import { deepSynthesis, synthesisCandidates } from "../../core/brain/deep-synthesis.ts";
+import { discoverIdeas, ideaCandidates } from "../../core/brain/idea-discovery.ts";
+import { auditMoc, MocAuditError } from "../../core/brain/link-graph/moc-audit.ts";
+import { normaliseWikilinkTarget } from "../../core/brain/wikilink.ts";
+import { isoSecond } from "../../core/brain/time.ts";
+import { normalizeAgentArgument } from "../../core/agent-identity.ts";
+import { normalizeEntityName } from "../../core/brain/entities/canonical.ts";
+import { listDeadEnds, recordDeadEnd } from "../../core/brain/dead-ends.ts";
+import { buildForesight, FORESIGHT_HORIZON_DAYS } from "../../core/brain/temporal/foresight.ts";
+import { aggregateQuantities } from "../../core/brain/truth/aggregate.ts";
+import { detectAgentCollisions } from "../../core/brain/truth/collision.ts";
+import { computeTruthStateWithConflicts } from "../../core/brain/truth/conflicts.ts";
+import { appendClaimEvent, readClaimEvents } from "../../core/brain/truth/store.ts";
+import { INVALID_PARAMS, MCPError } from "../protocol.ts";
+import type { ServerContext, ToolDefinition } from "../tools.ts";
+import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
+import { coerceStr, coerceBool } from "../coerce.ts";
+import { optionalPositiveInt } from "./shared.ts";
+
+/** Forward-looking projection envelope; read-only fold. */
+function toolBrainForesight(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Record<string, unknown> {
+ const horizonRaw = args["horizon_days"];
+ let horizonDays = FORESIGHT_HORIZON_DAYS;
+ if (horizonRaw !== undefined && horizonRaw !== null) {
+ if (typeof horizonRaw !== "number" || !Number.isInteger(horizonRaw) || horizonRaw < 1) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_foresight: horizon_days must be a positive integer",
+ );
+ }
+ horizonDays = horizonRaw;
+ }
+ return { ...buildForesight(ctx.vault, { now: new Date(), horizonDays }) };
+}
+
+// ----- brain_labels (t_7a41f42d) ---------------------------------------------
+
+/**
+ * Bridge discovery over the vec index: discover regenerates the
+ * reviewable proposals artifact, accept writes one related wikilink,
+ * dismiss persists a pair suppression, list reads the artifact back.
+ */
+async function toolBrainBridges(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const op = args["operation"];
+ if (op !== "discover" && op !== "list" && op !== "accept" && op !== "dismiss") {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_bridges: operation must be discover|list|accept|dismiss",
+ );
+ }
+ if (op === "accept" || op === "dismiss") {
+ const source = args["source"];
+ const target = args["target"];
+ if (typeof source !== "string" || source.trim() === "") {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_bridges ${op}: source must be a vault-relative path`,
+ );
+ }
+ if (typeof target !== "string" || target.trim() === "") {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_bridges ${op}: target must be a vault-relative path`,
+ );
+ }
+ if (op === "dismiss") {
+ return {
+ dismissed: bridgePairKey(source, target),
+ added: dismissBridge(ctx.vault, source, target),
+ };
+ }
+ try {
+ const pack = loadSchemaPack(ctx.vault);
+ return { ...acceptBridge(ctx.vault, source, target, { pack }), source, target };
+ } catch (exc) {
+ const message = (exc as Error).message ?? String(exc);
+ if (/outside the vault|does not exist|link constraint/.test(message)) {
+ throw new MCPError(INVALID_PARAMS, `brain_bridges accept: ${message}`);
+ }
+ throw exc;
+ }
+ }
+ if (op === "list") {
+ const path = join(ctx.vault, "Brain", "proposals", "bridges.md");
+ if (!existsSync(path)) return { exists: false, proposals: 0 };
+ const [meta] = parseFrontmatter(path);
+ return {
+ exists: true,
+ path: "Brain/proposals/bridges.md",
+ generated_at: meta["generated_at"] ?? null,
+ proposals: Number(meta["proposals"] ?? 0),
+ };
+ }
+ // discover
+ const max = args["max"];
+ if (max !== undefined && (!Number.isInteger(max) || (max as number) < 1)) {
+ throw new MCPError(INVALID_PARAMS, "brain_bridges discover: max must be a positive integer");
+ }
+ const minSimilarity = args["min_similarity"];
+ if (
+ minSimilarity !== undefined &&
+ (typeof minSimilarity !== "number" || minSimilarity <= 0 || minSimilarity > 1)
+ ) {
+ throw new MCPError(INVALID_PARAMS, "brain_bridges discover: min_similarity must be in (0, 1]");
+ }
+ const searchConfig = resolveSearchConfig({
+ vault: ctx.vault,
+ configPath: ctx.configPath ?? undefined,
+ });
+ if (!existsSync(searchConfig.dbPath)) {
+ return { vec_available: false, proposals: [], reason: "index not built" };
+ }
+ const store = await Store.open(searchConfig, { mode: "read" });
+ const now = new Date();
+ try {
+ const dismissed = readDismissedBridges(ctx.vault);
+ const report = discoverBridges(store, {
+ ...(max !== undefined ? { maxProposals: max as number } : {}),
+ ...(minSimilarity !== undefined ? { minSimilarity } : {}),
+ dismissed,
+ });
+ writeBridgeProposals(ctx.vault, report, { now });
+ try {
+ appendMetric(ctx.vault, {
+ surface: "bridge_discovery",
+ runAt: isoSecond(now),
+ payload: {
+ proposals: report.proposals.length,
+ scanned_candidates: report.scannedCandidates,
+ vec_available: report.vecAvailable,
+ dismissed_total: dismissed.size,
+ },
+ });
+ } catch {
+ // Metrics are observability, not correctness.
+ }
+ return {
+ vec_available: report.vecAvailable,
+ ...(report.reason !== undefined ? { reason: report.reason } : {}),
+ scanned_candidates: report.scannedCandidates,
+ proposals: report.proposals,
+ artifact: "Brain/proposals/bridges.md",
+ };
+ } finally {
+ await store.close();
+ }
+}
+
+// ----- brain_clusters (t_4ba927ec) --------------------------------------------
+
+/** Graph-wide community detection with materialized cluster notes. */
+async function toolBrainClusters(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const op = args["operation"];
+ if (op !== "run" && op !== "list") {
+ throw new MCPError(INVALID_PARAMS, "brain_clusters: operation must be run|list");
+ }
+ if (op === "list") {
+ const dir = join(ctx.vault, "Brain", "clusters");
+ if (!existsSync(dir)) return { clusters: [] };
+ const clusters = readdirSync(dir)
+ .filter((f) => f.endsWith(".md"))
+ .toSorted()
+ .map((f) => {
+ const [meta] = parseFrontmatter(join(dir, f));
+ return meta["kind"] === "brain-cluster"
+ ? {
+ path: `Brain/clusters/${f}`,
+ cluster: String(meta["cluster"] ?? ""),
+ size: Number(meta["size"] ?? 0),
+ density: Number(meta["density"] ?? 0),
+ generated_at: String(meta["generated_at"] ?? ""),
+ }
+ : null;
+ })
+ .filter((c) => c !== null);
+ return { clusters };
+ }
+ const minSize = args["min_size"];
+ if (minSize !== undefined && (!Number.isInteger(minSize) || (minSize as number) < 2)) {
+ throw new MCPError(INVALID_PARAMS, "brain_clusters run: min_size must be an integer >= 2");
+ }
+ const searchConfig = resolveSearchConfig({
+ vault: ctx.vault,
+ configPath: ctx.configPath ?? undefined,
+ });
+ if (!existsSync(searchConfig.dbPath)) {
+ return { communities: [], reason: "index not built" };
+ }
+ const store = await Store.open(searchConfig, { mode: "read" });
+ const now = new Date();
+ try {
+ const communities = detectCommunities(
+ store,
+ minSize !== undefined ? { minSize: minSize as number } : {},
+ );
+ const materialized = materializeClusterNotes(ctx.vault, communities, { store, now });
+ try {
+ appendMetric(ctx.vault, {
+ surface: "communities",
+ runAt: isoSecond(now),
+ payload: {
+ communities: communities.length,
+ sizes: communities.map((c) => c.size),
+ written: materialized.written.length,
+ removed: materialized.removed.length,
+ },
+ });
+ } catch {
+ // Metrics are observability, not correctness.
+ }
+ return {
+ communities: communities.map((c) => ({
+ id: c.id,
+ size: c.size,
+ density: c.density,
+ members: c.members.map((m) => m.path),
+ })),
+ written: materialized.written,
+ removed: materialized.removed,
+ };
+ } finally {
+ await store.close();
+ }
+}
+
+// ----- brain_benchmark (t_e2215d49) -------------------------------------------
+
+/**
+ * Per-MOC coverage audit. Classifies cluster members into
+ * `wellCovered` / `fragile` / `candidateMissing` and surfaces a
+ * `suggestedNext` candidate. MOC detection is purely structural -
+ * outbound link count + link density.
+ */
+async function toolBrainMocAudit(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const idRaw = args["id"];
+ if (typeof idRaw !== "string" || idRaw.trim().length === 0) {
+ throw new MCPError(INVALID_PARAMS, "brain_moc_audit: id must be a non-empty string");
+ }
+ const targetId = normaliseWikilinkTarget(idRaw);
+ try {
+ const report = auditMoc(ctx.vault, targetId);
+ return {
+ vault_path: ctx.vault,
+ hub_id: report.hubId,
+ outbound_count: report.outboundCount,
+ well_covered: report.wellCovered,
+ fragile: report.fragile,
+ candidate_missing: report.candidateMissing,
+ ...(report.suggestedNext ? { suggested_next: report.suggestedNext } : {}),
+ };
+ } catch (err) {
+ if (err instanceof MocAuditError) {
+ throw new MCPError(INVALID_PARAMS, `brain_moc_audit: ${err.message}`);
+ }
+ throw err;
+ }
+}
+
+// ----- Temporal subsystem MCP wrappers (v0.10.18) --------------------------
+
+async function toolBrainDeepSynthesis(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const topic = coerceStr(args, "topic", true)!;
+ const limit = optionalPositiveInt(args, "limit", "brain_deep_synthesis") ?? 30;
+ if (limit > 100) {
+ throw new MCPError(INVALID_PARAMS, "brain_deep_synthesis: limit must be at most 100");
+ }
+ const enqueue = coerceBool(args, "triggers");
+ const now = new Date();
+ const searchConfig = resolveSearchConfig({
+ vault: ctx.vault,
+ configPath: ctx.configPath ?? undefined,
+ });
+ const report = await deepSynthesis(searchConfig, topic, { now, limit });
+ let triggersCreated: number | undefined;
+ if (enqueue) {
+ const result = createTriggers(ctx.vault, synthesisCandidates(report), {
+ now,
+ cooldownDays: resolveTriggerCooldownDays(ctx.configPath ?? undefined),
+ });
+ triggersCreated = result.created.length;
+ }
+ return {
+ topic: report.topic,
+ generated_at: report.generatedAt,
+ checked: report.checked,
+ notes: report.notes,
+ agreements: report.agreements,
+ contradictions: report.contradictions,
+ stale_claims: report.staleClaims.map((s) => ({
+ path: s.path,
+ age_days: s.ageDays,
+ superseded_by: s.supersededBy,
+ })),
+ gaps: report.gaps,
+ contaminated: report.contaminated,
+ ...(triggersCreated !== undefined ? { triggers_created: triggersCreated } : {}),
+ };
+}
+
+// ----- brain_idea_discovery (Workspace Insight Suite) ------------------------
+
+function toolBrainIdeaDiscovery(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Record<string, unknown> {
+ const cap = optionalPositiveInt(args, "cap", "brain_idea_discovery") ?? 5;
+ if (cap > 50) {
+ throw new MCPError(INVALID_PARAMS, "brain_idea_discovery: cap must be at most 50");
+ }
+ const enqueue = coerceBool(args, "triggers");
+ const now = new Date();
+ const ideas = discoverIdeas(ctx.vault, { now, cap });
+ let triggersCreated: number | undefined;
+ if (enqueue) {
+ const result = createTriggers(ctx.vault, ideaCandidates(ideas), {
+ now,
+ cooldownDays: resolveTriggerCooldownDays(ctx.configPath ?? undefined),
+ });
+ triggersCreated = result.created.length;
+ }
+ return {
+ ideas: ideas.map((idea) => ({
+ kind: idea.kind,
+ title: idea.title,
+ reason: idea.reason,
+ score: idea.score,
+ source_artifacts: idea.sourceArtifacts,
+ })),
+ ...(triggersCreated !== undefined ? { triggers_created: triggersCreated } : {}),
+ };
+}
+
+// ----- brain_context_pack (v0.10.15) ---------------------------------------
+
+/**
+ * Operator/agent surface over the entity claim ledger: ingest one
+ * claim, render slots/conflicts from the fold, aggregate exact-match
+ * quantities, report cross-agent collisions. Read ops are pure folds
+ * over the append-only ledger.
+ */
+function toolBrainTruth(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Record<string, unknown> {
+ const op = args["operation"];
+ if (
+ op !== "ingest" &&
+ op !== "slots" &&
+ op !== "conflicts" &&
+ op !== "aggregate" &&
+ op !== "collisions"
+ ) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_truth: operation must be ingest|slots|conflicts|aggregate|collisions",
+ );
+ }
+ const requireStr = (name: string): string => {
+ const value = args[name];
+ if (typeof value !== "string" || value.trim() === "") {
+ throw new MCPError(INVALID_PARAMS, `brain_truth ${op}: ${name} must be a non-empty string`);
+ }
+ return value;
+ };
+
+ if (op === "ingest") {
+ const quantityValue = args["quantity_value"];
+ if (
+ (quantityValue === undefined || quantityValue === null) &&
+ (typeof args["quantity_unit"] === "string" || typeof args["quantity_action"] === "string")
+ ) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_truth ingest: quantity_value is required when quantity_unit or quantity_action is provided",
+ );
+ }
+ let quantity: { value: number; unit: string | null; action: string | null } | undefined;
+ if (quantityValue !== undefined && quantityValue !== null) {
+ if (typeof quantityValue !== "number" || !Number.isFinite(quantityValue)) {
+ throw new MCPError(INVALID_PARAMS, "brain_truth ingest: quantity_value must be a number");
+ }
+ quantity = {
+ value: quantityValue,
+ unit: typeof args["quantity_unit"] === "string" ? (args["quantity_unit"] as string) : null,
+ action:
+ typeof args["quantity_action"] === "string" ? (args["quantity_action"] as string) : null,
+ };
+ }
+ const agentArg = args["agent"];
+ const agent =
+ normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??
+ resolveAgentName(ctx.configPath ?? undefined);
+ const result = appendClaimEvent(ctx.vault, {
+ ts: isoSecond(new Date()),
+ agent,
+ entity: requireStr("entity"),
+ aspect: requireStr("aspect"),
+ value: requireStr("value"),
+ ...(quantity !== undefined ? { valueKind: "quantity" as const, quantity } : {}),
+ source: requireStr("source"),
+ });
+ return {
+ ok: true,
+ entity: result.event.entity,
+ aspect: result.event.aspect,
+ path: result.path,
+ };
+ }
+
+ const events = readClaimEvents(ctx.vault).events;
+ if (op === "slots" || op === "conflicts") {
+ const state = computeTruthStateWithConflicts(events);
+ if (op === "conflicts") return { events: state.events, conflicts: state.conflicts };
+ const entityFilter = args["entity"];
+ const slots =
+ typeof entityFilter === "string" && entityFilter.trim() !== ""
+ ? state.slots.filter((s) => s.entity === normalizeEntityName(entityFilter))
+ : state.slots;
+ return { events: state.events, slots };
+ }
+ if (op === "aggregate") {
+ const state = computeTruthStateWithConflicts(events);
+ return {
+ ...aggregateQuantities(state.slots, {
+ ...(typeof args["action"] === "string" ? { action: args["action"] as string } : {}),
+ unit: typeof args["unit"] === "string" ? (args["unit"] as string) : null,
+ ...(typeof args["entity"] === "string" ? { entity: args["entity"] as string } : {}),
+ }),
+ };
+ }
+ return {
+ collisions: detectAgentCollisions(events, { now: new Date() }),
+ };
+}
+
+// ----- brain_concept_synthesis (v0.10.17) ----------------------------------
+
+/**
+ * Negative-knowledge registry: record one tried-and-failed approach
+ * or list the bounded active set, newest first.
+ */
+function toolBrainDeadEnds(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Record<string, unknown> {
+ const op = args["operation"];
+ if (op !== "record" && op !== "list") {
+ throw new MCPError(INVALID_PARAMS, "brain_dead_ends: operation must be record|list");
+ }
+ if (op === "list") {
+ const { entries, warnings } = listDeadEnds(ctx.vault);
+ return { entries, warnings };
+ }
+ const approach = args["approach"];
+ const reason = args["reason"];
+ if (typeof approach !== "string" || approach.trim() === "") {
+ throw new MCPError(INVALID_PARAMS, "brain_dead_ends record: approach must be non-empty");
+ }
+ if (typeof reason !== "string" || reason.trim() === "") {
+ throw new MCPError(INVALID_PARAMS, "brain_dead_ends record: reason must be non-empty");
+ }
+ const agentArg = args["agent"];
+ const agent =
+ normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??
+ resolveAgentName(ctx.configPath ?? undefined);
+ const result = recordDeadEnd(ctx.vault, {
+ approach,
+ reason,
+ ...(typeof args["context"] === "string" ? { context: args["context"] as string } : {}),
+ agent,
+ now: new Date(),
+ });
+ return { ok: true, id: result.entry.id, path: result.entry.path, archived: result.archived };
+}
+
+// ----- brain_truth (Entity Truth & Self-Improving Dream Suite) ---------------
+
+export const KNOWLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
+ {
+ name: "brain_foresight",
+ description:
+ "Forward-looking projection (Brain's only anticipatory surface): recurring routines coming due within the horizon via cadence arithmetic, recent open commitments, and open questions - deterministic, every item carries sources.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ horizon_days: {
+ type: "integer",
+ minimum: 1,
+ description: "Forward horizon in days (default 14).",
+ },
+ },
+ additionalProperties: false,
+ },
+ handler: toolBrainForesight,
+ previewBudget: MCP_PREVIEW_BUDGET,
+ },
+ {
+ name: "brain_bridges",
+ description:
+ "Bridge discovery over the vec index: discover proposes links between embedding-near notes that share no edge (orphan-first, regenerates Brain/proposals/bridges.md, records a metric); accept writes one related wikilink into the source note; dismiss silences a pair; list reads the artifact back.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["discover", "list", "accept", "dismiss"],
+ description: "Tool operation.",
+ },
+ source: { type: "string", description: "Vault-relative source note (accept/dismiss)." },
+ target: { type: "string", description: "Vault-relative target note (accept/dismiss)." },
+ max: { type: "integer", minimum: 1, description: "Proposal cap (discover)." },
+ min_similarity: {
+ type: "number",
+ exclusiveMinimum: 0,
+ maximum: 1,
+ description: "Cosine similarity threshold (discover, default 0.8).",
+ },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainBridges,
+ previewBudget: MCP_PREVIEW_BUDGET,
+ },
+ {
+ name: "brain_clusters",
+ description:
+ "Graph-wide community detection: run applies deterministic label propagation over the resolved link graph, materializes one derived note per community of size >= min_size under Brain/clusters/, removes stale generated notes, and records a metric; list reads the generated notes back.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: { type: "string", enum: ["run", "list"], description: "Tool operation." },
+ min_size: {
+ type: "integer",
+ minimum: 2,
+ description: "Smallest community that materializes (run, default 4).",
+ },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainClusters,
+ previewBudget: MCP_PREVIEW_BUDGET,
+ },
+ {
+ name: "brain_moc_audit",
+ description:
+ "Per-MOC coverage audit. Given a hub note id, classifies its outbound cluster into well-covered / fragile / candidate-missing and surfaces a suggested-next candidate. MOC detection is purely structural (outbound link count + link density). Read-only.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ description: "Hub note id (e.g. `pref-foo`). Wikilink decoration is stripped if present.",
+ },
+ },
+ required: ["id"],
+ additionalProperties: false,
+ },
+ handler: toolBrainMocAudit,
+ },
+ {
+ name: "brain_deep_synthesis",
+ description:
+ "Topic-scoped deterministic dossier: matched notes, agreements (positive typed relations), contradictions, stale claims, and knowledge gaps (dangling wikilinks). Evidence assembly only - prose synthesis stays with the caller. Optional triggers=true enqueues findings.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ topic: { type: "string", minLength: 1, maxLength: 500 },
+ limit: { type: "integer", minimum: 1, maximum: 100 },
+ triggers: {
+ type: "boolean",
+ description: "Enqueue contradiction/gap findings into the trigger queue.",
+ },
+ },
+ required: ["topic"],
+ additionalProperties: false,
+ },
+ previewBudget: MCP_PREVIEW_BUDGET,
+ handler: toolBrainDeepSynthesis,
+ },
+ {
+ name: "brain_idea_discovery",
+ description:
+ "Ranked next-direction candidates from the vault's open loops: unanswered open questions, orphan research notes (no inbound links), and aging unresolved inbox signals. Deterministic scoring; triggers=true enqueues the ranked ideas.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ cap: { type: "integer", minimum: 1, maximum: 50 },
+ triggers: {
+ type: "boolean",
+ description: "Enqueue the ranked ideas into the trigger queue.",
+ },
+ },
+ additionalProperties: false,
+ },
+ previewBudget: MCP_PREVIEW_BUDGET,
+ handler: toolBrainIdeaDiscovery,
+ },
+ {
+ name: "brain_truth",
+ description:
+ "Entity claim ledger: ingest a claim, render current-truth slots with superseded history, list contested conflicts (ask_user), aggregate exact-match quantities, report cross-agent collisions.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["ingest", "slots", "conflicts", "aggregate", "collisions"],
+ description: "Tool operation.",
+ },
+ entity: {
+ type: "string",
+ description: "Entity name (ingest, slots filter, aggregate filter).",
+ },
+ aspect: { type: "string", description: "Aspect slot for ingest." },
+ value: { type: "string", description: "Claim value for ingest." },
+ source: { type: "string", description: "Provenance wikilink/path for ingest." },
+ agent: { type: "string", description: "Agent identity override for ingest." },
+ quantity_value: { type: "number", description: "Numeric value for quantity claims." },
+ quantity_unit: { type: "string", description: "Unit token for quantity claims." },
+ quantity_action: { type: "string", description: "Measured action for quantity claims." },
+ action: { type: "string", description: "Measured action for aggregate." },
+ unit: { type: "string", description: "Unit token for aggregate (omit for unitless)." },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainTruth,
+ previewBudget: MCP_PREVIEW_BUDGET,
+ },
+ {
+ name: "brain_dead_ends",
+ description:
+ "Negative-knowledge registry (Brain/dead-ends/): record one tried-and-failed approach with why it failed, or list the bounded active set so recall surfaces avoid-X alongside prefer-Y.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["record", "list"],
+ description: "Tool operation.",
+ },
+ approach: { type: "string", description: "What was tried (record)." },
+ reason: { type: "string", description: "Why it failed or was set aside (record)." },
+ context: { type: "string", description: "Optional context (record)." },
+ agent: { type: "string", description: "Agent identity override (record)." },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainDeadEnds,
+ previewBudget: MCP_PREVIEW_BUDGET,
+ },
+]);
diff --git a/src/mcp/brain/landscape-tools.ts b/src/mcp/brain/landscape-tools.ts
new file mode 100644
index 00000000..5043ec68
--- /dev/null
+++ b/src/mcp/brain/landscape-tools.ts
@@ -0,0 +1,59 @@
+/**
+ * MCP landscape discovery across configured servers.
+ *
+ * Extracted from the former brain-tools.ts monolith; registration
+ * happens through the aggregator, which preserves the public
+ * BRAIN_TOOLS surface.
+ */
+
+import { buildMcpLandscape } from "../../core/graph/mcp-config.ts";
+import type { ServerContext, ToolDefinition } from "../tools.ts";
+
+async function toolMcpLandscape(ctx: ServerContext): Promise<Record<string, unknown>> {
+ const landscape = buildMcpLandscape(ctx.vault);
+ return {
+ vault_path: ctx.vault,
+ servers: landscape.servers.map((s) => ({
+ name: s.name,
+ source: s.source,
+ packages: s.packages,
+ env: s.env,
+ })),
+ };
+}
+
+// ----- Consolidated view tools (token-diet, t_3920db77) ---------------------
+
+export const LANDSCAPE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
+ {
+ name: "brain_mcp_landscape",
+ description:
+ "List the Model Context Protocol servers configured across the vault: each server's name, the config file that declares it, the packages it pulls, and the env-var NAMES it requires. Environment values are never read. Discovery is vault-relative. Read-only.",
+ inputSchema: {
+ type: "object",
+ properties: {},
+ additionalProperties: false,
+ },
+ outputSchema: {
+ type: "object",
+ required: ["vault_path", "servers"],
+ properties: {
+ vault_path: { type: "string" },
+ servers: {
+ type: "array",
+ items: {
+ type: "object",
+ required: ["name", "source", "packages", "env"],
+ properties: {
+ name: { type: "string" },
+ source: { type: "string" },
+ packages: { type: "array", items: { type: "string" } },
+ env: { type: "array", items: { type: "string" } },
+ },
+ },
+ },
+ },
+ },
+ handler: toolMcpLandscape,
+ },
+]);
diff --git a/src/mcp/brain/pack-tools.ts b/src/mcp/brain/pack-tools.ts
new file mode 100644
index 00000000..52ade060
--- /dev/null
+++ b/src/mcp/brain/pack-tools.ts
@@ -0,0 +1,592 @@
+/**
+ * Context packing surfaces: token-budgeted context pack, context
+ * receipts, preset diagnostics, and the pre-compress / pre-compact
+ * extraction paths.
+ *
+ * Extracted from the former brain-tools.ts monolith; registration
+ * happens through the aggregator, which preserves the public
+ * BRAIN_TOOLS surface.
+ */
+
+import { resolveSearchFocusContextPack } from "../../core/config.ts";
+import { resolveSearchConfig } from "../../core/search/index.ts";
+import { readActiveSessionFocus } from "../../core/search/session-focus.ts";
+import { packContext } from "../../core/brain/context-pack.ts";
+import { buildPreCompressPack } from "../../core/brain/pre-compress-pack.ts";
+import {
+ getContextReceipt,
+ isContextReceiptTrigger,
+ listContextReceipts,
+ summarizeContextReceipt,
+ type ContextReceiptOptions,
+} from "../../core/brain/context-receipts.ts";
+import {
+ diffContextPreset,
+ getContextPreset,
+ listContextPresets,
+ suggestContextPreset,
+ type ContextPresetCurrentConfig,
+} from "../../core/brain/context-presets.ts";
+import { extractPreCompactRecords } from "../../core/brain/pre-compact-extract.ts";
+import { INVALID_PARAMS, MCPError } from "../protocol.ts";
+import type { ServerContext, ToolDefinition } from "../tools.ts";
+import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
+import { coerceStr, coerceStrList, coerceBool } from "../coerce.ts";
+import {
+ coercePositiveInteger,
+ optionalPositiveInt,
+ optionalStringArg,
+ requiredStringArg,
+ telemetryOptionsFromArgs,
+} from "./shared.ts";
+
+/**
+ * Bounded-token vault slice ordered by importance tier then recency.
+ * Lets an agent prime its context window under a strict budget.
+ */
+async function toolBrainContextPack(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const maxRaw = args["max_tokens"];
+ const maxTokens =
+ typeof maxRaw === "number"
+ ? maxRaw
+ : typeof maxRaw === "string" && /^[0-9]+$/.test(maxRaw.trim())
+ ? Number.parseInt(maxRaw.trim(), 10)
+ : Number.NaN;
+ if (!Number.isInteger(maxTokens) || maxTokens <= 0) {
+ throw new MCPError(INVALID_PARAMS, "brain_context_pack: max_tokens must be a positive integer");
+ }
+ const query = typeof args["query"] === "string" ? (args["query"] as string) : undefined;
+ const includeLanes = coerceBool(args, "lanes");
+ const cacheStable = coerceBool(args, "cache_stable");
+ const dedupRepeated = coerceBool(args, "dedup_repeated");
+ const attentionFlowIds = coerceStrList(args, "attention_flow_ids");
+ const maxCharsPerMemory = optionalPositiveInt(args, "max_chars_per_memory", "brain_context_pack");
+ const maxTotalChars = optionalPositiveInt(args, "max_total_chars", "brain_context_pack");
+ const receipt = receiptOptionsFromArgs("brain_context_pack", args, "context_pack", "mcp");
+ const telemetry = telemetryOptionsFromArgs("brain_context_pack", args, "mcp");
+ // Focus wiring (Agent Surface Suite, t_5b478e47): gated on the
+ // search_focus_context_pack config key (default off) so the default
+ // pack stays byte-identical. Fail-soft - a broken search config
+ // never breaks the pack.
+ let sessionFocus: ReturnType<typeof readActiveSessionFocus> = null;
+ if (resolveSearchFocusContextPack(ctx.configPath ?? undefined)) {
+ // Argument validation stays OUTSIDE the fail-soft block: an invalid
+ // focus_session is a caller error (INVALID_PARAMS), not a config
+ // read to swallow.
+ const focusSession = coerceStr(args, "focus_session", false) ?? undefined;
+ try {
+ const searchConfig = resolveSearchConfig({
+ vault: ctx.vault,
+ configPath: ctx.configPath ?? undefined,
+ });
+ sessionFocus = readActiveSessionFocus(searchConfig, focusSession);
+ } catch {
+ sessionFocus = null;
+ }
+ }
+ const report = packContext(ctx.vault, {
+ maxTokens,
+ ...(sessionFocus !== null ? { sessionFocus } : {}),
+ ...(query ? { query } : {}),
+ ...(includeLanes ? { includeLanes: true } : {}),
+ ...(receipt !== undefined ? { receipt } : {}),
+ ...(cacheStable || dedupRepeated
+ ? {
+ transforms: {
+ ...(cacheStable ? { cacheStableOrdering: true } : {}),
+ ...(dedupRepeated ? { deduplicateRepeatedContext: true } : {}),
+ },
+ }
+ : {}),
+ ...(maxCharsPerMemory !== undefined ? { maxCharsPerMemory } : {}),
+ ...(maxTotalChars !== undefined ? { maxTotalChars } : {}),
+ ...(telemetry !== undefined ? { telemetry } : {}),
+ ...(attentionFlowIds.length > 0 ? { attentionFlowIds } : {}),
+ });
+ return {
+ vault_path: ctx.vault,
+ max_tokens: report.maxTokens,
+ tokens_used: report.tokensUsed,
+ items: report.items.map((i) => ({
+ id: i.id,
+ path: i.path,
+ tier: i.tier,
+ tokens: i.tokens,
+ body: i.body,
+ trimmed: i.trimmed,
+ ...(i.originalRank !== undefined ? { original_rank: i.originalRank } : {}),
+ ...(i.stableRank !== undefined ? { stable_rank: i.stableRank } : {}),
+ ...(i.dedupedFrom !== undefined ? { deduped_from: i.dedupedFrom } : {}),
+ ...(i.referenceHint !== undefined ? { reference_hint: i.referenceHint } : {}),
+ ...(i.safety ? { safety: i.safety } : {}),
+ })),
+ skipped: report.skipped.map((s) => ({
+ id: s.id,
+ tokens: s.tokens,
+ reason: s.reason,
+ })),
+ ...(report.receiptId ? { receipt_id: report.receiptId } : {}),
+ ...(report.telemetryId ? { telemetry_id: report.telemetryId } : {}),
+ ...(report.lanes ? { lanes: report.lanes } : {}),
+ };
+}
+
+// ----- brain_context_receipts ---------------------------------------------
+
+async function toolBrainContextReceipts(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const operation = optionalStringArg("brain_context_receipts", args, "operation");
+ if (operation === "list") {
+ const trigger = optionalStringArg("brain_context_receipts", args, "trigger");
+ if (trigger !== undefined && !isContextReceiptTrigger(trigger)) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_context_receipts: trigger must be context_pack or pre_compress",
+ );
+ }
+ const host = optionalStringArg("brain_context_receipts", args, "host");
+ const sessionId = optionalStringArg("brain_context_receipts", args, "session_id");
+ const limit = coercePositiveInteger("brain_context_receipts", "limit", args["limit"]);
+ const receipts = listContextReceipts(ctx.vault, {
+ ...(trigger !== undefined ? { trigger } : {}),
+ ...(host !== undefined ? { host } : {}),
+ ...(sessionId !== undefined ? { sessionId } : {}),
+ ...(limit !== undefined ? { limit } : {}),
+ });
+ const summaries = receipts.map(summarizeContextReceipt);
+ return {
+ vault_path: ctx.vault,
+ total: summaries.length,
+ receipts: summaries,
+ };
+ }
+
+ if (operation === "show") {
+ const id = optionalStringArg("brain_context_receipts", args, "id");
+ if (id === undefined) {
+ throw new MCPError(INVALID_PARAMS, "brain_context_receipts: id is required for show");
+ }
+ const receipt = getContextReceipt(ctx.vault, id);
+ if (receipt === null) {
+ throw new MCPError(INVALID_PARAMS, `brain_context_receipts: receipt not found: ${id}`);
+ }
+ return {
+ id: receipt.id,
+ kind: receipt.kind,
+ createdAt: receipt.createdAt,
+ sourceRefs: receipt.sourceRefs,
+ payload: receipt.payload,
+ private: receipt.private,
+ redacted: receipt.redacted,
+ };
+ }
+
+ throw new MCPError(INVALID_PARAMS, "brain_context_receipts: operation must be list or show");
+}
+
+function receiptOptionsFromArgs(
+ tool: string,
+ args: Record<string, unknown>,
+ trigger: "context_pack" | "pre_compress",
+ defaultHost: string,
+): ContextReceiptOptions | undefined {
+ if (!coerceBool(args, "receipt")) return undefined;
+ return {
+ host: optionalStringArg(tool, args, "receipt_host") ?? defaultHost,
+ trigger,
+ ...(optionalStringArg(tool, args, "session_id") !== undefined
+ ? { sessionId: optionalStringArg(tool, args, "session_id") }
+ : {}),
+ ...(optionalStringArg(tool, args, "turn_id") !== undefined
+ ? { turnId: optionalStringArg(tool, args, "turn_id") }
+ : {}),
+ };
+}
+
+async function toolBrainContextPresets(
+ _ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const operation = optionalStringArg("brain_context_presets", args, "operation");
+ if (operation === "show") {
+ const presetId = optionalStringArg("brain_context_presets", args, "preset_id");
+ const result =
+ presetId === undefined ? { presets: listContextPresets() } : getContextPreset(presetId);
+ if (result === null) {
+ throw new MCPError(INVALID_PARAMS, `brain_context_presets: unknown preset ${presetId}`);
+ }
+ return Array.isArray(result) ? { presets: result } : { ...result };
+ }
+ if (operation === "suggest") {
+ const model = optionalStringArg("brain_context_presets", args, "model");
+ const window = coercePositiveInteger(
+ "brain_context_presets",
+ "context_window_tokens",
+ args["context_window_tokens"],
+ );
+ return {
+ ...suggestContextPreset({
+ ...(model !== undefined ? { model } : {}),
+ ...(window !== undefined ? { contextWindowTokens: window } : {}),
+ }),
+ };
+ }
+ if (operation === "diff") {
+ const presetId = optionalStringArg("brain_context_presets", args, "preset_id");
+ if (presetId === undefined) {
+ throw new MCPError(INVALID_PARAMS, "brain_context_presets: preset_id is required for diff");
+ }
+ return {
+ ...diffContextPreset(presetId, contextPresetCurrentConfig(args["current"])),
+ };
+ }
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_context_presets: operation must be show, suggest, or diff",
+ );
+}
+
+function contextPresetCurrentConfig(raw: unknown): ContextPresetCurrentConfig {
+ if (raw === undefined || raw === null) return {};
+ if (typeof raw !== "object" || Array.isArray(raw)) {
+ throw new MCPError(INVALID_PARAMS, "brain_context_presets: current must be an object");
+ }
+ return raw as ContextPresetCurrentConfig;
+}
+
+// ----- brain_pre_compact_extract ------------------------------------------
+
+/**
+ * Read-only bundle of the highest-confidence confirmed preferences plus
+ * the head of active.md, rendered as a system-prompt addendum for a host
+ * runtime to inject just before a context-compression event.
+ */
+async function toolBrainPreCompressPack(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const topK = optionalPositiveInt(args, "top_k", "brain_pre_compress_pack") ?? 10;
+ const maxCharsPerMemory = optionalPositiveInt(
+ args,
+ "max_chars_per_memory",
+ "brain_pre_compress_pack",
+ );
+ const maxTotalChars = optionalPositiveInt(args, "max_total_chars", "brain_pre_compress_pack");
+ const receipt = receiptOptionsFromArgs("brain_pre_compress_pack", args, "pre_compress", "mcp");
+ const telemetry = telemetryOptionsFromArgs("brain_pre_compress_pack", args, "mcp");
+ const pack = buildPreCompressPack(ctx.vault, {
+ topK,
+ ...(maxCharsPerMemory !== undefined ? { maxCharsPerMemory } : {}),
+ ...(maxTotalChars !== undefined ? { maxTotalChars } : {}),
+ ...(receipt !== undefined ? { receipt } : {}),
+ ...(telemetry !== undefined ? { telemetry } : {}),
+ });
+ return {
+ vault_path: ctx.vault,
+ text: pack.text,
+ active_head_included: pack.activeHeadIncluded,
+ ...(pack.activeHeadSafety ? { active_head_safety: pack.activeHeadSafety } : {}),
+ total_chars: pack.totalChars,
+ ...(pack.receiptId ? { receipt_id: pack.receiptId } : {}),
+ ...(pack.telemetryId ? { telemetry_id: pack.telemetryId } : {}),
+ items: pack.items.map((i) => ({
+ id: i.id,
+ principle: i.principle,
+ trimmed: i.trimmed,
+ ...(i.safety ? { safety: i.safety } : {}),
+ })),
+ };
+}
+
+async function toolBrainPreCompactExtract(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const sessionId = requiredStringArg("brain_pre_compact_extract", args, "session_id");
+ const turnStart = requiredStringArg("brain_pre_compact_extract", args, "turn_start");
+ const turnEnd = requiredStringArg("brain_pre_compact_extract", args, "turn_end");
+ const text = requiredStringArg("brain_pre_compact_extract", args, "text");
+ const maxChars = coercePositiveInteger(
+ "brain_pre_compact_extract",
+ "max_chars",
+ args["max_chars"],
+ );
+ const result = extractPreCompactRecords(ctx.vault, {
+ sessionId,
+ turnStart,
+ turnEnd,
+ text,
+ ...(optionalStringArg("brain_pre_compact_extract", args, "host") !== undefined
+ ? { host: optionalStringArg("brain_pre_compact_extract", args, "host") }
+ : {}),
+ ...(maxChars !== undefined ? { maxChars } : {}),
+ });
+ return { count: result.records.length, ...result };
+}
+
+// ----- session recall DAG --------------------------------------------------
+
+export const PACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
+ {
+ name: "brain_context_pack",
+ previewBudget: MCP_PREVIEW_BUDGET,
+ description:
+ "Return the highest-tier, most recent vault slice that fits under `max_tokens`. Ordered core → supporting → peripheral, newest first; stops adding pages when the next page would exceed the budget. Read-only.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ max_tokens: {
+ type: "integer",
+ minimum: 1,
+ description: "Strict upper bound on the returned slice's token count.",
+ },
+ query: {
+ type: "string",
+ description: "Optional case/Unicode-insensitive substring filter on topic + principle.",
+ },
+ focus_session: {
+ type: "string",
+ minLength: 1,
+ maxLength: 128,
+ description:
+ "Session id whose bound search focus boosts matching memories (requires search_focus_context_pack).",
+ },
+ max_chars_per_memory: {
+ type: "integer",
+ minimum: 1,
+ description:
+ "Optional per-page character cap so one huge page cannot crowd out the rest; trimmed pages carry `trimmed: true`.",
+ },
+ max_total_chars: {
+ type: "integer",
+ minimum: 1,
+ description:
+ "Optional second ceiling (code points) on the cumulative size of the returned slice. Lowest-priority overflow is dropped with an `over-char-budget` skip reason.",
+ },
+ lanes: {
+ type: "boolean",
+ description:
+ "When true, also return polarity-aware directives, constraints, and consider lanes. Legacy flat `items` remains present.",
+ },
+ cache_stable: {
+ type: "boolean",
+ description:
+ "When true, reorder the selected items by stable id and annotate their original rank.",
+ },
+ dedup_repeated: {
+ type: "boolean",
+ description:
+ "When true, replace repeated context bodies with reference hints to an earlier emitted item.",
+ },
+ attention_flow_ids: {
+ type: "array",
+ items: { type: "string" },
+ description:
+ "Optional declarative attention flow ids to inject as a synthetic context block.",
+ },
+ receipt: {
+ type: "boolean",
+ description: "When true, emit an opt-in context receipt for this context-pack run.",
+ },
+ receipt_host: {
+ type: "string",
+ description: "Optional host/runtime name for emitted receipts; defaults to `mcp`.",
+ },
+ telemetry: {
+ type: "boolean",
+ description:
+ "When true, emit an opt-in recall telemetry record for this context-pack run.",
+ },
+ telemetry_host: {
+ type: "string",
+ description: "Optional host/runtime name for emitted telemetry; defaults to `mcp`.",
+ },
+ session_id: {
+ type: "string",
+ description: "Optional session id recorded on emitted telemetry.",
+ },
+ turn_id: {
+ type: "string",
+ description: "Optional turn id recorded on emitted telemetry.",
+ },
+ },
+ required: ["max_tokens"],
+ additionalProperties: false,
+ },
+ handler: toolBrainContextPack,
+ },
+ {
+ name: "brain_context_receipts",
+ description:
+ "List context receipt summaries or show one full receipt by id. Receipts are append-only continuity records emitted by opt-in context injection callers. Read-only.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["list", "show"],
+ description: "Use list for summaries, show for one full receipt by id.",
+ },
+ id: {
+ type: "string",
+ description: "Receipt id required when operation is show.",
+ },
+ trigger: {
+ type: "string",
+ enum: ["context_pack", "pre_compress"],
+ description: "Optional list filter by injection trigger.",
+ },
+ host: {
+ type: "string",
+ description: "Optional list filter by host/runtime name.",
+ },
+ session_id: {
+ type: "string",
+ description: "Optional list filter by recorded session id.",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ description: "Optional maximum number of summaries to return.",
+ },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainContextReceipts,
+ },
+ {
+ name: "brain_context_presets",
+ description:
+ "Show, suggest, or diff read-only context budget presets. Diagnostics only; never writes configuration.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["show", "suggest", "diff"],
+ description:
+ "show returns presets, suggest chooses by model/window, diff compares current values.",
+ },
+ preset_id: {
+ type: "string",
+ description: "Preset id for show/diff, e.g. tight-context or long-context.",
+ },
+ model: {
+ type: "string",
+ description: "Optional model name hint for suggest.",
+ },
+ context_window_tokens: {
+ type: "integer",
+ minimum: 1,
+ description: "Optional context-window size hint for suggest.",
+ },
+ current: {
+ type: "object",
+ description:
+ "Optional current values for diff: { context_pack, pre_compress, overrides }. Overrides preserve caller-managed paths.",
+ },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainContextPresets,
+ },
+ {
+ // No preview budget: the addendum is meant to be injected whole and
+ // is already bounded by its own per-entry / total character caps.
+ name: "brain_pre_compress_pack",
+ description:
+ "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: {
+ top_k: {
+ type: "integer",
+ minimum: 1,
+ description:
+ "Maximum number of preferences to include, highest-confidence first (default 10).",
+ },
+ max_chars_per_memory: {
+ type: "integer",
+ minimum: 1,
+ description:
+ "Optional per-entry character cap (code points); trimmed entries carry `trimmed: true`.",
+ },
+ max_total_chars: {
+ type: "integer",
+ minimum: 1,
+ description:
+ "Optional total character cap (code points) across the addendum; lowest-priority overflow is dropped.",
+ },
+ receipt: {
+ type: "boolean",
+ description: "When true, emit an opt-in context receipt for this pre-compress run.",
+ },
+ receipt_host: {
+ type: "string",
+ description: "Optional host/runtime name for emitted receipts; defaults to `mcp`.",
+ },
+ telemetry: {
+ type: "boolean",
+ description:
+ "When true, emit an opt-in recall telemetry record for this pre-compress run.",
+ },
+ telemetry_host: {
+ type: "string",
+ description: "Optional host/runtime name for emitted telemetry; defaults to `mcp`.",
+ },
+ session_id: {
+ type: "string",
+ description: "Optional session id recorded on emitted telemetry.",
+ },
+ turn_id: {
+ type: "string",
+ description: "Optional turn id recorded on emitted telemetry.",
+ },
+ },
+ additionalProperties: false,
+ },
+ handler: toolBrainPreCompressPack,
+ },
+ {
+ name: "brain_pre_compact_extract",
+ description:
+ "Extract typed Decision/Commitment/Outcome/Rule/Open question records from bounded text into continuity storage.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ session_id: {
+ type: "string",
+ description: "Session identifier used for idempotency and source refs.",
+ },
+ turn_start: {
+ type: "string",
+ description: "First source turn id in the extracted segment.",
+ },
+ turn_end: {
+ type: "string",
+ description: "Last source turn id in the extracted segment.",
+ },
+ text: {
+ type: "string",
+ description: "Bounded text segment to scan for labeled extraction lines.",
+ },
+ host: { type: "string", description: "Optional host/client label." },
+ max_chars: {
+ type: "integer",
+ minimum: 1,
+ description: "Optional maximum input characters to scan before extracting.",
+ },
+ },
+ required: ["session_id", "turn_start", "turn_end", "text"],
+ additionalProperties: false,
+ },
+ handler: toolBrainPreCompactExtract,
+ },
+]);
diff --git a/src/mcp/brain/procedure-tools.ts b/src/mcp/brain/procedure-tools.ts
new file mode 100644
index 00000000..b32d6535
--- /dev/null
+++ b/src/mcp/brain/procedure-tools.ts
@@ -0,0 +1,296 @@
+/**
+ * Procedural memory: skill proposals, procedural reconcile, recurrence diagnostics, and the procedural graph.
+ *
+ * Extracted from the former brain-tools.ts monolith; registration
+ * happens through the aggregator, which preserves the public
+ * BRAIN_TOOLS surface.
+ */
+
+import { join } from "node:path";
+import {
+ acceptSkillProposal,
+ learnSkillProposals,
+ listPendingSkillProposals,
+ rejectSkillProposal,
+} from "../../core/brain/skill-proposals.ts";
+import {
+ listProceduralMemory,
+ markProceduralMemoryUsed,
+ reconcileProceduralMemory,
+} from "../../core/brain/procedural-memory.ts";
+import { readProceduralGraph, rebuildProceduralGraph } from "../../core/brain/procedural-graph.ts";
+import { readProceduralHints, rebuildProceduralHints } from "../../core/brain/procedural-hints.ts";
+import {
+ applyRecurrenceEvidence,
+ getRecurrenceEntry,
+ listRecurrenceEntries,
+ purgeRecurrenceSource,
+} from "../../core/brain/recurrence.ts";
+import { INVALID_PARAMS, MCPError } from "../protocol.ts";
+import type { ServerContext, ToolDefinition } from "../tools.ts";
+import { coerceStrList } from "../coerce.ts";
+import { optionalPositiveInt, optionalStringArg, requiredStringArg } from "./shared.ts";
+
+async function toolBrainSkillProposals(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const operation = requiredStringArg("brain_skill_proposals", args, "operation");
+ if (operation === "learn") {
+ const minSupport = optionalPositiveInt(args, "min_support", "brain_skill_proposals");
+ const result =
+ minSupport !== undefined
+ ? learnSkillProposals(ctx.vault, { minSupport })
+ : learnSkillProposals(ctx.vault);
+ return { ...result };
+ }
+ if (operation === "list") {
+ const proposals = listPendingSkillProposals(ctx.vault);
+ return { total: proposals.length, proposals };
+ }
+ if (operation === "accept") {
+ const slug = requiredStringArg("brain_skill_proposals", args, "slug");
+ const note = optionalStringArg("brain_skill_proposals", args, "note");
+ const reviewed = note
+ ? acceptSkillProposal(ctx.vault, slug, { note })
+ : acceptSkillProposal(ctx.vault, slug);
+ return { ...reviewed };
+ }
+ if (operation === "reject") {
+ const slug = requiredStringArg("brain_skill_proposals", args, "slug");
+ const note = requiredStringArg("brain_skill_proposals", args, "note");
+ const reviewed = rejectSkillProposal(ctx.vault, slug, { note });
+ return { ...reviewed };
+ }
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_skill_proposals: operation must be one of learn|list|accept|reject",
+ );
+}
+
+async function toolBrainProceduralMemory(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const operation = requiredStringArg("brain_procedural_memory", args, "operation");
+ if (operation === "reconcile") {
+ const roots = coerceStrList(args, "roots");
+ const effectiveRoots =
+ roots.length > 0
+ ? roots
+ : [
+ join(ctx.vault, "Brain", "procedures"),
+ join(ctx.vault, "skills"),
+ join(ctx.vault, "runbooks"),
+ ];
+ return {
+ ...reconcileProceduralMemory(ctx.vault, { roots: effectiveRoots }),
+ };
+ }
+ if (operation === "list") {
+ const entries = listProceduralMemory(ctx.vault);
+ return { total: entries.length, entries };
+ }
+ if (operation === "mark_used") {
+ const id = requiredStringArg("brain_procedural_memory", args, "id");
+ const updated = markProceduralMemoryUsed(ctx.vault, id);
+ if (!updated) {
+ throw new MCPError(INVALID_PARAMS, `brain_procedural_memory: unknown entry id: ${id}`);
+ }
+ return { ...updated };
+ }
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_procedural_memory: operation must be one of reconcile|list|mark_used",
+ );
+}
+
+async function toolBrainRecurrence(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const operation = requiredStringArg("brain_recurrence", args, "operation");
+ if (operation === "list") {
+ const entries = listRecurrenceEntries(ctx.vault);
+ return { total: entries.length, entries };
+ }
+ if (operation === "show") {
+ const contentHash = requiredStringArg("brain_recurrence", args, "content_hash");
+ const entry = getRecurrenceEntry(ctx.vault, contentHash);
+ if (!entry) {
+ throw new MCPError(INVALID_PARAMS, `brain_recurrence: unknown content hash: ${contentHash}`);
+ }
+ return { ...entry };
+ }
+ if (operation === "learn" || operation === "forget") {
+ const contentHash = requiredStringArg("brain_recurrence", args, "content_hash");
+ const scope = requiredStringArg("brain_recurrence", args, "scope");
+ const sourceId = requiredStringArg("brain_recurrence", args, "source_id");
+ const entry = applyRecurrenceEvidence(ctx.vault, {
+ contentHash,
+ scope,
+ sourceId,
+ action: operation,
+ });
+ return { operation, entry };
+ }
+ if (operation === "purge_source") {
+ const sourceId = requiredStringArg("brain_recurrence", args, "source_id");
+ purgeRecurrenceSource(ctx.vault, sourceId);
+ return { ok: true, source_id: sourceId };
+ }
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_recurrence: operation must be one of list|show|learn|forget|purge_source",
+ );
+}
+
+async function toolBrainProceduralGraph(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const operation = requiredStringArg("brain_procedural_graph", args, "operation");
+ if (operation === "rebuild") {
+ const graph = rebuildProceduralGraph(ctx.vault);
+ const hints = rebuildProceduralHints(ctx.vault, { graph });
+ return {
+ operation,
+ graph: {
+ nodes: graph.nodes.length,
+ edges: graph.edges.length,
+ generated_at: graph.generated_at,
+ },
+ hints: {
+ entries: hints.entries.length,
+ generated_at: hints.generated_at,
+ },
+ };
+ }
+ if (operation === "show") {
+ const graph = readProceduralGraph(ctx.vault);
+ if (!graph) {
+ throw new MCPError(INVALID_PARAMS, "brain_procedural_graph: graph projection not found");
+ }
+ return { ...graph };
+ }
+ if (operation === "hints") {
+ const hints = readProceduralHints(ctx.vault);
+ if (!hints) {
+ throw new MCPError(INVALID_PARAMS, "brain_procedural_graph: hints projection not found");
+ }
+ return { ...hints };
+ }
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_procedural_graph: operation must be one of rebuild|show|hints",
+ );
+}
+
+export const PROCEDURE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
+ {
+ name: "brain_skill_proposals",
+ description:
+ "Learn/list/review deterministic skill proposals from continuity records (learn, list, accept, reject).",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["learn", "list", "accept", "reject"],
+ description: "Tool operation.",
+ },
+ min_support: {
+ type: "integer",
+ minimum: 1,
+ description: "Optional minimum evidence support for learn.",
+ },
+ slug: {
+ type: "string",
+ description: "Proposal slug for accept/reject.",
+ },
+ note: {
+ type: "string",
+ description: "Optional review note; required for reject.",
+ },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainSkillProposals,
+ },
+ {
+ name: "brain_procedural_memory",
+ description:
+ "Reconcile/list procedural memory index and update usage sidecar (reconcile, list, mark_used).",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["reconcile", "list", "mark_used"],
+ description: "Tool operation.",
+ },
+ roots: {
+ type: "array",
+ items: { type: "string" },
+ description: "Optional root directories for reconcile.",
+ },
+ id: {
+ type: "string",
+ description: "Procedural entry id for mark_used.",
+ },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainProceduralMemory,
+ },
+ {
+ name: "brain_recurrence",
+ description:
+ "Inspect and update recurrence/support diagnostics (list, show, learn, forget, purge_source).",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["list", "show", "learn", "forget", "purge_source"],
+ description: "Tool operation.",
+ },
+ content_hash: {
+ type: "string",
+ description: "Content hash for show/learn/forget.",
+ },
+ scope: {
+ type: "string",
+ description: "Scope for learn/forget.",
+ },
+ source_id: {
+ type: "string",
+ description: "Source id for learn/forget/purge_source.",
+ },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainRecurrence,
+ },
+ {
+ name: "brain_procedural_graph",
+ description:
+ "Rebuild/show procedural graph projection and prospective hint projection (rebuild, show, hints).",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["rebuild", "show", "hints"],
+ description: "Tool operation.",
+ },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainProceduralGraph,
+ },
+]);
diff --git a/src/mcp/brain/query-tools.ts b/src/mcp/brain/query-tools.ts
new file mode 100644
index 00000000..02d0e11c
--- /dev/null
+++ b/src/mcp/brain/query-tools.ts
@@ -0,0 +1,633 @@
+/**
+ * Read-only lookups: preference/topic/log queries, per-agent views, backlinks, audit trail, sources dashboard, and unlinked mentions.
+ *
+ * Extracted from the former brain-tools.ts monolith; registration
+ * happens through the aggregator, which preserves the public
+ * BRAIN_TOOLS surface.
+ */
+
+import { buildBacklinkIndex } from "../../core/brain/backlinks.ts";
+import { readPrefAudit } from "../../core/brain/pref-audit.ts";
+import { aggregateSources } from "../../core/brain/portability/sources.ts";
+import { findUnlinkedMentions } from "../../core/brain/link-graph/unlinked-mentions.ts";
+import { normaliseWikilinkTarget } from "../../core/brain/wikilink.ts";
+import {
+ BrainNotFoundError,
+ queryByLogSince,
+ queryByPreference,
+ queryByTopic,
+} from "../../core/brain/query.ts";
+import { diffAgentSources, type AgentSourceDiffMode } from "../../core/brain/agent-source/diff.ts";
+import { queryAgentSources } from "../../core/brain/agent-source/query.ts";
+import type { AgentSourceContributionKind } from "../../core/brain/agent-source/types.ts";
+import {
+ type BrainPreference,
+ type BrainRetired,
+ type BrainSignal,
+} from "../../core/brain/types.ts";
+import type { BrainLogEntry } from "../../core/brain/log.ts";
+import { INVALID_PARAMS, MCPError } from "../protocol.ts";
+import type { ServerContext, ToolDefinition } from "../tools.ts";
+import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
+import {
+ coerceStr,
+ coerceStrList,
+ coerceBoolOptional,
+ coerceIsoDate,
+ coerceFormat,
+ coerceInt,
+ coerceStringOptional,
+} from "../coerce.ts";
+import { emitGatedTelemetry } from "../../core/brain/continuity/emit.ts";
+import { emitRecallTelemetry } from "../../core/brain/recall-telemetry.ts";
+
+async function toolBrainQuery(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const preference = coerceStr(args, "preference", false);
+ const topic = coerceStr(args, "topic", false);
+ const since = coerceIsoDate(args, "since");
+ // `format` is accepted for forward-compat (design doc §9.2 names it),
+ // but the structured response shape is identical regardless — the
+ // caller serialises however they want. We validate the value to catch
+ // typos early.
+ coerceFormat(args);
+
+ const supplied = [preference, topic, since].filter((v) => v !== null).length;
+ if (supplied === 0) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_query requires exactly one of: preference, topic, since",
+ );
+ }
+ if (supplied > 1) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_query accepts at most one of: preference, topic, since",
+ );
+ }
+
+ // Recall telemetry (t_405b8053): per-call opt-in mirroring
+ // brain_search. The payload carries the query KIND only - never the
+ // supplied preference id / topic slug / timestamp value.
+ const telemetry = coerceBoolOptional(args, "telemetry") ?? false;
+ const telemetryHost = coerceStringOptional(args, "telemetry_host", 200) ?? "mcp";
+ const telemetrySessionId = coerceStringOptional(args, "session_id", 512);
+ const telemetryTurnId = coerceStringOptional(args, "turn_id", 512);
+ const queryKind = preference !== null ? "preference" : topic !== null ? "topic" : "since";
+ const startedAtMs = Date.now();
+ const emitQueryTelemetry = (status: "ok" | "empty" | "error", resultCount: number): void => {
+ // Lazy emit kernel (t_5d7aa7c5): gate off = thunk never runs; a
+ // throwing continuity write can never fail the query itself.
+ emitGatedTelemetry(telemetry || undefined, () =>
+ emitRecallTelemetry(ctx.vault, {
+ host: telemetryHost,
+ ...(telemetrySessionId !== undefined ? { sessionId: telemetrySessionId } : {}),
+ ...(telemetryTurnId !== undefined ? { turnId: telemetryTurnId } : {}),
+ mode: "query",
+ status,
+ durationMs: Date.now() - startedAtMs,
+ resultCount,
+ gaps:
+ status === "error" ? ["query_error"] : status === "empty" ? ["no_matching_context"] : [],
+ metadata: { query_kind: queryKind },
+ }),
+ );
+ };
+
+ try {
+ if (preference !== null) {
+ try {
+ const res = queryByPreference(ctx.vault, preference);
+ emitQueryTelemetry(res.evidence.length > 0 ? "ok" : "empty", res.evidence.length);
+ return {
+ mode: "preference",
+ preference: serializePreference(res.preference),
+ evidence: res.evidence.map(serializeLogEntry),
+ };
+ } catch (exc) {
+ if (exc instanceof BrainNotFoundError) {
+ throw new Error(exc.message, { cause: exc });
+ }
+ throw exc;
+ }
+ }
+
+ if (topic !== null) {
+ const res = queryByTopic(ctx.vault, topic);
+ const resultCount = res.signals.length + res.all_log_events.length;
+ emitQueryTelemetry(resultCount > 0 ? "ok" : "empty", resultCount);
+ return {
+ mode: "topic",
+ topic,
+ signals: res.signals.map(serializeSignal),
+ preference: res.preference ? serializePreference(res.preference) : null,
+ all_log_events: res.all_log_events.map(serializeLogEntry),
+ };
+ }
+
+ // since
+ const res = queryByLogSince(ctx.vault, since!);
+ emitQueryTelemetry(res.length > 0 ? "ok" : "empty", res.length);
+ return {
+ mode: "since",
+ since: since!.toISOString(),
+ events: res.map(serializeLogEntry),
+ };
+ } catch (exc) {
+ emitQueryTelemetry("error", 0);
+ throw exc;
+ }
+}
+
+// ----- brain_agent_query / brain_agent_diff --------------------------------
+
+async function toolBrainAgentQuery(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const topic = coerceStr(args, "topic", false);
+ const query = coerceStr(args, "query", false);
+ const kind = coerceAgentContributionKind(args, "kind");
+ return queryAgentSources(ctx.vault, {
+ agents: coerceStrList(args, "agents"),
+ ...(topic !== null ? { topic } : {}),
+ ...(query !== null ? { query } : {}),
+ ...(kind !== null ? { kind } : {}),
+ limit: coerceInt(args, "limit", 50, 1, 500),
+ }) as unknown as Record<string, unknown>;
+}
+
+async function toolBrainAgentDiff(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const mode = coerceAgentDiffMode(args, "mode");
+ const topic = coerceStr(args, "topic", false);
+ const query = coerceStr(args, "query", false);
+ const kind = coerceAgentContributionKind(args, "kind");
+ return diffAgentSources(ctx.vault, {
+ ...(mode !== null ? { mode } : {}),
+ agents: coerceStrList(args, "agents"),
+ ...(topic !== null ? { topic } : {}),
+ ...(query !== null ? { query } : {}),
+ ...(kind !== null ? { kind } : {}),
+ limit: coerceInt(args, "limit", 50, 1, 500),
+ }) as unknown as Record<string, unknown>;
+}
+
+function coerceAgentContributionKind(
+ args: Record<string, unknown>,
+ key: string,
+): AgentSourceContributionKind | null {
+ const raw = coerceStr(args, key, false);
+ if (raw === null) return null;
+ if (raw !== "signal" && raw !== "preference" && raw !== "log") {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `argument '${key}' must be 'signal', 'preference', or 'log'`,
+ );
+ }
+ return raw;
+}
+
+function coerceAgentDiffMode(
+ args: Record<string, unknown>,
+ key: string,
+): AgentSourceDiffMode | null {
+ const raw = coerceStr(args, key, false);
+ if (raw === null) return null;
+ if (raw !== "browse" && raw !== "search" && raw !== "diff" && raw !== "map") {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `argument '${key}' must be 'browse', 'search', 'diff', or 'map'`,
+ );
+ }
+ return raw;
+}
+
+// ----- brain_backlinks -----------------------------------------------------
+
+async function toolBrainBacklinks(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const id = coerceStr(args, "id", true)!;
+ // The index is keyed by normalised wikilink targets. Run callers'
+ // input through the same normaliser so `pref-foo`, `[[pref-foo]]`,
+ // `[[pref-foo|Alias]]`, and `Brain/preferences/pref-foo.md` all
+ // resolve to the same lookup.
+ const target = normaliseWikilinkTarget(id);
+ const index = buildBacklinkIndex(ctx.vault);
+ const refs = index.get(target) ?? [];
+ return {
+ id: target,
+ count: refs.length,
+ refs: refs.map((r) => ({
+ source: r.source,
+ source_kind: r.sourceKind,
+ field: r.field,
+ ...(r.timestamp !== undefined ? { timestamp: r.timestamp } : {}),
+ })),
+ };
+}
+
+async function toolBrainAudit(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const raw = coerceStr(args, "pref_id", true)!;
+ // The trail is keyed by the original `pref-<slug>` id. Run the input
+ // through the shared wikilink normaliser first (handles `[[id]]`,
+ // `[[id|Alias]]`, and `Brain/.../id.md` forms), then strip the
+ // pref-/ret- prefix so every reference resolves to one trail.
+ const slug = normaliseWikilinkTarget(raw)
+ .replace(/^(?:pref-|ret-)/, "")
+ .trim();
+ if (slug.length === 0) {
+ throw new Error(`brain_audit: empty preference slug after normalising '${raw}'`);
+ }
+ const prefId = `pref-${slug}`;
+ const { records, warnings } = readPrefAudit(ctx.vault, prefId);
+ return {
+ pref_id: prefId,
+ count: records.length,
+ records,
+ warnings: warnings.map((w) => w.message),
+ };
+}
+
+async function toolBrainSources(
+ ctx: ServerContext,
+ _args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ void _args;
+ const report = aggregateSources(ctx.vault);
+ return {
+ sources: report.sources,
+ total_active: report.total_active,
+ total_processed: report.total_processed,
+ };
+}
+
+/**
+ * Raw-text mentions of a target's title / aliases that are NOT
+ * already inside `[[...]]` wikilinks. Read-only walker over
+ * `Brain/preferences/` and `Brain/retired/`. Match boundary is
+ * Unicode-aware (`\p{L}`, `\p{N}`), language-agnostic.
+ */
+async function toolBrainUnlinkedMentions(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const idRaw = args["id"];
+ if (typeof idRaw !== "string" || idRaw.trim().length === 0) {
+ throw new MCPError(INVALID_PARAMS, "brain_unlinked_mentions: id must be a non-empty string");
+ }
+ const targetId = normaliseWikilinkTarget(idRaw);
+ // Limit coercion mirrors the v0.10.16 `brain_operator_summary`
+ // precedent: accept either a number or a strict integer-literal
+ // string (`"5"` ok; `"abc"`, `"3abc"`, `"2.5"` rejected). This
+ // keeps the MCP boundary uniform across new tools.
+ const limitRaw = args["limit"];
+ let limit: number | undefined;
+ if (limitRaw !== undefined && limitRaw !== null) {
+ if (typeof limitRaw === "number") {
+ if (!Number.isInteger(limitRaw) || limitRaw < 1) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_unlinked_mentions: limit must be a positive integer",
+ );
+ }
+ limit = limitRaw;
+ } else if (typeof limitRaw === "string") {
+ const trimmed = limitRaw.trim();
+ if (trimmed === "" || !/^[0-9]+$/.test(trimmed)) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_unlinked_mentions: limit must be a positive integer",
+ );
+ }
+ const parsed = Number.parseInt(trimmed, 10);
+ if (parsed < 1) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_unlinked_mentions: limit must be a positive integer",
+ );
+ }
+ limit = parsed;
+ } else {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_unlinked_mentions: limit must be a positive integer",
+ );
+ }
+ }
+ const mentions = findUnlinkedMentions(ctx.vault, targetId, limit !== undefined ? { limit } : {});
+ return {
+ vault_path: ctx.vault,
+ target_id: targetId,
+ mentions: mentions.map((m) => ({
+ source: m.source,
+ line: m.line,
+ term: m.term,
+ context: m.contextSnippet,
+ })),
+ };
+}
+
+// ----- brain_foresight (t_08a79c81) -----------------------------------------
+
+function serializeSignal(s: BrainSignal): Record<string, unknown> {
+ return {
+ kind: s.kind,
+ id: s.id,
+ created_at: s.created_at,
+ topic: s.topic,
+ signal: s.signal,
+ agent: s.agent,
+ principle: s.principle,
+ tags: [...s.tags],
+ ...(s.scope !== undefined ? { scope: s.scope } : {}),
+ ...(s.source !== undefined ? { source: [...s.source] } : {}),
+ ...(s.raw !== undefined ? { raw: s.raw } : {}),
+ };
+}
+
+function serializePreference(p: BrainPreference | BrainRetired): Record<string, unknown> {
+ if (p.kind === "brain-retired") {
+ return {
+ kind: p.kind,
+ id: p.id,
+ status: p.status,
+ retired_at: p.retired_at,
+ retired_reason: p.retired_reason,
+ retired_by: p.retired_by,
+ ...(p.superseded_by !== undefined ? { superseded_by: p.superseded_by } : {}),
+ created_at: p.created_at,
+ topic: p.topic,
+ ...(p.scope !== undefined ? { scope: p.scope } : {}),
+ principle: p.principle,
+ evidenced_by: [...p.evidenced_by],
+ applied_count: p.applied_count,
+ violated_count: p.violated_count,
+ last_evidence_at: p.last_evidence_at,
+ confidence: p.confidence,
+ confidence_value: p.confidence_value,
+ pinned: p.pinned,
+ tags: [...p.tags],
+ ...(p.aliases !== undefined ? { aliases: [...p.aliases] } : {}),
+ };
+ }
+ return {
+ kind: p.kind,
+ id: p.id,
+ created_at: p.created_at,
+ confirmed_at: p.confirmed_at,
+ unconfirmed_until: p.unconfirmed_until,
+ topic: p.topic,
+ ...(p.scope !== undefined ? { scope: p.scope } : {}),
+ status: p.status,
+ principle: p.principle,
+ evidenced_by: [...p.evidenced_by],
+ applied_count: p.applied_count,
+ violated_count: p.violated_count,
+ last_evidence_at: p.last_evidence_at,
+ confidence: p.confidence,
+ confidence_value: p.confidence_value,
+ pinned: p.pinned,
+ tags: [...p.tags],
+ ...(p.supersedes !== undefined ? { supersedes: p.supersedes } : {}),
+ ...(p.aliases !== undefined ? { aliases: [...p.aliases] } : {}),
+ };
+}
+
+function serializeLogEntry(e: BrainLogEntry): Record<string, unknown> {
+ // Preserve the structured payload verbatim (array values stay arrays).
+ // JSON.stringify handles `ReadonlyArray<string>` and string values
+ // identically. `Object.entries` widens the value type to `unknown` for
+ // generic-keyed records under `verbatimModuleSyntax`; narrow explicitly.
+ const body: Record<string, string | ReadonlyArray<string>> = {};
+ for (const [k, v] of Object.entries(e.body) as ReadonlyArray<
+ readonly [string, string | ReadonlyArray<string>]
+ >) {
+ body[k] = Array.isArray(v) ? [...v] : v;
+ }
+ return {
+ timestamp: e.timestamp,
+ event_type: e.eventType,
+ body,
+ };
+}
+
+// ----- Misc ----------------------------------------------------------------
+
+const BRAIN_QUERY_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {
+ type: "object",
+ required: ["mode"],
+ properties: {
+ mode: { type: "string", enum: ["preference", "topic", "since"] },
+ },
+};
+
+// ----- brain_operator_summary (v0.10.16) -----------------------------------
+
+export const QUERY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
+ {
+ 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: {
+ type: "object",
+ properties: {
+ preference: {
+ type: "string",
+ description:
+ "Preference id (`pref-...` or `ret-...`) to look up with its evidence trail.",
+ },
+ topic: {
+ type: "string",
+ description: "Topic slug to aggregate signals + active/retired preference + log events.",
+ },
+ since: {
+ type: "string",
+ description: "ISO-8601 timestamp; returns every Brain log event with timestamp >= since.",
+ },
+ format: {
+ type: "string",
+ enum: ["markdown", "json"],
+ description:
+ "Reserved for forward-compat; the structured response is the same regardless.",
+ },
+ telemetry: {
+ type: "boolean",
+ description:
+ "Opt-in recall telemetry: emit one continuity record (mode 'query', kind-only payload) for this call.",
+ },
+ telemetry_host: { type: "string", maxLength: 200 },
+ session_id: { type: "string", maxLength: 512 },
+ turn_id: { type: "string", maxLength: 512 },
+ },
+ additionalProperties: false,
+ },
+ outputSchema: BRAIN_QUERY_OUTPUT_SCHEMA,
+ handler: toolBrainQuery,
+ },
+ {
+ 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: {
+ type: "object",
+ properties: {
+ agents: {
+ type: "array",
+ items: { type: "string" },
+ description: "Agent ids to query. Omit or pass [] to query all known agents.",
+ },
+ topic: {
+ type: "string",
+ description: "Exact Brain topic filter.",
+ },
+ query: {
+ type: "string",
+ description:
+ "Case-insensitive substring matched against deterministic contribution text.",
+ },
+ kind: {
+ type: "string",
+ enum: ["signal", "preference", "log"],
+ description: "Contribution kind filter.",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ maximum: 500,
+ description: "Maximum contributions returned. Defaults to 50.",
+ },
+ },
+ additionalProperties: false,
+ },
+ handler: toolBrainAgentQuery,
+ },
+ {
+ name: "brain_agent_diff",
+ description:
+ "Read-only comparison between source agents using the same provenance foundation as brain_agent_query. Supports browse, search, diff, and map modes.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ enum: ["browse", "search", "diff", "map"],
+ description:
+ "Comparison mode. Defaults to search when query is supplied, otherwise browse.",
+ },
+ agents: {
+ type: "array",
+ items: { type: "string" },
+ description: "Agent ids to compare. Omit or pass [] to compare all known agents.",
+ },
+ topic: {
+ type: "string",
+ description: "Exact Brain topic filter.",
+ },
+ query: {
+ type: "string",
+ description:
+ "Case-insensitive substring matched against deterministic contribution text.",
+ },
+ kind: {
+ type: "string",
+ enum: ["signal", "preference", "log"],
+ description: "Contribution kind filter.",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ maximum: 500,
+ description: "Maximum contributions returned before comparison. Defaults to 50.",
+ },
+ },
+ additionalProperties: false,
+ },
+ handler: toolBrainAgentDiff,
+ },
+ {
+ 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: {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ description:
+ "Target id (e.g. `pref-foo`, `ret-bar`, `sig-2026-05-14-baz`). Wikilink decoration is stripped if present.",
+ },
+ },
+ required: ["id"],
+ additionalProperties: false,
+ },
+ handler: toolBrainBacklinks,
+ },
+ {
+ 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 revisions. Accepts pref-/ret-/bare/wikilink ids. Read-only.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ pref_id: {
+ type: "string",
+ description:
+ "Preference id (e.g. `pref-foo`). `ret-foo`, bare `foo`, and `[[pref-foo]]` all resolve to the same trail.",
+ },
+ },
+ required: ["pref_id"],
+ additionalProperties: false,
+ },
+ handler: toolBrainAudit,
+ },
+ {
+ name: "brain_sources",
+ description:
+ "Read-only dashboard of the brain's signals grouped by (agent, source_type) with active/processed and distinct-topic counts plus totals.",
+ inputSchema: {
+ type: "object",
+ properties: {},
+ additionalProperties: false,
+ },
+ handler: toolBrainSources,
+ },
+ {
+ 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: {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ description:
+ "Target id (e.g. `pref-foo`, `ret-bar`). Wikilink decoration is stripped if present.",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ description:
+ "Maximum number of mentions to return. Defaults to 100; the scanner stops as soon as the cap is hit.",
+ },
+ },
+ required: ["id"],
+ additionalProperties: false,
+ },
+ handler: toolBrainUnlinkedMentions,
+ },
+]);
diff --git a/src/mcp/brain/recall-tools.ts b/src/mcp/brain/recall-tools.ts
new file mode 100644
index 00000000..9bb5f285
--- /dev/null
+++ b/src/mcp/brain/recall-tools.ts
@@ -0,0 +1,441 @@
+/**
+ * Recall quality: benchmark, self-tuning, recall telemetry, and imported-session recall (grep/describe/expand).
+ *
+ * Extracted from the former brain-tools.ts monolith; registration
+ * happens through the aggregator, which preserves the public
+ * BRAIN_TOOLS surface.
+ */
+
+import { resolveSearchConfig } from "../../core/search/index.ts";
+import { appendMetric } from "../../core/brain/metrics.ts";
+import { parseRecallBenchmarkDataset, runRecallBenchmark } from "../../core/search/benchmark.ts";
+import { loadTunedParameters, resetTuning, tuneRecall } from "../../core/search/tuning.ts";
+import { listGateTelemetry, summarizeGateTelemetry } from "../../core/brain/gate-telemetry.ts";
+import {
+ isRecallTelemetryMode,
+ isRecallTelemetryStatus,
+ listRecallTelemetry,
+ summarizeRecallTelemetry,
+ type RecallTelemetryFilter,
+ type RecallTelemetryMode,
+ type RecallTelemetryStatus,
+} from "../../core/brain/recall-telemetry.ts";
+import {
+ describeSessionRecall,
+ expandSessionRecall,
+ searchSessionRecall,
+} from "../../core/brain/session-recall.ts";
+import { isoSecond } from "../../core/brain/time.ts";
+import { INVALID_PARAMS, MCPError } from "../protocol.ts";
+import type { ServerContext, ToolDefinition } from "../tools.ts";
+import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
+import { coercePositiveInteger, optionalStringArg, requiredStringArg } from "./shared.ts";
+
+/** Recall-quality benchmark over an inline dataset. */
+async function toolBrainBenchmark(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const op = args["operation"];
+ if (op !== "run") {
+ throw new MCPError(INVALID_PARAMS, "brain_benchmark: operation must be run");
+ }
+ const k = args["k"];
+ if (k !== undefined && (!Number.isInteger(k) || (k as number) < 1)) {
+ throw new MCPError(INVALID_PARAMS, "brain_benchmark run: k must be a positive integer");
+ }
+ let dataset;
+ try {
+ dataset = parseRecallBenchmarkDataset(args["dataset"]);
+ } catch (exc) {
+ throw new MCPError(INVALID_PARAMS, `brain_benchmark run: ${(exc as Error).message}`);
+ }
+ const searchConfig = resolveSearchConfig({
+ vault: ctx.vault,
+ configPath: ctx.configPath ?? undefined,
+ });
+ const now = new Date();
+ const report = await runRecallBenchmark(searchConfig, dataset, {
+ ...(k !== undefined ? { k: k as number } : {}),
+ expand: args["expand"] === true,
+ });
+ try {
+ appendMetric(ctx.vault, {
+ surface: "recall_benchmark",
+ runAt: isoSecond(now),
+ payload: {
+ total: report.total,
+ k: report.k,
+ expand: report.expand,
+ hit_at_k: report.hitAtK,
+ mrr: report.mrr,
+ misses: report.perQuery.filter((q) => !q.hit).map((q) => q.id),
+ },
+ });
+ } catch {
+ // Metrics are observability, not correctness.
+ }
+ return {
+ total: report.total,
+ k: report.k,
+ expand: report.expand,
+ hit_at_k: report.hitAtK,
+ mrr: report.mrr,
+ per_query: report.perQuery,
+ };
+}
+
+// ----- brain_tune (t_ae973491) -------------------------------------------------
+
+/** Opt-in self-tuning recall: run the grid, inspect, or reset. */
+async function toolBrainTune(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const op = args["operation"];
+ if (op !== "run" && op !== "status" && op !== "reset") {
+ throw new MCPError(INVALID_PARAMS, "brain_tune: operation must be run|status|reset");
+ }
+ const searchConfig = resolveSearchConfig({
+ vault: ctx.vault,
+ configPath: ctx.configPath ?? undefined,
+ });
+ if (op === "status") {
+ return {
+ enabled: searchConfig.recall.selfTuningEnabled,
+ tuned: loadTunedParameters(ctx.vault),
+ };
+ }
+ if (op === "reset") {
+ return { removed: resetTuning(ctx.vault) };
+ }
+ const k = args["k"];
+ if (k !== undefined && (!Number.isInteger(k) || (k as number) < 1)) {
+ throw new MCPError(INVALID_PARAMS, "brain_tune run: k must be a positive integer");
+ }
+ let dataset;
+ try {
+ dataset = parseRecallBenchmarkDataset(args["dataset"]);
+ } catch (exc) {
+ throw new MCPError(INVALID_PARAMS, `brain_tune run: ${(exc as Error).message}`);
+ }
+ const now = new Date();
+ const report = await tuneRecall(searchConfig, dataset, {
+ ...(k !== undefined ? { k: k as number } : {}),
+ now,
+ });
+ try {
+ appendMetric(ctx.vault, {
+ surface: "self_tuning",
+ runAt: isoSecond(now),
+ payload: {
+ chosen: report.chosen,
+ evaluated: report.evaluated.length,
+ best_mrr: Math.max(...report.evaluated.map((e) => e.mrr)),
+ dataset_hash: report.datasetHash,
+ },
+ });
+ } catch {
+ // Metrics are observability, not correctness.
+ }
+ return {
+ chosen: report.chosen,
+ evaluated: report.evaluated.map((e) => ({ params: e.params, mrr: e.mrr, hit_at_k: e.hitAtK })),
+ dataset_hash: report.datasetHash,
+ };
+}
+
+// ----- brain_dead_ends (t_be62c62d) -----------------------------------------
+
+async function toolBrainRecallTelemetry(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const operation = optionalStringArg("brain_recall_telemetry", args, "operation");
+ const filter = recallTelemetryFilter(args);
+
+ if (operation === "list") {
+ const records = listRecallTelemetry(ctx.vault, filter);
+ return { vault_path: ctx.vault, total: records.length, records };
+ }
+ if (operation === "summary") {
+ const summary = summarizeRecallTelemetry(ctx.vault, filter);
+ return { ...summary };
+ }
+ // Gate-decision telemetry (Workspace Insight Suite, t_65036e02):
+ // records emitted by brain_recall_gate when recall_gate_telemetry is on.
+ if (operation === "gate_list") {
+ const records = listGateTelemetry(ctx.vault, {
+ ...(filter.host !== undefined ? { host: filter.host } : {}),
+ ...(filter.since !== undefined ? { since: filter.since } : {}),
+ ...(filter.until !== undefined ? { until: filter.until } : {}),
+ ...(filter.limit !== undefined ? { limit: filter.limit } : {}),
+ });
+ return { vault_path: ctx.vault, total: records.length, records };
+ }
+ if (operation === "gate_summary") {
+ const summary = summarizeGateTelemetry(ctx.vault, {
+ ...(filter.host !== undefined ? { host: filter.host } : {}),
+ ...(filter.since !== undefined ? { since: filter.since } : {}),
+ ...(filter.until !== undefined ? { until: filter.until } : {}),
+ });
+ return { ...summary };
+ }
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_recall_telemetry: operation must be list, summary, gate_list, or gate_summary",
+ );
+}
+
+function recallTelemetryFilter(args: Record<string, unknown>): RecallTelemetryFilter {
+ const mode = coerceRecallTelemetryMode(args["mode"]);
+ const status = coerceRecallTelemetryStatus(args["status"]);
+ const host = optionalStringArg("brain_recall_telemetry", args, "host");
+ const since = optionalStringArg("brain_recall_telemetry", args, "since");
+ const until = optionalStringArg("brain_recall_telemetry", args, "until");
+ const limit = coercePositiveInteger("brain_recall_telemetry", "limit", args["limit"]);
+ return {
+ ...(mode !== undefined ? { mode } : {}),
+ ...(status !== undefined ? { status } : {}),
+ ...(host !== undefined ? { host } : {}),
+ ...(since !== undefined ? { since } : {}),
+ ...(until !== undefined ? { until } : {}),
+ ...(limit !== undefined ? { limit } : {}),
+ };
+}
+
+function coerceRecallTelemetryMode(raw: unknown): RecallTelemetryMode | undefined {
+ if (raw === undefined || raw === null) return undefined;
+ const trimmed = typeof raw === "string" ? raw.trim() : raw;
+ if (!isRecallTelemetryMode(trimmed)) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_recall_telemetry: mode must be search, context_pack, or pre_compress",
+ );
+ }
+ return trimmed;
+}
+
+function coerceRecallTelemetryStatus(raw: unknown): RecallTelemetryStatus | undefined {
+ if (raw === undefined || raw === null) return undefined;
+ const trimmed = typeof raw === "string" ? raw.trim() : raw;
+ if (!isRecallTelemetryStatus(trimmed)) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_recall_telemetry: status must be ok, empty, error, or timeout",
+ );
+ }
+ return trimmed;
+}
+
+// ----- brain_context_presets ----------------------------------------------
+
+async function toolBrainSessionGrep(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const limit = coercePositiveInteger("brain_session_grep", "limit", args["limit"]);
+ const snippetChars = coercePositiveInteger(
+ "brain_session_grep",
+ "snippet_chars",
+ args["snippet_chars"],
+ );
+ return {
+ ...searchSessionRecall(ctx.vault, {
+ query: requiredStringArg("brain_session_grep", args, "query"),
+ ...(optionalStringArg("brain_session_grep", args, "session_id") !== undefined
+ ? {
+ sessionId: optionalStringArg("brain_session_grep", args, "session_id"),
+ }
+ : {}),
+ ...(limit !== undefined ? { limit } : {}),
+ ...(snippetChars !== undefined ? { snippetChars } : {}),
+ }),
+ };
+}
+
+async function toolBrainSessionDescribe(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ return {
+ ...describeSessionRecall(ctx.vault, {
+ sessionId: requiredStringArg("brain_session_describe", args, "session_id"),
+ }),
+ };
+}
+
+async function toolBrainSessionExpand(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const rawLimit = coercePositiveInteger("brain_session_expand", "raw_limit", args["raw_limit"]);
+ return {
+ ...expandSessionRecall(ctx.vault, {
+ id: requiredStringArg("brain_session_expand", args, "id"),
+ ...(rawLimit !== undefined ? { rawLimit } : {}),
+ ...(optionalStringArg("brain_session_expand", args, "cursor") !== undefined
+ ? { cursor: optionalStringArg("brain_session_expand", args, "cursor") }
+ : {}),
+ }),
+ };
+}
+
+// ----- brain_pre_compress_pack (v0.20.0) -----------------------------------
+
+export const RECALL_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
+ {
+ name: "brain_benchmark",
+ description:
+ "Recall-quality benchmark: score the vault's live hybrid recall against a fixed dataset ({queries: [{id, query, expected: [paths]}]}) - hit@k and MRR per query and aggregate - and record one recall_benchmark metric so quality is chartable over time.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: { type: "string", enum: ["run"], description: "Tool operation." },
+ dataset: {
+ type: "object",
+ description: "Benchmark dataset: {queries: [{id, query, expected, k?}]}.",
+ },
+ k: { type: "integer", minimum: 1, description: "Rank depth (default 5)." },
+ expand: { type: "boolean", description: "Route queries through deterministic expansion." },
+ },
+ required: ["operation", "dataset"],
+ additionalProperties: false,
+ },
+ handler: toolBrainBenchmark,
+ previewBudget: MCP_PREVIEW_BUDGET,
+ },
+ {
+ name: "brain_tune",
+ description:
+ "Opt-in self-tuning recall: run grid-evaluates bounded parameters (pool multiplier, traversal depth, learned weights, expansion) against a benchmark dataset and persists the winner to Brain/search/tuning.json; status shows the validated state; reset deletes it. Search honors it only when enabled.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["run", "status", "reset"],
+ description: "Tool operation.",
+ },
+ dataset: { type: "object", description: "Benchmark dataset (run)." },
+ k: { type: "integer", minimum: 1, description: "Rank depth (run, default 5)." },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainTune,
+ previewBudget: MCP_PREVIEW_BUDGET,
+ },
+ {
+ 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: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["list", "summary", "gate_list", "gate_summary"],
+ description:
+ "list/summary for recall telemetry; gate_list/gate_summary for recall-gate decisions.",
+ },
+ mode: {
+ type: "string",
+ enum: ["search", "context_pack", "pre_compress"],
+ description: "Optional filter by recall mode.",
+ },
+ status: {
+ type: "string",
+ enum: ["ok", "empty", "error", "timeout"],
+ description: "Optional filter by telemetry status.",
+ },
+ host: {
+ type: "string",
+ description: "Optional filter by host/runtime name.",
+ },
+ since: {
+ type: "string",
+ description: "Optional inclusive lower timestamp bound.",
+ },
+ until: {
+ type: "string",
+ description: "Optional inclusive upper timestamp bound.",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ description: "Optional maximum record count for list.",
+ },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainRecallTelemetry,
+ },
+ {
+ name: "brain_session_grep",
+ previewBudget: MCP_PREVIEW_BUDGET,
+ description: "Search imported session recall raw turns and summary nodes.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ query: { type: "string", description: "Search text." },
+ session_id: {
+ type: "string",
+ description: "Optional session id filter.",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ description: "Maximum hits to return.",
+ },
+ snippet_chars: {
+ type: "integer",
+ minimum: 1,
+ description: "Maximum chars per hit snippet.",
+ },
+ },
+ required: ["query"],
+ additionalProperties: false,
+ },
+ handler: toolBrainSessionGrep,
+ },
+ {
+ name: "brain_session_describe",
+ description: "Describe counts and summary depths for an imported session recall DAG.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ session_id: { type: "string", description: "Session id to describe." },
+ },
+ required: ["session_id"],
+ additionalProperties: false,
+ },
+ handler: toolBrainSessionDescribe,
+ },
+ {
+ name: "brain_session_expand",
+ previewBudget: MCP_PREVIEW_BUDGET,
+ description:
+ "Expand a session recall raw or summary node to immediate sources and paginated exact raw turn content.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ id: { type: "string", description: "Session recall record id." },
+ raw_limit: {
+ type: "integer",
+ minimum: 1,
+ description: "Maximum raw turn items to return.",
+ },
+ cursor: {
+ type: "string",
+ description: "Raw turn pagination cursor from a previous response.",
+ },
+ },
+ required: ["id"],
+ additionalProperties: false,
+ },
+ handler: toolBrainSessionExpand,
+ },
+]);
diff --git a/src/mcp/brain/review-tools.ts b/src/mcp/brain/review-tools.ts
new file mode 100644
index 00000000..8a870893
--- /dev/null
+++ b/src/mcp/brain/review-tools.ts
@@ -0,0 +1,206 @@
+/**
+ * Lifecycle review: pre-dream intent review, retention lifecycle, dream dry-run preview, and staleness scan.
+ *
+ * Extracted from the former brain-tools.ts monolith; registration
+ * happens through the aggregator, which preserves the public
+ * BRAIN_TOOLS surface.
+ */
+
+import { resolveSearchConfig } from "../../core/search/index.ts";
+import { buildTimelineIndex } from "../../core/brain/temporal/build-index.ts";
+import { findStaleEntries } from "../../core/brain/temporal/stale-watch.ts";
+import { loadTemporalConfigSafe } from "../../core/brain/policy.ts";
+import { buildIntentReview } from "../../core/brain/intent-review.ts";
+import { buildRetentionReview } from "../../core/brain/retention.ts";
+import { buildReviewCandidates } from "../../core/brain/review-candidates.ts";
+import type { ServerContext, ToolDefinition } from "../tools.ts";
+import { coerceIsoDate } from "../coerce.ts";
+
+async function toolBrainIntentReview(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const nowDate = coerceIsoDate(args, "now");
+ const report = buildIntentReview(ctx.vault, nowDate ? { now: nowDate } : {});
+ return {
+ schema_version: report.schema_version,
+ generated_at: report.generated_at,
+ reviews: report.reviews.map((review) => ({
+ topic: review.topic,
+ decision: review.decision,
+ signal_count: review.signal_count,
+ risk_band: review.risk_band,
+ risk_score: review.risk_score,
+ reasons: [...review.reasons],
+ })),
+ };
+}
+
+async function toolBrainRetention(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const nowDate = coerceIsoDate(args, "now");
+ const report = buildRetentionReview(ctx.vault, nowDate ? { now: nowDate } : {});
+ return {
+ schema_version: report.schema_version,
+ generated_at: report.generated_at,
+ summary: report.summary,
+ recommendations: report.recommendations.map((recommendation) => ({
+ id: recommendation.id,
+ artifact_type: recommendation.artifact_type,
+ action: recommendation.action,
+ reason: recommendation.reason,
+ path: recommendation.path,
+ })),
+ };
+}
+
+async function toolBrainReviewCandidates(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const nowDate = coerceIsoDate(args, "now");
+ // Surprisal annotation (t_fddfe64a) is best-effort: a resolvable
+ // search config adds novelty ranking, anything else degrades to the
+ // plain report.
+ let searchConfig: ReturnType<typeof resolveSearchConfig> | undefined;
+ try {
+ searchConfig = resolveSearchConfig({
+ vault: ctx.vault,
+ configPath: ctx.configPath ?? undefined,
+ });
+ } catch {
+ searchConfig = undefined;
+ }
+ const report = await buildReviewCandidates(ctx.vault, {
+ ...(nowDate ? { now: nowDate } : {}),
+ ...(searchConfig !== undefined ? { searchConfig } : {}),
+ });
+ return {
+ ...(report.signal_novelty !== undefined ? { signal_novelty: report.signal_novelty } : {}),
+ would_create: [...report.would_create],
+ would_promote: [...report.would_promote],
+ would_retire: report.would_retire.map((r) => ({
+ id: r.id,
+ reason: r.reason,
+ })),
+ would_supersede: report.would_supersede.map((r) => ({
+ id: r.id,
+ reason: r.reason,
+ })),
+ clusters_below_threshold: report.clusters_below_threshold.map((c) => ({
+ topic: c.topic,
+ signal_count: c.signal_count,
+ distinct_agents: c.distinct_agents,
+ age_days: c.age_days,
+ failed_gates: [...c.failed_gates],
+ })),
+ gated_retires: report.gated_retires.map((g) => ({
+ pref_id: g.pref_id,
+ topic: g.topic,
+ applied_count: g.applied_count,
+ violated_count: g.violated_count,
+ threshold: g.threshold,
+ attempted_reason: g.attempted_reason,
+ })),
+ intent_reviews: report.intent_reviews.map((review) => ({
+ topic: review.topic,
+ decision: review.decision,
+ signal_count: review.signal_count,
+ risk_band: review.risk_band,
+ risk_score: review.risk_score,
+ reasons: [...review.reasons],
+ })),
+ };
+}
+
+// ----- brain_apply_evidence ------------------------------------------------
+
+/**
+ * `brain_stale_scan` - structural staleness report for preferences,
+ * signals, and log files. Thresholds come from the `temporal:` config
+ * block.
+ */
+async function toolBrainStaleScan(
+ ctx: ServerContext,
+ _args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ void _args;
+ const cfg = loadTemporalConfigSafe(ctx.vault);
+ const index = buildTimelineIndex(ctx.vault, {});
+ const report = findStaleEntries(index, ctx.vault, cfg);
+ return {
+ vault_path: ctx.vault,
+ thresholds: report.thresholds,
+ stale_preferences: report.stalePreferences,
+ stale_signals: report.staleSignals,
+ stale_log_files: report.staleLogFiles,
+ generated_at: report.generatedAt,
+ };
+}
+
+export const REVIEW_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
+ {
+ name: "brain_intent_review",
+ description:
+ "Read-only pre-dream intent review over active signal clusters. Returns each topic's decision, signal count, risk band, risk score, and reasons without mutating files.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ now: {
+ type: "string",
+ description:
+ "Optional ISO-8601 timestamp used as the wall clock for the review (testing / replay).",
+ },
+ },
+ additionalProperties: false,
+ },
+ handler: toolBrainIntentReview,
+ },
+ {
+ name: "brain_retention",
+ description:
+ "Recommendation-only lifecycle review over retired preferences and processed signals. Returns keep/improve/park/prune candidates and never deletes or moves artifacts.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ now: {
+ type: "string",
+ description:
+ "Optional ISO-8601 timestamp used as the wall clock for the review (testing / replay).",
+ },
+ },
+ additionalProperties: false,
+ },
+ handler: toolBrainRetention,
+ },
+ {
+ name: "brain_review_candidates",
+ description:
+ "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: {
+ now: {
+ type: "string",
+ description:
+ "Optional ISO-8601 timestamp used as the wall clock for the dry-run (testing / replay).",
+ },
+ },
+ additionalProperties: false,
+ },
+ handler: toolBrainReviewCandidates,
+ },
+ {
+ name: "brain_stale_scan",
+ description:
+ "Structural staleness report: preferences, signals, and Brain/log files inactive longer than the configured `temporal:` thresholds (stale_pref_days / stale_signal_days / stale_log_days). Read-only.",
+ inputSchema: {
+ type: "object",
+ properties: {},
+ additionalProperties: false,
+ },
+ handler: toolBrainStaleScan,
+ },
+]);
diff --git a/src/mcp/brain/shared.ts b/src/mcp/brain/shared.ts
new file mode 100644
index 00000000..f6fac703
--- /dev/null
+++ b/src/mcp/brain/shared.ts
@@ -0,0 +1,201 @@
+/**
+ * Helpers shared by the Brain MCP domain modules: argument
+ * coercion, vault-relative path rendering, and the consolidated
+ * view dispatcher used by brain_brief / brain_analytics.
+ */
+
+import { isAbsolute, relative, resolve } from "node:path";
+import { resolveTimezone } from "../../core/config.ts";
+import { type RecallTelemetryOptions } from "../../core/brain/recall-telemetry.ts";
+import { isoSecond } from "../../core/brain/time.ts";
+import { formatLocalTimestamp } from "../../core/brain/present-time.ts";
+import { INVALID_PARAMS, MCPError } from "../protocol.ts";
+import type { ServerContext } from "../tools.ts";
+import { coerceBool } from "../coerce.ts";
+
+export const ISO_DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
+
+export function coerceIsoTimestampOrDate(
+ tool: string,
+ field: string,
+ raw: unknown,
+ shape: "date-only" | "date-or-timestamp" = "date-or-timestamp",
+): string | undefined {
+ if (raw === undefined || raw === null) return undefined;
+ if (typeof raw !== "string" || raw.trim().length === 0) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `${tool}: ${field} must be an ISO date${shape === "date-or-timestamp" ? " or ISO timestamp" : " (YYYY-MM-DD)"}`,
+ );
+ }
+ const v = raw.trim();
+ if (shape === "date-only" && !ISO_DATE_ONLY_RE.test(v)) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `${tool}: ${field} must be an ISO date (YYYY-MM-DD); got ${JSON.stringify(v)}`,
+ );
+ }
+ // Validate by parsing - rejects "2026-13-99" / "garbage" / etc.
+ const ms = Date.parse(v);
+ if (!Number.isFinite(ms)) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `${tool}: ${field} must be a parseable ISO date${shape === "date-or-timestamp" ? " or timestamp" : ""}; got ${JSON.stringify(v)}`,
+ );
+ }
+ return v;
+}
+
+export function coercePositiveInteger(
+ tool: string,
+ field: string,
+ raw: unknown,
+): number | undefined {
+ if (raw === undefined || raw === null) return undefined;
+ if (typeof raw === "number") {
+ if (!Number.isInteger(raw) || raw < 1) {
+ throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a positive integer`);
+ }
+ return raw;
+ }
+ if (typeof raw === "string") {
+ const trimmed = raw.trim();
+ if (trimmed === "" || !/^[0-9]+$/.test(trimmed)) {
+ throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a positive integer`);
+ }
+ const parsed = Number.parseInt(trimmed, 10);
+ if (parsed < 1) {
+ throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a positive integer`);
+ }
+ return parsed;
+ }
+ throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a positive integer`);
+}
+
+export 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);
+}
+
+/**
+ * Timezone presentation (t_2ccadc6a): when the operator configured an
+ * IANA zone, brief/analytics envelopes gain two ADDITIVE fields - a
+ * `timezone` echo and `local_time` (the render instant in that zone).
+ * Stored timestamps inside the envelope stay canonical UTC; with no
+ * timezone configured the envelope is byte-identical to 0.45.0.
+ */
+export function localizeEnvelope(ctx: ServerContext, result: unknown): unknown {
+ if (result === null || typeof result !== "object" || Array.isArray(result)) return result;
+ const tz = resolveTimezone(ctx.configPath ?? undefined);
+ if (tz === null) return result;
+ return {
+ ...(result as Record<string, unknown>),
+ timezone: tz,
+ local_time: formatLocalTimestamp(isoSecond(new Date()), tz),
+ };
+}
+
+/** Parse an optional positive-integer arg, throwing INVALID_PARAMS otherwise. */
+export function optionalPositiveInt(
+ args: Record<string, unknown>,
+ key: string,
+ tool: string,
+): number | undefined {
+ const raw = args[key];
+ if (raw === undefined) return undefined;
+ const n =
+ typeof raw === "number"
+ ? raw
+ : typeof raw === "string" && /^[0-9]+$/.test(raw.trim())
+ ? Number.parseInt(raw.trim(), 10)
+ : Number.NaN;
+ if (!Number.isInteger(n) || n <= 0) {
+ throw new MCPError(INVALID_PARAMS, `${tool}: ${key} must be a positive integer`);
+ }
+ return n;
+}
+
+export function optionalStringArg(
+ tool: string,
+ args: Record<string, unknown>,
+ key: string,
+): string | undefined {
+ const raw = args[key];
+ if (raw === undefined || raw === null) return undefined;
+ if (typeof raw !== "string" || raw.trim().length === 0) {
+ throw new MCPError(INVALID_PARAMS, `${tool}: ${key} must be a non-empty string`);
+ }
+ return raw.trim();
+}
+
+export function requiredStringArg(
+ tool: string,
+ args: Record<string, unknown>,
+ key: string,
+): string {
+ const value = optionalStringArg(tool, args, key);
+ if (value === undefined) throw new MCPError(INVALID_PARAMS, `${tool}: ${key} is required`);
+ return value;
+}
+
+// ----- brain_recall_telemetry ---------------------------------------------
+
+export function telemetryOptionsFromArgs(
+ tool: string,
+ args: Record<string, unknown>,
+ defaultHost: string,
+): RecallTelemetryOptions | undefined {
+ if (!coerceBool(args, "telemetry")) return undefined;
+ return {
+ host: optionalStringArg(tool, args, "telemetry_host") ?? defaultHost,
+ ...(optionalStringArg(tool, args, "session_id") !== undefined
+ ? { sessionId: optionalStringArg(tool, args, "session_id") }
+ : {}),
+ ...(optionalStringArg(tool, args, "turn_id") !== undefined
+ ? { turnId: optionalStringArg(tool, args, "turn_id") }
+ : {}),
+ };
+}
+
+/**
+ * Produce a vault-relative path, swallowing errors (a defensive pattern
+ * for output rendering). Exported for unit tests
+ * — internal callers stay inside this module.
+ *
+ * @internal
+ */
+export function vaultRelativeSafe(vault: string, target: string): string {
+ const absVault = resolve(vault);
+ const absTarget = resolve(target);
+ // Use Node's path.relative so the separator handling matches the host
+ // OS (forward-slashes on POSIX, back-slashes on Windows). The prior
+ // implementation hard-coded `"/"` and silently broke on Windows when
+ // the vault sat under e.g. `C:\Users\...`.
+ const rel = relative(absVault, absTarget);
+ if (rel === "") return "";
+ // `relative()` returns a path starting with `..` (or, in rare drive-
+ // mismatch cases on Windows, an absolute path) when the target sits
+ // outside the vault. In both situations we return the original target
+ // unchanged — callers treat that as "not under vault" and render it
+ // as-is.
+ if (rel.startsWith("..") || isAbsolute(rel)) return target;
+ return rel;
+}
+
+// ----- Tool registration ---------------------------------------------------
diff --git a/src/mcp/brain/workspace-tools.ts b/src/mcp/brain/workspace-tools.ts
new file mode 100644
index 00000000..1f363b64
--- /dev/null
+++ b/src/mcp/brain/workspace-tools.ts
@@ -0,0 +1,210 @@
+/**
+ * Workspace intent chains and the proactive trigger queue.
+ *
+ * Extracted from the former brain-tools.ts monolith; registration
+ * happens through the aggregator, which preserves the public
+ * BRAIN_TOOLS surface.
+ */
+
+import { resolveAgentName, resolveTriggerCooldownDays } from "../../core/config.ts";
+import { scanTriggers } from "../../core/brain/triggers/scan.ts";
+import { listTriggers, transitionTrigger } from "../../core/brain/triggers/store.ts";
+import { isTriggerStatus, type TriggerRecord } from "../../core/brain/triggers/types.ts";
+import {
+ listIntentions,
+ moveIntentionToHistory,
+ setIntention,
+ showIntention,
+} from "../../core/brain/intentions.ts";
+import { INVALID_PARAMS, MCPError } from "../protocol.ts";
+import type { ServerContext, ToolDefinition } from "../tools.ts";
+import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
+import { coerceStr } from "../coerce.ts";
+
+function toolBrainIntention(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Record<string, unknown> {
+ const operation = coerceStr(args, "operation", true)!;
+ if (operation === "list") {
+ return {
+ intentions: listIntentions(ctx.vault).map((chain) => ({
+ scope: chain.scope,
+ version: chain.version,
+ updated_at: chain.updatedAt,
+ text: chain.text,
+ })),
+ };
+ }
+ const scope = coerceStr(args, "scope", true)!;
+ if (operation === "set") {
+ const text = coerceStr(args, "text", true)!;
+ const chain = setIntention(ctx.vault, {
+ scope,
+ text,
+ agent: resolveAgentName(ctx.configPath ?? undefined),
+ });
+ return { operation, scope: chain.scope, version: chain.version, path: chain.path };
+ }
+ if (operation === "show") {
+ const chain = showIntention(ctx.vault, scope);
+ if (chain === null) return { operation, scope, present: false };
+ return {
+ operation,
+ scope: chain.scope,
+ present: true,
+ version: chain.version,
+ updated_at: chain.updatedAt,
+ text: chain.text,
+ history: chain.history,
+ path: chain.path,
+ };
+ }
+ if (operation === "move") {
+ const moved = moveIntentionToHistory(ctx.vault, { scope });
+ return { operation, scope: moved.scope, archive_path: moved.archivePath };
+ }
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_intention operation must be one of: set, show, list, move",
+ );
+}
+
+// ----- brain_trigger (Workspace Insight Suite) ------------------------------
+
+function triggerToJson(record: TriggerRecord): Record<string, unknown> {
+ return {
+ id: record.id,
+ kind: record.kind,
+ status: record.effectiveStatus,
+ urgency: record.urgency,
+ reason: record.reason,
+ suggested_action: record.suggestedAction,
+ source_artifacts: record.sourceArtifacts,
+ cooldown_key: record.cooldownKey,
+ created_at: record.createdAt,
+ expires_at: record.expiresAt,
+ delivered_at: record.deliveredAt,
+ resolved_at: record.resolvedAt,
+ };
+}
+
+const TRIGGER_TERMINAL = new Set(["acted", "dismissed", "expired"]);
+
+function toolBrainTrigger(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Record<string, unknown> {
+ const operation = coerceStr(args, "operation", true)!;
+ const now = new Date();
+ if (operation === "scan") {
+ const cooldownDays = resolveTriggerCooldownDays(ctx.configPath ?? undefined);
+ const result = scanTriggers(ctx.vault, { now, cooldownDays });
+ return {
+ operation,
+ candidates: result.candidates,
+ created: result.created.map(triggerToJson),
+ skipped: result.skipped.map((skip) => ({
+ cooldown_key: skip.cooldownKey,
+ reason: skip.reason,
+ })),
+ };
+ }
+ if (operation === "list" || operation === "history") {
+ const statusRaw = coerceStr(args, "status", false);
+ if (statusRaw !== null && statusRaw !== undefined && !isTriggerStatus(statusRaw)) {
+ throw new MCPError(INVALID_PARAMS, `brain_trigger: unknown status '${statusRaw}'`);
+ }
+ let records = listTriggers(ctx.vault, {
+ now,
+ ...(statusRaw ? { status: statusRaw } : {}),
+ });
+ if (operation === "history") {
+ records = records.filter((record) => TRIGGER_TERMINAL.has(record.effectiveStatus));
+ } else if (!statusRaw) {
+ records = records.filter((record) => !TRIGGER_TERMINAL.has(record.effectiveStatus));
+ }
+ return { operation, triggers: records.map(triggerToJson) };
+ }
+ if (operation === "acknowledge" || operation === "dismiss" || operation === "act") {
+ const id = coerceStr(args, "id", true)!;
+ try {
+ return {
+ operation,
+ trigger: triggerToJson(transitionTrigger(ctx.vault, id, operation, { now })),
+ };
+ } catch (err) {
+ throw new MCPError(INVALID_PARAMS, `brain_trigger: ${(err as Error).message}`);
+ }
+ }
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_trigger operation must be one of: scan, list, history, acknowledge, dismiss, act",
+ );
+}
+
+// ----- brain_deep_synthesis (Workspace Insight Suite) -----------------------
+
+export const WORKSPACE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
+ {
+ name: "brain_intention",
+ description:
+ "Scoped current-intention chains under Brain/intentions/: set updates a workstream's now-document (prior text lands in its history trail), show/list read, move retires the chain into history/.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["set", "show", "list", "move"],
+ description: "Operation to perform.",
+ },
+ scope: {
+ type: "string",
+ minLength: 1,
+ maxLength: 128,
+ description: "Workstream or session label (normalised to a scope slug).",
+ },
+ text: {
+ type: "string",
+ minLength: 1,
+ maxLength: 4000,
+ description: "Intention text for the set operation.",
+ },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ previewBudget: MCP_PREVIEW_BUDGET,
+ handler: toolBrainIntention,
+ },
+ {
+ name: "brain_trigger",
+ description:
+ "Grounded proactive trigger queue under Brain/triggers/: scan generates deduped triggers from health/retention data, list/history read by lifecycle status, acknowledge/dismiss/act transition one trigger. Anti-nag: cooldown keys keep the same issue from reappearing every run.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["scan", "list", "history", "acknowledge", "dismiss", "act"],
+ description: "Operation to perform.",
+ },
+ id: {
+ type: "string",
+ minLength: 1,
+ maxLength: 128,
+ description: "Trigger id for acknowledge/dismiss/act.",
+ },
+ status: {
+ type: "string",
+ enum: ["pending", "delivered", "acknowledged", "acted", "dismissed", "expired"],
+ description: "Effective-status filter for list.",
+ },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ previewBudget: MCP_PREVIEW_BUDGET,
+ handler: toolBrainTrigger,
+ },
+]);
diff --git a/tests/cli/brain-verb-context.test.ts b/tests/cli/brain-verb-context.test.ts
new file mode 100644
index 00000000..04d4235b
--- /dev/null
+++ b/tests/cli/brain-verb-context.test.ts
@@ -0,0 +1,64 @@
+/**
+ * Unit tests for the shared Brain verb context helpers. Every verb
+ * under src/cli/brain/verbs/ resolves its (config, vault) pair and
+ * acting agent through these instead of repeating the resolution
+ * boilerplate per file.
+ */
+
+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 { CliError } from "../../src/cli/argparse.ts";
+import { brainVerbContext, resolveBrainAgent } from "../../src/cli/brain/helpers.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+
+let configHome: string;
+let savedConfigEnv: string | undefined;
+let vaultDir: string;
+
+beforeEach(() => {
+ configHome = mkdtempSync(join(tmpdir(), "o2b-verbctx-cfg-"));
+ vaultDir = mkdtempSync(join(tmpdir(), "o2b-verbctx-vault-"));
+ savedConfigEnv = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ const configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vaultDir}\nagent_name: config-agent\n`);
+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;
+});
+
+afterEach(() => {
+ if (savedConfigEnv === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfigEnv;
+ rmSync(configHome, { recursive: true, force: true });
+ rmSync(vaultDir, { recursive: true, force: true });
+});
+
+describe("brainVerbContext", () => {
+ test("an explicit --vault flag wins over the configured vault", () => {
+ const ctx = brainVerbContext({ vault: "/explicit/vault" });
+ expect(ctx.vault).toBe("/explicit/vault");
+ });
+
+ test("falls back to the configured vault when no flag is given", () => {
+ const ctx = brainVerbContext({});
+ expect(ctx.vault).toBe(vaultDir);
+ expect(typeof ctx.config).toBe("string");
+ });
+
+ test("rejects an explicitly empty --vault flag with a CliError", () => {
+ expect(() => brainVerbContext({ vault: " " })).toThrow(CliError);
+ });
+});
+
+describe("resolveBrainAgent", () => {
+ test("an explicit --agent flag wins over the configured agent", () => {
+ const ctx = brainVerbContext({});
+ expect(resolveBrainAgent({ agent: "flag-agent" }, ctx.config)).toBe("flag-agent");
+ });
+
+ test("falls back to the configured agent name", () => {
+ const ctx = brainVerbContext({});
+ expect(resolveBrainAgent({}, ctx.config)).toBe("config-agent");
+ });
+});
diff --git a/tests/core/brain.confidence-value.test.ts b/tests/core/brain.confidence-value.test.ts
index fa31132c..0342ba98 100644
--- a/tests/core/brain.confidence-value.test.ts
+++ b/tests/core/brain.confidence-value.test.ts
@@ -7,7 +7,10 @@
import { describe, expect, test } from "bun:test";
-import { computeConfidence, type ConfidenceComputeResult } from "../../src/core/brain/dream.ts";
+import {
+ computeConfidence,
+ type ConfidenceComputeResult,
+} from "../../src/core/brain/confidence.ts";
import { DEFAULT_BRAIN_CONFIG } from "../../src/core/brain/policy.ts";
const cfg = DEFAULT_BRAIN_CONFIG;
diff --git a/tests/core/brain.policy.test.ts b/tests/core/brain.policy.test.ts
index b14fdc46..fd60b8a0 100644
--- a/tests/core/brain.policy.test.ts
+++ b/tests/core/brain.policy.test.ts
@@ -3,6 +3,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { parseBrainYaml } from "../../src/core/brain/yaml-parse.ts";
import {
BRAIN_CONFIG_SUPPORTED_VERSIONS,
BrainConfigError,
@@ -11,7 +12,6 @@ import {
formatPrimaryAgentYamlValue,
loadBrainConfig,
loadBrainConfigDetailed,
- parseBrainYaml,
validateBrainConfig,
validateBrainConfigDetailed,
} from "../../src/core/brain/policy.ts";
diff --git a/tests/core/brain.set-primary.test.ts b/tests/core/brain.set-primary.test.ts
index 95eb98be..7b81f69e 100644
--- a/tests/core/brain.set-primary.test.ts
+++ b/tests/core/brain.set-primary.test.ts
@@ -5,11 +5,8 @@ import { join } from "node:path";
import { bootstrapBrain } from "../../src/core/brain/init.ts";
import { brainConfigPath } from "../../src/core/brain/paths.ts";
-import {
- BrainConfigError,
- validateBrainConfig,
- parseBrainYaml,
-} from "../../src/core/brain/policy.ts";
+import { parseBrainYaml } from "../../src/core/brain/yaml-parse.ts";
+import { BrainConfigError, validateBrainConfig } from "../../src/core/brain/policy.ts";
import { setPrimaryAgent } from "../../src/core/brain/set-primary.ts";
let vault: string;
diff --git a/tests/core/brain/dream-modules.test.ts b/tests/core/brain/dream-modules.test.ts
new file mode 100644
index 00000000..96948bf0
--- /dev/null
+++ b/tests/core/brain/dream-modules.test.ts
@@ -0,0 +1,128 @@
+/**
+ * Unit tests for the sub-modules extracted from dream.ts:
+ * confidence computation, reconcile outcomes, and the apply-evidence
+ * refresh scanner. Behavior is pinned by the existing dream suite;
+ * these cases exercise each module in isolation.
+ */
+
+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 {
+ BAND_RANK,
+ computeConfidence,
+ rebandConfidence,
+} from "../../../src/core/brain/confidence.ts";
+import { buildReconcileOutcomes } from "../../../src/core/brain/reconcile-outcomes.ts";
+import { emptyPlan, filterWithinWindow } from "../../../src/core/brain/dream-plan.ts";
+import { scanApplyEvidence } from "../../../src/core/brain/dream-refresh.ts";
+import { DEFAULT_BRAIN_CONFIG } from "../../../src/core/brain/policy.ts";
+import { appendLogEvent } from "../../../src/core/brain/log.ts";
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+
+const NOW = new Date("2026-06-09T12:00:00Z");
+
+describe("confidence module", () => {
+ test("computeConfidence returns zero value and low band without evidence", () => {
+ const r = computeConfidence(0, 0, null, DEFAULT_BRAIN_CONFIG, NOW);
+ expect(r.value).toBe(0);
+ expect(r.band).toBe("low");
+ });
+
+ test("computeConfidence rewards fresh applied evidence", () => {
+ const r = computeConfidence(10, 0, NOW.toISOString(), DEFAULT_BRAIN_CONFIG, NOW);
+ expect(r.value).toBeGreaterThan(0.5);
+ expect(BAND_RANK[r.band]).toBeGreaterThanOrEqual(BAND_RANK["medium"]);
+ });
+
+ test("rebandConfidence maps a raw value back onto the configured bands", () => {
+ expect(rebandConfidence(0, DEFAULT_BRAIN_CONFIG).band).toBe("low");
+ expect(rebandConfidence(1, DEFAULT_BRAIN_CONFIG).band).toBe("high");
+ });
+});
+
+const mkWindowSignal = (createdAt: string) => ({
+ path: "/tmp/x.md",
+ active: true,
+ signal: { id: "sig-x", topic: "t", signal: "positive", created_at: createdAt },
+});
+
+describe("dream-plan helpers", () => {
+ test("filterWithinWindow keeps only signals inside the window", () => {
+ const recent = mkWindowSignal("2026-06-08T12:00:00Z");
+ const old = mkWindowSignal("2026-01-01T00:00:00Z");
+ const filtered = filterWithinWindow(
+ // Minimal structural records are enough for the window filter.
+ [recent, old] as never,
+ 14,
+ NOW,
+ );
+ expect(filtered).toHaveLength(1);
+ expect((filtered[0] as { signal: { created_at: string } }).signal.created_at).toBe(
+ "2026-06-08T12:00:00Z",
+ );
+ });
+});
+
+describe("buildReconcileOutcomes", () => {
+ test("returns empty outcomes when the plan flags no contradictions", () => {
+ const outcomes = buildReconcileOutcomes(
+ { signals: [], preferences: [], retired: [], corrupted: [] },
+ emptyPlan(),
+ DEFAULT_BRAIN_CONFIG,
+ NOW,
+ );
+ expect(outcomes.openQuestions).toEqual([]);
+ expect(outcomes.autoResolved).toEqual([]);
+ });
+});
+
+describe("scanApplyEvidence", () => {
+ let vault: string;
+ let configHome: string;
+
+ beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-refresh-vault-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-refresh-cfg-"));
+ const configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ bootstrapBrain(vault, { configPath });
+ });
+
+ afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+ });
+
+ test("collects apply-evidence events and resolves merge aliases", () => {
+ appendLogEvent(vault, {
+ timestamp: "2026-06-09T10:00:00Z",
+ agent: "tester",
+ eventType: "apply-evidence",
+ body: { preference: "[[pref-old-rule]]", result: "applied" },
+ });
+ appendLogEvent(vault, {
+ timestamp: "2026-06-09T10:05:00Z",
+ agent: "tester",
+ eventType: "merge",
+ body: { keep: "[[pref-new-rule]]", drop: "[[pref-old-rule]]" },
+ });
+ appendLogEvent(vault, {
+ timestamp: "2026-06-09T10:10:00Z",
+ agent: "tester",
+ eventType: "apply-evidence",
+ body: { preference: "[[pref-new-rule]]", result: "violated", outcome: "failure" },
+ });
+
+ const entries = scanApplyEvidence(vault);
+ expect(entries).toHaveLength(2);
+ // The merge alias folds the old slug into the surviving one.
+ expect(entries.map((e) => e.pref_slug)).toEqual(["new-rule", "new-rule"]);
+ expect(entries[0]?.result).toBe("applied");
+ expect(entries[1]?.result).toBe("violated");
+ expect(entries[1]?.outcome).toBe("failure");
+ });
+});
diff --git a/tests/core/brain/notes-config.test.ts b/tests/core/brain/notes-config.test.ts
index 026e64fe..f71d3682 100644
--- a/tests/core/brain/notes-config.test.ts
+++ b/tests/core/brain/notes-config.test.ts
@@ -11,10 +11,10 @@
import { describe, expect, test } from "bun:test";
+import { parseBrainYaml } from "../../../src/core/brain/yaml-parse.ts";
import {
BrainConfigError,
BRAIN_NOTES_DEFAULTS,
- parseBrainYaml,
resolveNotes,
validateBrainConfigDetailed,
} from "../../../src/core/brain/policy.ts";
diff --git a/tests/core/brain/outcome-evidence.test.ts b/tests/core/brain/outcome-evidence.test.ts
index 811ffe28..38d0e9d2 100644
--- a/tests/core/brain/outcome-evidence.test.ts
+++ b/tests/core/brain/outcome-evidence.test.ts
@@ -14,7 +14,8 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { appendApplyEvidence } from "../../../src/core/brain/apply-evidence.ts";
-import { dream, OUTCOME_REGRESSION_PENALTY } from "../../../src/core/brain/dream.ts";
+import { dream } from "../../../src/core/brain/dream.ts";
+import { OUTCOME_REGRESSION_PENALTY } from "../../../src/core/brain/dream-refresh.ts";
import { collectEvidenceForSlug } from "../../../src/core/brain/evidence.ts";
import { bootstrapBrain } from "../../../src/core/brain/init.ts";
import { readLogDay } from "../../../src/core/brain/log-jsonl.ts";
diff --git a/tests/core/brain/policy-active.test.ts b/tests/core/brain/policy-active.test.ts
index 5636bfe1..bd9c17b7 100644
--- a/tests/core/brain/policy-active.test.ts
+++ b/tests/core/brain/policy-active.test.ts
@@ -3,11 +3,8 @@
*/
import { describe, expect, test } from "bun:test";
-import {
- BrainConfigError,
- parseBrainYaml,
- validateBrainConfigDetailed,
-} from "../../../src/core/brain/policy.ts";
+import { parseBrainYaml } from "../../../src/core/brain/yaml-parse.ts";
+import { BrainConfigError, validateBrainConfigDetailed } from "../../../src/core/brain/policy.ts";
function validate(yaml: string) {
return validateBrainConfigDetailed(parseBrainYaml(yaml), "<test>");
diff --git a/tests/core/brain/policy-guardrails.test.ts b/tests/core/brain/policy-guardrails.test.ts
index 84b24878..db90970d 100644
--- a/tests/core/brain/policy-guardrails.test.ts
+++ b/tests/core/brain/policy-guardrails.test.ts
@@ -5,10 +5,10 @@
import { describe, expect, test } from "bun:test";
+import { parseBrainYaml } from "../../../src/core/brain/yaml-parse.ts";
import {
BRAIN_GUARDRAIL_DEFAULTS,
BrainConfigError,
- parseBrainYaml,
resolveGuardrails,
validateBrainConfigDetailed,
} from "../../../src/core/brain/policy.ts";
diff --git a/tests/core/brain/policy-health.test.ts b/tests/core/brain/policy-health.test.ts
index c6c2fe48..81c853a6 100644
--- a/tests/core/brain/policy-health.test.ts
+++ b/tests/core/brain/policy-health.test.ts
@@ -6,10 +6,10 @@
import { describe, expect, test } from "bun:test";
+import { parseBrainYaml } from "../../../src/core/brain/yaml-parse.ts";
import {
BRAIN_HEALTH_DEFAULTS,
BrainConfigError,
- parseBrainYaml,
resolveHealth,
validateBrainConfigDetailed,
} from "../../../src/core/brain/policy.ts";
diff --git a/tests/core/brain/temporal/bi-temporal-atoms.test.ts b/tests/core/brain/temporal/bi-temporal-atoms.test.ts
index ec992590..67455b52 100644
--- a/tests/core/brain/temporal/bi-temporal-atoms.test.ts
+++ b/tests/core/brain/temporal/bi-temporal-atoms.test.ts
@@ -12,9 +12,9 @@
import { describe, expect, test } from "bun:test";
+import { parseBrainYaml } from "../../../../src/core/brain/yaml-parse.ts";
import {
BrainConfigError,
- parseBrainYaml,
validateBrainConfigDetailed,
} from "../../../../src/core/brain/policy.ts";
import { BRAIN_TEMPORAL_DEFAULTS, resolveTemporal } from "../../../../src/core/brain/policy.ts";
diff --git a/tests/core/brain/wikilink-syntax.test.ts b/tests/core/brain/wikilink-syntax.test.ts
new file mode 100644
index 00000000..aa976b06
--- /dev/null
+++ b/tests/core/brain/wikilink-syntax.test.ts
@@ -0,0 +1,159 @@
+/**
+ * Characterization tests for the canonical wikilink regex variants.
+ *
+ * Before the SOLID/DRY refactor, seven modules each declared their own
+ * `[[...]]` regex; these tests pin the exact contract of every variant
+ * so the consolidation into `src/core/brain/wikilink.ts` is provably
+ * behavior-preserving for each former call site.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import {
+ ANCHORED_WIKILINK_RE,
+ EXACT_WIKILINK_RE,
+ RICH_WIKILINK_RE,
+ WIKILINK_ALIAS_RE,
+ WIKILINK_DETECT_RE,
+ WIKILINK_TARGET_RE,
+} from "../../../src/core/brain/wikilink.ts";
+
+function allMatches(re: RegExp, text: string): RegExpMatchArray[] {
+ return [...text.matchAll(re)];
+}
+
+describe("WIKILINK_TARGET_RE (vault.ts / lint-consolidate.ts contract)", () => {
+ test("captures bare target and leaves suffix group empty", () => {
+ const [m] = allMatches(WIKILINK_TARGET_RE, "see [[Note]] here");
+ expect(m?.[1]).toBe("Note");
+ expect(m?.[2]).toBeUndefined();
+ });
+
+ test("captures alias suffix separately from target", () => {
+ const [m] = allMatches(WIKILINK_TARGET_RE, "[[Note|display text]]");
+ expect(m?.[1]).toBe("Note");
+ expect(m?.[2]).toBe("|display text");
+ });
+
+ test("captures heading suffix separately from target", () => {
+ const [m] = allMatches(WIKILINK_TARGET_RE, "[[Note#Heading]]");
+ expect(m?.[1]).toBe("Note");
+ expect(m?.[2]).toBe("#Heading");
+ });
+
+ test("matches multiple links in one line", () => {
+ const ms = allMatches(WIKILINK_TARGET_RE, "[[a]] and [[b]]");
+ expect(ms.map((m) => m[1])).toEqual(["a", "b"]);
+ });
+
+ test("does not join two adjacent links", () => {
+ const ms = allMatches(WIKILINK_TARGET_RE, "[[a]][[b]]");
+ expect(ms.map((m) => m[1])).toEqual(["a", "b"]);
+ });
+
+ test("tolerates folder prefixes and dots in the target", () => {
+ const [m] = allMatches(WIKILINK_TARGET_RE, "[[Folder/file.md]]");
+ expect(m?.[1]).toBe("Folder/file.md");
+ });
+
+ test("pins historical behavior: target may span newlines", () => {
+ // `[^\]|#]` does not exclude `\n`; vault.ts has always matched a
+ // bracket pair that spans lines. Pinned, not endorsed.
+ const ms = allMatches(WIKILINK_TARGET_RE, "[[a\nb]]");
+ expect(ms.map((m) => m[1])).toEqual(["a\nb"]);
+ });
+
+ test("supports replace-based rewriting with suffix preservation", () => {
+ const out = "x [[old#H]] y [[old|Alias]]".replace(
+ WIKILINK_TARGET_RE,
+ (_match, target: string, suffix: string | undefined) =>
+ `[[${target === "old" ? "new" : target}${suffix ?? ""}]]`,
+ );
+ expect(out).toBe("x [[new#H]] y [[new|Alias]]");
+ });
+});
+
+describe("WIKILINK_ALIAS_RE (search/links.ts and search/entities.ts contract)", () => {
+ test("captures target and alias", () => {
+ const [m] = allMatches(WIKILINK_ALIAS_RE, "[[Note|alias]]");
+ expect(m?.[1]).toBe("Note");
+ expect(m?.[2]).toBe("alias");
+ });
+
+ test("captures bare target with undefined alias", () => {
+ const [m] = allMatches(WIKILINK_ALIAS_RE, "[[Note]]");
+ expect(m?.[1]).toBe("Note");
+ expect(m?.[2]).toBeUndefined();
+ });
+
+ test("keeps heading anchor inside the target capture", () => {
+ // The alias-aware variant splits only on `|`; `#` stays in m[1].
+ const [m] = allMatches(WIKILINK_ALIAS_RE, "[[Note#sec]]");
+ expect(m?.[1]).toBe("Note#sec");
+ });
+
+ test("does not match across newlines", () => {
+ expect(allMatches(WIKILINK_ALIAS_RE, "[[a\nb]]")).toHaveLength(0);
+ });
+
+ test("handles unicode targets and aliases", () => {
+ const [m] = allMatches(WIKILINK_ALIAS_RE, "[[Проект 🚀|план]]");
+ expect(m?.[1]).toBe("Проект 🚀");
+ expect(m?.[2]).toBe("план");
+ });
+});
+
+describe("RICH_WIKILINK_RE (link-graph parse/format contract)", () => {
+ test("captures the full bracket body including alias and anchor", () => {
+ const [m] = allMatches(RICH_WIKILINK_RE, "[[Note#Head|alias]]");
+ expect(m?.[1]).toBe("Note#Head|alias");
+ });
+
+ test("does not collapse adjacent links into one match", () => {
+ const ms = allMatches(RICH_WIKILINK_RE, "[[a]] mid [[b]]");
+ expect(ms.map((m) => m[1])).toEqual(["a", "b"]);
+ });
+
+ test("does not match across newlines", () => {
+ expect(allMatches(RICH_WIKILINK_RE, "[[a\nb]]")).toHaveLength(0);
+ });
+
+ test("supports replace-based rewriting of the body", () => {
+ const out = "x [[a|b]] y".replace(
+ RICH_WIKILINK_RE,
+ (_m, body: string) => `[[${body.toUpperCase()}]]`,
+ );
+ expect(out).toBe("x [[A|B]] y");
+ });
+});
+
+describe("WIKILINK_DETECT_RE (search/query-plan.ts contract)", () => {
+ test("detects a wikilink anywhere in the string", () => {
+ expect(WIKILINK_DETECT_RE.test("find [[Note]] please")).toBe(true);
+ });
+
+ test("rejects text without a complete bracket pair", () => {
+ expect(WIKILINK_DETECT_RE.test("no link [here]")).toBe(false);
+ expect(WIKILINK_DETECT_RE.test("[[unclosed")).toBe(false);
+ });
+
+ test("is not global, so repeated test() calls stay stateless", () => {
+ expect(WIKILINK_DETECT_RE.global).toBe(false);
+ expect(WIKILINK_DETECT_RE.test("[[a]]")).toBe(true);
+ expect(WIKILINK_DETECT_RE.test("[[a]]")).toBe(true);
+ });
+});
+
+describe("ANCHORED_WIKILINK_RE / EXACT_WIKILINK_RE (brain/wikilink.ts internals)", () => {
+ test("anchored variant strips a leading wikilink prefix only", () => {
+ const m = ANCHORED_WIKILINK_RE.exec("[[Note|alias]] trailing");
+ expect(m?.[1]).toBe("Note|alias");
+ expect(ANCHORED_WIKILINK_RE.exec("prose [[Note]]")).toBeNull();
+ });
+
+ test("exact variant requires the whole string to be one wikilink", () => {
+ expect(EXACT_WIKILINK_RE.exec("[[Note]]")?.[1]).toBe("Note");
+ expect(EXACT_WIKILINK_RE.exec("[[Note]] x")).toBeNull();
+ expect(EXACT_WIKILINK_RE.exec(" [[Note]]")).toBeNull();
+ });
+});
diff --git a/tests/core/brain/yaml-parse.test.ts b/tests/core/brain/yaml-parse.test.ts
new file mode 100644
index 00000000..38669d10
--- /dev/null
+++ b/tests/core/brain/yaml-parse.test.ts
@@ -0,0 +1,51 @@
+/**
+ * Unit tests for the YAML subset parser extracted from policy.ts.
+ *
+ * The parser grammar itself is unchanged by the extraction; the broad
+ * grammar/error coverage stays in tests/core/brain.policy.test.ts
+ * (loadBrainConfig round-trips). These cases pin the module contract
+ * in isolation.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import { parseBrainYaml } from "../../../src/core/brain/yaml-parse.ts";
+
+describe("parseBrainYaml", () => {
+ test("parses top-level scalars with type coercion", () => {
+ const parsed = parseBrainYaml("schema_version: 1\nname: 'quoted'\nflag: true\nempty: null\n");
+ expect(parsed).toEqual({ schema_version: 1, name: "quoted", flag: true, empty: null });
+ });
+
+ test("parses one-level blocks and inline arrays", () => {
+ const parsed = parseBrainYaml("retire:\n stale_evidence_days: 90\n tags: [a, 'b c']\n");
+ expect(parsed).toEqual({ retire: { stale_evidence_days: 90, tags: ["a", "b c"] } });
+ });
+
+ test("parses block-level dash lists", () => {
+ const parsed = parseBrainYaml("notes:\n read_paths:\n - Notes\n - Projects\n");
+ expect(parsed).toEqual({ notes: { read_paths: ["Notes", "Projects"] } });
+ });
+
+ test("skips comments and blank lines", () => {
+ const parsed = parseBrainYaml("# header\n\nschema_version: 1 # trailing\n");
+ expect(parsed).toEqual({ schema_version: 1 });
+ });
+
+ test("rejects nested blocks deeper than one level", () => {
+ expect(() => parseBrainYaml("a:\n b:\n c: 1\n")).toThrow(
+ "nested blocks deeper than one level are not supported",
+ );
+ });
+
+ test("rejects duplicate keys with line context", () => {
+ expect(() => parseBrainYaml("a: 1\na: 2\n")).toThrow("duplicate top-level key 'a'");
+ expect(() => parseBrainYaml("b:\n x: 1\n x: 2\n")).toThrow("duplicate key 'x' in block 'b'");
+ });
+
+ test("rejects unterminated quoted strings in inline arrays", () => {
+ expect(() => parseBrainYaml("tags: ['open]\n")).toThrow(
+ "unterminated quoted string in inline array",
+ );
+ });
+});
diff --git a/tests/core/fs-atomic.test.ts b/tests/core/fs-atomic.test.ts
index c129d60b..3decf9fa 100644
--- a/tests/core/fs-atomic.test.ts
+++ b/tests/core/fs-atomic.test.ts
@@ -1,9 +1,21 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import {
+ existsSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ statSync,
+ writeFileSync,
+} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { atomicCreateFileSyncExclusive, atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import {
+ atomicCreateFileSyncExclusive,
+ atomicWriteFileSync,
+ atomicWriteText,
+} from "../../src/core/fs-atomic.ts";
let tmp: string;
@@ -83,3 +95,51 @@ describe("atomicCreateFileSyncExclusive", () => {
expect(readFileSync(target, "utf8")).toBe("deep");
});
});
+
+describe("atomicWriteText", () => {
+ test("preserves old content when validation rejects the candidate", () => {
+ const target = join(tmp, "state.yaml");
+ writeFileSync(target, "schema_version: 1\n", "utf8");
+
+ expect(() =>
+ atomicWriteText(target, "broken: true\n", {
+ validate: () => {
+ throw new Error("candidate failed lint");
+ },
+ }),
+ ).toThrow("candidate failed lint");
+
+ expect(readFileSync(target, "utf8")).toBe("schema_version: 1\n");
+ const leakedTemps = readdirSync(tmp).filter(
+ (name) => name.startsWith(".state.yaml.") && name.endsWith(".tmp"),
+ );
+ expect(leakedTemps).toHaveLength(0);
+ });
+
+ test("writes the candidate atomically after validation passes", () => {
+ const target = join(tmp, "Brain", "_brain.yaml");
+
+ atomicWriteText(target, "schema_version: 1\nschema:\n", {
+ validate: (candidate) => expect(candidate).toContain("schema_version"),
+ });
+
+ expect(readFileSync(target, "utf8")).toBe("schema_version: 1\nschema:\n");
+ });
+
+ test("defaults to private 0o600 mode and honors a mode override", () => {
+ const strict = join(tmp, "strict.txt");
+ atomicWriteText(strict, "secret");
+ expect(statSync(strict).mode & 0o777).toBe(0o600);
+
+ const open = join(tmp, "open.txt");
+ atomicWriteText(open, "public", { mode: 0o644 });
+ expect(statSync(open).mode & 0o777).toBe(0o644);
+ });
+
+ test("overwrites an existing target", () => {
+ const target = join(tmp, "x.yaml");
+ atomicWriteText(target, "first\n");
+ atomicWriteText(target, "second\n");
+ expect(readFileSync(target, "utf8")).toBe("second\n");
+ });
+});
diff --git a/tests/core/layering.test.ts b/tests/core/layering.test.ts
new file mode 100644
index 00000000..d729d1db
--- /dev/null
+++ b/tests/core/layering.test.ts
@@ -0,0 +1,68 @@
+/**
+ * Layering guard for the core layer.
+ *
+ * The CLI owns exit codes and stdout formatting; src/core must never
+ * terminate the process or write to stdout directly. Fail-soft
+ * diagnostics on stderr (process.stderr.write, console.error) are an
+ * established core pattern and stay allowed.
+ *
+ * This is a source scan, not an AST pass: comment-only lines are
+ * skipped, everything else that mentions a banned call fails with a
+ * file:line pointer.
+ */
+
+import { describe, expect, test } from "bun:test";
+import { readFileSync, readdirSync, statSync } from "node:fs";
+import { join } from "node:path";
+
+const CORE_ROOT = join(import.meta.dir, "..", "..", "src", "core");
+
+const BANNED = [
+ { pattern: "process.exit", reason: "core must not terminate the process" },
+ { pattern: "process.stdout.write", reason: "stdout formatting belongs to the CLI layer" },
+ { pattern: "console.log(", reason: "stdout logging belongs to the CLI layer" },
+] as const;
+
+function walk(dir: string): string[] {
+ const out: string[] = [];
+ for (const name of readdirSync(dir)) {
+ const path = join(dir, name);
+ if (statSync(path).isDirectory()) {
+ out.push(...walk(path));
+ } else if (name.endsWith(".ts")) {
+ out.push(path);
+ }
+ }
+ return out;
+}
+
+function isCommentLine(line: string): boolean {
+ const trimmed = line.trimStart();
+ return trimmed.startsWith("//") || trimmed.startsWith("*") || trimmed.startsWith("/*");
+}
+
+describe("core layering", () => {
+ test("src/core never calls process.exit, process.stdout.write, or console.log", () => {
+ const violations: string[] = [];
+ for (const file of walk(CORE_ROOT)) {
+ const lines = readFileSync(file, "utf8").split("\n");
+ lines.forEach((line, i) => {
+ if (isCommentLine(line)) return;
+ for (const { pattern, reason } of BANNED) {
+ if (line.includes(pattern)) {
+ violations.push(`${file}:${i + 1} uses ${pattern} (${reason})`);
+ }
+ }
+ });
+ }
+ expect(violations).toEqual([]);
+ });
+
+ test("the scan actually detects a banned call", () => {
+ // Self-check so a broken walk or pattern list cannot rot into a
+ // vacuously green guard.
+ expect(isCommentLine(" // process.exit(1)")).toBe(true);
+ expect(isCommentLine(" process.exit(1);")).toBe(false);
+ expect(walk(CORE_ROOT).length).toBeGreaterThan(100);
+ });
+});
diff --git a/tests/core/reliability.test.ts b/tests/core/reliability.test.ts
index f300ab70..12f2d103 100644
--- a/tests/core/reliability.test.ts
+++ b/tests/core/reliability.test.ts
@@ -1,10 +1,9 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
-import { basename, dirname, join } from "node:path";
+import { join } from "node:path";
import { appendAuditRecord } from "../../src/core/reliability/audit.ts";
-import { atomicWriteText } from "../../src/core/reliability/atomic.ts";
import { withFileLock } from "../../src/core/reliability/lock.ts";
import { buildProbeReport } from "../../src/core/reliability/probe.ts";
@@ -19,37 +18,6 @@ afterEach(() => {
rmSync(tmp, { recursive: true, force: true });
});
-describe("atomicWriteText", () => {
- test("preserves old content when validation rejects the candidate", () => {
- const target = join(tmp, "state.yaml");
- writeFileSync(target, "schema_version: 1\n", "utf8");
-
- expect(() =>
- atomicWriteText(target, "broken: true\n", {
- validate: () => {
- throw new Error("candidate failed lint");
- },
- }),
- ).toThrow("candidate failed lint");
-
- expect(readFileSync(target, "utf8")).toBe("schema_version: 1\n");
- const leakedTemps = readdirSync(dirname(target)).filter(
- (name) => name.startsWith(`.${basename(target)}.`) && name.endsWith(".tmp"),
- );
- expect(leakedTemps).toHaveLength(0);
- });
-
- test("writes the candidate atomically after validation passes", () => {
- const target = join(tmp, "Brain", "_brain.yaml");
-
- atomicWriteText(target, "schema_version: 1\nschema:\n", {
- validate: (candidate) => expect(candidate).toContain("schema_version"),
- });
-
- expect(readFileSync(target, "utf8")).toBe("schema_version: 1\nschema:\n");
- });
-});
-
describe("withFileLock", () => {
test("serializes access to a lock target and releases after callback", async () => {
const target = join(tmp, "Brain", "_brain.yaml");
diff --git a/tests/mcp/brain-tools-parity.test.ts b/tests/mcp/brain-tools-parity.test.ts
new file mode 100644
index 00000000..0dce6103
--- /dev/null
+++ b/tests/mcp/brain-tools-parity.test.ts
@@ -0,0 +1,89 @@
+/**
+ * Frozen-surface parity guard for the Brain MCP tool set.
+ *
+ * v1.0.0 froze the public MCP surface; this test pins the exact tool
+ * names BRAIN_TOOLS advertises so the per-domain module split (and any
+ * future registry change) is provably name-set-preserving. A failure
+ * here means the public surface changed - that requires a deliberate
+ * major/minor release decision, not a refactor.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import { BRAIN_TOOLS } from "../../src/mcp/brain-tools.ts";
+
+const FROZEN_BRAIN_TOOL_NAMES = [
+ "brain_agent_diff",
+ "brain_agent_query",
+ "brain_analytics",
+ "brain_apply_evidence",
+ "brain_audit",
+ "brain_backlinks",
+ "brain_benchmark",
+ "brain_bridges",
+ "brain_brief",
+ "brain_clusters",
+ "brain_context",
+ "brain_context_pack",
+ "brain_context_presets",
+ "brain_context_receipts",
+ "brain_dead_ends",
+ "brain_deep_synthesis",
+ "brain_doctor",
+ "brain_dream",
+ "brain_entity",
+ "brain_feedback",
+ "brain_foresight",
+ "brain_health",
+ "brain_idea_discovery",
+ "brain_intent_review",
+ "brain_intention",
+ "brain_labels",
+ "brain_maintenance",
+ "brain_mcp_landscape",
+ "brain_moc_audit",
+ "brain_note",
+ "brain_pinned_context",
+ "brain_pre_compact_extract",
+ "brain_pre_compress_pack",
+ "brain_procedural_graph",
+ "brain_procedural_memory",
+ "brain_query",
+ "brain_recall_telemetry",
+ "brain_recurrence",
+ "brain_retention",
+ "brain_review_candidates",
+ "brain_secrets",
+ "brain_session_describe",
+ "brain_session_expand",
+ "brain_session_grep",
+ "brain_skill_proposals",
+ "brain_sources",
+ "brain_stale_scan",
+ "brain_switch_vault",
+ "brain_tiers",
+ "brain_trigger",
+ "brain_truth",
+ "brain_tune",
+ "brain_unlinked_mentions",
+ "brain_write_session",
+] as const;
+
+describe("BRAIN_TOOLS frozen surface", () => {
+ test("advertises exactly the v1.x tool-name set", () => {
+ const names = BRAIN_TOOLS.map((t) => t.name).toSorted();
+ expect(names).toEqual([...FROZEN_BRAIN_TOOL_NAMES]);
+ });
+
+ test("has no duplicate tool names", () => {
+ const names = BRAIN_TOOLS.map((t) => t.name);
+ expect(new Set(names).size).toBe(names.length);
+ });
+
+ test("every tool carries a handler and an input schema", () => {
+ for (const tool of BRAIN_TOOLS) {
+ expect(typeof tool.handler).toBe("function");
+ expect(tool.inputSchema).toBeDefined();
+ }
+ });
+});