Skip to content

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

TypeScript

feat: Brain Portability & Interop Suite - bank export/import, page contract, brain_create_note, in-process SDK (v1.9.0) (#98)

Sol Aitken929d54c2e7f4
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 10bb18e6..214f4310 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.8.0",
+ "version": "1.9.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 7c89f9dc..1d3d82e1 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.8.0",
+ "version": "1.9.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 de610a4e..4808b5cd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,46 @@ 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.9.0] - 2026-06-14
+
+### Added
+
+- **Brain Portability & Interop Suite.** Brain content becomes portable in and
+ out of a vault, with provenance, and programmatically writable - composing the
+ existing portability helpers rather than adding a new subsystem. Every unit is
+ an additive new surface; no existing exporter, importer, CLI verb, or MCP tool
+ changes behaviour.
+ - **Whole-vault bank export/import (`o2b brain bank-export` / `bank-import`).**
+ `exportBankBundle` composes the existing exporters - preferences, the page
+ link-graph, the page interchange contract, and the read-only sources
+ dashboard - into one deterministic, schema-versioned envelope for backup,
+ cross-instance migration, or downstream-tool ingest. `importBankBundle`
+ reconstructs the part that round-trips (the page graph, delegated to
+ `importVaultGraph` under a conflict mode) and reports preferences, page
+ contracts, and the sources dashboard as carried-not-restored - no silent
+ partial restore. An unsupported bundle schema fails loudly with a typed
+ `BankImportError`.
+ - **Page interchange contract (`projectPageContracts`).** A pure, read-only
+ projection of every user vault page to a stable, schema-versioned record
+ (`path`, `kind`, advisory `confidence`/`provenance`, flattened `citations`,
+ `aliases`, `freshness`) a downstream importer can consume without knowing
+ Open Second Brain internals. Derivation is structural only (frontmatter
+ fields, body wikilinks, typed-relation targets, file mtime); an absent
+ advisory field is reported as `null`, never synthesised.
+ - **`brain_create_note` MCP tool.** Writes an actual vault note file (path +
+ frontmatter + content) atomically through `ensureInsideVault` - distinct
+ from `brain_note`, which only appends a log line. Refuses path traversal, the
+ Brain machinery root, vault-scope-excluded paths, and overwriting an existing
+ note, each with a typed error mapped to INVALID_PARAMS.
+ - **In-process SDK (`createBrain(vault)`).** A thin faƧade over the existing
+ core functions - bank export/import, graph export/import, preference export,
+ `ingestSource`, and `createNote` - plus source-backed reads
+ (`listSources`/`getSource`/`deleteSource`) over the `kind: brain-source`
+ summary pages. Every method is a one-line delegation; the upstream
+ `writeStatus` maps to `ingestSource` (Open Second Brain has no separate
+ source status lifecycle). A source id that resolves outside `Brain/sources`
+ is treated as not-found and never deleted.
+
## [1.8.0] - 2026-06-13
### Added
@@ -5388,6 +5428,7 @@ plugin config (vault field)`, and exits with a clear
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[1.9.0]: https://github.com/itechmeat/open-second-brain/compare/v1.8.0...v1.9.0
[1.8.0]: https://github.com/itechmeat/open-second-brain/compare/v1.7.0...v1.8.0
[1.7.0]: https://github.com/itechmeat/open-second-brain/compare/v1.6.0...v1.7.0
[1.6.0]: https://github.com/itechmeat/open-second-brain/compare/v1.5.0...v1.6.0
diff --git a/README.md b/README.md
index 46fc5196..7a00b90f 100644
--- a/README.md
+++ b/README.md
@@ -88,6 +88,7 @@ Each non-Hermes target writes a sidecar manifest under `<vault>/.open-second-bra
- **A vault that stays fresh, consistent, and scoped.** `o2b search watch` keeps the index live as you edit, debounced and incremental; note identity is Unicode-normalized so the same file is one entry across macOS and Linux devices instead of a phantom cross-device duplicate; and recall accepts an opt-in `agent_scope` so a page marked with an `owner:` is reachable only to its owner while shared pages stay open to all.
- **Knowledge that knows where it came from.** Drop a source document and the agent's extraction becomes cross-referenced entity and concept pages plus a summary page that backlinks the source and lists its connections; N sources become one dated report whose every finding cites the source that flagged it; a derived fact carries a `deduced`/`inferred` provenance level and links back to its premises, and recall trusts an operator-stated rule above a machine-derived one. A fact can declare an `owner:` so multi-agent brains keep separate truth spaces, and a standing-query attention flow surfaces the open loops you declare. The plugin never runs a model itself - the agent owns generation, the vault owns the durable, provenanced record - and every behaviour is opt-in.
- **An index that survives interruption.** Stopping `o2b search watch` mid-sync finishes the in-flight pass at a file boundary before exiting (within `search_shutdown_grace_seconds`) instead of killing it mid-write; an incremental run is already resumable through the unchanged-file fastpath, and `search_resume_reindex` extends that to a full rebuild - an interrupted reindex resumes its staging build instead of starting over, guarded by a signature so a drifted build is discarded rather than trusted. Both default off, so behaviour is unchanged unless you ask for it.
+- **A brain you can carry, hand off, and write to in process.** `o2b brain bank-export` serialises a whole vault - preferences, the page graph, a per-page interchange contract (path, kind, advisory confidence/provenance, citations, aliases, freshness), and the sources dashboard - into one deterministic, schema-versioned bundle for backup, migration, or downstream-tool ingest; `bank-import` reconstructs the page graph and reports the rest as carried-not-restored rather than faking a full restore. A `brain_create_note` MCP tool writes an actual vault note (path + frontmatter + content) atomically, refusing traversal, the Brain root, and clobbering. And `createBrain(vault)` is a thin in-process SDK over the same core functions - bank/graph export-import, preference export, source ingest plus list/get/delete, and note creation - so scripts and agents manage brain content without the CLI or MCP layer.
That is the day-to-day picture. The full capability surface, every CLI verb, and the mental model live in the [documentation](#documentation) below.
diff --git a/docs/brainstorm/brain-portability-interop/cli-output/claude.md b/docs/brainstorm/brain-portability-interop/cli-output/claude.md
new file mode 100644
index 00000000..65a47cee
--- /dev/null
+++ b/docs/brainstorm/brain-portability-interop/cli-output/claude.md
@@ -0,0 +1,34 @@
+### Variant 1: SDK-centric hub
+- **Approach**: Build Unit C's `createBrain(vault)` faƧade first and make it the single composition point. Unit A's bank export/import, Unit B's per-page projection, and Unit D's `brain_create_note` all route their logic through the SDK, so the CLI verbs and MCP tool become thin shells over `createBrain(vault)`. One object owns the orchestration of `exportPreferencesJson` + `exportVaultGraph` + `aggregateSources`.
+- **Trade-offs**:
+ - Pro: a single chokepoint eliminates duplication across CLI, MCP, and SDK surfaces; the SDK is dogfooded by its own consumers.
+ - Pro: write paths (`writeStatus`, note creation) share one provenance/guard implementation.
+ - Con: tension with the "SDK must be a thin faƧade, not a reimplementation" constraint - if bundle orchestration lives in the SDK it stops being thin.
+ - Con: forces C to land before A/B/D, serialising the four units and making the SDK the critical path.
+ - Con: risk of SDK scope creep into a de-facto new subsystem, which the task explicitly discourages.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Variant 2: Layered core with thin peer adapters
+- **Approach**: Add a small core bundle module beside the existing portability helpers (e.g. `portability/bundle.ts` composing the existing exporters into a schema-versioned bank envelope, plus `portability/page.ts` defining Unit B's decoupled per-page contract as a pure projection). Each surface is a thin, independent adapter over those core functions: Unit A is CLI verbs, Unit C re-exposes the same core functions (including source-backed writes) as a faƧade, and Unit D is an MCP tool calling vault/path helpers directly. No surface depends on another surface.
+- **Trade-offs**:
+ - Pro: matches the repo's established structure exactly (one file per portability concern, one CLI verb per file, tool-def array), so each unit lands as a near-independent PR over shared core.
+ - Pro: keeps the SDK genuinely thin (re-export, not orchestrate) and keeps B's contract decoupled from OSB internals in its own projection module.
+ - Pro: byte-identical-when-off and per-entry import validation fall out naturally from reusing the existing envelope conventions.
+ - Con: four units touch the shared bundle module, needing light coordination on the envelope shape.
+ - Con: slightly more files than folding into an existing module.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 3: Bank-as-graph-extension
+- **Approach**: Avoid a new bundle module by extending the existing `exportVaultGraph` / `importVaultGraph` envelope to optionally carry preferences, sources/provenance, and Unit B's per-page fields as extra sections and per-node attributes of the same graph bundle. Units C and D are added as small surfaces on top, reusing the extended exporter for any whole-vault read.
+- **Trade-offs**:
+ - Pro: smallest code footprint; literally one existing serialisation path reused, with its conflict modes and `ensureInsideVault` guards already in place.
+ - Con: overloads a link-graph exporter with non-graph concerns (preferences, sources), conflating "page graph" with "whole bank."
+ - Con: envelope versioning becomes muddy - `GRAPH_VERSION` now gates unrelated bank content, so the bank format cannot evolve independently.
+ - Con: bolting B's contract onto graph nodes works against the "decoupled from OSB internals, stable interchange schema" requirement.
+- **Complexity**: small
+- **Risk**: medium
+
+### Recommended: Variant 2
+**Rationale**: It mirrors the repository's existing portability conventions (discrete core modules, thin CLI/MCP/SDK adapters as peers), which keeps the SDK a genuine faƧade and Unit B's interchange contract cleanly decoupled, satisfying the stated constraints directly. It composes the existing exporters into a new schema-versioned bank envelope rather than overloading the graph exporter (Variant 3) or centralising orchestration in the SDK (Variant 1), so the four units can land additively and independently in one release without forking a parallel serialisation path.
diff --git a/docs/brainstorm/brain-portability-interop/cli-output/prompt.md b/docs/brainstorm/brain-portability-interop/cli-output/prompt.md
new file mode 100644
index 00000000..92169c44
--- /dev/null
+++ b/docs/brainstorm/brain-portability-interop/cli-output/prompt.md
@@ -0,0 +1,71 @@
+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
+
+Ship a "Brain Portability & Interop" suite for Open Second Brain: a bundle of four small, related, additive units that make brain content portable in and out of a vault, with full provenance, and programmatically writable. The four units share one release and should reuse the existing portability infrastructure rather than introduce a new subsystem.
+
+## Unit A - Whole-vault (bank) export/import for cross-instance migration (kanban t_7eff6f39)
+Open Second Brain today has only piecemeal export: `exportPreferencesJson` / `exportPreferencesLlmsTxt` (preferences only) and `exportVaultGraph` / `importVaultGraph` (page link-graph stubs only). There is no single operation to export a whole brain ("bank") for migration to another instance, nor to import it back. Operators who want to migrate their brain, share a knowledge bank, or back up/restore portions have no tooling. Provide a deterministic, schema-versioned whole-vault export bundle (preferences + page graph + sources/provenance metadata) and a matching importer with conflict modes, reusing the existing exporters. "Bank" maps to OSB's vault.
+
+## Unit B - JSON export-bridge contract for downstream importers (kanban t_3b07fdfb, child of Unit A)
+Define a standardized, documented per-page JSON export contract that downstream memory importers can ingest: per page emit `path`, `kind`, advisory `confidence`/`provenance`, flattened `citations`, `aliases`, and `freshness`. This is the stable interchange schema the Unit A bundle carries for vault pages, decoupled from OSB internals so an external tool can consume it.
+
+## Unit C - In-process SDK with source-backed write APIs (kanban t_e1f07d74)
+Brain operations today are CLI-driven or MCP-tool-driven. Expose an in-process SDK (e.g. `createBrain(vault)`) returning a small faƧade over existing core functions, including source-backed write APIs: `writeStatus`, `listSources`, `getSource`, `deleteSource`. This lets other tools/scripts/agents manage brain content programmatically with full source provenance, complementing the existing MCP tools and CLI without duplicating their logic.
+
+## Unit D - brain_create_note MCP tool (kanban t_a957bc48)
+The MCP server exposes `brain_note` (appends one line to `Brain/log/<today>.md`) but no tool that creates an actual vault note file. Add a `brain_create_note` MCP tool accepting `path`, `frontmatter`, and `content`; it writes a Markdown file atomically, respects vault-scope / ignore / private rules and path-traversal guards (`ensureInsideVault`), and returns the created note's vault-relative path and metadata. Complements `brain_note` (log append) and `brain_feedback` (signal write).
+
+# Project context
+
+Open Second Brain: TypeScript on the Bun runtime, SQLite (bun:sqlite, FTS5 + sqlite-vec), an MCP stdio server, an `o2b` CLI, and an Obsidian/Markdown vault. The kernel is provider-agnostic - Open Second Brain never calls an LLM itself; any synthesis is delegated to the connected agent. Every opt-in feature must be byte-identical to prior behaviour when its flag is off.
+
+Recent commits:
+- 7cdbfc0 feat: Indexer Durability & Resilience Suite (v1.8.0)
+- 8b679fe feat: Knowledge Provenance Suite (v1.7.0)
+- 6e59a42 feat: Vault Integrity & Trust Suite (v1.6.0)
+- e4df212 feat: Search & Recall Quality Suite (v1.5.0)
+
+Related existing files (reuse, do not duplicate):
+- src/core/brain/export.ts - `ExportFormat = "json" | "llms-txt"`, `BRAIN_EXPORT_SCHEMA_VERSION = 1`, `collectExportRows`, `exportPreferencesJson`, `exportPreferencesLlmsTxt` (preferences only; deterministic; sorted by id).
+- src/core/brain/portability/graph.ts - `exportVaultGraph` / `importVaultGraph` (page link-graph; `GRAPH_VERSION = "1"`; conflict modes skip|overwrite|merge; per-node runtime guard; `ensureInsideVault`; `{{role}}` token resolution via vault-map).
+- src/core/brain/portability/codec.ts - `compress` / `expand`.
+- src/core/brain/portability/sources.ts - `aggregateSources` (read-only per-source dashboard over inbox+processed signals).
+- src/core/brain/portability/origins.ts - `SearchOrigin`, `listSearchOrigins` (origin kinds: active|profile|source).
+- src/core/vault.ts - `listVaultPages`, `parseFrontmatter`, `writeFrontmatterAtomic`, `extractWikilinks`, `EXCLUDED_DIRS`.
+- src/core/brain/paths.ts - `ensureInsideVault`, `brainDirs`, `BRAIN_ROOT_REL`.
+- src/mcp/brain/feedback-tools.ts - tool definitions array (`brain_note`, `brain_feedback`, ...), each `{ name, description, inputSchema, handler }`; handlers receive a context carrying `ctx.vault`; helpers `vaultRelativeSafe`, `appendLogEvent`.
+- src/cli/brain/verbs/ - one file per `o2b brain <verb>`; existing `export.ts`, `graph-export.ts`, `graph-import.ts`.
+
+Conventions:
+- Deterministic, sorted, timestamp-free serialisation so re-export is byte-identical (see exportVaultGraph).
+- Untrusted JSON on import is validated per-entry with a runtime guard; a malformed entry is rejected and the run continues, never throws mid-import.
+- Schema-versioned export envelopes (`schema` field) so importers can detect drift.
+- All writes guarded by `ensureInsideVault`; atomic writes via `writeFrontmatterAtomic` / `.new`-then-rename.
+
+Constraints:
+- No new external dependencies, especially no heavy ones (no headless browser, no PDF engine).
+- Provider-agnostic: the kernel must not call an LLM. Any LLM-derived field (e.g. a summary) is supplied by the connected agent, not synthesised in-core.
+- Language-agnostic: no hardcoded natural-language word lists (stop-words, keywords, greetings) in any language. Use structural signals, explicit frontmatter fields, or corpus frequency.
+- No misleading fallbacks: a feature that cannot do its job must fail loudly (typed error), not silently no-op or return fabricated data.
+- No TypeScript `as` cast crutches: build values with the correct type from the start (conditional spreads, narrowing functions).
+- Byte-identical-when-flags-off: anything opt-in must not change existing output/ordering/shape when disabled.
+- Reuse the existing exporters/importers and portability helpers; do not fork a parallel serialisation path.
+- The SDK must be a thin faƧade over existing core functions, not a reimplementation.
+
+# 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/brain-portability-interop/design.md b/docs/brainstorm/brain-portability-interop/design.md
new file mode 100644
index 00000000..ce285837
--- /dev/null
+++ b/docs/brainstorm/brain-portability-interop/design.md
@@ -0,0 +1,151 @@
+# Brain Portability & Interop - portable, provenance-bearing, programmatically writable brain content
+
+**Status:** draft
+**Author:** claude-dev-agent (via feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+Open Second Brain can export pieces of a brain (preferences via `export.ts`,
+the page link-graph via `portability/graph.ts`) but has no single operation to
+move a whole brain ("bank") between instances, no standardized per-page
+interchange contract a downstream importer can rely on, no in-process SDK for
+programmatic callers, and no MCP tool to create an actual vault note (only
+`brain_note`, which appends one log line). This suite closes those four gaps
+additively, reusing the existing portability infrastructure rather than forking
+a parallel serialisation path.
+
+## Scope
+
+- **Unit B - Page interchange contract** (`portability/page-contract.ts`): a
+ pure, read-only projection of every user vault page to a stable,
+ schema-versioned record `{ path, kind, confidence, provenance, citations,
+ aliases, freshness }`, decoupled from OSB internals so an external tool can
+ consume it. Structural derivation only (frontmatter fields + wikilinks + file
+ mtime); no LLM synthesis, no natural-language heuristics.
+- **Unit D - `createNote` primitive + `brain_create_note` MCP tool**: a shared
+ core primitive `createNote(vault, { path, frontmatter, content })` that writes
+ a Markdown file atomically under `ensureInsideVault`, honouring vault-scope /
+ ignore / private rules, and the thin MCP tool that wraps it. Reused by Unit C.
+- **Unit A - Whole-vault (bank) export/import** (`portability/bundle.ts`): a
+ deterministic, schema-versioned bank envelope composing the existing
+ exporters (preferences + page graph + page-contract records + the read-only
+ sources dashboard) plus an importer that restores the page graph (delegating
+ to `importVaultGraph`) and preferences, under explicit conflict modes. CLI
+ verbs `o2b brain bank-export` / `bank-import`.
+- **Unit C - In-process SDK** (`sdk.ts`): `createBrain(vault)` returning a thin
+ faƧade over existing core functions: bank export/import, graph export/import,
+ preference export, source-backed operations (`ingestSource`, `listSources`,
+ `getSource`, `deleteSource`), and `createNote`. No reimplementation - every
+ method delegates to a core function.
+
+## Out of scope
+
+- PDF export (kanban t_64d65fb7): needs a heavy dependency (headless browser /
+ PDF engine), against the no-new-heavy-deps rule. Left in triage.
+- A source *status lifecycle*. OSB ingested sources (`kind: brain-source`
+ pages) carry provenance and `created_at`/`updated_at` but no processing-status
+ enum. The upstream `writeStatus` API maps to the existing `ingestSource`
+ write (which stamps `updated_at` and rewrites idempotently); we do NOT invent
+ a status field just to mirror the upstream name.
+- Re-importing the sources dashboard. `aggregateSources` is a derived read-only
+ projection over signals; it is carried in the export bundle as informational
+ metadata, not restored on import. The import result reports this explicitly
+ rather than silently pretending to restore it.
+- Multi-target typed-relation fidelity on import: inherited from
+ `importVaultGraph`'s documented frontmatter-parser limitation; unchanged here.
+
+## Chosen approach
+
+Variant 2 from the brainstorm (consultant-recommended): **Layered core with thin
+peer adapters.** Each portability concern is a discrete core module beside the
+existing helpers; every surface (CLI verb, MCP tool, SDK method) is an
+independent thin adapter over those core functions, and no surface depends on
+another surface. This keeps the SDK a genuine faƧade (re-export, not
+orchestrate), keeps Unit B's contract decoupled in its own projection module,
+and lets the four units land additively in one release. The two rejected
+variants either centralised orchestration in the SDK (Variant 1, breaking the
+"thin faƧade" constraint and serialising the units) or overloaded the link-graph
+exporter with non-graph bank content (Variant 3, muddying `GRAPH_VERSION` and
+working against Unit B's "decoupled, stable interchange schema" requirement).
+
+## Design decisions
+
+- **Separate version constants per envelope.** The bank bundle gets its own
+ `BANK_BUNDLE_SCHEMA_VERSION`; the page contract gets `PAGE_CONTRACT_VERSION`.
+ Neither reuses `GRAPH_VERSION` or `BRAIN_EXPORT_SCHEMA_VERSION`, so each format
+ evolves independently and an importer can detect drift per section.
+- **Compose, never fork.** `exportBankBundle` calls `collectExportRows`,
+ `exportVaultGraph`, `projectPageContracts`, and `aggregateSources`;
+ `importBankBundle` delegates page reconstruction to `importVaultGraph`. No new
+ serialisation of pages/preferences is written from scratch.
+- **Structural, language-agnostic page `kind`.** `kind` reads the frontmatter
+ `kind:` field when present (e.g. `brain-source`), else a structural default
+ (`note`). No keyword/title heuristics in any language.
+- **Provenance/confidence are advisory and read-only.** Read from frontmatter
+ if present, else `null`. The provider-agnostic kernel never synthesises them.
+- **Citations are derived structurally.** Flattened, sorted-unique union of body
+ wikilink targets and typed-relation targets - the same extraction the graph
+ exporter already uses - so the contract stays decoupled from any NL parsing.
+- **Per-entry runtime validation on import.** Mirrors `importVaultGraph`: every
+ untrusted JSON entry is shape-guarded; a malformed entry is rejected into a
+ `rejected[]` list and the run continues, never throws mid-import. No `as`
+ casts - guards narrow `unknown` to the input type.
+- **Honest import result.** `importBankBundle` returns a structured result with
+ per-section counts (graph created/skipped/overwritten/merged/rejected,
+ preferences restored/skipped, and `sourcesCarriedNotRestored`) so the caller
+ sees exactly what happened. No "fully restored" claim where only part is.
+- **`createNote` is the single write primitive.** Both the MCP tool and the SDK
+ method call it; it enforces `ensureInsideVault`, atomic write, and vault-scope
+ / ignore / private rejection with a typed error (no silent skip).
+- **Byte-identical-when-off.** All four units are additive new surfaces. No
+ existing exporter, importer, CLI verb, MCP tool, or default path changes
+ behaviour; with none of the new verbs/tools/SDK invoked, output is identical.
+
+## File changes
+
+New core modules:
+- `src/core/brain/portability/page-contract.ts` - `PageContract`,
+ `PAGE_CONTRACT_VERSION`, `projectPageContracts(vault)`.
+- `src/core/brain/portability/bundle.ts` - `BankBundle`,
+ `BANK_BUNDLE_SCHEMA_VERSION`, `exportBankBundle(vault)`,
+ `importBankBundle(vault, bundle, { mode })`, per-entry guards.
+- `src/core/brain/notes/create-note.ts` - `CreateNoteInput`, `CreateNoteResult`,
+ `createNote(vault, input)`, typed `CreateNoteError`.
+- `src/core/brain/sdk.ts` - `createBrain(vault)` faƧade + its return type.
+
+New / modified surfaces:
+- `src/cli/brain/verbs/bank-export.ts`, `src/cli/brain/verbs/bank-import.ts` -
+ new CLI verbs; registered in the brain verb dispatcher.
+- `src/mcp/brain/notes-tools.ts` (or an addition to `feedback-tools.ts`) -
+ `brain_create_note` tool definition + handler; registered in the tools array,
+ `registry-guard.ts`, and `profiles.ts`.
+
+Modified docs / manifests:
+- `README.md`, `CHANGELOG.md` (one new version entry + link-ref).
+- `package.json` version bump + `bun run scripts/sync-version.ts` (inside this PR
+ per `CLAUDE.md`).
+
+Tests (TDD, one suite per unit):
+- `tests/core/brain/portability/page-contract.test.ts`
+- `tests/core/brain/portability/bundle.test.ts`
+- `tests/core/brain/notes/create-note.test.ts`
+- `tests/core/brain/sdk.test.ts`
+- `tests/mcp/brain-create-note.test.ts`
+- CLI verb coverage for `bank-export` / `bank-import` following the existing
+ graph-export/graph-import test pattern.
+
+## Risks and open questions
+
+- **Preference restore semantics.** Restoring preferences must reuse the
+ existing preference writer and respect the chosen conflict mode; resolve the
+ exact writer + idempotency contract during Task 3 (verify `writePreference`'s
+ overwrite behaviour before wiring). If a clean reusable writer does not exist,
+ scope preference *restore* out of import (still exported) rather than forking
+ a parallel writer - and say so in the result object.
+- **Registry-completeness tests.** Adding an MCP tool likely trips a
+ registry/profile completeness test; update `registry-guard.ts` and
+ `profiles.ts` in the same task so the suite stays green.
+- **Sources dashboard in the bundle.** Carried as informational metadata only;
+ the import result names it as not-restored so the bundle cannot be read as a
+ full round-trip of signals.
diff --git a/docs/brainstorm/brain-portability-interop/plan.md b/docs/brainstorm/brain-portability-interop/plan.md
new file mode 100644
index 00000000..37f3afc7
--- /dev/null
+++ b/docs/brainstorm/brain-portability-interop/plan.md
@@ -0,0 +1,96 @@
+# Brain Portability & Interop - implementation plan
+
+Implemented one atomic unit at a time via TDD on `feat/brain-portability-interop`.
+Order is dependency-driven: the pure projection first, then the shared write
+primitive, then the bundle that composes them, then the SDK faƧade over all.
+
+## Tasks
+
+### Task 1: Page interchange contract (Unit B)
+- **Files**: `src/core/brain/portability/page-contract.ts` (new);
+ `tests/core/brain/portability/page-contract.test.ts` (new).
+- **Surface**: `PAGE_CONTRACT_VERSION`, `PageContract`,
+ `projectPageContracts(vault): ReadonlyArray<PageContract>` - pure, read-only.
+- **Behaviour**: one record per user vault page (Brain machinery + ignored dirs
+ excluded, same exclusion set as `exportVaultGraph`): `path` (vault-relative
+ POSIX), `kind` (frontmatter `kind:` else `"note"`), `confidence`
+ (frontmatter, else null), `provenance` (frontmatter, else null), `citations`
+ (sorted-unique union of body wikilinks + typed-relation targets), `aliases`
+ (frontmatter, else empty), `freshness` (frontmatter `updated_at`/`updated`
+ else file mtime as ISO second). Sorted by `path` for determinism.
+- **Acceptance**: tests cover field derivation, structural `kind` default,
+ null confidence/provenance when absent, citation flattening + sort, alias
+ passthrough, freshness fallback to mtime, deterministic ordering, and Brain-
+ root/ignored-dir exclusion. No NL heuristics; no `as` casts.
+- **Depends on**: none.
+
+### Task 2: createNote primitive + brain_create_note MCP tool (Unit D)
+- **Files**: `src/core/brain/notes/create-note.ts` (new);
+ `src/mcp/brain/notes-tools.ts` (new) wired into the MCP tools array;
+ `src/mcp/registry-guard.ts`, `src/mcp/profiles.ts` (register the tool);
+ `tests/core/brain/notes/create-note.test.ts` (new);
+ `tests/mcp/brain-create-note.test.ts` (new).
+- **Surface**: `createNote(vault, { path, frontmatter, content })` ->
+ `{ path, created }`; typed `CreateNoteError` for guard failures.
+- **Behaviour**: resolve the target via `ensureInsideVault`; reject (typed
+ throw, not silent) a path that escapes the vault, lands in the Brain root, or
+ matches a vault-scope ignore/private rule; write atomically via
+ `writeFrontmatterAtomic`; return the vault-relative path. The MCP tool is a
+ thin handler returning a small fixed-shape ack via `vaultRelativeSafe`.
+- **Acceptance**: tests cover happy-path create with frontmatter+body,
+ path-traversal rejection, Brain-root rejection, ignore/private rejection,
+ atomic overwrite semantics, and the MCP tool happy-path + error-code mapping.
+ Registry/profile completeness tests stay green.
+- **Depends on**: none (but shares the primitive Unit C reuses).
+
+### Task 3: Bank export/import + CLI verbs (Unit A)
+- **Files**: `src/core/brain/portability/bundle.ts` (new);
+ `src/cli/brain/verbs/bank-export.ts`, `src/cli/brain/verbs/bank-import.ts`
+ (new) + dispatcher registration;
+ `tests/core/brain/portability/bundle.test.ts` (new) + CLI verb tests
+ following the graph-export/graph-import pattern.
+- **Surface**: `BANK_BUNDLE_SCHEMA_VERSION`, `BankBundle`,
+ `exportBankBundle(vault): BankBundle`,
+ `importBankBundle(vault, bundle, { mode }): BankImportResult`.
+- **Behaviour**: export composes `exportPreferencesJson`'s rows,
+ `exportVaultGraph`, `projectPageContracts`, and `aggregateSources` into one
+ schema-versioned envelope (deterministic, sorted). Import validates the
+ envelope shape, delegates page reconstruction to `importVaultGraph` under the
+ chosen conflict mode, restores preferences via the existing preference writer
+ (or scopes restore out with an explicit result flag if no clean writer
+ exists), and reports the sources dashboard as carried-not-restored. Per-entry
+ guards; malformed entries collected, never thrown.
+- **Acceptance**: tests cover round-trip export->import, schema version on the
+ envelope, conflict modes (skip/overwrite/merge) via the delegated importer,
+ per-entry rejection of malformed input, and the honest result object
+ (per-section counts + sources-not-restored flag).
+- **Depends on**: Task 1 (page contract).
+
+### Task 4: In-process SDK (Unit C)
+- **Files**: `src/core/brain/sdk.ts` (new); `tests/core/brain/sdk.test.ts`
+ (new).
+- **Surface**: `createBrain(vault)` returning a faƧade:
+ `exportBank()`, `importBank(bundle, opts)`, `exportGraph()`,
+ `importGraph(graph, opts)`, `exportPreferences(format)`,
+ `ingestSource(input, opts)`, `listSources()`, `getSource(id)`,
+ `deleteSource(id)`, `createNote(input)`.
+- **Behaviour**: every method is a one-line delegation to the corresponding core
+ function (`exportBankBundle`, `importBankBundle`, `exportVaultGraph`,
+ `importVaultGraph`, `exportPreferencesJson`/`exportPreferencesLlmsTxt`,
+ `ingestSource`, a `kind: brain-source` page enumeration for list/get,
+ `ensureInsideVault`-guarded delete, and `createNote`). The upstream
+ `writeStatus` maps to `ingestSource` (documented); no fabricated status field.
+- **Acceptance**: tests assert each faƧade method delegates and returns the core
+ result (export round-trip through the SDK, source create/list/get/delete
+ lifecycle, createNote via the SDK), and that the SDK adds no behaviour beyond
+ delegation.
+- **Depends on**: Task 1, Task 2, Task 3, and existing `ingestSource`.
+
+## Cross-cutting (Phase 4-5, after all tasks)
+
+- Full suite (`bun test`), `bun run typecheck`, `bun run lint`,
+ `bun run scripts/sync-version.ts --check`.
+- README capability paragraph + CHANGELOG entry under the new version heading
+ with its compare link-ref.
+- `package.json` version bump + `bun run scripts/sync-version.ts` (inside this
+ PR per `CLAUDE.md`).
diff --git a/docs/brainstorm/brain-portability-interop/variants.md b/docs/brainstorm/brain-portability-interop/variants.md
new file mode 100644
index 00000000..aa7603b2
--- /dev/null
+++ b/docs/brainstorm/brain-portability-interop/variants.md
@@ -0,0 +1,109 @@
+# Brain Portability & Interop - brainstorm audit trail
+
+Primary consultant: Claude Code (`claude -p`), exit 0, 3 parseable variants.
+Fallback (Codex) not invoked - the primary returned a complete, parseable set.
+
+The full consultant output is preserved verbatim in
+`cli-output/claude.md`; the variants are reproduced below.
+
+---
+
+### Variant 1: SDK-centric hub
+- **Approach**: Build Unit C's `createBrain(vault)` faƧade first and make it the
+ single composition point. Unit A's bank export/import, Unit B's per-page
+ projection, and Unit D's `brain_create_note` all route their logic through the
+ SDK, so the CLI verbs and MCP tool become thin shells over `createBrain(vault)`.
+ One object owns the orchestration of `exportPreferencesJson` +
+ `exportVaultGraph` + `aggregateSources`.
+- **Trade-offs**:
+ - Pro: a single chokepoint eliminates duplication across CLI, MCP, and SDK
+ surfaces; the SDK is dogfooded by its own consumers.
+ - Pro: write paths (`writeStatus`, note creation) share one provenance/guard
+ implementation.
+ - Con: tension with the "SDK must be a thin faƧade, not a reimplementation"
+ constraint - if bundle orchestration lives in the SDK it stops being thin.
+ - Con: forces C to land before A/B/D, serialising the four units and making the
+ SDK the critical path.
+ - Con: risk of SDK scope creep into a de-facto new subsystem, which the task
+ explicitly discourages.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Variant 2: Layered core with thin peer adapters
+- **Approach**: Add a small core bundle module beside the existing portability
+ helpers (e.g. `portability/bundle.ts` composing the existing exporters into a
+ schema-versioned bank envelope, plus `portability/page.ts` defining Unit B's
+ decoupled per-page contract as a pure projection). Each surface is a thin,
+ independent adapter over those core functions: Unit A is CLI verbs, Unit C
+ re-exposes the same core functions (including source-backed writes) as a
+ faƧade, and Unit D is an MCP tool calling vault/path helpers directly. No
+ surface depends on another surface.
+- **Trade-offs**:
+ - Pro: matches the repo's established structure exactly (one file per
+ portability concern, one CLI verb per file, tool-def array), so each unit
+ lands as a near-independent PR over shared core.
+ - Pro: keeps the SDK genuinely thin (re-export, not orchestrate) and keeps B's
+ contract decoupled from OSB internals in its own projection module.
+ - Pro: byte-identical-when-off and per-entry import validation fall out
+ naturally from reusing the existing envelope conventions.
+ - Con: four units touch the shared bundle module, needing light coordination on
+ the envelope shape.
+ - Con: slightly more files than folding into an existing module.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 3: Bank-as-graph-extension
+- **Approach**: Avoid a new bundle module by extending the existing
+ `exportVaultGraph` / `importVaultGraph` envelope to optionally carry
+ preferences, sources/provenance, and Unit B's per-page fields as extra sections
+ and per-node attributes of the same graph bundle. Units C and D are added as
+ small surfaces on top, reusing the extended exporter for any whole-vault read.
+- **Trade-offs**:
+ - Pro: smallest code footprint; literally one existing serialisation path
+ reused, with its conflict modes and `ensureInsideVault` guards already in
+ place.
+ - Con: overloads a link-graph exporter with non-graph concerns (preferences,
+ sources), conflating "page graph" with "whole bank."
+ - Con: envelope versioning becomes muddy - `GRAPH_VERSION` now gates unrelated
+ bank content, so the bank format cannot evolve independently.
+ - Con: bolting B's contract onto graph nodes works against the "decoupled from
+ OSB internals, stable interchange schema" requirement.
+- **Complexity**: small
+- **Risk**: medium
+
+### Recommended (consultant): Variant 2
+
+> It mirrors the repository's existing portability conventions (discrete core
+> modules, thin CLI/MCP/SDK adapters as peers), which keeps the SDK a genuine
+> faƧade and Unit B's interchange contract cleanly decoupled, satisfying the
+> stated constraints directly. It composes the existing exporters into a new
+> schema-versioned bank envelope rather than overloading the graph exporter
+> (Variant 3) or centralising orchestration in the SDK (Variant 1), so the four
+> units can land additively and independently in one release without forking a
+> parallel serialisation path.
+
+---
+
+## Orchestrator decision: agree with Variant 2
+
+No override. Variant 2 is the only option that satisfies all four hard
+constraints at once:
+
+- **"SDK is a thin faƧade, not a reimplementation"** - Variant 1 violates this by
+ moving bundle orchestration into the SDK; Variant 2 keeps orchestration in
+ core modules and the SDK delegates.
+- **"Unit B decoupled, stable interchange schema"** - Variant 3 violates this by
+ bolting the contract onto graph nodes under `GRAPH_VERSION`; Variant 2 gives
+ it its own module and `PAGE_CONTRACT_VERSION`.
+- **"Reuse existing exporters, no parallel serialisation path"** - Variant 2
+ composes `collectExportRows` + `exportVaultGraph` + `aggregateSources` instead
+ of re-serialising.
+- **"Additive, byte-identical-when-off"** - Variant 2's peer adapters add new
+ surfaces without touching existing ones; Variant 1's serialisation of the four
+ units and Variant 3's envelope overloading both increase blast radius.
+
+Implementation detail decided beyond the consultant's output: the page-contract
+module is named `page-contract.ts` (not `page.ts`) to avoid colliding with the
+generic "page" vocabulary already used across the vault layer, and the upstream
+`writeStatus` source API maps to the existing `ingestSource` write rather than a
+fabricated status field (OSB has no source status lifecycle).
diff --git a/docs/mcp.md b/docs/mcp.md
index 92d8736f..36428255 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -18,9 +18,10 @@ in Open Second Brain depends on the MCP server being running.
## Tool Highlights
-The full server currently advertises 57 tools; 18 further names stay callable
-through `tools/call` as hidden deprecated aliases (see "Consolidated views and
-deprecated aliases" below). The table highlights the operator-facing core,
+The full server currently advertises 77 tools; the 18 deprecated predecessor
+names were removed in 1.0.0 and now answer a precise INVALID_PARAMS tombstone
+(see "Consolidated views and deprecated aliases" below). The table highlights
+the operator-facing core,
schema, agent-source, health, and recovery tools; the full surface
also includes Brain writer, review, query, temporal, link-graph, and search
tools. In Claude Code, the full schema can push MCP definitions beyond 10% of
@@ -55,6 +56,7 @@ flags for a narrower per-process full server.
| `brain_session_describe` | Describe raw-turn counts and summary depths for one imported session recall DAG. | `session_id` |
| `brain_session_expand` | Expand a raw or summary session recall node to immediate sources and paginated raw turn content. | `id` |
| `brain_sources` | Read-only dashboard of signals grouped by (agent, source_type) with active/processed and distinct-topic counts. | — |
+| `brain_create_note` | Write an actual vault note file (path + frontmatter + content) atomically inside the vault. Distinct from `brain_note` (log append); refuses traversal, the Brain root, excluded paths, and clobbering. | `path` |
| `schema_inspect` | Read-only schema inspection for any view: `view: graph \| lint \| stats \| orphans \| explain_type \| active_pack \| packs`. | `view` (`token` for `explain_type`) |
| `schema_apply_mutations` | Apply audited, locked schema mutations to `Brain/_brain.yaml`. | `mutations` |
| `brain_watchdog` | Probe Brain config, required dirs, and search-index health; optionally apply safe directory remediation. | — |
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 26b5fdef..48a863c5 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.8.0",
+ "version": "1.9.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 7a430b22..29e8870c 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.8.0",
+ "version": "1.9.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 63d84707..c2ab609e 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.8.0"
+version: "1.9.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 ed8f4126..9372d931 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.8.0",
+ "version": "1.9.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 63d84707..c2ab609e 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.8.0"
+version: "1.9.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 9891e71e..b2cafcaa 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.8.0"
+version = "1.9.0"
description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/src/cli/brain.ts b/src/cli/brain.ts
index 0fb9039f..4a013cfd 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -56,6 +56,8 @@ import {
cmdBrainSchema,
cmdBrainGraphExport,
cmdBrainGraphImport,
+ cmdBrainBankExport,
+ cmdBrainBankImport,
cmdBrainBacklinks,
cmdBrainSemanticsBackfill,
cmdBrainMcpLandscape,
@@ -229,6 +231,10 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promis
return await cmdBrainGraphExport(rest);
case "graph-import":
return await cmdBrainGraphImport(rest);
+ case "bank-export":
+ return await cmdBrainBankExport(rest);
+ case "bank-import":
+ return await cmdBrainBankImport(rest);
case "backlinks":
return await cmdBrainBacklinks(rest);
case "semantics-backfill":
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
index bd628bf7..0a368c54 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -63,6 +63,8 @@ Brain verbs (observing memory):
schema Inspect resolved schema vocabulary and artifact token usage
graph-export Serialise the vault knowledge graph to graph.json
graph-import Reconstruct vault pages from graph.json (--mode skip|overwrite|merge)
+ bank-export Serialise a whole-vault bank bundle (prefs + graph + pages + sources)
+ bank-import Reconstruct the page graph from a bank bundle (--mode skip|overwrite|merge)
backlinks List inbound references to a Brain artifact id
semantics-backfill Preview deterministic typed preference-edge backfill proposals
mcp-landscape List MCP servers configured across the vault (packages, env names)
@@ -382,6 +384,15 @@ export const VERB_HELP: Record<string, string> = {
"usage: o2b brain graph-import <file> [--mode skip|overwrite|merge] [--vault <path>] [--json]\n" +
"Reconstruct vault page stubs from a graph.json. skip (default) never\n" +
"overwrites; merge unions wikilinks/relations; writes are vault-guarded.\n",
+ "bank-export":
+ "usage: o2b brain bank-export [--vault <path>] [--out <file>]\n" +
+ "Serialise a whole-vault bank bundle (preferences + page graph + page\n" +
+ "contracts + sources dashboard) to a schema-versioned JSON. Read-only.\n",
+ "bank-import":
+ "usage: o2b brain bank-import <file> [--mode skip|overwrite|merge] [--vault <path>] [--json]\n" +
+ "Reconstruct the page graph from a bank bundle. Preferences, page\n" +
+ "contracts, and the sources dashboard are reported as carried-not-restored;\n" +
+ "an unsupported bundle schema fails loudly.\n",
"morning-brief":
"usage: o2b brain morning-brief [--vault <path>] [--json] [--top-k <n>]\n" +
" [--lookback-days <n>] [--max-chars-per-memory <n>] [--max-total-chars <n>]\n" +
diff --git a/src/cli/brain/verbs/bank-export.ts b/src/cli/brain/verbs/bank-export.ts
new file mode 100644
index 00000000..e04721ba
--- /dev/null
+++ b/src/cli/brain/verbs/bank-export.ts
@@ -0,0 +1,33 @@
+import { atomicWriteFileSync } from "../../../core/fs-atomic.ts";
+import { exportBankBundle } from "../../../core/brain/portability/bundle.ts";
+import { brainVerbContext, fail, parse } from "../helpers.ts";
+
+/**
+ * `o2b brain bank-export [--out <file>]` - serialise a whole-vault bank
+ * bundle (preferences + page graph + page contracts + sources dashboard)
+ * to a schema-versioned JSON. Prints to stdout, or writes to
+ * `--out <file>`. Read-only on the vault.
+ */
+export async function cmdBrainBankExport(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, { vault: { type: "string" }, out: { type: "string" } });
+ const { vault } = brainVerbContext(flags);
+
+ let json: string;
+ try {
+ json = JSON.stringify(exportBankBundle(vault), null, 2) + "\n";
+ } catch (exc) {
+ return fail(`bank-export failed: ${(exc as Error).message ?? exc}`);
+ }
+
+ try {
+ if (typeof flags["out"] === "string") {
+ atomicWriteFileSync(flags["out"], json);
+ process.stdout.write(`wrote ${flags["out"]}\n`);
+ } else {
+ process.stdout.write(json);
+ }
+ } catch (exc) {
+ return fail(`bank-export failed to write output: ${(exc as Error).message ?? exc}`);
+ }
+ return 0;
+}
diff --git a/src/cli/brain/verbs/bank-import.ts b/src/cli/brain/verbs/bank-import.ts
new file mode 100644
index 00000000..3bd1bea6
--- /dev/null
+++ b/src/cli/brain/verbs/bank-import.ts
@@ -0,0 +1,67 @@
+import { readFileSync } from "node:fs";
+
+import { BankImportError, importBankBundle } from "../../../core/brain/portability/bundle.ts";
+import type { GraphImportMode } from "../../../core/brain/portability/graph.ts";
+import { brainVerbContext, fail, parse } from "../helpers.ts";
+
+const MODES: ReadonlyArray<GraphImportMode> = ["skip", "overwrite", "merge"];
+
+/**
+ * `o2b brain bank-import <file> [--mode skip|overwrite|merge] [--json]`
+ * reconstruct the page graph from a bank bundle.json. `skip` (default)
+ * never overwrites; preferences, page contracts, and the sources
+ * dashboard are reported as carried-not-restored. An unsupported bundle
+ * schema fails loudly.
+ */
+export async function cmdBrainBankImport(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ mode: { type: "string" },
+ });
+ const file = positional[0];
+ if (!file) {
+ process.stderr.write("usage: o2b brain bank-import <file> [--mode skip|overwrite|merge]\n");
+ return 2;
+ }
+
+ const mode = (flags["mode"] as string | undefined) ?? "skip";
+ if (!MODES.includes(mode as GraphImportMode)) {
+ process.stderr.write(
+ `error: bank-import: --mode must be one of ${MODES.join(" | ")}; got ${mode}\n`,
+ );
+ return 2;
+ }
+
+ const { vault } = brainVerbContext(flags);
+
+ // JSON boundary: parse then hand the loosely-typed shape to the
+ // importer, which validates the schema and guards every graph node.
+ let bundle: { schema?: unknown; graph?: { nodes?: ReadonlyArray<unknown> } };
+ try {
+ bundle = JSON.parse(readFileSync(file, "utf8")) as typeof bundle;
+ } catch (exc) {
+ return fail(`bank-import: failed to read ${file}: ${(exc as Error).message ?? exc}`);
+ }
+
+ let result;
+ try {
+ result = importBankBundle(vault, bundle, { mode: mode as GraphImportMode });
+ } catch (exc) {
+ if (exc instanceof BankImportError) return fail(`bank-import: ${exc.message}`);
+ return fail(`bank-import failed: ${(exc as Error).message ?? exc}`);
+ }
+
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
+ } else {
+ const g = result.graph;
+ process.stdout.write(
+ `graph: created ${g.created.length}, overwritten ${g.overwritten.length}, ` +
+ `merged ${g.merged.length}, skipped ${g.skipped.length}, rejected ${g.rejected.length}\n` +
+ `carried (not restored): ${result.preferencesCarried} preferences, ` +
+ `${result.pagesCarried} page contracts, sources ${result.sourcesCarried ? "yes" : "no"}\n`,
+ );
+ }
+ return 0;
+}
diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.ts
index 055c5bd4..fa3fed4e 100644
--- a/src/cli/brain/verbs/index.ts
+++ b/src/cli/brain/verbs/index.ts
@@ -40,6 +40,8 @@ export { cmdBrainSources } from "./sources.ts";
export { cmdBrainSchema } from "./schema.ts";
export { cmdBrainGraphExport } from "./graph-export.ts";
export { cmdBrainGraphImport } from "./graph-import.ts";
+export { cmdBrainBankExport } from "./bank-export.ts";
+export { cmdBrainBankImport } from "./bank-import.ts";
export { cmdBrainBacklinks } from "./backlinks.ts";
export { cmdBrainSemanticsBackfill } from "./semantics-backfill.ts";
export { cmdBrainMcpLandscape } from "./mcp-landscape.ts";
diff --git a/src/core/brain/ingest/sources-registry.ts b/src/core/brain/ingest/sources-registry.ts
new file mode 100644
index 00000000..dd1a8d7d
--- /dev/null
+++ b/src/core/brain/ingest/sources-registry.ts
@@ -0,0 +1,151 @@
+/**
+ * Ingested-source registry (Brain Portability & Interop suite, Unit C
+ * support).
+ *
+ * Read/list/delete over the per-source summary pages the ingest pipeline
+ * writes under `Brain/sources` with `kind: brain-source`. These are the
+ * "sources" the in-process SDK's source CRUD operates on (`ingestSource`
+ * is the write; this module is the read + delete half).
+ *
+ * Every read or delete addresses a source by its vault-relative summary
+ * path (the id `ingestSource` returns). An id that resolves outside
+ * `Brain/sources` is treated as not-found - never read as a source and
+ * never deleted - so the delete cannot be turned into an arbitrary
+ * unlink.
+ */
+
+import { existsSync, readdirSync, rmSync } from "node:fs";
+import { join, relative, posix, sep } from "node:path";
+
+import type { FrontmatterMap, FrontmatterValue } from "../../types.ts";
+import { ensureInsideVault } from "../../path-safety.ts";
+import { parseFrontmatter } from "../../vault.ts";
+import { BRAIN_SOURCES_REL } from "../paths.ts";
+import { BRAIN_SOURCE_KIND } from "./ingest.ts";
+
+export interface IngestedSource {
+ /** Vault-relative POSIX path of the summary page - the id for get/delete. */
+ readonly path: string;
+ readonly sourcePath: string | null;
+ readonly sourceHash: string | null;
+ readonly createdAt: string | null;
+ readonly updatedAt: string | null;
+}
+
+export interface IngestedSourceDetail extends IngestedSource {
+ /** Markdown body of the summary page. */
+ readonly body: string;
+}
+
+function sourcesDir(vault: string): string {
+ return join(vault, BRAIN_SOURCES_REL);
+}
+
+function stringField(meta: FrontmatterMap, key: string): string | null {
+ const value: FrontmatterValue | undefined = meta[key];
+ return typeof value === "string" && value.length > 0 ? value : null;
+}
+
+function toPosixRel(vault: string, abs: string): string {
+ return relative(vault, abs).split(/[\\/]/).join(posix.sep);
+}
+
+function summary(vault: string, abs: string, meta: FrontmatterMap): IngestedSource {
+ return {
+ path: toPosixRel(vault, abs),
+ sourcePath: stringField(meta, "source_path"),
+ sourceHash: stringField(meta, "source_hash"),
+ createdAt: stringField(meta, "created_at"),
+ updatedAt: stringField(meta, "updated_at"),
+ };
+}
+
+/**
+ * Resolve an untrusted source id to an absolute path that is guaranteed
+ * to live inside `Brain/sources`. Returns null when the id escapes the
+ * vault or lands outside the sources dir.
+ */
+function resolveSourceAbs(vault: string, id: string): string | null {
+ let abs: string;
+ try {
+ abs = ensureInsideVault(join(vault, id), vault);
+ } catch {
+ return null;
+ }
+ const dir = sourcesDir(vault);
+ if (abs !== dir && !abs.startsWith(dir + sep)) return null;
+ return abs;
+}
+
+/** List every ingested-source summary page, sorted by path. Read-only. */
+export function listIngestedSources(vault: string): ReadonlyArray<IngestedSource> {
+ const dir = sourcesDir(vault);
+ if (!existsSync(dir)) return [];
+ let entries: ReadonlyArray<string>;
+ try {
+ entries = readdirSync(dir);
+ } catch {
+ return [];
+ }
+ const out: IngestedSource[] = [];
+ for (const name of entries) {
+ if (!name.endsWith(".md")) continue;
+ const abs = join(dir, name);
+ let meta: FrontmatterMap;
+ try {
+ [meta] = parseFrontmatter(abs);
+ } catch {
+ continue;
+ }
+ if (meta["kind"] !== BRAIN_SOURCE_KIND) continue;
+ out.push(summary(vault, abs, meta));
+ }
+ out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
+ return out;
+}
+
+/**
+ * Read one ingested source by its vault-relative summary path. Returns
+ * null when the id is outside `Brain/sources`, the file is missing, or
+ * the page is not a `brain-source`.
+ */
+export function getIngestedSource(vault: string, id: string): IngestedSourceDetail | null {
+ const abs = resolveSourceAbs(vault, id);
+ if (abs === null || !existsSync(abs)) return null;
+ let meta: FrontmatterMap;
+ let body: string;
+ try {
+ [meta, body] = parseFrontmatter(abs);
+ } catch {
+ return null;
+ }
+ if (meta["kind"] !== BRAIN_SOURCE_KIND) return null;
+ return { ...summary(vault, abs, meta), body };
+}
+
+/**
+ * Delete one ingested-source summary page. Returns true when a
+ * `brain-source` page existed and was removed, false otherwise. An id
+ * outside `Brain/sources` or a non-source page is never deleted.
+ */
+export function deleteIngestedSource(vault: string, id: string): boolean {
+ const abs = resolveSourceAbs(vault, id);
+ if (abs === null || !existsSync(abs)) return false;
+ let meta: FrontmatterMap;
+ try {
+ [meta] = parseFrontmatter(abs);
+ } catch {
+ return false;
+ }
+ if (meta["kind"] !== BRAIN_SOURCE_KIND) return false;
+ try {
+ rmSync(abs);
+ } catch (err) {
+ // A concurrent delete (ENOENT after the existence check) means the page
+ // is already gone - honestly report "not removed by us". Any other error
+ // (permissions, I/O) is a real fault and must surface, not be hidden.
+ if ((err as NodeJS.ErrnoException)?.code === "ENOENT") return false;
+ throw err;
+ }
+ return true;
+}
diff --git a/src/core/brain/notes/create-note.ts b/src/core/brain/notes/create-note.ts
new file mode 100644
index 00000000..55e6d38d
--- /dev/null
+++ b/src/core/brain/notes/create-note.ts
@@ -0,0 +1,122 @@
+/**
+ * createNote primitive (Brain Portability & Interop suite, Unit D).
+ *
+ * The single write primitive behind the `brain_create_note` MCP tool and
+ * the SDK `createNote` method. It writes one Markdown note atomically,
+ * funnelled through `ensureInsideVault`, and refuses - with a typed
+ * {@link CreateNoteError}, never a silent skip - any path that is not a
+ * `.md` file, traverses outside the vault, lands in the Brain machinery
+ * root, is excluded by the vault scope, or would clobber an existing
+ * file. Refusing loudly is deliberate: a connected agent must learn its
+ * write was rejected rather than believe a note exists when it does not.
+ */
+
+import { mkdirSync } from "node:fs";
+import { dirname, join, posix } from "node:path";
+
+import type { FrontmatterMap } from "../../types.ts";
+import { ensureInsideVault } from "../../path-safety.ts";
+import { writeFrontmatterAtomic } from "../../vault.ts";
+import { inspectPath, resolveVaultScope } from "../../vault-scope/index.ts";
+import { BRAIN_ROOT_REL } from "../paths.ts";
+
+/** Machine-readable reason a {@link createNote} call was refused. */
+export type CreateNoteErrorCode = "invalid_path" | "excluded" | "exists" | "outside_vault";
+
+export class CreateNoteError extends Error {
+ readonly code: CreateNoteErrorCode;
+ constructor(code: CreateNoteErrorCode, message: string) {
+ super(message);
+ this.name = "CreateNoteError";
+ this.code = code;
+ }
+}
+
+export interface CreateNoteInput {
+ /** Vault-relative target path; must end in `.md`. */
+ readonly path: string;
+ /** Optional frontmatter map written above the body. */
+ readonly frontmatter?: FrontmatterMap;
+ /** Optional Markdown body. */
+ readonly content?: string;
+}
+
+export interface CreateNoteResult {
+ /** Vault-relative POSIX path of the created note. */
+ readonly path: string;
+ readonly created: true;
+}
+
+/**
+ * Create one Markdown note in the vault. Returns the created note's
+ * vault-relative path; throws {@link CreateNoteError} on any refusal.
+ */
+export function createNote(vault: string, input: CreateNoteInput): CreateNoteResult {
+ if (!input.path.toLowerCase().endsWith(".md")) {
+ throw new CreateNoteError("invalid_path", `note path must end in .md: ${input.path}`);
+ }
+ // The tool addresses notes by a vault-relative path; an absolute path is
+ // ambiguous (which root?) and is refused rather than silently re-rooted.
+ if (input.path.startsWith("/") || input.path.startsWith("\\")) {
+ throw new CreateNoteError("invalid_path", `note path must be vault-relative: ${input.path}`);
+ }
+
+ // inspectPath normalises the relative path and throws on `..` traversal;
+ // an absolute path also has no place here. Translate both into a typed
+ // CreateNoteError so callers get one error surface.
+ const scope = resolveVaultScope(vault);
+ let inspected;
+ try {
+ inspected = inspectPath(input.path, scope, vault);
+ } catch (err) {
+ throw new CreateNoteError("invalid_path", err instanceof Error ? err.message : String(err));
+ }
+ const relPath = inspected.relPath;
+ if (relPath === "") {
+ throw new CreateNoteError("invalid_path", `empty note path: ${input.path}`);
+ }
+
+ // The Brain machinery root is owned by the brain's own writers; a
+ // free-form note tool must never author into it (default vault-scope
+ // rules ignore Brain/.snapshots only, not the whole Brain root).
+ const firstSegment = relPath.split("/")[0];
+ if (firstSegment === BRAIN_ROOT_REL) {
+ throw new CreateNoteError(
+ "excluded",
+ `the Brain machinery root is not writable via create_note: ${relPath}`,
+ );
+ }
+
+ if (inspected.excluded) {
+ throw new CreateNoteError(
+ "excluded",
+ `path is excluded by vault scope (${inspected.rule?.raw ?? "rule"}): ${relPath}`,
+ );
+ }
+
+ let abs: string;
+ try {
+ abs = ensureInsideVault(join(vault, relPath), vault);
+ } catch (err) {
+ throw new CreateNoteError("outside_vault", err instanceof Error ? err.message : String(err));
+ }
+
+ mkdirSync(dirname(abs), { recursive: true });
+ try {
+ writeFrontmatterAtomic(abs, input.frontmatter ?? {}, input.content ?? "", {
+ overwrite: false,
+ existsErrorKind: "note",
+ vaultForRelativePath: vault,
+ });
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException)?.code;
+ const exists =
+ code === "EEXIST" || (err instanceof Error && /already exists/.test(err.message));
+ if (exists) {
+ throw new CreateNoteError("exists", `note already exists: ${relPath}`);
+ }
+ throw err;
+ }
+
+ return { path: relPath.split(/[\\/]/).join(posix.sep), created: true };
+}
diff --git a/src/core/brain/portability/bundle.ts b/src/core/brain/portability/bundle.ts
new file mode 100644
index 00000000..abac49c7
--- /dev/null
+++ b/src/core/brain/portability/bundle.ts
@@ -0,0 +1,124 @@
+/**
+ * Whole-vault (bank) export/import (Brain Portability & Interop suite,
+ * Unit A).
+ *
+ * `exportBankBundle` composes the existing exporters - preferences
+ * (`collectExportRows`), the page link-graph (`exportVaultGraph`), the
+ * page interchange contract (`projectPageContracts`), and the read-only
+ * sources dashboard (`aggregateSources`) - into one schema-versioned
+ * envelope for backup, cross-instance migration, or downstream-tool
+ * ingest. It forks no serialisation path; it only assembles.
+ *
+ * `importBankBundle` reconstructs the part that round-trips: the page
+ * graph, delegated to `importVaultGraph` under a conflict mode. The
+ * other sections are carried in the bundle for fidelity but are NOT
+ * silently "restored": preferences have a delicate confidence/audit
+ * lifecycle, the page contract is a read projection, and the sources
+ * dashboard is derived. The result object reports each carried section
+ * explicitly so the bundle can never be read as a full round-trip of
+ * material it did not reconstruct.
+ */
+
+import { collectExportRows, type ExportedPreferenceRow } from "../export.ts";
+import { isoSecond } from "../time.ts";
+import { vaultDisplayName } from "../templates.ts";
+import {
+ exportVaultGraph,
+ importVaultGraph,
+ type GraphImportMode,
+ type GraphImportResult,
+ type VaultGraph,
+} from "./graph.ts";
+import { projectPageContracts, type PageContract } from "./page-contract.ts";
+import { aggregateSources, type SourcesReport } from "./sources.ts";
+
+export const BANK_BUNDLE_SCHEMA_VERSION = "1";
+
+export interface BankBundle {
+ readonly schema: string;
+ /** Snapshot timestamp (ISO second). Not part of the content sections. */
+ readonly generated_at: string;
+ readonly vault_basename: string;
+ readonly preferences: ReadonlyArray<ExportedPreferenceRow>;
+ readonly graph: VaultGraph;
+ readonly pages: ReadonlyArray<PageContract>;
+ readonly sources: SourcesReport;
+}
+
+/**
+ * Export a whole-vault bank bundle. The content sections are
+ * deterministic (each underlying exporter sorts); only `generated_at`
+ * varies between runs. Pure and read-only on the vault.
+ */
+export function exportBankBundle(vault: string): BankBundle {
+ return {
+ schema: BANK_BUNDLE_SCHEMA_VERSION,
+ generated_at: isoSecond(),
+ vault_basename: vaultDisplayName(vault),
+ preferences: collectExportRows(vault),
+ graph: exportVaultGraph(vault),
+ pages: projectPageContracts(vault),
+ sources: aggregateSources(vault),
+ };
+}
+
+/** Raised when a whole-bundle invariant fails (e.g. an unknown schema). */
+export class BankImportError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "BankImportError";
+ }
+}
+
+export interface BankImportResult {
+ readonly schema: string;
+ /** Page-graph reconstruction outcome (delegated to importVaultGraph). */
+ readonly graph: GraphImportResult;
+ /** Preferences present in the bundle but not restored (lifecycle-sensitive). */
+ readonly preferencesCarried: number;
+ /** Page-contract records present in the bundle but not restored (a read projection). */
+ readonly pagesCarried: number;
+ /** Whether the bundle carried a sources dashboard (derived; not restored). */
+ readonly sourcesCarried: boolean;
+}
+
+/** Loosely-typed bundle input - untrusted JSON, validated here. */
+interface BankBundleInput {
+ readonly schema?: unknown;
+ readonly graph?: { readonly nodes?: ReadonlyArray<unknown> };
+ readonly preferences?: unknown;
+ readonly pages?: unknown;
+ readonly sources?: unknown;
+}
+
+/**
+ * Import a bank bundle: reconstruct the page graph and report what else
+ * the bundle carried. An unsupported schema fails loudly with a
+ * {@link BankImportError}; a malformed individual graph node is rejected
+ * per-entry by `importVaultGraph` and the run continues.
+ */
+export function importBankBundle(
+ vault: string,
+ bundle: BankBundleInput,
+ opts: { mode?: GraphImportMode } = {},
+): BankImportResult {
+ if (bundle === null || typeof bundle !== "object") {
+ throw new BankImportError("invalid bank bundle payload: expected an object");
+ }
+ if (bundle.schema !== BANK_BUNDLE_SCHEMA_VERSION) {
+ throw new BankImportError(
+ `unsupported bank bundle schema: expected ${BANK_BUNDLE_SCHEMA_VERSION}, got ${String(bundle.schema)}`,
+ );
+ }
+
+ const graphInput = bundle.graph ?? { nodes: [] };
+ const graph = importVaultGraph(vault, graphInput, { mode: opts.mode ?? "skip" });
+
+ return {
+ schema: BANK_BUNDLE_SCHEMA_VERSION,
+ graph,
+ preferencesCarried: Array.isArray(bundle.preferences) ? bundle.preferences.length : 0,
+ pagesCarried: Array.isArray(bundle.pages) ? bundle.pages.length : 0,
+ sourcesCarried: bundle.sources !== undefined && bundle.sources !== null,
+ };
+}
diff --git a/src/core/brain/portability/graph.ts b/src/core/brain/portability/graph.ts
index 0d698fb0..a3a16adb 100644
--- a/src/core/brain/portability/graph.ts
+++ b/src/core/brain/portability/graph.ts
@@ -195,7 +195,10 @@ function readExisting(path: string): { links: string[]; relations: Record<string
*/
export function importVaultGraph(
vault: string,
- graph: { nodes?: ReadonlyArray<GraphNodeInput> },
+ // Untrusted input (JSON from a graph.json or a bank bundle); every node
+ // is shape-guarded per entry below, so the element type is `unknown`
+ // rather than a structural promise the runtime does not enforce.
+ graph: { nodes?: ReadonlyArray<unknown> },
opts: { mode?: GraphImportMode } = {},
): GraphImportResult {
const mode: GraphImportMode = opts.mode ?? "skip";
@@ -208,7 +211,11 @@ export function importVaultGraph(
};
const vaultMap = loadVaultMap(vault);
- for (const node of graph.nodes ?? []) {
+ // Guard the container shape: a non-array `nodes` (string, object, scalar)
+ // from untrusted JSON would otherwise throw or mis-iterate. Per-entry
+ // validation below still rejects each malformed element.
+ const nodes = Array.isArray(graph.nodes) ? graph.nodes : [];
+ for (const node of nodes) {
// Validate the node shape per entry: a single malformed JSON node is
// rejected and the import continues, instead of throwing and aborting
// the whole run. `graph` arrives from untrusted JSON, so the static
diff --git a/src/core/brain/portability/page-contract.ts b/src/core/brain/portability/page-contract.ts
new file mode 100644
index 00000000..41fba724
--- /dev/null
+++ b/src/core/brain/portability/page-contract.ts
@@ -0,0 +1,135 @@
+/**
+ * Page interchange contract (Brain Portability & Interop suite, Unit B).
+ *
+ * `projectPageContracts` serialises every user vault page (the Brain
+ * machinery root and the standard ignored dirs excluded) into a stable,
+ * sorted, schema-versioned interchange record a downstream importer can
+ * consume without knowing OSB internals. Each record carries the page's
+ * `path`, `kind`, advisory `confidence`/`provenance`, flattened
+ * `citations`, `aliases`, and `freshness`.
+ *
+ * Derivation is structural only - frontmatter fields, body wikilinks,
+ * typed-relation targets, and the file mtime. The provider-agnostic
+ * kernel never synthesises a field, and no natural-language heuristic
+ * (keyword/title matching in any language) is used: an absent advisory
+ * field is reported as `null`, never guessed.
+ */
+
+import { statSync } from "node:fs";
+import { posix, relative } from "node:path";
+
+import { EXCLUDED_DIRS, extractWikilinks, listVaultPages, parseFrontmatter } from "../../vault.ts";
+import type { FrontmatterMap, FrontmatterValue } from "../../types.ts";
+import {
+ extractFrontmatterRelations,
+ normalizeRelationTarget,
+} from "../../graph/frontmatter-relations.ts";
+import { BRAIN_ROOT_REL } from "../paths.ts";
+import { isoSecond } from "../time.ts";
+
+export const PAGE_CONTRACT_VERSION = "1";
+
+/** Structural default `kind` for a page with no frontmatter `kind:` field. */
+export const DEFAULT_PAGE_KIND = "note";
+
+export interface PageContract {
+ /** Vault-relative POSIX path. */
+ readonly path: string;
+ /** Frontmatter `kind:` when present, else the structural default. */
+ readonly kind: string;
+ /** Advisory: frontmatter `confidence` (number or string) when present. */
+ readonly confidence: number | string | null;
+ /** Advisory: frontmatter `provenance` string when present. */
+ readonly provenance: string | null;
+ /** Sorted-unique body wikilink + typed-relation targets. */
+ readonly citations: ReadonlyArray<string>;
+ /** Frontmatter `aliases`, else empty. */
+ readonly aliases: ReadonlyArray<string>;
+ /** Frontmatter `updated_at`/`updated` else the file mtime (ISO second). */
+ readonly freshness: string | null;
+}
+
+/** Frontmatter timestamp fields, in precedence order, for `freshness`. */
+const FRESHNESS_FIELDS = ["updated_at", "updated"] as const;
+
+function stringField(meta: FrontmatterMap, key: string): string | null {
+ const value: FrontmatterValue | undefined = meta[key];
+ return typeof value === "string" && value.length > 0 ? value : null;
+}
+
+function confidenceField(meta: FrontmatterMap): number | string | null {
+ const value: FrontmatterValue | undefined = meta["confidence"];
+ if (typeof value === "number") return value;
+ if (typeof value === "string" && value.length > 0) return value;
+ return null;
+}
+
+function aliasField(meta: FrontmatterMap): ReadonlyArray<string> {
+ const value: FrontmatterValue | undefined = meta["aliases"];
+ if (!Array.isArray(value)) return [];
+ return value.filter((item): item is string => typeof item === "string");
+}
+
+function sortedUnique(values: Iterable<string>): string[] {
+ return [...new Set([...values].filter((v) => v.length > 0))].toSorted();
+}
+
+/**
+ * Collect a page's citations: every body wikilink plus every typed
+ * relation target, normalised, de-duplicated, and sorted. Reuses the
+ * same extraction the graph exporter uses so the contract stays
+ * decoupled from any natural-language parsing.
+ */
+function collectCitations(meta: FrontmatterMap, body: string): string[] {
+ const targets: string[] = [];
+ for (const raw of extractWikilinks(body)) {
+ const norm = normalizeRelationTarget(raw);
+ if (norm !== null) targets.push(norm);
+ }
+ for (const edge of extractFrontmatterRelations(meta)) targets.push(edge.target);
+ return sortedUnique(targets);
+}
+
+function freshnessOf(meta: FrontmatterMap, absPath: string): string | null {
+ for (const field of FRESHNESS_FIELDS) {
+ const stamp = stringField(meta, field);
+ if (stamp !== null) return stamp;
+ }
+ try {
+ return isoSecond(statSync(absPath).mtime);
+ } catch {
+ // A page that listed but cannot be stat'd has no derivable freshness;
+ // report null rather than fabricating a timestamp.
+ return null;
+ }
+}
+
+/**
+ * Project every user vault page to a {@link PageContract}, sorted by
+ * `path` for deterministic output. Pure and read-only.
+ */
+export function projectPageContracts(vault: string): ReadonlyArray<PageContract> {
+ const pages = listVaultPages(vault, { skipDirs: [...EXCLUDED_DIRS, BRAIN_ROOT_REL] });
+ const contracts: PageContract[] = [];
+ for (const page of pages) {
+ let body: string;
+ try {
+ const [, parsedBody] = parseFrontmatter(page.path);
+ body = parsedBody;
+ } catch {
+ continue;
+ }
+ const meta = page.metadata;
+ contracts.push({
+ path: relative(vault, page.path).split(/[\\/]/).join(posix.sep),
+ kind: stringField(meta, "kind") ?? DEFAULT_PAGE_KIND,
+ confidence: confidenceField(meta),
+ provenance: stringField(meta, "provenance"),
+ citations: collectCitations(meta, body),
+ aliases: aliasField(meta),
+ freshness: freshnessOf(meta, page.path),
+ });
+ }
+ contracts.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
+ return contracts;
+}
diff --git a/src/core/brain/sdk.ts b/src/core/brain/sdk.ts
new file mode 100644
index 00000000..0f1ec51c
--- /dev/null
+++ b/src/core/brain/sdk.ts
@@ -0,0 +1,104 @@
+/**
+ * In-process SDK (Brain Portability & Interop suite, Unit C).
+ *
+ * `createBrain(vault)` returns a thin faƧade over the existing core
+ * functions, so other tools, scripts, and agents can manage brain
+ * content programmatically without the CLI or MCP layer. Every method is
+ * a one-line delegation; the SDK adds no behaviour of its own and forks
+ * no logic. It is the in-process analogue of the CLI/MCP surfaces, not a
+ * new subsystem.
+ *
+ * Source-backed writes map to OSB's actual model: `ingestSource` is the
+ * write (the upstream `writeStatus` analogue - OSB stamps `updated_at`
+ * and rewrites idempotently rather than tracking a separate status
+ * lifecycle), and `listSources`/`getSource`/`deleteSource` operate on the
+ * `kind: brain-source` summary pages.
+ */
+
+import type { CreateNoteInput, CreateNoteResult } from "./notes/create-note.ts";
+import { createNote } from "./notes/create-note.ts";
+import type { ExportedPreferencesJson } from "./export.ts";
+import { exportPreferencesJson, exportPreferencesLlmsTxt } from "./export.ts";
+import {
+ type BankBundle,
+ type BankImportResult,
+ exportBankBundle,
+ importBankBundle,
+} from "./portability/bundle.ts";
+import {
+ type GraphImportMode,
+ type GraphImportResult,
+ type VaultGraph,
+ exportVaultGraph,
+ importVaultGraph,
+} from "./portability/graph.ts";
+import type {
+ IngestSourceInput,
+ IngestSourceOptions,
+ IngestSourceResult,
+} from "./ingest/ingest.ts";
+import { ingestSource } from "./ingest/ingest.ts";
+import type { IngestedSource, IngestedSourceDetail } from "./ingest/sources-registry.ts";
+import {
+ deleteIngestedSource,
+ getIngestedSource,
+ listIngestedSources,
+} from "./ingest/sources-registry.ts";
+
+export interface BrainSdk {
+ /** The vault every method is bound to. */
+ readonly vault: string;
+
+ // Whole-vault bank export/import (Unit A).
+ exportBank(): BankBundle;
+ importBank(
+ bundle: Parameters<typeof importBankBundle>[1],
+ opts?: { mode?: GraphImportMode },
+ ): BankImportResult;
+
+ // Page link-graph export/import.
+ exportGraph(): VaultGraph;
+ importGraph(
+ graph: { nodes?: ReadonlyArray<unknown> },
+ opts?: { mode?: GraphImportMode },
+ ): GraphImportResult;
+
+ // Preference export.
+ exportPreferencesJson(): ExportedPreferencesJson;
+ exportPreferencesLlmsTxt(): string;
+
+ // Source-backed writes + reads.
+ ingestSource(input: IngestSourceInput, opts: IngestSourceOptions): IngestSourceResult;
+ listSources(): ReadonlyArray<IngestedSource>;
+ getSource(id: string): IngestedSourceDetail | null;
+ deleteSource(id: string): boolean;
+
+ // Note authoring.
+ createNote(input: CreateNoteInput): CreateNoteResult;
+}
+
+/**
+ * Build an in-process Brain faƧade bound to one vault. Each method
+ * delegates to the corresponding core function.
+ */
+export function createBrain(vault: string): BrainSdk {
+ return {
+ vault,
+
+ exportBank: () => exportBankBundle(vault),
+ importBank: (bundle, opts) => importBankBundle(vault, bundle, opts ?? {}),
+
+ exportGraph: () => exportVaultGraph(vault),
+ importGraph: (graph, opts) => importVaultGraph(vault, graph, opts ?? {}),
+
+ exportPreferencesJson: () => exportPreferencesJson(vault),
+ exportPreferencesLlmsTxt: () => exportPreferencesLlmsTxt(vault),
+
+ ingestSource: (input, opts) => ingestSource(vault, input, opts),
+ listSources: () => listIngestedSources(vault),
+ getSource: (id) => getIngestedSource(vault, id),
+ deleteSource: (id) => deleteIngestedSource(vault, id),
+
+ createNote: (input) => createNote(vault, input),
+ };
+}
diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.ts
index ad30dda4..6cfdbb71 100644
--- a/src/mcp/brain-tools.ts
+++ b/src/mcp/brain-tools.ts
@@ -30,6 +30,7 @@ import { NER_TOOLS } from "./brain/ner-tools.ts";
import { INGEST_TOOLS } from "./brain/ingest-tools.ts";
import { RESEARCH_TOOLS } from "./brain/research-tools.ts";
import { DERIVE_TOOLS } from "./brain/derive-tools.ts";
+import { NOTES_TOOLS } from "./brain/notes-tools.ts";
import type { ToolDefinition } from "./tools.ts";
export { vaultRelativeSafe } from "./brain/shared.ts";
@@ -55,4 +56,5 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
...INGEST_TOOLS,
...RESEARCH_TOOLS,
...DERIVE_TOOLS,
+ ...NOTES_TOOLS,
]);
diff --git a/src/mcp/brain/notes-tools.ts b/src/mcp/brain/notes-tools.ts
new file mode 100644
index 00000000..34bfffd1
--- /dev/null
+++ b/src/mcp/brain/notes-tools.ts
@@ -0,0 +1,107 @@
+/**
+ * Brain note-authoring surface: `brain_create_note`.
+ *
+ * Distinct from `brain_note` (which appends one narrative line to the
+ * daily log), this tool writes an actual vault note file - path,
+ * frontmatter, and body - through the shared `createNote` primitive.
+ * The primitive enforces the vault-scope, path-traversal, Brain-root,
+ * and no-clobber guards; this handler only coerces arguments and maps a
+ * typed `CreateNoteError` to a client-side INVALID_PARAMS.
+ */
+
+import type { FrontmatterMap, FrontmatterValue } from "../../core/types.ts";
+import { createNote, CreateNoteError } from "../../core/brain/notes/create-note.ts";
+import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";
+import type { ServerContext, ToolDefinition } from "../tools.ts";
+import { coerceStr } from "../coerce.ts";
+
+/**
+ * Narrow an untrusted `frontmatter` argument to a {@link FrontmatterMap}.
+ * Accepts a plain object whose values are strings, numbers, booleans, or
+ * string arrays (the frontmatter value domain); rejects anything else
+ * with INVALID_PARAMS rather than silently dropping it.
+ */
+function parseFrontmatterArg(value: unknown): FrontmatterMap | undefined {
+ if (value === undefined || value === null) return undefined;
+ if (typeof value !== "object" || Array.isArray(value)) {
+ throw new MCPError(INVALID_PARAMS, "brain_create_note: frontmatter must be an object");
+ }
+ // Prototype-free target + explicit rejection of prototype-mutating keys:
+ // `frontmatter` is untrusted, and a `__proto__`/`constructor`/`prototype`
+ // key with an array value would otherwise pollute the object prototype.
+ const out: FrontmatterMap = Object.create(null) as FrontmatterMap;
+ for (const [key, raw] of Object.entries(value)) {
+ if (key === "__proto__" || key === "constructor" || key === "prototype") {
+ throw new MCPError(INVALID_PARAMS, `brain_create_note: invalid frontmatter key "${key}"`);
+ }
+ let coerced: FrontmatterValue;
+ if (typeof raw === "string" || typeof raw === "number" || typeof raw === "boolean") {
+ coerced = raw;
+ } else if (Array.isArray(raw) && raw.every((item) => typeof item === "string")) {
+ coerced = raw.filter((item): item is string => typeof item === "string");
+ } else {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_create_note: frontmatter.${key} must be a string, number, boolean, or string array`,
+ );
+ }
+ out[key] = coerced;
+ }
+ return out;
+}
+
+async function toolBrainCreateNote(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const path = coerceStr(args, "path", true)!;
+ const content = coerceStr(args, "content", false);
+ const frontmatter = parseFrontmatterArg(args["frontmatter"]);
+
+ try {
+ const res = createNote(ctx.vault, {
+ path,
+ ...(frontmatter !== undefined ? { frontmatter } : {}),
+ ...(content !== null && content !== undefined ? { content } : {}),
+ });
+ return { created: res.created, path: res.path };
+ } catch (err) {
+ // Every CreateNoteError is a client-input fault (bad path, excluded
+ // location, or an existing target); report it as INVALID_PARAMS with
+ // the typed message. Anything else is a genuine I/O fault.
+ if (err instanceof CreateNoteError) {
+ throw new MCPError(INVALID_PARAMS, `brain_create_note: ${err.message}`);
+ }
+ throw new MCPError(INTERNAL_ERROR, err instanceof Error ? err.message : String(err));
+ }
+}
+
+export const NOTES_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
+ {
+ name: "brain_create_note",
+ description:
+ "Create an actual vault note file (path + frontmatter + content), written atomically inside the vault. Distinct from brain_note, which only appends a log line. Refuses path traversal, the Brain machinery root, vault-scope-excluded paths, and overwriting an existing note.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ path: {
+ type: "string",
+ description: "Vault-relative target path; must end in .md and stay inside the vault.",
+ },
+ frontmatter: {
+ type: "object",
+ description:
+ "Optional frontmatter map; values are strings, numbers, booleans, or string arrays.",
+ additionalProperties: { type: ["string", "number", "boolean", "array"] },
+ },
+ content: {
+ type: "string",
+ description: "Optional Markdown body written below the frontmatter.",
+ },
+ },
+ required: ["path"],
+ additionalProperties: false,
+ },
+ handler: toolBrainCreateNote,
+ },
+]);
diff --git a/src/mcp/registry-guard.ts b/src/mcp/registry-guard.ts
index 05fb3b5b..fcbb9370 100644
--- a/src/mcp/registry-guard.ts
+++ b/src/mcp/registry-guard.ts
@@ -83,6 +83,7 @@ export const PREVIEW_BUDGET_EXEMPT: Readonly<Record<string, string>> = Object.fr
brain_feedback: "write; returns a small fixed-shape ack",
brain_apply_evidence: "write; returns a small fixed-shape ack",
brain_note: "write; returns a small fixed-shape ack",
+ brain_create_note: "write; returns the created note path and a created flag",
brain_pinned_context: "pinned.md is operator-curated and small by practice",
brain_recall_feedback: "write; returns one event receipt plus bounded weights",
brain_switch_vault: "write; returns a small profile ack",
diff --git a/tests/cli/bank-bundle-cli.test.ts b/tests/cli/bank-bundle-cli.test.ts
new file mode 100644
index 00000000..2a8d8fbd
--- /dev/null
+++ b/tests/cli/bank-bundle-cli.test.ts
@@ -0,0 +1,94 @@
+/**
+ * CLI surface for the Brain Portability & Interop suite (Unit A):
+ * `o2b brain bank-export | bank-import`. Locks argument shape, --json,
+ * --mode validation, and exit codes; the core has its own unit coverage.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let config: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-bank-cli-"));
+ vault = join(tmp, "vault");
+ config = join(tmp, "config.yaml");
+});
+afterEach(() => rmSync(tmp, { recursive: true, force: true }));
+
+async function bootstrap(): Promise<void> {
+ expect(
+ (
+ await runCli(["init", "--vault", vault, "--name", "T"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ })
+ ).returncode,
+ ).toBe(0);
+ expect(
+ (
+ await runCli(["brain", "init", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ })
+ ).returncode,
+ ).toBe(0);
+}
+
+describe("o2b brain bank-export / bank-import", () => {
+ test("bank-export emits a schema-versioned bundle with content sections", async () => {
+ await bootstrap();
+ writeFileSync(join(vault, "Note.md"), "---\ntitle: Note\n---\nlinks to [[Other]].\n");
+ const exp = await runCli(["brain", "bank-export"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(exp.returncode).toBe(0);
+ const bundle = JSON.parse(exp.stdout);
+ expect(bundle.schema).toBe("1");
+ expect(Array.isArray(bundle.graph.nodes)).toBe(true);
+ expect(Array.isArray(bundle.pages)).toBe(true);
+ expect(Array.isArray(bundle.preferences)).toBe(true);
+ });
+
+ test("bank-export then bank-import round-trips the page graph", async () => {
+ await bootstrap();
+ writeFileSync(join(vault, "Note.md"), "---\ntitle: Note\n---\nlinks to [[Other]].\n");
+ const exp = await runCli(["brain", "bank-export"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(exp.returncode).toBe(0);
+ const bundleFile = join(tmp, "bank.json");
+ writeFileSync(bundleFile, exp.stdout);
+ const imp = await runCli(["brain", "bank-import", bundleFile, "--mode", "skip", "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(imp.returncode).toBe(0);
+ const result = JSON.parse(imp.stdout);
+ // The page already exists in the same vault -> skipped (idempotent).
+ expect(result.graph.skipped).toContain("Note.md");
+ expect(typeof result.pagesCarried).toBe("number");
+ });
+
+ test("bank-import rejects an unknown --mode", async () => {
+ await bootstrap();
+ writeFileSync(join(tmp, "b.json"), '{"schema":"1","graph":{"nodes":[]}}');
+ const r = await runCli(["brain", "bank-import", join(tmp, "b.json"), "--mode", "bogus"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).not.toBe(0);
+ });
+
+ test("bank-import fails loudly on an unsupported schema", async () => {
+ await bootstrap();
+ writeFileSync(join(tmp, "old.json"), '{"schema":"999","graph":{"nodes":[]}}');
+ const r = await runCli(["brain", "bank-import", join(tmp, "old.json")], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).not.toBe(0);
+ expect(r.stderr).toContain("schema");
+ });
+});
diff --git a/tests/core/brain/ingest/sources-registry.test.ts b/tests/core/brain/ingest/sources-registry.test.ts
new file mode 100644
index 00000000..6c917770
--- /dev/null
+++ b/tests/core/brain/ingest/sources-registry.test.ts
@@ -0,0 +1,94 @@
+/**
+ * Ingested-source registry (Brain Portability & Interop suite, Unit C
+ * support). Read/list/delete over the `kind: brain-source` summary pages
+ * the ingest pipeline writes under Brain/sources. The SDK source CRUD
+ * delegates here. Guarded: an id that resolves outside Brain/sources is
+ * treated as not-found, never deleted.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
+import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";
+import { ingestSource } from "../../../../src/core/brain/ingest/ingest.ts";
+import {
+ deleteIngestedSource,
+ getIngestedSource,
+ listIngestedSources,
+} from "../../../../src/core/brain/ingest/sources-registry.ts";
+
+let vault: string;
+let configHome: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-sources-reg-vault-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-sources-reg-cfg-"));
+ const configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+function seedSource(sourcePath: string): string {
+ const res = ingestSource(
+ vault,
+ {
+ sourcePath,
+ summary: `summary of ${sourcePath}`,
+ extraction: { entities: [{ category: "concept", name: "Topic" }], relations: [] },
+ },
+ { agent: "claude", now: new Date("2026-01-01T00:00:00Z") },
+ );
+ return res.summaryPath;
+}
+
+describe("ingested-source registry", () => {
+ test("lists ingested source pages, sorted by path", () => {
+ seedSource("Articles/a.md");
+ seedSource("Articles/b.md");
+ const sources = listIngestedSources(vault);
+ expect(sources.length).toBe(2);
+ const paths = sources.map((s) => s.path);
+ expect(paths).toEqual([...paths].toSorted());
+ expect(sources[0]!.sourcePath).toBeDefined();
+ });
+
+ test("ignores non-source markdown in the sources dir", () => {
+ seedSource("Articles/a.md");
+ // A stray markdown file without the brain-source kind is not a source.
+ writeFileSync(join(vault, "Brain/sources/stray.md"), "---\ntitle: Stray\n---\nx\n");
+ expect(listIngestedSources(vault).length).toBe(1);
+ });
+
+ test("getIngestedSource returns the record with its body, else null", () => {
+ const id = seedSource("Articles/a.md");
+ const detail = getIngestedSource(vault, id);
+ expect(detail).not.toBeNull();
+ expect(detail!.path).toBe(id);
+ expect(detail!.body).toContain("summary of Articles/a.md");
+ expect(getIngestedSource(vault, "Brain/sources/does-not-exist.md")).toBeNull();
+ });
+
+ test("deleteIngestedSource removes the page and reports whether it existed", () => {
+ const id = seedSource("Articles/a.md");
+ expect(deleteIngestedSource(vault, id)).toBe(true);
+ expect(getIngestedSource(vault, id)).toBeNull();
+ expect(deleteIngestedSource(vault, id)).toBe(false);
+ });
+
+ test("an id outside Brain/sources is treated as not-found, never deleted", () => {
+ writeFileSync(join(vault, "Outside.md"), "important user note");
+ expect(deleteIngestedSource(vault, "Outside.md")).toBe(false);
+ expect(getIngestedSource(vault, "Outside.md")).toBeNull();
+ // The unrelated file must remain on disk - the guard never deletes it.
+ expect(existsSync(join(vault, "Outside.md"))).toBe(true);
+ expect(deleteIngestedSource(vault, "../escape.md")).toBe(false);
+ });
+});
diff --git a/tests/core/brain/notes/create-note.test.ts b/tests/core/brain/notes/create-note.test.ts
new file mode 100644
index 00000000..0f98a07a
--- /dev/null
+++ b/tests/core/brain/notes/create-note.test.ts
@@ -0,0 +1,100 @@
+/**
+ * createNote primitive (Brain Portability & Interop suite, Unit D).
+ *
+ * The shared write primitive behind the `brain_create_note` MCP tool and
+ * the SDK `createNote` method. Writes a Markdown note atomically under
+ * `ensureInsideVault`, honouring vault-scope ignore rules and refusing
+ * the Brain machinery root, path traversal, and clobbering an existing
+ * file - every refusal is a typed `CreateNoteError`, never a silent skip.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { createNote, CreateNoteError } from "../../../../src/core/brain/notes/create-note.ts";
+
+let vault: string;
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-create-note-"));
+});
+afterEach(() => rmSync(vault, { recursive: true, force: true }));
+
+describe("createNote", () => {
+ test("writes a note with frontmatter and body, returns the vault-relative path", () => {
+ const res = createNote(vault, {
+ path: "Notes/New.md",
+ frontmatter: { title: "New", tags: ["a", "b"] },
+ content: "Hello body.",
+ });
+ expect(res.created).toBe(true);
+ expect(res.path).toBe("Notes/New.md");
+ const written = readFileSync(join(vault, "Notes/New.md"), "utf8");
+ expect(written).toContain("title: New");
+ expect(written).toContain("Hello body.");
+ });
+
+ test("creates intermediate directories", () => {
+ createNote(vault, { path: "A/B/C/Deep.md", content: "x" });
+ expect(existsSync(join(vault, "A/B/C/Deep.md"))).toBe(true);
+ });
+
+ test("allows a note with no frontmatter and no content", () => {
+ const res = createNote(vault, { path: "Notes/Empty.md" });
+ expect(res.created).toBe(true);
+ expect(existsSync(join(vault, "Notes/Empty.md"))).toBe(true);
+ });
+
+ test("rejects a non-.md path with a typed error", () => {
+ expect(() => createNote(vault, { path: "Notes/data.json", content: "x" })).toThrow(
+ CreateNoteError,
+ );
+ });
+
+ test("rejects path traversal with a typed error", () => {
+ expect(() => createNote(vault, { path: "../escape.md", content: "x" })).toThrow(
+ CreateNoteError,
+ );
+ expect(existsSync(join(vault, "..", "escape.md"))).toBe(false);
+ });
+
+ test("rejects an absolute path with a typed error", () => {
+ expect(() => createNote(vault, { path: "/etc/evil.md", content: "x" })).toThrow(
+ CreateNoteError,
+ );
+ });
+
+ test("refuses to write into the Brain machinery root", () => {
+ expect(() => createNote(vault, { path: "Brain/sneaky.md", content: "x" })).toThrow(
+ CreateNoteError,
+ );
+ expect(existsSync(join(vault, "Brain/sneaky.md"))).toBe(false);
+ });
+
+ test("refuses a vault-scope excluded path", () => {
+ expect(() => createNote(vault, { path: ".obsidian/plugins/x.md", content: "x" })).toThrow(
+ CreateNoteError,
+ );
+ });
+
+ test("refuses to clobber an existing note (no overwrite)", () => {
+ mkdirSync(join(vault, "Notes"), { recursive: true });
+ writeFileSync(join(vault, "Notes/Dup.md"), "original", "utf8");
+ expect(() => createNote(vault, { path: "Notes/Dup.md", content: "new" })).toThrow(
+ CreateNoteError,
+ );
+ // The original content is untouched.
+ expect(readFileSync(join(vault, "Notes/Dup.md"), "utf8")).toBe("original");
+ });
+
+ test("the typed error carries a machine-readable code", () => {
+ try {
+ createNote(vault, { path: "../escape.md", content: "x" });
+ throw new Error("expected throw");
+ } catch (err) {
+ expect(err).toBeInstanceOf(CreateNoteError);
+ expect((err as CreateNoteError).code).toBe("invalid_path");
+ }
+ });
+});
diff --git a/tests/core/brain/portability/bundle.test.ts b/tests/core/brain/portability/bundle.test.ts
new file mode 100644
index 00000000..5733e634
--- /dev/null
+++ b/tests/core/brain/portability/bundle.test.ts
@@ -0,0 +1,127 @@
+/**
+ * Whole-vault (bank) export/import (Brain Portability & Interop suite,
+ * Unit A). `exportBankBundle` composes the existing exporters into one
+ * schema-versioned envelope; `importBankBundle` reconstructs the page
+ * graph (delegating to importVaultGraph) and reports every other carried
+ * section honestly as exported-not-restored.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ BANK_BUNDLE_SCHEMA_VERSION,
+ BankImportError,
+ exportBankBundle,
+ importBankBundle,
+} from "../../../../src/core/brain/portability/bundle.ts";
+
+let vault: string;
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-bank-bundle-"));
+});
+afterEach(() => rmSync(vault, { recursive: true, force: true }));
+
+function note(rel: string, content: string): void {
+ const p = join(vault, rel);
+ mkdirSync(join(p, ".."), { recursive: true });
+ writeFileSync(p, content, "utf8");
+}
+
+describe("exportBankBundle", () => {
+ test("emits a schema-versioned envelope composing the existing exporters", () => {
+ note("Notes/Alpha.md", "---\ntitle: Alpha\n---\nlinks to [[Beta]].\n");
+ note("Notes/Beta.md", "---\ntitle: Beta\nkind: brain-source\n---\nleaf.\n");
+ const bundle = exportBankBundle(vault);
+ expect(bundle.schema).toBe(BANK_BUNDLE_SCHEMA_VERSION);
+ expect(typeof bundle.generated_at).toBe("string");
+ expect(bundle.graph.nodes.some((n) => n.id === "Alpha")).toBe(true);
+ expect(bundle.pages.some((p) => p.path === "Notes/Beta.md" && p.kind === "brain-source")).toBe(
+ true,
+ );
+ expect(Array.isArray(bundle.preferences)).toBe(true);
+ expect(bundle.sources).toBeDefined();
+ });
+
+ test("the content sections are deterministic across two exports", () => {
+ note("Notes/B.md", "---\ntitle: B\n---\nsee [[A]].\n");
+ note("Notes/A.md", "---\ntitle: A\n---\nleaf.\n");
+ const first = exportBankBundle(vault);
+ const second = exportBankBundle(vault);
+ // generated_at is a snapshot timestamp; the content sections are stable.
+ expect(JSON.stringify(first.graph)).toBe(JSON.stringify(second.graph));
+ expect(JSON.stringify(first.pages)).toBe(JSON.stringify(second.pages));
+ expect(JSON.stringify(first.preferences)).toBe(JSON.stringify(second.preferences));
+ });
+});
+
+describe("importBankBundle", () => {
+ test("round-trips: export from one vault reconstructs page stubs in another", () => {
+ note("Notes/Alpha.md", "---\ntitle: Alpha\n---\nlinks to [[Beta]].\n");
+ const bundle = exportBankBundle(vault);
+
+ const dest = mkdtempSync(join(tmpdir(), "o2b-bank-dest-"));
+ try {
+ const result = importBankBundle(dest, bundle, { mode: "skip" });
+ expect(result.schema).toBe(BANK_BUNDLE_SCHEMA_VERSION);
+ expect(result.graph.created).toContain("Notes/Alpha.md");
+ expect(existsSync(join(dest, "Notes/Alpha.md"))).toBe(true);
+ } finally {
+ rmSync(dest, { recursive: true, force: true });
+ }
+ });
+
+ test("reports preferences, pages, and sources as carried-not-restored", () => {
+ note("Notes/Alpha.md", "---\ntitle: Alpha\nkind: note\n---\nx\n");
+ const bundle = exportBankBundle(vault);
+ const dest = mkdtempSync(join(tmpdir(), "o2b-bank-dest2-"));
+ try {
+ const result = importBankBundle(dest, bundle, { mode: "skip" });
+ expect(result.pagesCarried).toBe(bundle.pages.length);
+ expect(result.preferencesCarried).toBe(bundle.preferences.length);
+ expect(result.sourcesCarried).toBe(true);
+ } finally {
+ rmSync(dest, { recursive: true, force: true });
+ }
+ });
+
+ test("honours the conflict mode delegated to importVaultGraph", () => {
+ note("Notes/Alpha.md", "---\ntitle: Alpha\n---\nx\n");
+ const bundle = exportBankBundle(vault);
+ // skip leaves an existing page untouched.
+ const r1 = importBankBundle(vault, bundle, { mode: "skip" });
+ expect(r1.graph.skipped).toContain("Notes/Alpha.md");
+ });
+
+ test("rejects an unsupported schema loudly (typed error), never silently", () => {
+ expect(() => importBankBundle(vault, { schema: "999", graph: { nodes: [] } })).toThrow(
+ BankImportError,
+ );
+ });
+
+ test("rejects a null or scalar payload with the typed error, not a raw throw", () => {
+ expect(() => importBankBundle(vault, null as never)).toThrow(BankImportError);
+ expect(() => importBankBundle(vault, 42 as never)).toThrow(BankImportError);
+ });
+
+ test("tolerates a non-array nodes container without throwing", () => {
+ const result = importBankBundle(vault, {
+ schema: BANK_BUNDLE_SCHEMA_VERSION,
+ graph: { nodes: "not-an-array" as never },
+ });
+ expect(result.graph.created).toEqual([]);
+ expect(result.graph.rejected).toEqual([]);
+ });
+
+ test("a malformed graph node is rejected per-entry, not thrown", () => {
+ const bundle = {
+ schema: BANK_BUNDLE_SCHEMA_VERSION,
+ graph: { nodes: [{ path: 42 }, { path: "Notes/Ok.md", title: "Ok" }] },
+ };
+ const result = importBankBundle(vault, bundle, { mode: "skip" });
+ expect(result.graph.rejected.length).toBe(1);
+ expect(result.graph.created).toContain("Notes/Ok.md");
+ });
+});
diff --git a/tests/core/brain/portability/page-contract.test.ts b/tests/core/brain/portability/page-contract.test.ts
new file mode 100644
index 00000000..12be80f5
--- /dev/null
+++ b/tests/core/brain/portability/page-contract.test.ts
@@ -0,0 +1,110 @@
+/**
+ * Page interchange contract (Brain Portability & Interop suite, Unit B).
+ *
+ * `projectPageContracts` is a pure, read-only projection of every user
+ * vault page (Brain machinery + ignored dirs excluded) to a stable,
+ * schema-versioned interchange record. Structural derivation only: no
+ * LLM synthesis and no natural-language heuristics.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ PAGE_CONTRACT_VERSION,
+ projectPageContracts,
+} from "../../../../src/core/brain/portability/page-contract.ts";
+
+let vault: string;
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-page-contract-"));
+});
+afterEach(() => rmSync(vault, { recursive: true, force: true }));
+
+function note(rel: string, content: string): void {
+ const p = join(vault, rel);
+ mkdirSync(join(p, ".."), { recursive: true });
+ writeFileSync(p, content, "utf8");
+}
+
+describe("projectPageContracts", () => {
+ test("exposes a stable schema version", () => {
+ expect(PAGE_CONTRACT_VERSION).toBe("1");
+ });
+
+ test("projects one record per user page with a vault-relative POSIX path", () => {
+ note("Notes/Alpha.md", "---\ntitle: Alpha\n---\nbody\n");
+ const pages = projectPageContracts(vault);
+ expect(pages.length).toBe(1);
+ expect(pages[0]!.path).toBe("Notes/Alpha.md");
+ });
+
+ test("kind reads the frontmatter field, else defaults structurally to note", () => {
+ note("Sources/S.md", "---\ntitle: S\nkind: brain-source\n---\nx\n");
+ note("Notes/Plain.md", "---\ntitle: Plain\n---\nx\n");
+ const byPath = new Map(projectPageContracts(vault).map((p) => [p.path, p]));
+ expect(byPath.get("Sources/S.md")!.kind).toBe("brain-source");
+ expect(byPath.get("Notes/Plain.md")!.kind).toBe("note");
+ });
+
+ test("confidence and provenance are advisory: present when set, null otherwise", () => {
+ note("Notes/Has.md", "---\ntitle: Has\nconfidence: 0.8\nprovenance: stated\n---\nx\n");
+ note("Notes/None.md", "---\ntitle: None\n---\nx\n");
+ const byPath = new Map(projectPageContracts(vault).map((p) => [p.path, p]));
+ // The advisory value is reported faithfully as the frontmatter parser
+ // yields it (string-based), never coerced or fabricated.
+ expect(byPath.get("Notes/Has.md")!.confidence).toBe("0.8");
+ expect(byPath.get("Notes/Has.md")!.provenance).toBe("stated");
+ expect(byPath.get("Notes/None.md")!.confidence).toBeNull();
+ expect(byPath.get("Notes/None.md")!.provenance).toBeNull();
+ });
+
+ test("citations flatten body wikilinks and typed-relation targets, sorted-unique", () => {
+ note(
+ "Notes/Cite.md",
+ "---\ntitle: Cite\nrelated: [[Zeta]]\n---\nsee [[Beta]] and [[Alpha]] and [[Beta]].\n",
+ );
+ const page = projectPageContracts(vault).find((p) => p.path === "Notes/Cite.md")!;
+ expect(page.citations).toEqual(["Alpha", "Beta", "Zeta"]);
+ });
+
+ test("aliases pass through from frontmatter, else empty", () => {
+ note("Notes/Al.md", "---\ntitle: Al\naliases: [A1, A2]\n---\nx\n");
+ note("Notes/NoAl.md", "---\ntitle: NoAl\n---\nx\n");
+ const byPath = new Map(projectPageContracts(vault).map((p) => [p.path, p]));
+ expect(byPath.get("Notes/Al.md")!.aliases).toEqual(["A1", "A2"]);
+ expect(byPath.get("Notes/NoAl.md")!.aliases).toEqual([]);
+ });
+
+ test("freshness reads a frontmatter timestamp when present", () => {
+ note("Notes/Fresh.md", "---\ntitle: Fresh\nupdated_at: 2026-01-02T03:04:05Z\n---\nx\n");
+ const page = projectPageContracts(vault).find((p) => p.path === "Notes/Fresh.md")!;
+ expect(page.freshness).toBe("2026-01-02T03:04:05Z");
+ });
+
+ test("freshness falls back to the file mtime (ISO) when no frontmatter timestamp", () => {
+ note("Notes/Mtime.md", "---\ntitle: Mtime\n---\nx\n");
+ const page = projectPageContracts(vault).find((p) => p.path === "Notes/Mtime.md")!;
+ // No frontmatter timestamp -> a non-null ISO string derived from mtime.
+ expect(page.freshness).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/);
+ });
+
+ test("excludes the Brain machinery root and ignored dirs", () => {
+ note("Notes/User.md", "---\ntitle: User\n---\nx\n");
+ note("Brain/preferences/pref-x.md", "---\nkind: brain-preference\ntitle: PrefX\n---\ny\n");
+ const paths = projectPageContracts(vault).map((p) => p.path);
+ expect(paths).toContain("Notes/User.md");
+ expect(paths.some((p) => p.startsWith("Brain/"))).toBe(false);
+ });
+
+ test("output is deterministic and sorted by path", () => {
+ note("Notes/B.md", "---\ntitle: B\n---\nx\n");
+ note("Notes/A.md", "---\ntitle: A\n---\nx\n");
+ const first = projectPageContracts(vault);
+ const second = projectPageContracts(vault);
+ expect(JSON.stringify(first)).toBe(JSON.stringify(second));
+ expect(first.map((p) => p.path)).toEqual(["Notes/A.md", "Notes/B.md"]);
+ });
+});
diff --git a/tests/core/brain/sdk.test.ts b/tests/core/brain/sdk.test.ts
new file mode 100644
index 00000000..64795442
--- /dev/null
+++ b/tests/core/brain/sdk.test.ts
@@ -0,0 +1,98 @@
+/**
+ * In-process SDK (Brain Portability & Interop suite, Unit C).
+ *
+ * `createBrain(vault)` is a thin faƧade: every method delegates to an
+ * existing core function. These tests assert the faƧade returns the core
+ * result and that the source CRUD lifecycle works end to end through it.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+import { createBrain } from "../../../src/core/brain/sdk.ts";
+import { BANK_BUNDLE_SCHEMA_VERSION } from "../../../src/core/brain/portability/bundle.ts";
+
+let vault: string;
+let configHome: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-sdk-vault-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-sdk-cfg-"));
+ const configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+describe("createBrain", () => {
+ test("exposes the bound vault", () => {
+ expect(createBrain(vault).vault).toBe(vault);
+ });
+
+ test("exportBank delegates to the bank exporter", () => {
+ writeFileSync(join(vault, "Note.md"), "---\ntitle: Note\n---\nlinks [[Other]].\n");
+ const bundle = createBrain(vault).exportBank();
+ expect(bundle.schema).toBe(BANK_BUNDLE_SCHEMA_VERSION);
+ expect(bundle.graph.nodes.some((n) => n.id === "Note")).toBe(true);
+ });
+
+ test("exportGraph / importGraph round-trip through the faƧade", () => {
+ writeFileSync(join(vault, "Note.md"), "---\ntitle: Note\n---\nlinks [[Other]].\n");
+ const brain = createBrain(vault);
+ const graph = brain.exportGraph();
+ const dest = mkdtempSync(join(tmpdir(), "o2b-sdk-dest-"));
+ try {
+ const result = createBrain(dest).importGraph(graph, { mode: "skip" });
+ expect(result.created).toContain("Note.md");
+ } finally {
+ rmSync(dest, { recursive: true, force: true });
+ }
+ });
+
+ test("exportPreferencesJson returns the schema-versioned export", () => {
+ const out = createBrain(vault).exportPreferencesJson();
+ expect(out.schema).toBeDefined();
+ expect(Array.isArray(out.preferences)).toBe(true);
+ });
+
+ test("source CRUD lifecycle: ingest -> list -> get -> delete", () => {
+ const brain = createBrain(vault);
+ const res = brain.ingestSource(
+ {
+ sourcePath: "Articles/x.md",
+ summary: "summary x",
+ extraction: { entities: [{ category: "concept", name: "Topic" }], relations: [] },
+ },
+ { agent: "claude", now: new Date("2026-01-01T00:00:00Z") },
+ );
+ expect(res.created).toBe(true);
+
+ const listed = brain.listSources();
+ expect(listed.length).toBe(1);
+ const id = listed[0]!.path;
+
+ const detail = brain.getSource(id);
+ expect(detail!.body).toContain("summary x");
+
+ expect(brain.deleteSource(id)).toBe(true);
+ expect(brain.listSources().length).toBe(0);
+ });
+
+ test("createNote writes a vault note through the faƧade", () => {
+ const res = createBrain(vault).createNote({
+ path: "Notes/Sdk.md",
+ frontmatter: { title: "Sdk" },
+ content: "via sdk",
+ });
+ expect(res.created).toBe(true);
+ expect(existsSync(join(vault, "Notes/Sdk.md"))).toBe(true);
+ });
+});
diff --git a/tests/mcp/brain-create-note.test.ts b/tests/mcp/brain-create-note.test.ts
new file mode 100644
index 00000000..5d4329fc
--- /dev/null
+++ b/tests/mcp/brain-create-note.test.ts
@@ -0,0 +1,92 @@
+/**
+ * MCP integration test for `brain_create_note` (Brain Portability &
+ * Interop suite, Unit D). The tool writes an actual vault note file
+ * (path + frontmatter + content) - distinct from `brain_note`, which
+ * only appends a log line. Handler exercised directly with a minimal
+ * context. Refusals map to INVALID_PARAMS and write nothing.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import { NOTES_TOOLS } from "../../src/mcp/brain/notes-tools.ts";
+import { MCPError } from "../../src/mcp/protocol.ts";
+import type { ServerContext } from "../../src/mcp/tools.ts";
+
+let vault: string;
+let configHome: string;
+let ctx: ServerContext;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-create-note-tool-vault-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-create-note-tool-cfg-"));
+ const configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+ bootstrapBrain(vault, { configPath });
+ ctx = { vault, configPath, repoRoot: null };
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+const tool = NOTES_TOOLS.find((t) => t.name === "brain_create_note")!;
+const handler = tool.handler;
+
+describe("brain_create_note", () => {
+ test("is registered with a write-shaped name and schema", () => {
+ expect(tool).toBeDefined();
+ expect(tool.inputSchema.required).toContain("path");
+ });
+
+ test("creates a note file with frontmatter and content, returns its path", async () => {
+ const res = await handler(ctx, {
+ path: "Notes/FromAgent.md",
+ frontmatter: { title: "From Agent", tags: ["x"] },
+ content: "Captured by an agent.",
+ });
+ expect(res).toMatchObject({ created: true, path: "Notes/FromAgent.md" });
+ const md = readFileSync(join(vault, "Notes/FromAgent.md"), "utf8");
+ expect(md).toContain("title: From Agent");
+ expect(md).toContain("Captured by an agent.");
+ });
+
+ test("path traversal is rejected with INVALID_PARAMS and writes nothing", async () => {
+ await expect(handler(ctx, { path: "../escape.md", content: "x" })).rejects.toThrow(MCPError);
+ expect(existsSync(join(vault, "..", "escape.md"))).toBe(false);
+ });
+
+ test("writing into the Brain root is rejected with INVALID_PARAMS", async () => {
+ await expect(handler(ctx, { path: "Brain/x.md", content: "x" })).rejects.toThrow(MCPError);
+ expect(existsSync(join(vault, "Brain/x.md"))).toBe(false);
+ });
+
+ test("a non-object frontmatter is rejected with INVALID_PARAMS", async () => {
+ await expect(
+ handler(ctx, { path: "Notes/Bad.md", frontmatter: "not-an-object", content: "x" }),
+ ).rejects.toThrow(MCPError);
+ });
+
+ test("a prototype-mutating frontmatter key is rejected, never assigned", async () => {
+ // JSON.parse creates an OWN "__proto__" key (the real JSON-RPC vector),
+ // unlike an object literal where __proto__ sets the prototype.
+ const frontmatter = JSON.parse('{"__proto__": ["polluted"]}');
+ await expect(
+ handler(ctx, { path: "Notes/Proto.md", frontmatter, content: "x" }),
+ ).rejects.toThrow(MCPError);
+ expect(existsSync(join(vault, "Notes/Proto.md"))).toBe(false);
+ });
+
+ test("clobbering an existing note is rejected", async () => {
+ await handler(ctx, { path: "Notes/Once.md", content: "first" });
+ await expect(handler(ctx, { path: "Notes/Once.md", content: "second" })).rejects.toThrow(
+ MCPError,
+ );
+ expect(readFileSync(join(vault, "Notes/Once.md"), "utf8")).toContain("first");
+ });
+});
diff --git a/tests/mcp/brain-tools-parity.test.ts b/tests/mcp/brain-tools-parity.test.ts
index dba780d7..d9bcbe10 100644
--- a/tests/mcp/brain-tools-parity.test.ts
+++ b/tests/mcp/brain-tools-parity.test.ts
@@ -34,6 +34,7 @@ const FROZEN_BRAIN_TOOL_NAMES = [
"brain_context_pack",
"brain_context_presets",
"brain_context_receipts",
+ "brain_create_note",
"brain_dead_ends",
"brain_deep_synthesis",
"brain_derive_fact",
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index aa56fbb9..57528f8d 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -191,6 +191,8 @@ describe("tool listing", () => {
"brain_review_candidates",
"brain_apply_evidence",
"brain_note",
+ // Brain Portability & Interop suite: write an actual vault note file.
+ "brain_create_note",
"brain_pinned_context",
"brain_context",
"brain_query",
@@ -533,7 +535,8 @@ describe("stdio loop", () => {
// + brain_eval (Search & Recall Quality Suite) = 72.
// + brain_intake_entities / brain_ingest_source / brain_research_report
// / brain_derive_fact (Knowledge Provenance Suite, v1.7.0) = 76.
- expect(list.result.tools.length).toBe(76);
+ // + brain_create_note (Brain Portability & Interop Suite) = 77.
+ expect(list.result.tools.length).toBe(77);
});
test("returns parse error for invalid JSON", async () => {
diff --git a/tests/mcp/removed-tools.test.ts b/tests/mcp/removed-tools.test.ts
index 88e97552..2266aeba 100644
--- a/tests/mcp/removed-tools.test.ts
+++ b/tests/mcp/removed-tools.test.ts
@@ -138,5 +138,6 @@ test("the shadow surface is gone: no hidden tools, removed names unlisted", asyn
method: "tools/list",
params: {},
})) as { result: { tools: Array<{ name: string }> } };
- expect(list.result.tools.length).toBe(76);
+ // 76 + brain_create_note (Brain Portability & Interop Suite) = 77.
+ expect(list.result.tools.length).toBe(77);
});