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

v0.16.0 - Agent boundary control surfaces: pinned context, Markdown links, MCP output contracts (#43)

Sol Aitken9b87838bd26b
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 46e384a3..6a426b13 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.15.0",
+ "version": "0.16.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 e7be0b1e..f1fbefa0 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.15.0",
+ "version": "0.16.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 bd3bdadf..5f272eab 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,34 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [0.16.0] - 2026-05-28
+
+Agent boundary control surfaces. Open Second Brain now gives agents a
+transient current-task scratchpad, configurable Markdown-link output for
+presentation surfaces, explicit MCP output contracts, and deterministic
+private-region stripping before memory writes. These are additive controls:
+permanent preferences still live in Obsidian-compatible Brain files, while
+short-lived facts and boundary checks stay outside the learning loop.
+
+### Added
+
+- `Brain/pinned.md` plus the `brain_pinned_context` MCP tool for read/write/
+ append/clear operations on transient current-task context.
+- `brain_context` now returns a structured `pinned` block and includes pinned
+ content in its text card when present.
+- `link_output_format: markdown` config support, with `OBSIDIAN_LINK_FORMAT`
+ as an env override for presentation output such as `brain_digest`.
+- Lightweight MCP `outputSchema` contracts and boundary validation for
+ `brain_context`, `brain_pinned_context`, `brain_query`, and `brain_search`.
+- `<private>...</private>` region stripping in the shared redactor before
+ secret-shaped assignment masking.
+
+### Changed
+
+- The always-loaded writer MCP surface now has five tools: `brain_feedback`,
+ `brain_apply_evidence`, `brain_note`, `brain_pinned_context`, and
+ `brain_context`.
+
## [0.15.0] - 2026-05-28
Cross-agent query foundation. Open Second Brain now exposes a read-only
@@ -1780,7 +1808,7 @@ with `source_type: inline`, the source-file wikilink in `source`,
and a `dedup_hash`over the normalised payload. After capture
the source line is annotated`@osbβœ“ [[sig-...]]`(inline form)
or the info-string flips to`osb-checked`with a`<!-- @osbβœ“
- [[sig-...]] -->`comment line (block form), making re-runs
+ [[sig-...]] -->`comment line (block form), making re-runs
idempotent. Default ignore set covers`Brain/`, `.git`,
`node_modules`, `.obsidian`, `.trash`, `.stversions`,
`.open-second-brain`; additional excludes via `--exclude`,
@@ -3126,6 +3154,8 @@ plugin config (vault field)`, and exits with a clear
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[0.16.0]: https://github.com/itechmeat/open-second-brain/compare/v0.15.0...v0.16.0
+[0.15.0]: https://github.com/itechmeat/open-second-brain/compare/v0.14.1...v0.15.0
[0.14.1]: https://github.com/itechmeat/open-second-brain/compare/v0.14.0...v0.14.1
[0.14.0]: https://github.com/itechmeat/open-second-brain/compare/v0.13.0...v0.14.0
[0.13.0]: https://github.com/itechmeat/open-second-brain/compare/v0.12.0...v0.13.0
diff --git a/README.md b/README.md
index 6110e380..4f94d9cb 100644
--- a/README.md
+++ b/README.md
@@ -112,7 +112,7 @@ The capabilities you actually feel day to day:
| 9 | Hybrid search that explains itself | `o2b search "<query>" --property type=decision --property status=open` β€” SQLite + FTS5 and an optional semantic layer, fused and then sharpened by a recall-quality suite: MMR diversity so near-duplicates do not crowd the top, link-graph traversal that surfaces notes one hop from a hit, entity-boosting for proper-noun precision, and header-anchored chunking so a mid-document chunk keeps its section context. Every result carries a `why_retrieved` breakdown of the layers that ranked it. |
| 10 | Pay Memory β€” audit every paid action | When the agent spends money (Solana-Foundation `pay`, third-party APIs) every receipt lands in `Brain/payments/<date>/`. Spending policy, approval gate, daily Telegram report. The agent never holds wallet keys. |
-These are the headline capabilities. The full surface also includes: importing Claude Code memory directories, daily logging-discipline cron, cross-project pointers for shared vaults, source-agent query and comparison (`brain_agent_query`, `brain_agent_diff`, `o2b brain agent-query`, `o2b brain agent-diff`), the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, an operator dashboard, the v0.12.0 Brain Integrity Suite (content-hash drift detection, durable workrun checkpoints, destructive-from-confirmed retire gate, and the `brain_review_candidates` MCP tool that previews what the next dream pass would do without writing anything), the v0.13.0 Hybrid Search and Recall Quality suite (explainable recall, MMR diversity, link-graph traversal, entity-boosted retrieval, header-anchored chunking), and the v0.14.0 Semantic Brain Health and Self-Maintenance suite (cross-preference contradiction detection, concept-gap and stale-claim surfacing, per-preference edit-history, a clean/watch/investigate reconciliation verdict via `brain_health`, and dependency-ordered `doctor --remediate`). Browse [`docs/cli-reference.md`](docs/cli-reference.md) for every verb and [`docs/how-it-works.md`](docs/how-it-works.md) for the mental model.
+These are the headline capabilities. The full surface also includes: importing Claude Code memory directories, daily logging-discipline cron, cross-project pointers for shared vaults, transient pinned session context through `brain_pinned_context` / `Brain/pinned.md`, source-agent query and comparison (`brain_agent_query`, `brain_agent_diff`, `o2b brain agent-query`, `o2b brain agent-diff`), the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, an operator dashboard, configurable Markdown-link presentation output, MCP output-contract checks for core agent-facing tools, private-region stripping with `<private>...</private>`, the v0.12.0 Brain Integrity Suite (content-hash drift detection, durable workrun checkpoints, destructive-from-confirmed retire gate, and the `brain_review_candidates` MCP tool that previews what the next dream pass would do without writing anything), the v0.13.0 Hybrid Search and Recall Quality suite (explainable recall, MMR diversity, link-graph traversal, entity-boosted retrieval, header-anchored chunking), and the v0.14.0 Semantic Brain Health and Self-Maintenance suite (cross-preference contradiction detection, concept-gap and stale-claim surfacing, per-preference edit-history, a clean/watch/investigate reconciliation verdict via `brain_health`, and dependency-ordered `doctor --remediate`). Browse [`docs/cli-reference.md`](docs/cli-reference.md) for every verb and [`docs/how-it-works.md`](docs/how-it-works.md) for the mental model.
## CLI
@@ -137,6 +137,7 @@ Full list (~50 verbs across `o2b`, `o2b brain`, `o2b vault`, `o2b discipline`, P
- Secrets are not supposed to live in the vault. Daily logs and config exports go through a best-effort redactor for common secret-name patterns.
- Brain mutations (`dream`, `merge`, `upgrade`) take a pre-run snapshot with a SHA-256 sidecar; `o2b brain rollback` aborts on drift unless `--force-rollback`.
- Hooks (Claude Code, Codex) only inject text into the agent's context; they never write to the vault directly.
+- Text written through Brain/Pay Memory redaction strips `<private>...</private>` regions before storage and masks secret-shaped assignments such as `api_key=...`.
## Updating
diff --git a/docs/brainstorm/agent-boundary-control-surfaces/README.md b/docs/brainstorm/agent-boundary-control-surfaces/README.md
new file mode 100644
index 00000000..9581ee93
--- /dev/null
+++ b/docs/brainstorm/agent-boundary-control-surfaces/README.md
@@ -0,0 +1,8 @@
+# Agent Boundary Control Surfaces
+
+Phase 0 artifacts for the feature-release scope covering:
+
+- `t_8e4fe118` - transient session pinning.
+- `t_06058a8c` - configurable Markdown link output format.
+- `t_b3995e58` - MCP output contract enforcement.
+- `t_c12e0e9c` - private-region stripping, included only as a small shared redaction helper.
diff --git a/docs/brainstorm/agent-boundary-control-surfaces/cli-output/claude.md b/docs/brainstorm/agent-boundary-control-surfaces/cli-output/claude.md
new file mode 100644
index 00000000..f8a7e0ba
--- /dev/null
+++ b/docs/brainstorm/agent-boundary-control-surfaces/cli-output/claude.md
@@ -0,0 +1,41 @@
+### Variant 1: Independent additive slices
+
+- **Approach**: Land each task as its own thin, isolated slice with no shared abstraction. `Brain/pinned.md` gets a small `src/core/brain/pinned.ts` and a `brain_pinned_context` tool (read/write/clear ops), with `brain_context` appending pinned content beside active prefs. Link output adds a `link_output_format` key to `src/core/config.ts` plus a renderer branch in `src/core/brain/wikilink.ts`/`src/core/search/links.ts`. Contract enforcement adds an optional JSON-Schema field to `ToolDefinition` in `src/mcp/tools.ts` and a validation step in `MCPServer.handleToolsCall` against `structuredContent`. The cavemem helper is a `stripPrivateRegions` pass added to `src/core/redactor.ts`, invoked from the existing Brain/Pay Memory write boundary that already calls `redactRawOutput`.
+- **Trade-offs**:
+ - Pro: aligns with the "small additive surfaces" constraint; each slice ships behind its own tests, fits TDD feature-by-feature, and reviews independently.
+ - Pro: no new cross-cutting abstraction to design, document, or migrate later if priorities change.
+ - Pro: the conditional cavemem task collapses to one regex + helper export reused by existing redactor callers β€” exactly the "small shared redaction helper" the gating clause requires.
+ - Con: four logically related boundary surfaces ship without a common shape; future similar features re-invent registration/wiring patterns.
+ - Con: contract validation lives ad-hoc in the MCP server rather than as a reusable layer; subsequent tools must remember to wire it.
+- **Complexity**: small
+- **Risk**: low
+
+### Variant 2: Unified boundary-stage pipeline
+
+- **Approach**: Introduce a generalized "boundary pipeline" abstraction (e.g., `src/mcp/boundary.ts`) with explicit inbound (context-assembly) and outbound (response-shaping) stages, each registered by name. Pinned-content load becomes an inbound stage on `brain_context`; link rendering, contract validation, and private-region stripping become outbound stages applied to `structuredContent` and text payloads. `MCPServer.handleToolsCall` becomes a thin driver over this pipeline; `src/core/redactor.ts` plugs in as one outbound stage.
+- **Trade-offs**:
+ - Pro: principled, extensible seam that anticipates further boundary control surfaces.
+ - Pro: contract validation, redaction, and link formatting are uniformly applied without per-tool wiring.
+ - Con: introduces a cross-cutting abstraction for only 3-4 concrete features β€” exactly the broad refactor the constraints warn against.
+ - Con: harder to land TDD feature-by-feature; each slice now depends on the pipeline scaffold being merged first.
+ - Con: backward-compat risk on `MCPServer.handleToolsCall` envelope semantics (`content` + `structuredContent`), and on Brain context composition tested by `tests/mcp/brain.test.ts`.
+ - Con: the cavemem gating clause explicitly forbids "real-time session lifecycle hooks"; a generic stage pipeline edges toward that shape.
+- **Complexity**: large
+- **Risk**: medium
+
+### Variant 3: Direction-split surfaces (inbound context vs outbound envelope)
+
+- **Approach**: Group the work into two cohesive but small surfaces. An inbound "session context" surface adds `Brain/pinned.md` plus the `brain_pinned_context` tool and extends `brain_context` to compose active prefs + pinned snippet. An outbound "envelope" surface adds a single `renderEnvelope` helper that the MCP server calls before returning tool results: it applies the `link_output_format` config to any rendered wikilinks, validates `structuredContent` against per-tool JSON Schemas declared on `ToolDefinition`, and runs the new `stripPrivateRegions` pass (also exported from `src/core/redactor.ts` so Brain writers can call it on the write path).
+- **Trade-offs**:
+ - Pro: organizes the four tasks by data direction, which matches how the existing code is already split (`brain-tools.ts` for inbound context vs `redactor.ts`/`tools.ts` for outbound shaping).
+ - Pro: still avoids a generic pipeline; each surface is one new file plus targeted edits.
+ - Pro: makes contract enforcement a property of the envelope rather than per-tool code, while staying smaller than Variant 2.
+ - Con: bundles three logically distinct outbound concerns (link formatting, schema validation, private-region stripping) into one helper whose responsibilities will drift.
+ - Con: introduces an envelope abstraction that current tests (`tests/mcp/mcp.test.ts`) do not yet exercise β€” moderate test churn.
+ - Con: harder to ship piecewise because the envelope is a shared seam; first task lands the seam, later tasks must conform.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Recommended: Variant 1
+
+**Rationale**: The project's stated constraints β€” additive surfaces over broad refactors, TDD feature-by-feature, backward-compatible public APIs, and the conditional cavemem clause requiring a _small_ shared redaction helper β€” all favor independent slices. The four tasks happen to touch the agent boundary but do not share enough mechanism to justify a pipeline (Variant 2) or even a shared envelope (Variant 3); each slice is a few dozen lines against well-isolated files (`brain-tools.ts`, `wikilink.ts`/`links.ts`, `tools.ts`/`server.ts`, `redactor.ts`) with existing test homes. If a real cross-cutting need emerges later (e.g., a second tool needing the same JSON-Schema check), extracting from the concrete implementations will be straightforward and lower-risk than designing the abstraction up front.
diff --git a/docs/brainstorm/agent-boundary-control-surfaces/cli-output/prompt.md b/docs/brainstorm/agent-boundary-control-surfaces/cli-output/prompt.md
new file mode 100644
index 00000000..60a4b424
--- /dev/null
+++ b/docs/brainstorm/agent-boundary-control-surfaces/cli-output/prompt.md
@@ -0,0 +1,169 @@
+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
+
+Multi-task feature-release scope selected by the operator from the Open Second Brain kanban board.
+
+## Task t_8e4fe118: [upstream:obsidian-second-brain] Core memory pinning for transient session context
+
+**Source**: https://github.com/eugeniughelbur/obsidian-second-brain/releases/tag/v4.0.0
+**Repo**: eugeniughelbur/obsidian-second-brain (726 stars)
+**Released**: v4.0.0 (2026-04-09T12:56:58Z)
+
+## What
+Upstream introduced PINNED.md, a scratchpad loaded at L0 (alongside identity context) for task-specific critical facts. During complex multi-turn sessions, the agent suggests pinning key facts so they survive context window rotation. The user can also manually pin. The file is cleared when the task completes. This sits below the full vault context, providing a focused, cheap way to keep current-task state available.
+
+## Why useful for OSB
+OSB's brain_context loads active preferences at session start, but there's no mechanism for an agent to pin transient task-specific facts that shouldn't become permanent preferences. During long debugging sessions, code reviews, or multi-step workflows, agents need to remember facts like "the bug is in the auth middleware, not the controller" without polluting the permanent preference store. A PINNED.md equivalent would give agents a focused, low-token-cost scratchpad for current-session context.
+
+## Status in OSB
+- **Verdict**: present_weaker
+- **Codegraph hints**: OSB has brain_context (loads active preferences), brain_feedback (records signals), and memory tools. No transient session-scoped pinning mechanism exists. src/mcp/brain-tools.ts handles context loading and signal recording.
+
+## Notes
+This is lighter-weight than a full preference β€” it's session-scoped, not vault-scoped. OSB could implement as a Brain/pinned.md file with a simple MCP tool to read/write/clear it, loaded alongside active prefs in brain_context.
+
+Triage comment: clean; priority 4; clear drop-in with Brain/pinned.md plus read/write/clear MCP tool loaded alongside active prefs in brain_context; low-risk additive session scratchpad.
+
+## Task t_06058a8c: [upstream:obsidian-wiki] Configurable markdown link output format
+
+**Source**: https://github.com/Ar9av/obsidian-wiki/releases/tag/v2026.05
+**Repo**: Ar9av/obsidian-wiki (977β˜…)
+**Released**: v2026.05 (2026-05-06T05:56:13Z)
+
+## What
+Set `OBSIDIAN_LINK_FORMAT=markdown` in config to output `[page](path/to/page.md)` instead of `[[wikilinks]]`. Useful for publishing wikis outside Obsidian or using them in standard Markdown renderers that don't understand wikilinks.
+
+## Why useful for OSB
+OSB already parses both wikilinks and markdown links internally (LinkType in src/core/search/links.ts), but the output format is not configurable. Some consumers of OSB's vault (CI pipelines, GitHub rendering, non-Obsidian tools) would benefit from standard markdown link output. This is a small but impactful configuration option.
+
+## Status in OSB
+- **Verdict**: present_weaker
+- **Codegraph hints**: src/core/search/links.ts:15 (LinkType = "wikilink" | "markdown_link" | "tag") β€” parser supports both. No configurable output format exists. src/core/brain/migrate-frontmatter.ts:123 β€” frontmatter rewriting already handles format migration.
+
+## Notes
+Straightforward config addition. Could be a `link_output_format` setting in OSB's config.yaml. The internal parsing already handles both formats so this is purely an output formatting concern.
+
+Triage comment: cleanest drop-in; priority 4; links.ts already parses both wikilink and markdown_link; only an output formatter plus config flag is needed, low risk.
+
+## Task t_b3995e58: [upstream:contextlattice] Agent boundary contract enforcement for MCP output
+
+**Source**: https://github.com/sheawinkler/contextlattice/releases/tag/v3.3.28
+**Repo**: sheawinkler/contextlattice (61β˜…)
+**Released**: v3.3.28 (2026-05-25T17:39:06Z)
+
+## What
+ContextLattice v3.3.28 enforces machine-readable output contracts across agent boundary surfaces. It adds generated contract constants for Go and Rust consumers, and public agent-context gate coverage for contract registry changes. This ensures that any agent producing output through the lattice layer must conform to pre-declared contracts, with compile-time validation for Go/Rust consumers.
+
+## Why useful for OSB
+OSB exposes MCP tools to connected agents but has no mechanism to validate or constrain the format of tool output. A contract enforcement layer would allow OSB to declare output schemas for brain_search, brain_query, and other tools, ensuring downstream agents receive structured, machine-parseable results. This would improve reliability in multi-agent pipelines where OSB output feeds into other systems.
+
+## Status in OSB
+- **Verdict**: not_in_osb_useful
+- **Codegraph hints**: src/mcp/tools.ts:57 (ToolDefinition interface), src/mcp/tools.ts:193 (ToolScope type), src/mcp/tools.ts:207 (buildToolTable). OSB defines tool metadata but has no output contract validation or schema enforcement on tool results.
+
+## Notes
+Upstream uses a contract registry with generated constants for compiled languages. OSB could implement a lighter-weight version: JSON Schema output contracts validated at the MCP tool boundary, or typed result envelopes for brain tools.
+
+Triage comment: priority 3; JSON Schema validation at MCP tool boundary; additive, lighter-weight than upstream registry, clear scope.
+
+## Conditional task t_c12e0e9c: [upstream:cavemem] Privacy-aware memory capture with region stripping
+
+Include this task only if it can remain a small shared redaction helper reused by write/import boundaries without pulling in real-time session lifecycle hooks or path-glob exclusion.
+
+**Source**: https://github.com/JuliusBrussee/cavemem/releases/tag/v0.1.0
+**Repo**: JuliusBrussee/cavemem (446β˜…)
+**Released**: v0.1.0 (2026-04-18T00:48:33Z)
+
+## What
+cavemem strips content inside <private>...</private> tags at the write boundary before anything reaches storage. Path globs (excludePatterns) exclude entire directories from capture. The worker binds to 127.0.0.1 only. Privacy filtering happens synchronously in the hook handler, before compression.
+
+## Why useful for OSB
+OSB already has SECRET_ASSIGNMENT_RE in src/core/event-log.ts:17 that catches KEY=VALUE secret patterns, but has no mechanism for agents to mark specific regions of conversation as private, nor path-based exclusion for memory capture. A private tag stripping system would let agents and users explicitly control what enters the brain, complementing the existing secret redactor. Path exclusion would prevent sensitive directories from being captured during session imports.
+
+## Status in OSB
+- **Verdict**: not_in_osb_useful
+- **Codegraph hints**: src/core/event-log.ts:17 (SECRET_ASSIGNMENT_RE β€” regex-based secret detection, no region-based stripping), src/core/event-log.ts:23 (redactText function), src/mcp/pay-memory-tools.ts:355 (receipt redactor). No XML-tag-based region stripping or path-glob exclusion exists.
+
+## Notes
+The private tag approach is agent-friendly β€” agents can wrap sensitive content themselves. Path exclusion via globs complements this for directory-level control. Both are simpler and more deterministic than pattern-based secret detection.
+
+Triage comment: priority 3; child of real-time session-capture group; concrete hints, but needs design on region stripping.
+
+# Project context
+
+Project: Open Second Brain, TypeScript on Bun, deterministic Obsidian-vault memory layer exposed via CLI and MCP.
+
+Recent commits:
+66980b2 (HEAD -> main, origin/main, origin/HEAD) ci: drop bun version floor, track latest only (#42)
+feca6a7 (tag: v0.15.0) v0.15.0 - Cross-agent query foundation: source-agent provenance retrieval and comparison (#41)
+ffde4ac (tag: v0.14.1) chore(release): v0.14.1 (#40)
+bc97b38 refactor: add validation toolchain and normalize project formatting (#39)
+b76199a (tag: v0.14.0) v0.14.0 - Semantic Brain Health and Self-Maintenance: contradiction detection, concept gaps, stale claims, edit-history, remediation (#38)
+2147640 (tag: v0.13.0) v0.13.0 - Hybrid Search and Recall Quality: explainable recall, MMR, link traversal, entity boost, header anchoring (#37)
+84886d1 (tag: v0.12.0) v0.12.0 - Brain Integrity Suite: typed collision detection, content-hash drift, durable dream workruns (#36)
+c002268 (tag: v0.11.0) v0.11.0 - Brain-centric vault layout: one agent-owned root, opt-in user notes (#35)
+a8d4803 (tag: v0.10.18) v0.10.18 - temporal axis: timeline, belief evolution, stale watch, daily brief, weekly synthesis (#34)
+d0598af (tag: v0.10.17) v0.10.17 - link graph surfaces (aliases, anchors, mentions, synthesis, MOC audit, property filter, vault instruction) (#33)
+3b7dfe9 (tag: v0.10.16) v0.10.16: trust and operator surfaces - verification, verdict, dashboard (#32)
+d045ea1 (tag: v0.10.15) chore: bump version to 0.10.15 (#31)
+5755200 v0.10.15: vault care bundle - metadata, dedup, lint, context-pack, actions (#30)
+9d9636b (tag: v0.10.14) feat: index fastpath, PEM/JWT redaction, vault connection health (v0.10.14) (#29)
+7d81f0b (tag: v0.10.13) feat: codegraph-partner skill + o2b doctor check (v0.10.13) (#28)
+0462b91 (tag: v0.10.12) feat: v0.10.12 operational friction reduction (#27)
+9d8af95 (tag: v0.10.11) Merge pull request #26 from itechmeat/feature/v0.10.11-multi-runtime-install
+852c9b5 v0.10.11: address CodeRabbit review
+f819f32 v0.10.11: Multi-runtime install orchestrator + Most-applied in digest
+88bce1f (tag: v0.10.10) Merge pull request #25 from itechmeat/feature/v0.10.10-pull-channels
+
+Related files:
+- src/mcp/tools.ts: ToolDefinition, buildToolTable, writer/full scope filtering.
+- src/mcp/server.ts: MCPServer.handleToolsCall and toolResult generate content + structuredContent envelopes.
+- src/mcp/brain-tools.ts: brain_context, brain_feedback, brain_note, brain_query and Brain tool definitions.
+- src/mcp/search-tools.ts and src/mcp/pay-memory-tools.ts: sibling MCP slices.
+- src/core/brain/paths.ts: canonical Brain paths and root constants.
+- src/core/brain/wikilink.ts: normaliseWikilinkTarget, parseWikilink, renderPrefLink.
+- src/core/search/links.ts: LinkType includes wikilink and markdown_link; parser already sees both.
+- src/core/config.ts: simple YAML config parsing/discovery and redaction of secret-looking config keys.
+- src/core/redactor.ts: redactRawOutput, normaliseTextField, sanitiseTextField shared by Brain/Pay Memory writers.
+- tests/mcp/mcp.test.ts: handshake, tool listing, JSON-RPC/tool call envelope coverage.
+- tests/mcp/brain.test.ts: Brain MCP integration tests around brain_context, feedback, query, digest.
+- tests/core/brain.wikilink.test.ts: wikilink/renderPrefLink tests.
+- tests/core/redactor.test.ts: redactor and normaliseTextField tests.
+- docs/mcp.md, docs/how-it-works.md, docs/cli-reference.md, README.md, CHANGELOG.md.
+
+Conventions:
+- Deterministic, dependency-light TypeScript; avoid LLM-dependent runtime behavior.
+- Data lives as plain Markdown under Brain/ in the user's Obsidian vault.
+- MCP tool responses include `content` text plus `structuredContent` JSON.
+- Writer MCP server includes `brain_feedback`, `brain_apply_evidence`, `brain_note`, and `brain_context` because `brain_context` must be available at session start.
+- Configuration is a simple `key: value` YAML subset via `src/core/config.ts`; no new YAML dependency.
+- Existing redaction is best-effort and deterministic; never promise perfect secrecy.
+- Tests use `bun:test`; common verification commands are `bun test`, `bun run typecheck`, `bun run lint`, `bun run validate`, and `bun run sync-version:check`.
+- Public artifacts should use the full name Open Second Brain, not abbreviations.
+
+Constraints:
+- Keep public APIs backward compatible unless unavoidable.
+- Prefer small additive surfaces over broad refactors.
+- Do not add runtime dependencies unless the benefit is clear.
+- Do not pull the real-time session lifecycle task into this PR.
+- Version bump is explicitly required by the operator before GitHub push, despite the generic playbook default that usually bumps during release.
+- Implement with TDD feature-by-feature after design is accepted by the orchestrator.
+- Self-review must compare all changes against main before push.
+
+# 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/agent-boundary-control-surfaces/design.md b/docs/brainstorm/agent-boundary-control-surfaces/design.md
new file mode 100644
index 00000000..c98a8a04
--- /dev/null
+++ b/docs/brainstorm/agent-boundary-control-surfaces/design.md
@@ -0,0 +1,88 @@
+# Agent Boundary Control Surfaces - transient context, link output, contracts, and private-region stripping
+
+**Status:** draft
+**Author:** GitHub Copilot (via feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+Open Second Brain gives agents a durable Brain through deterministic CLI and MCP tools, but several small boundary controls are still missing. Agents can load `Brain/active.md`, but they cannot pin short-lived task facts without turning them into permanent preferences. Brain outputs are Obsidian-first wikilinks even when a downstream consumer wants standard Markdown links, and MCP tools expose structured payloads without validating output contracts at the boundary. Finally, the redactor catches secret-looking assignments but does not let a user or agent explicitly mark a region as private before it reaches storage.
+
+## Scope
+
+- Add a transient pinned-context surface backed by `Brain/pinned.md`.
+- Expose one MCP tool for pinned context read/write/append/clear operations.
+- Include pinned context in `brain_context` so runtimes without a session-start hook can load active rules plus current-task facts in one call.
+- Add a dependency-free link output format resolver for `link_output_format: wikilink | markdown` in the existing config file.
+- Keep on-disk Brain artifacts Obsidian-compatible by default; apply the configured Markdown-link format to presentation outputs, not to internal identity fields that must stay stable.
+- Add a lightweight MCP output contract mechanism: optional `outputSchema` on `ToolDefinition`, validated against returned `structuredContent` before the MCP envelope is emitted.
+- Add output schemas first for the new pinned-context tool and the highest-value existing Brain/search surfaces touched by this release (`brain_context`, `brain_query`, `brain_search`), with loose object schemas where exact payload details are intentionally extensible.
+- Add `stripPrivateRegions` to the shared redactor and run it before secret assignment redaction through `redactRawOutput` / `sanitiseTextField`.
+- Update docs, changelog, tests, and project version before push as requested by the operator.
+
+## Out of scope
+
+- Real-time session lifecycle hooks, workers, or embedding changes from the parent cavemem task.
+- Path-glob capture exclusion from the cavemem task; this needs a separate vault-scope design.
+- A generic boundary pipeline abstraction for all inbound/outbound surfaces.
+- Rewriting persisted Brain files from wikilinks to Markdown links.
+- Full JSON Schema draft compliance; the validator only covers the schema subset used by MCP contracts in this release.
+- Visibility tags, retention lifecycle review, multi-phase dream, schema packs, and vector backend work.
+
+## Chosen approach
+
+Use independent additive slices. The pinned-context feature gets a small core module and MCP tool, link output gets a small config resolver plus presentation renderer options, MCP contracts get an optional `outputSchema` field and a focused validator at `toolResult`, and private-region stripping extends the existing redactor. This keeps each task testable in isolation and avoids introducing a cross-cutting pipeline before the codebase has more than one concrete need for it.
+
+## Design decisions
+
+- `Brain/pinned.md` lives at the Brain root beside `active.md`, because it is session/task context rather than an inbox signal, preference, retired rule, or log event.
+- The pinned-context MCP tool uses an explicit operation field (`read`, `write`, `append`, `clear`) instead of several tool names, so the writer-server surface grows by one tool and remains easy to advertise.
+- Pinned content is returned as its own structured `pinned` block from `brain_context`, and also appended to the human-readable `content` only when non-empty. Agents get a stable machine field and humans still see one combined context card.
+- Private-region stripping is included only as a deterministic text transform. It strips balanced `<private>...</private>` blocks case-insensitively and leaves an audit marker; malformed/unclosed tags are handled conservatively by stripping from the opening tag to end of input.
+- `redactRawOutput` runs `stripPrivateRegions` before assignment/key redaction, so any existing writer using `sanitiseTextField` receives the new privacy behaviour without per-call drift.
+- `link_output_format` accepts only `wikilink` or `markdown`; invalid or absent config falls back to `wikilink` for backward compatibility.
+- Markdown-link rendering preserves the same display title sanitisation as wikilinks and points to stable vault-relative Brain paths (`Brain/preferences/pref-*.md`, `Brain/retired/ret-*.md`) when the helper can infer them.
+- MCP output contracts validate `structuredContent` before `content` text is generated, so the text mirror cannot accidentally serialize an invalid object.
+- Contract failure is an internal server error, not a client `INVALID_PARAMS`, because the tool handler returned a shape that violates its own declaration.
+- The schema validator is local and deliberately small: object/string/number/integer/boolean/array/null, `required`, `properties`, `items`, `enum`, and `additionalProperties: false` are enough for the planned contracts.
+- The generic playbook says version bump usually happens during release, but the operator explicitly requested a project version bump before GitHub push; this branch follows the operator override.
+
+## File changes
+
+Expected new files:
+
+- `src/core/brain/pinned.ts`
+- `src/mcp/output-contract.ts`
+- `tests/core/brain.pinned.test.ts`
+- `tests/mcp/output-contract.test.ts`
+- `docs/brainstorm/agent-boundary-control-surfaces/*`
+
+Expected modified files:
+
+- `src/core/brain/paths.ts`
+- `src/core/brain/wikilink.ts`
+- `src/core/config.ts`
+- `src/core/redactor.ts`
+- `src/mcp/tools.ts`
+- `src/mcp/server.ts`
+- `src/mcp/brain-tools.ts`
+- `src/mcp/search-tools.ts`
+- `tests/core/brain.wikilink.test.ts`
+- `tests/core/redactor.test.ts`
+- `tests/mcp/brain.test.ts`
+- `tests/mcp/mcp.test.ts`
+- `tests/mcp/mcp-json.test.ts` if contract assertions fit better there
+- `README.md`
+- `docs/mcp.md`
+- `docs/how-it-works.md`
+- `docs/cli-reference.md`
+- `CHANGELOG.md`
+- `package.json` and version-synced metadata files via `bun run sync-version`
+
+## Risks and open questions
+
+- `brain_context` content composition must stay backward compatible for agents that only read `content`. The new `pinned` block should be additive.
+- Link-format configuration can become too broad if applied to persisted Brain internals. Keep it presentation-only unless a separate storage-migration task explicitly changes that contract.
+- Output schemas for broad tools such as `brain_search` must stay loose enough to avoid breaking extensibility while still catching gross contract drift.
+- Private-region stripping may surprise users if they intentionally write literal XML-like examples. Document the behaviour clearly and test escaped/malformed cases.
+- The exact MCP tool name should avoid confusion with the existing CLI preference pin command. Implementation should prefer a name like `brain_pinned_context` unless local naming conventions strongly point elsewhere.
diff --git a/docs/brainstorm/agent-boundary-control-surfaces/plan.md b/docs/brainstorm/agent-boundary-control-surfaces/plan.md
new file mode 100644
index 00000000..b397b528
--- /dev/null
+++ b/docs/brainstorm/agent-boundary-control-surfaces/plan.md
@@ -0,0 +1,38 @@
+# Agent Boundary Control Surfaces - implementation plan
+
+## Tasks
+
+### Task 1: Private-region redaction helper
+- **Files**: `src/core/redactor.ts`, `tests/core/redactor.test.ts`, docs that describe redaction.
+- **Acceptance**: `bun test tests/core/redactor.test.ts` proves balanced, case-insensitive, multiline, and unclosed `<private>...</private>` regions are stripped before secret redaction and normalisation.
+- **Depends on**: none.
+
+### Task 2: Pinned context core
+- **Files**: `src/core/brain/paths.ts`, `src/core/brain/pinned.ts`, `tests/core/brain.pinned.test.ts`.
+- **Acceptance**: focused core tests prove missing pinned context reads as empty, write/append/clear are vault-safe and deterministic, and content is sanitised through the shared redactor.
+- **Depends on**: Task 1.
+
+### Task 3: Pinned context MCP surface
+- **Files**: `src/mcp/brain-tools.ts`, `src/mcp/tools.ts`, `src/mcp/instructions.ts`, `tests/mcp/brain.test.ts`, `tests/mcp/mcp.test.ts`.
+- **Acceptance**: MCP tests prove `brain_pinned_context` read/write/append/clear behaviour and prove `brain_context` returns a structured `pinned` block while preserving existing active context fields.
+- **Depends on**: Task 2.
+
+### Task 4: Configurable link output format
+- **Files**: `src/core/config.ts`, `src/core/brain/wikilink.ts`, presentation call sites selected during implementation, `tests/core/brain.wikilink.test.ts`, relevant CLI/MCP tests.
+- **Acceptance**: tests prove default wikilink output remains unchanged, `link_output_format: markdown` renders stable Markdown links for preference/retired references in presentation output, and invalid config values fall back to wikilink.
+- **Depends on**: none.
+
+### Task 5: MCP output contracts
+- **Files**: `src/mcp/output-contract.ts`, `src/mcp/tools.ts`, `src/mcp/server.ts`, `src/mcp/brain-tools.ts`, `src/mcp/search-tools.ts`, `tests/mcp/output-contract.test.ts`, `tests/mcp/mcp.test.ts`; use `tests/mcp/mcp-json.test.ts` only for existing JSON-envelope regression coverage that already belongs there.
+- **Acceptance**: focused tests prove the schema subset validator, MCP tool calls validate `structuredContent` before text serialization, declared contracts pass for covered tools, and a deliberately invalid handler shape becomes an internal tool error.
+- **Depends on**: Task 3 for the new pinned-context contract.
+
+### Task 6: Documentation, changelog, and version bump
+- **Files**: `README.md`, `docs/mcp.md`, `docs/how-it-works.md`, `docs/cli-reference.md`, `CHANGELOG.md`, `package.json`, version-synced files.
+- **Acceptance**: docs describe pinned context, link output config, MCP contracts, and private-region stripping; `bun run sync-version:check` passes after the explicit pre-push version bump.
+- **Depends on**: Tasks 1-5.
+
+### Task 7: Self-review and QA
+- **Files**: no planned source changes unless review finds defects.
+- **Acceptance**: self-review compares the feature branch against `main`; focused tests, `bun run typecheck`, `bun run lint`, `bun run sync-version:check`, and `bun run validate` pass or any failure is fixed in-branch before the pre-push `ask_report` stop-point.
+- **Depends on**: Task 6.
diff --git a/docs/brainstorm/agent-boundary-control-surfaces/variants.md b/docs/brainstorm/agent-boundary-control-surfaces/variants.md
new file mode 100644
index 00000000..8e31071c
--- /dev/null
+++ b/docs/brainstorm/agent-boundary-control-surfaces/variants.md
@@ -0,0 +1,57 @@
+# Agent Boundary Control Surfaces - variants audit trail
+
+## Consultant
+
+Primary consultant: Claude Code (`claude -p docs/brainstorm/agent-boundary-control-surfaces/cli-output/prompt.md`)
+
+Fallback consultant: not run because the primary consultant returned exactly three parseable variants and one recommendation.
+
+## Variants
+
+### Variant 1: Independent additive slices
+
+- **Approach**: Land each task as its own thin, isolated slice with no shared abstraction. `Brain/pinned.md` gets a small `src/core/brain/pinned.ts` and a `brain_pinned_context` tool (read/write/clear ops), with `brain_context` appending pinned content beside active prefs. Link output adds a `link_output_format` key to `src/core/config.ts` plus a renderer branch in `src/core/brain/wikilink.ts`/`src/core/search/links.ts`. Contract enforcement adds an optional JSON-Schema field to `ToolDefinition` in `src/mcp/tools.ts` and a validation step in `MCPServer.handleToolsCall` against `structuredContent`. The cavemem helper is a `stripPrivateRegions` pass added to `src/core/redactor.ts`, invoked from the existing Brain/Pay Memory write boundary that already calls `redactRawOutput`.
+- **Trade-offs**:
+ - Pro: aligns with the "small additive surfaces" constraint; each slice ships behind its own tests, fits TDD feature-by-feature, and reviews independently.
+ - Pro: no new cross-cutting abstraction to design, document, or migrate later if priorities change.
+ - Pro: the conditional cavemem task collapses to one regex + helper export reused by existing redactor callers β€” exactly the "small shared redaction helper" the gating clause requires.
+ - Con: four logically related boundary surfaces ship without a common shape; future similar features re-invent registration/wiring patterns.
+ - Con: contract validation lives ad-hoc in the MCP server rather than as a reusable layer; subsequent tools must remember to wire it.
+- **Complexity**: small
+- **Risk**: low
+
+### Variant 2: Unified boundary-stage pipeline
+
+- **Approach**: Introduce a generalized "boundary pipeline" abstraction (e.g., `src/mcp/boundary.ts`) with explicit inbound (context-assembly) and outbound (response-shaping) stages, each registered by name. Pinned-content load becomes an inbound stage on `brain_context`; link rendering, contract validation, and private-region stripping become outbound stages applied to `structuredContent` and text payloads. `MCPServer.handleToolsCall` becomes a thin driver over this pipeline; `src/core/redactor.ts` plugs in as one outbound stage.
+- **Trade-offs**:
+ - Pro: principled, extensible seam that anticipates further boundary control surfaces.
+ - Pro: contract validation, redaction, and link formatting are uniformly applied without per-tool wiring.
+ - Con: introduces a cross-cutting abstraction for only 3-4 concrete features β€” exactly the broad refactor the constraints warn against.
+ - Con: harder to land TDD feature-by-feature; each slice now depends on the pipeline scaffold being merged first.
+ - Con: backward-compat risk on `MCPServer.handleToolsCall` envelope semantics (`content` + `structuredContent`), and on Brain context composition tested by `tests/mcp/brain.test.ts`.
+ - Con: the cavemem gating clause explicitly forbids "real-time session lifecycle hooks"; a generic stage pipeline edges toward that shape.
+- **Complexity**: large
+- **Risk**: medium
+
+### Variant 3: Direction-split surfaces (inbound context vs outbound envelope)
+
+- **Approach**: Group the work into two cohesive but small surfaces. An inbound "session context" surface adds `Brain/pinned.md` plus the `brain_pinned_context` tool and extends `brain_context` to compose active prefs + pinned snippet. An outbound "envelope" surface adds a single `renderEnvelope` helper that the MCP server calls before returning tool results: it applies the `link_output_format` config to any rendered wikilinks, validates `structuredContent` against per-tool JSON Schemas declared on `ToolDefinition`, and runs the new `stripPrivateRegions` pass (also exported from `src/core/redactor.ts` so Brain writers can call it on the write path).
+- **Trade-offs**:
+ - Pro: organizes the four tasks by data direction, which matches how the existing code is already split (`brain-tools.ts` for inbound context vs `redactor.ts`/`tools.ts` for outbound shaping).
+ - Pro: still avoids a generic pipeline; each surface is one new file plus targeted edits.
+ - Pro: makes contract enforcement a property of the envelope rather than per-tool code, while staying smaller than Variant 2.
+ - Con: bundles three logically distinct outbound concerns (link formatting, schema validation, private-region stripping) into one helper whose responsibilities will drift.
+ - Con: introduces an envelope abstraction that current tests (`tests/mcp/mcp.test.ts`) do not yet exercise β€” moderate test churn.
+ - Con: harder to ship piecewise because the envelope is a shared seam; first task lands the seam, later tasks must conform.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Recommended: Variant 1
+
+**Rationale**: The project's stated constraints β€” additive surfaces over broad refactors, TDD feature-by-feature, backward-compatible public APIs, and the conditional cavemem clause requiring a _small_ shared redaction helper β€” all favor independent slices. The four tasks happen to touch the agent boundary but do not share enough mechanism to justify a pipeline (Variant 2) or even a shared envelope (Variant 3); each slice is a few dozen lines against well-isolated files (`brain-tools.ts`, `wikilink.ts`/`links.ts`, `tools.ts`/`server.ts`, `redactor.ts`) with existing test homes. If a real cross-cutting need emerges later (e.g., a second tool needing the same JSON-Schema check), extracting from the concrete implementations will be straightforward and lower-risk than designing the abstraction up front.
+
+## Orchestrator decision
+
+I agree with Variant 1. The selected kanban scope intentionally combines several boundary-control tasks, but they do not yet justify a generic pipeline: pinned context is an inbound Brain context concern, link rendering is a presentation concern, MCP output contracts are a server-envelope concern, and private-region stripping belongs in the existing redactor. Keeping the first implementation concrete makes TDD simpler, limits migration risk, and leaves a cleaner extraction path if repeated patterns appear in later releases.
+
+The conditional privacy task is included only in its small helper form. Path-glob capture exclusions and real-time lifecycle hooks remain out of scope because they belong to the larger cavemem session-capture cluster and would turn this PR into an architecture shift.
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index 80a6d5fe..fdbc20d1 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -28,7 +28,7 @@ o2b brain feedback Record one taste signal (--topic, --signal, --prin
o2b brain dream Run the deterministic consolidation pass (idempotent; usually cron'd)
o2b brain apply-evidence Record applied / violated against a preference for a durable artifact
o2b brain note <text> Append a one-line narrative milestone to Brain/log/<today>.md (cron / shell mirror of brain_note)
-o2b brain digest Render a Markdown or JSON summary of recent Brain transitions; --window 7d for arbitrary lookback
+o2b brain digest Render a Markdown or JSON summary of recent Brain transitions; --window 7d for arbitrary lookback; Markdown links follow link_output_format / OBSIDIAN_LINK_FORMAT
o2b brain query Read helper: by preference, by topic, or by log timestamp
o2b brain agent-query Read source-agent provenance; filters by --agent, --topic, --query, --kind, --limit; --json mirrors brain_agent_query
o2b brain agent-diff Compare source-agent coverage in browse/search/diff/map modes; --json mirrors brain_agent_diff
@@ -150,5 +150,6 @@ vault-log Shell mirror of brain_note (one-liner narrative mi
- Every CLI mutation that touches Brain takes a pre-run snapshot under `Brain/.snapshots/` with a SHA-256 sidecar manifest. `o2b brain rollback` aborts on drift unless `--force-rollback`.
- `o2b ... --json` exists on every read verb and most write verbs (the JSON payload mirrors the MCP tool's response shape).
+- MCP-only `brain_pinned_context` manages `Brain/pinned.md`, a transient current-task scratchpad loaded by `brain_context`; it is intentionally not a learned preference CLI verb.
- `--dry-run` is supported by every mutating verb that touches more than a single file (`brain merge`, `brain rollback`, `brain upgrade`, `brain import-claude-memory`, `update`, ...).
- `--vault` always overrides the profile path; useful for multi-vault hosts where the config-resolved default is not the right target.
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index 297f23e3..0b326536 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -333,6 +333,7 @@ flowchart LR
Active -- PostCompact hook --> ClaudeCompact["Claude Code / Codex<br/>after /compact"]
Active -- "osb://preferences/active" --> MCPHost["MCP host (Hermes, others)"]
Active -- "brain_context tool" --> PullRT["Cursor / Aider / raw API<br/>(no SessionStart hook)"]
+ Pinned[Brain/pinned.md] -- "brain_context tool" --> PullRT
```
- **`Brain/active.md`** is a derived Markdown digest: confirmed
@@ -360,8 +361,12 @@ flowchart LR
- **`brain_context` MCP tool** (v0.10.10) lives in the always-loaded
writer-scope MCP server. Runtimes that lack a `SessionStart` hook
*and* do not auto-load MCP resources (Cursor, Aider, raw Claude
- API) can fetch the same `active.md` body plus active-preference
- counts with a single tool call.
+ API) can fetch the same `active.md` body, pinned current-task context,
+ and active-preference counts with a single tool call.
+- **`Brain/pinned.md`** is a transient scratchpad for current-task facts.
+ Agents update it through `brain_pinned_context` when a fact should survive
+ context rotation but should not become a durable preference. Clearing it
+ leaves the permanent Brain history untouched.
`active.md` is **not** edited by hand β€” `o2b brain dream` and pin /
unpin re-derive it from `preferences/` and `retired/`. Deleting the
@@ -379,7 +384,8 @@ are mirrored in MCP; destructive operations are CLI-only by design.
| Consolidation pass | `o2b brain dream` | `brain_dream` | mutates preferences/retired, atomic snapshot, regenerates `Brain/active.md` |
| Record application | `o2b brain apply-evidence` | `brain_apply_evidence`| appends log event; `result ∈ {applied, violated, outdated}`; artifact supports `[[file:120-145]]` ranges |
| Record milestone | `o2b brain note <text>` | `brain_note` | appends one `note` log event to `Brain/log/<today>.md` plus the JSONL sidecar. Multi-line collapses to one line. CLI mirror exists for cron / shell. |
-| Pull active context | β€” (use MCP) | `brain_context` | read-only; returns `Brain/active.md` body + counts. Always-loaded on the writer MCP server so runtimes without a `SessionStart` hook (Cursor, Aider, raw Claude API) can fetch it at session start. |
+| Pin current-task context | β€” (use MCP) | `brain_pinned_context`| writes/appends/clears `Brain/pinned.md`; transient context, not a learned preference |
+| Pull active context | β€” (use MCP) | `brain_context` | read-only; returns `Brain/active.md` body, pinned context + counts. Always-loaded on the writer MCP server so runtimes without a `SessionStart` hook (Cursor, Aider, raw Claude API) can fetch it at session start. |
| Render summary | `o2b brain digest [--window Nd]` | `brain_digest` | read-only; includes `top_applied`, `top_referenced`, and `agent_summary` sections |
| Inspect state | `o2b brain query` | `brain_query` | read-only |
| Computed backlinks | `o2b brain backlinks <id>` | `brain_backlinks` | read-only; inverted reference map across `preferences/`, `retired/`, `log/` |
@@ -520,6 +526,9 @@ through `src/core/redactor.ts` (promoted from Pay Memory) plus a
with `***REDACTED***`. The `raw` field is the only verbatim-quote
surface and is intentionally **not** redacted β€” it carries the
original user phrasing.
+- Explicit `<private>...</private>` regions are stripped before secret
+ assignment redaction. An unclosed `<private>` tag strips from the tag to
+ the end of the field, which is conservative for accidental paste leaks.
- Inputs that sanitise down to empty fall into the existing "missing
field" error branch, so the writer never persists a placeholder
signal.
diff --git a/docs/mcp.md b/docs/mcp.md
index e6c3efe6..23959443 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -258,8 +258,8 @@ server to your Codex MCP config the same way as Hermes.
The plugin's `.mcp.json` ships **two** MCP-server entries:
-- `open-second-brain` - the full surface (35 tools, including `brain_health`, `brain_agent_query`, and `brain_agent_diff`); subject to Claude Code's `MCPSearch` tool-search deferral when MCP definitions push the system prompt past 10% of the context window.
-- `open-second-brain-writer` - a minimal always-loaded surface of four tools: `brain_feedback`, `brain_apply_evidence`, `brain_note` (writers) and `brain_context` (read-only pull-bootstrap of `Brain/active.md`, v0.10.10). The agent records taste signals, evidence events, and milestone notes - and fetches the active rule digest at session start in runtimes without a SessionStart hook - without a ToolSearch round-trip on every session boot.
+- `open-second-brain` - the full surface (36 tools, including `brain_health`, `brain_agent_query`, `brain_agent_diff`, and `brain_pinned_context`); subject to Claude Code's `MCPSearch` tool-search deferral when MCP definitions push the system prompt past 10% of the context window.
+- `open-second-brain-writer` - a minimal always-loaded surface of five tools: `brain_feedback`, `brain_apply_evidence`, `brain_note`, `brain_pinned_context` (writers) and `brain_context` (read-only pull-bootstrap of `Brain/active.md` plus pinned context, v0.16.0). The agent records taste signals, evidence events, milestone notes, and current-task pinned facts - and fetches the active rule digest at session start in runtimes without a SessionStart hook - without a ToolSearch round-trip on every session boot.
Both servers reuse the same backing CLI (`o2b mcp --scope writer` vs the default `--scope full`). Handlers are byte-identical; the writer-mode instructions text explicitly tells the agent to prefer the writer copy over any duplicate the full server still exposes (both call the same code path).
@@ -268,6 +268,9 @@ Both servers reuse the same backing CLI (`o2b mcp --scope writer` vs the default
- The vault path is bound to the server instance at startup. Tools cannot
escape it.
- `second_brain_status` reuses the same redaction logic as `o2b export-config`.
-- Brain writers (`brain_feedback`, `brain_apply_evidence`, `brain_note`)
+- Brain writers (`brain_feedback`, `brain_apply_evidence`, `brain_note`,
+ `brain_pinned_context`)
go through atomic-rename writes so an interrupted call leaves either
the prior or the new file, never a torn hybrid.
+- MCP tools can declare lightweight output contracts; declared contracts are
+ validated against `structuredContent` before the text mirror is emitted.
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 53129fb1..72e71e88 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -2,7 +2,7 @@
"id": "open-second-brain",
"name": "Open Second Brain",
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",
- "version": "0.15.0",
+ "version": "0.16.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/openclaw/index.js b/openclaw/index.js
index 259d4f91..a6f75516 100644
--- a/openclaw/index.js
+++ b/openclaw/index.js
@@ -1649,7 +1649,13 @@ function stem(filename) {
}
// src/core/config.ts
-var SECRET_KEY_PARTS = ["key", "token", "secret", "password", "credential"];
+var SECRET_KEY_PARTS = [
+ "key",
+ "token",
+ "secret",
+ "password",
+ "credential"
+];
function defaultConfigPath() {
const override = process.env["OPEN_SECOND_BRAIN_CONFIG"];
if (override)
@@ -2021,7 +2027,11 @@ function checkCodexManifest(path) {
["keywords", "list"]
]);
if (problems.length > 0) {
- return { name: "codex_manifest", ok: false, message: `schema invalid: ${path} (${problems.join("; ")})` };
+ return {
+ name: "codex_manifest",
+ ok: false,
+ message: `schema invalid: ${path} (${problems.join("; ")})`
+ };
}
return { name: "codex_manifest", ok: true, message: `valid Codex manifest: ${path}` };
}
@@ -2056,7 +2066,11 @@ function checkClaudeManifest(path) {
problems.push("embedded 'commands' array is deprecated β€” author slash commands " + "as Markdown files under commands/ at plugin root instead");
}
if (problems.length > 0) {
- return { name: "claude_manifest", ok: false, message: `schema invalid: ${path} (${problems.join("; ")})` };
+ return {
+ name: "claude_manifest",
+ ok: false,
+ message: `schema invalid: ${path} (${problems.join("; ")})`
+ };
}
return { name: "claude_manifest", ok: true, message: `valid Claude manifest: ${path}` };
}
@@ -2102,7 +2116,11 @@ function checkOpenclawManifest(path) {
problems.push("missing or empty field 'configSchema'");
}
if (problems.length > 0) {
- return { name: "openclaw_manifest", ok: false, message: `schema invalid: ${path} (${problems.join("; ")})` };
+ return {
+ name: "openclaw_manifest",
+ ok: false,
+ message: `schema invalid: ${path} (${problems.join("; ")})`
+ };
}
return { name: "openclaw_manifest", ok: true, message: `valid OpenClaw manifest: ${path}` };
}
@@ -2196,14 +2214,13 @@ function loadReminderTemplate() {
return commonTemplateCache;
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
- throw new Error(`Failed to load identity reminder template from ${TEMPLATE_PATH}: ${message}`);
+ throw new Error(`Failed to load identity reminder template from ${TEMPLATE_PATH}: ${message}`, {
+ cause: err
+ });
}
}
var TEMPLATES_DIR = resolve2(dirname4(fileURLToPath(import.meta.url)), "..", "..", "templates");
-var PER_TARGET_PATHS = Object.freeze(Object.fromEntries(KNOWN_RUNTIME_TARGETS.map((t) => [
- t,
- resolve2(TEMPLATES_DIR, `identity-reminder.${t}.txt`)
-])));
+var PER_TARGET_PATHS = Object.freeze(Object.fromEntries(KNOWN_RUNTIME_TARGETS.map((t) => [t, resolve2(TEMPLATES_DIR, `identity-reminder.${t}.txt`)])));
var TEMPLATE_CACHE = new Map;
function tryReadTargetTemplate(target) {
const cached = TEMPLATE_CACHE.get(target);
@@ -2440,11 +2457,14 @@ function tzOffsetMinutes(instantMs, tz) {
}
// src/core/redactor.ts
var PLACEHOLDER = "***REDACTED***";
+var PRIVATE_REGION_PLACEHOLDER = "***PRIVATE***";
var MAX_REDACTOR_INPUT = 256 * 1024;
var TRUNCATION_MARKER = `
[…truncated for size; original exceeded 256 KB. Inspect raw output before sharing.]
`;
+var PRIVATE_OPEN_TAG_RE = /<private\b[^>]*>/gi;
+var PRIVATE_CLOSE_TAG_RE = /<\/private>/gi;
var SECRET_KEYS = [
"api_key",
"token",
@@ -2467,10 +2487,48 @@ var ENV_RE = new RegExp(`\\b(${KEY_PATTERN})(\\s*=\\s*)([^\\s\\r\\n]+)`, "gi");
var COLON_VALUE_RE = new RegExp(`(?<!")\\b(${KEY_PATTERN})(\\s*:\\s*)("[^"]*"|'[^']*'|[^\\r\\n]+)`, "gi");
var JSON_ENTRY_RE = new RegExp(`("(?:${KEY_PATTERN})"\\s*:\\s*)("(?:[^"\\\\]|\\\\.)*"|true|false|null|-?\\d+(?:\\.\\d+)?)`, "gi");
var BEARER_RE = /\b(Bearer\s+)([A-Za-z0-9._\-+/=]+)/gi;
+function stripPrivateRegions(text) {
+ if (!text)
+ return text;
+ let output = "";
+ let cursor = 0;
+ PRIVATE_OPEN_TAG_RE.lastIndex = 0;
+ PRIVATE_CLOSE_TAG_RE.lastIndex = 0;
+ while (cursor < text.length) {
+ PRIVATE_OPEN_TAG_RE.lastIndex = cursor;
+ const openMatch = PRIVATE_OPEN_TAG_RE.exec(text);
+ if (!openMatch) {
+ output += text.slice(cursor);
+ break;
+ }
+ output += text.slice(cursor, openMatch.index);
+ output += PRIVATE_REGION_PLACEHOLDER;
+ let depth = 1;
+ let scan = PRIVATE_OPEN_TAG_RE.lastIndex;
+ while (depth > 0) {
+ PRIVATE_OPEN_TAG_RE.lastIndex = scan;
+ PRIVATE_CLOSE_TAG_RE.lastIndex = scan;
+ const nextOpen = PRIVATE_OPEN_TAG_RE.exec(text);
+ const nextClose = PRIVATE_CLOSE_TAG_RE.exec(text);
+ if (!nextClose)
+ return output;
+ if (nextOpen && nextOpen.index < nextClose.index) {
+ depth += 1;
+ scan = PRIVATE_OPEN_TAG_RE.lastIndex;
+ } else {
+ depth -= 1;
+ scan = PRIVATE_CLOSE_TAG_RE.lastIndex;
+ }
+ }
+ cursor = scan;
+ }
+ return output;
+}
function redactRawOutput(text) {
if (!text)
return text;
let out = text.length > MAX_REDACTOR_INPUT ? text.slice(0, MAX_REDACTOR_INPUT) + TRUNCATION_MARKER : text;
+ out = stripPrivateRegions(out);
out = out.replace(JSON_ENTRY_RE, (_match, keyPart, value) => {
if (value.startsWith('"'))
return `${keyPart}"${PLACEHOLDER}"`;
@@ -2666,7 +2724,7 @@ function writeFrontmatterAtomic(path, metadata, body, opts = {}) {
} catch (err) {
if (opts.existsErrorKind && err?.code === "EEXIST") {
const rel = opts.vaultForRelativePath ? path.startsWith(opts.vaultForRelativePath + "/") ? path.slice(opts.vaultForRelativePath.length + 1) : path : path;
- throw new Error(`${opts.existsErrorKind} already exists: ${rel}`);
+ throw new Error(`${opts.existsErrorKind} already exists: ${rel}`, { cause: err });
}
throw err;
}
@@ -3214,13 +3272,17 @@ function loadPolicyRules(vault) {
} catch (err) {
if (err?.code === "ENOENT")
return null;
- throw new Error(`failed to read ${target}: ${err.message ?? String(err)}`);
+ throw new Error(`failed to read ${target}: ${err.message ?? String(err)}`, {
+ cause: err
+ });
}
let parsed;
try {
parsed = JSON.parse(text);
} catch (err) {
- throw new Error(`${target} is not valid JSON: ${err.message ?? String(err)}`);
+ throw new Error(`${target} is not valid JSON: ${err.message ?? String(err)}`, {
+ cause: err
+ });
}
return validatePolicyRules(parsed, target);
}
@@ -3678,19 +3740,25 @@ var openclaw_default = definePluginEntry({
api.registerTool({
name: "second_brain_status",
description: "Report Open Second Brain configuration and vault status.",
- parameters: { type: "object", properties: {}, additionalProperties: false },
+ parameters: {
+ type: "object",
+ properties: {},
+ additionalProperties: false
+ },
async execute() {
const vault = resolveVaultPath(api);
const discovery = discoverConfig();
const result = {
config_path: discovery.path,
config_exists: discovery.exists,
- config_keys: Object.keys(discovery.data).sort(),
+ config_keys: Object.keys(discovery.data).toSorted(),
config: redactMapping(discovery.data),
vault_path: vault,
vault_exists: existsSync6(vault)
};
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
+ return {
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
+ };
}
});
api.registerTool({
@@ -3722,7 +3790,11 @@ var openclaw_default = definePluginEntry({
throw new Error("argument 'limit' must be between 1 and 500");
const pages = listVaultPages(vault);
const needle = pattern ? pattern.toLowerCase() : null;
- const matched = (needle === null ? pages : pages.filter((p) => p.title.toLowerCase().includes(needle))).slice(0, limit).map((p) => ({ title: p.title, path: vaultRelative(p.path, vault), metadata: p.metadata }));
+ const matched = (needle === null ? pages : pages.filter((p) => p.title.toLowerCase().includes(needle))).slice(0, limit).map((p) => ({
+ title: p.title,
+ path: vaultRelative(p.path, vault),
+ metadata: p.metadata
+ }));
const result = {
vault_path: vault,
total_pages: pages.length,
@@ -3731,7 +3803,9 @@ var openclaw_default = definePluginEntry({
pattern,
pages: matched
};
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
+ return {
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
+ };
}
});
api.registerTool({
@@ -3754,9 +3828,15 @@ var openclaw_default = definePluginEntry({
const result = {
vault_path: vault,
ok: results.every((r) => r.ok),
- checks: results.map((r) => ({ name: r.name, ok: r.ok, message: r.message }))
+ checks: results.map((r) => ({
+ name: r.name,
+ ok: r.ok,
+ message: r.message
+ }))
+ };
+ return {
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
};
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
}
});
api.registerTool({
diff --git a/package.json b/package.json
index 13a11617..eb87b9cc 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.15.0",
+ "version": "0.16.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 9c848afc..487981a7 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.15.0"
+version: "0.16.0"
description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index 9612a6a5..376d4ea9 100644
--- a/plugins/codex/.codex-plugin/plugin.json
+++ b/plugins/codex/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.15.0",
+ "version": "0.16.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 0c7583c9..a1eaa9bf 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.15.0"
+version: "0.16.0"
description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/pyproject.toml b/pyproject.toml
index 949cfbd1..daceaeb4 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"
# CLI entry points (those moved to `package.json` `bin`).
[project]
name = "open-second-brain"
-version = "0.15.0"
+version = "0.16.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/verbs/digest.ts b/src/cli/brain/verbs/digest.ts
index 01fc3d0c..82070644 100644
--- a/src/cli/brain/verbs/digest.ts
+++ b/src/cli/brain/verbs/digest.ts
@@ -1,4 +1,4 @@
-import { defaultConfigPath } from "../../../core/config.ts";
+import { defaultConfigPath, resolveLinkOutputFormat } from "../../../core/config.ts";
import { renderDigest, type RenderDigestOptions } from "../../../core/brain/digest.ts";
import { parse, fail, resolveBrainVault, parseOptionalIsoDate } from "../helpers.ts";
@@ -45,6 +45,7 @@ export async function cmdBrainDigest(argv: string[]): Promise<number> {
...(sinceDate ? { since: sinceDate } : {}),
...(untilDate ? { until: untilDate } : {}),
format: flags["json"] ? "json" : "markdown",
+ linkOutputFormat: resolveLinkOutputFormat(config),
};
let result;
diff --git a/src/core/brain/digest.ts b/src/core/brain/digest.ts
index f7f16bcb..0517ca85 100644
--- a/src/core/brain/digest.ts
+++ b/src/core/brain/digest.ts
@@ -38,6 +38,8 @@
import { existsSync, readdirSync } from "node:fs";
import { join } from "node:path";
+import type { LinkOutputFormat } from "../config.ts";
+
import { backlinkCount, buildBacklinkIndex } from "./backlinks.ts";
import { computeAgentSummary, type AgentSummaryEntry } from "./digest-agent-summary.ts";
import { findMergeCandidates } from "./merge-candidates.ts";
@@ -73,6 +75,8 @@ export interface RenderDigestOptions {
readonly until?: Date;
/** Output format. Defaults to `markdown`. */
readonly format?: DigestFormat;
+ /** Presentation link format for Markdown output. Defaults to Obsidian wikilinks. */
+ readonly linkOutputFormat?: LinkOutputFormat;
/**
* Injection seam for deterministic tests: defaults the generated_at
* timestamp. Production callers do not pass this β€” the renderer
@@ -369,7 +373,8 @@ export function renderDigest(vault: string, opts: RenderDigestOptions = {}): Ren
}
// Markdown.
- const baseMd = empty ? renderEmptyMarkdown(until) : renderMarkdown(data, since, until);
+ const linkOutputFormat = opts.linkOutputFormat ?? "wikilink";
+ const baseMd = empty ? renderEmptyMarkdown(until) : renderMarkdown(data, since, until, linkOutputFormat);
const trustSection = renderTrustSection(opts.doctorResult, opts.dreamSummary);
const content = trustSection ? `${baseMd}\n${trustSection}` : baseMd;
return Object.freeze({ content, empty });
@@ -925,7 +930,12 @@ function renderEmptyMarkdown(until: Date): string {
return `Brain digest β€” ${ymd}: no changes\n`;
}
-function renderMarkdown(data: DigestData, since: Date, until: Date): string {
+function renderMarkdown(
+ data: DigestData,
+ since: Date,
+ until: Date,
+ linkOutputFormat: LinkOutputFormat,
+): string {
const sinceIso = since.toISOString();
const untilIso = until.toISOString();
const windowHours = Math.round((until.getTime() - since.getTime()) / (60 * 60 * 1000));
@@ -943,7 +953,7 @@ function renderMarkdown(data: DigestData, since: Date, until: Date): string {
const scope = item.scope ?? "β€”";
const trialDay = item.unconfirmed_until.slice(0, 10);
lines.push(
- `- ${renderPrefLink({ id: item.id, principle: item.principle })} β€” ${scope}, ${item.signal_count} signals, trial ends ${trialDay}`,
+ `- ${renderPrefLink({ id: item.id, principle: item.principle, format: linkOutputFormat })} β€” ${scope}, ${item.signal_count} signals, trial ends ${trialDay}`,
);
}
lines.push("");
@@ -954,7 +964,7 @@ function renderMarkdown(data: DigestData, since: Date, until: Date): string {
const scope = item.scope ?? "β€”";
const artifact = item.first_applied_artifact ?? "_(none)_";
lines.push(
- `- ${renderPrefLink({ id: item.id, principle: item.principle })} β€” ${scope}, first applied in ${artifact}`,
+ `- ${renderPrefLink({ id: item.id, principle: item.principle, format: linkOutputFormat })} β€” ${scope}, first applied in ${artifact}`,
);
}
lines.push("");
@@ -968,7 +978,7 @@ function renderMarkdown(data: DigestData, since: Date, until: Date): string {
? `${item.reason} (${item.days_stale} days)`
: item.reason;
lines.push(
- `- ${renderPrefLink({ id: item.id, principle: item.principle })} β€” ${scope}, ${detail}`,
+ `- ${renderPrefLink({ id: item.id, principle: item.principle, format: linkOutputFormat })} β€” ${scope}, ${detail}`,
);
}
lines.push("");
@@ -981,7 +991,7 @@ function renderMarkdown(data: DigestData, since: Date, until: Date): string {
for (const item of data.most_applied.entries) {
const scope = item.scope ?? "β€”";
lines.push(
- `- ${renderPrefLink({ id: item.id, principle: item.principle })} β€” ${scope}, ${item.applied_in_window} applied`,
+ `- ${renderPrefLink({ id: item.id, principle: item.principle, format: linkOutputFormat })} β€” ${scope}, ${item.applied_in_window} applied`,
);
}
lines.push("");
@@ -1007,7 +1017,7 @@ function renderMarkdown(data: DigestData, since: Date, until: Date): string {
const stats = `applied: ${item.applied_count}, violated: ${item.violated_count}`;
const tags = item.status === "quarantine" ? " [quarantine]" : "";
lines.push(
- `- ${renderPrefLink({ id: item.id, principle: item.principle })} β€” ${scope}, ${stats}${tags}`,
+ `- ${renderPrefLink({ id: item.id, principle: item.principle, format: linkOutputFormat })} β€” ${scope}, ${stats}${tags}`,
);
}
lines.push("");
@@ -1017,7 +1027,7 @@ function renderMarkdown(data: DigestData, since: Date, until: Date): string {
for (const item of data.top_referenced) {
const scope = item.scope ?? "β€”";
lines.push(
- `- ${renderPrefLink({ id: item.id, principle: item.principle })} β€” ${scope}, ${item.backlink_count} inbound`,
+ `- ${renderPrefLink({ id: item.id, principle: item.principle, format: linkOutputFormat })} β€” ${scope}, ${item.backlink_count} inbound`,
);
}
lines.push("");
@@ -1054,8 +1064,8 @@ function renderMarkdown(data: DigestData, since: Date, until: Date): string {
for (const item of data.merge_suggestions) {
const scope = item.scope ?? "β€”";
lines.push(
- `- ${renderPrefLink({ id: item.a, principle: item.principle_a })}` +
- ` β‰ˆ ${renderPrefLink({ id: item.b, principle: item.principle_b })}` +
+ `- ${renderPrefLink({ id: item.a, principle: item.principle_a, format: linkOutputFormat })}` +
+ ` β‰ˆ ${renderPrefLink({ id: item.b, principle: item.principle_b, format: linkOutputFormat })}` +
` β€” topic '${item.topic}', scope ${scope}, jaccard ${item.jaccard.toFixed(2)}`,
);
}
@@ -1069,7 +1079,7 @@ function renderMarkdown(data: DigestData, since: Date, until: Date): string {
? ` (applied: ${item.applied_count}, violated: ${item.violated_count})`
: "";
lines.push(
- `- ${renderPrefLink({ id: item.id, principle: item.principle })} ${item.from} β†’ ${item.to}${stats}`,
+ `- ${renderPrefLink({ id: item.id, principle: item.principle, format: linkOutputFormat })} ${item.from} β†’ ${item.to}${stats}`,
);
}
lines.push("");
@@ -1079,7 +1089,7 @@ function renderMarkdown(data: DigestData, since: Date, until: Date): string {
for (const item of data.contradictions) {
const topic = item.topic ? ` (topic: ${item.topic})` : "";
lines.push(
- `- ${renderPrefLink({ id: item.id, principle: item.principle })} β€” ${item.description}${topic}`,
+ `- ${renderPrefLink({ id: item.id, principle: item.principle, format: linkOutputFormat })} β€” ${item.description}${topic}`,
);
}
lines.push("");
diff --git a/src/core/brain/paths.ts b/src/core/brain/paths.ts
index 85c73565..33c79e6f 100644
--- a/src/core/brain/paths.ts
+++ b/src/core/brain/paths.ts
@@ -52,6 +52,7 @@ export const BRAIN_SNAPSHOTS_REL = posix.join(BRAIN_ROOT_REL, ".snapshots");
export const BRAIN_CONFIG_FILE = "_brain.yaml";
export const BRAIN_MANUAL_FILE = "_BRAIN.md";
export const BRAIN_ACTIVE_FILE = "active.md";
+export const BRAIN_PINNED_FILE = "pinned.md";
export const BRAIN_INDEX_FILE = "_INDEX.md";
/** Vault-relative path of the `o2b index` output file. */
@@ -116,6 +117,11 @@ export function brainActivePath(vault: string): string {
return ensureInsideVault(join(brainDirs(vault).brain, BRAIN_ACTIVE_FILE), vault);
}
+/** Path of the transient current-task scratchpad read by `brain_context`. */
+export function brainPinnedPath(vault: string): string {
+ return ensureInsideVault(join(brainDirs(vault).brain, BRAIN_PINNED_FILE), vault);
+}
+
/** Active-signal path: `Brain/inbox/sig-<date>-<slug>.md`. */
export function signalPath(vault: string, date: string, slug: string): string {
const d = validateIsoDate(date);
diff --git a/src/core/brain/pinned.ts b/src/core/brain/pinned.ts
new file mode 100644
index 00000000..3d35e373
--- /dev/null
+++ b/src/core/brain/pinned.ts
@@ -0,0 +1,53 @@
+import { existsSync, readFileSync } from "node:fs";
+
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { sanitiseTextField } from "../redactor.ts";
+import { brainPinnedPath } from "./paths.ts";
+
+export const MAX_PINNED_CONTEXT_LEN = 20_000;
+
+export interface PinnedContext {
+ readonly path: string;
+ readonly present: boolean;
+ readonly content: string;
+}
+
+export function readPinnedContext(vault: string): PinnedContext {
+ const path = brainPinnedPath(vault);
+ if (!existsSync(path)) {
+ return { path, present: false, content: "" };
+ }
+ return {
+ path,
+ present: true,
+ content: readFileSync(path, "utf8").trimEnd(),
+ };
+}
+
+export function writePinnedContext(vault: string, content: unknown): PinnedContext {
+ const path = brainPinnedPath(vault);
+ const normalised = normalisePinnedContent(content);
+ atomicWriteFileSync(path, normalised.length > 0 ? `${normalised}\n` : "");
+ return { path, present: true, content: normalised };
+}
+
+export function appendPinnedContext(vault: string, content: unknown): PinnedContext {
+ const incoming = normalisePinnedContent(content);
+ if (incoming.length === 0) return readPinnedContext(vault);
+
+ const current = readPinnedContext(vault).content;
+ const next = current.length > 0 ? `${current}\n\n${incoming}` : incoming;
+ return writePinnedContext(vault, next);
+}
+
+export function clearPinnedContext(vault: string): PinnedContext {
+ const path = brainPinnedPath(vault);
+ atomicWriteFileSync(path, "");
+ return { path, present: true, content: "" };
+}
+
+function normalisePinnedContent(content: unknown): string {
+ return sanitiseTextField(content, {
+ maxLen: MAX_PINNED_CONTEXT_LEN,
+ }).trim();
+}
diff --git a/src/core/brain/wikilink.ts b/src/core/brain/wikilink.ts
index 115c66cd..3858690c 100644
--- a/src/core/brain/wikilink.ts
+++ b/src/core/brain/wikilink.ts
@@ -28,6 +28,8 @@
import { basename } from "node:path";
+import type { LinkOutputFormat } from "../config.ts";
+
/**
* Strip wikilink decoration off `value` and return the bare target id.
*
@@ -207,6 +209,8 @@ export const MAX_PREF_LINK_TITLE_LEN = 80;
export function renderPrefLink(input: {
readonly id: string;
readonly principle?: string;
+ readonly format?: LinkOutputFormat;
+ readonly targetPath?: string;
}): string {
const raw = input.principle ?? "";
// Sanitisation pipeline, in order:
@@ -229,13 +233,21 @@ export function renderPrefLink(input: {
.replace(/[[\]|]/g, " ")
.replace(/\s+/g, " ")
.trim();
- if (title.length === 0) return `[[${input.id}]]`;
+ if (title.length === 0) {
+ if (input.format === "markdown") {
+ return renderMarkdownLink(input.id, inferBrainArtifactPath(input.id, input.targetPath));
+ }
+ return `[[${input.id}]]`;
+ }
// Measure the cap against code-point count (Array.from yields one
// entry per Unicode scalar) rather than UTF-16 code units so a
// string of 50 astral glyphs (100 code units, 50 code points) is
// not forced into the truncation path when the cap is 80.
const codepoints = Array.from(title);
if (codepoints.length <= MAX_PREF_LINK_TITLE_LEN) {
+ if (input.format === "markdown") {
+ return renderMarkdownLink(title, inferBrainArtifactPath(input.id, input.targetPath));
+ }
return `[[${input.id}|${title}]]`;
}
// Truncate to the cap, then back off to the previous word boundary β€”
@@ -247,7 +259,26 @@ export function renderPrefLink(input: {
let cutPoints = codepoints.slice(0, MAX_PREF_LINK_TITLE_LEN);
const lastSpace = cutPoints.lastIndexOf(" ");
if (lastSpace > 0) cutPoints = cutPoints.slice(0, lastSpace);
- return `[[${input.id}|${cutPoints.join("")}…]]`;
+ const truncated = `${cutPoints.join("")}…`;
+ if (input.format === "markdown") {
+ return renderMarkdownLink(truncated, inferBrainArtifactPath(input.id, input.targetPath));
+ }
+ return `[[${input.id}|${truncated}]]`;
+}
+
+function inferBrainArtifactPath(id: string, targetPath?: string): string {
+ if (targetPath) return targetPath;
+ if (id.startsWith("ret-")) return `Brain/retired/${id}.md`;
+ if (id.startsWith("pref-")) return `Brain/preferences/${id}.md`;
+ return `Brain/${id}.md`;
+}
+
+function renderMarkdownLink(label: string, targetPath: string): string {
+ return `[${label}](${encodeMarkdownTarget(targetPath)})`;
+}
+
+function encodeMarkdownTarget(targetPath: string): string {
+ return encodeURI(targetPath).replace(/\)/g, "%29");
}
function validateRangeText(text: string): ArtifactRange | null {
diff --git a/src/core/config.ts b/src/core/config.ts
index f14a5886..b1f497aa 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -15,10 +15,18 @@ import { atomicWriteFileSync } from "./fs-atomic.ts";
import { isFile } from "./fs-utils.ts";
import type { ConfigDiscovery } from "./types.ts";
-const SECRET_KEY_PARTS = ["key", "token", "secret", "password", "credential"] as const;
+const SECRET_KEY_PARTS = [
+ "key",
+ "token",
+ "secret",
+ "password",
+ "credential",
+] as const;
const CONFIG_VALUE_REJECTED_CHARS = ['"', "\\", "\n", "\r"] as const;
+export type LinkOutputFormat = "wikilink" | "markdown";
+
/**
* Resolve the location of the plugin config file.
*
@@ -85,9 +93,15 @@ export function discoverConfig(path?: string): ConfigDiscovery {
* dir. Rejects values containing characters that would break the simple parser
* on read-back rather than silently corrupting them.
*/
-export function setConfigValue(key: string, value: string, path?: string): string {
+export function setConfigValue(
+ key: string,
+ value: string,
+ path?: string,
+): string {
if (typeof value !== "string") {
- throw new TypeError(`config value for ${JSON.stringify(key)} must be a string`);
+ throw new TypeError(
+ `config value for ${JSON.stringify(key)} must be a string`,
+ );
}
for (const bad of CONFIG_VALUE_REJECTED_CHARS) {
if (value.includes(bad)) {
@@ -171,8 +185,17 @@ export function resolveAgentName(configPath?: string): string {
return "agent";
}
+export function resolveLinkOutputFormat(configPath?: string): LinkOutputFormat {
+ const env = process.env["OBSIDIAN_LINK_FORMAT"]?.trim();
+ const data = env ? {} : discoverConfig(configPath).data;
+ const raw = env || data["link_output_format"] || data["linkOutputFormat"];
+ return raw === "markdown" ? "markdown" : "wikilink";
+}
+
/** Replace values for keys whose name suggests a secret with `[REDACTED]`. */
-export function redactMapping<T extends Record<string, unknown>>(data: T): Record<string, unknown> {
+export function redactMapping<T extends Record<string, unknown>>(
+ data: T,
+): Record<string, unknown> {
const redacted: Record<string, unknown> = {};
for (const [key, value] of Object.entries(data)) {
const lowered = key.toLowerCase();
diff --git a/src/core/redactor.ts b/src/core/redactor.ts
index f77b4eca..c809a9bc 100644
--- a/src/core/redactor.ts
+++ b/src/core/redactor.ts
@@ -27,6 +27,8 @@
const PLACEHOLDER = "***REDACTED***";
+export const PRIVATE_REGION_PLACEHOLDER = "***PRIVATE***";
+
/**
* Maximum input size accepted by `redactRawOutput`. Receipts have no
* legitimate reason to embed multi-megabyte payloads β€” a runaway pipe
@@ -38,6 +40,9 @@ export const MAX_REDACTOR_INPUT = 256 * 1024;
const TRUNCATION_MARKER =
"\n\n[…truncated for size; original exceeded 256 KB. Inspect raw output before sharing.]\n";
+const PRIVATE_OPEN_TAG_RE = /<private\b[^>]*>/gi;
+const PRIVATE_CLOSE_TAG_RE = /<\/private>/gi;
+
/**
* Canonical list of secret-bearing field names. Each entry is the
* underscore-separated canonical form; the regex builder below makes
@@ -63,10 +68,15 @@ export const SECRET_KEYS: ReadonlyArray<string> = [
"session_token",
];
-const KEY_PATTERN = SECRET_KEYS.map((k) => k.replace(/[-_]/g, "[-_]?")).join("|");
+const KEY_PATTERN = SECRET_KEYS.map((k) => k.replace(/[-_]/g, "[-_]?")).join(
+ "|",
+);
// `key=value` (env-style): value runs to whitespace or end of line.
-const ENV_RE = new RegExp(`\\b(${KEY_PATTERN})(\\s*=\\s*)([^\\s\\r\\n]+)`, "gi");
+const ENV_RE = new RegExp(
+ `\\b(${KEY_PATTERN})(\\s*=\\s*)([^\\s\\r\\n]+)`,
+ "gi",
+);
// `key: value` outside of JSON quoting. Excludes the `"key": ...` JSON
// shape and the `Authorization: Bearer X` header (handled below).
@@ -87,11 +97,57 @@ const JSON_ENTRY_RE = new RegExp(
// and only replace the token portion.
const BEARER_RE = /\b(Bearer\s+)([A-Za-z0-9._\-+/=]+)/gi;
+export function stripPrivateRegions(text: string): string {
+ if (!text) return text;
+
+ let output = "";
+ let cursor = 0;
+ PRIVATE_OPEN_TAG_RE.lastIndex = 0;
+ PRIVATE_CLOSE_TAG_RE.lastIndex = 0;
+
+ while (cursor < text.length) {
+ PRIVATE_OPEN_TAG_RE.lastIndex = cursor;
+ const openMatch = PRIVATE_OPEN_TAG_RE.exec(text);
+ if (!openMatch) {
+ output += text.slice(cursor);
+ break;
+ }
+
+ output += text.slice(cursor, openMatch.index);
+ output += PRIVATE_REGION_PLACEHOLDER;
+
+ let depth = 1;
+ let scan = PRIVATE_OPEN_TAG_RE.lastIndex;
+ while (depth > 0) {
+ PRIVATE_OPEN_TAG_RE.lastIndex = scan;
+ PRIVATE_CLOSE_TAG_RE.lastIndex = scan;
+ const nextOpen = PRIVATE_OPEN_TAG_RE.exec(text);
+ const nextClose = PRIVATE_CLOSE_TAG_RE.exec(text);
+ if (!nextClose) return output;
+
+ if (nextOpen && nextOpen.index < nextClose.index) {
+ depth += 1;
+ scan = PRIVATE_OPEN_TAG_RE.lastIndex;
+ } else {
+ depth -= 1;
+ scan = PRIVATE_CLOSE_TAG_RE.lastIndex;
+ }
+ }
+ cursor = scan;
+ }
+
+ return output;
+}
+
export function redactRawOutput(text: string): string {
if (!text) return text;
let out =
- text.length > MAX_REDACTOR_INPUT ? text.slice(0, MAX_REDACTOR_INPUT) + TRUNCATION_MARKER : text;
+ text.length > MAX_REDACTOR_INPUT
+ ? text.slice(0, MAX_REDACTOR_INPUT) + TRUNCATION_MARKER
+ : text;
+
+ out = stripPrivateRegions(out);
// Order matters: handle JSON entries first so the COLON_VALUE_RE
// doesn't also match inside JSON pairs (the negative-lookbehind
@@ -108,18 +164,24 @@ export function redactRawOutput(text: string): string {
});
// Bearer headers BEFORE the generic colon rule.
- out = out.replace(BEARER_RE, (_match, prefix: string) => `${prefix}${PLACEHOLDER}`);
+ out = out.replace(
+ BEARER_RE,
+ (_match, prefix: string) => `${prefix}${PLACEHOLDER}`,
+ );
- out = out.replace(COLON_VALUE_RE, (match, key: string, sep: string, value: string) => {
- if (value.includes(PLACEHOLDER)) return match;
- if (value.startsWith('"') && value.endsWith('"')) {
- return `${key}${sep}"${PLACEHOLDER}"`;
- }
- if (value.startsWith("'") && value.endsWith("'")) {
- return `${key}${sep}'${PLACEHOLDER}'`;
- }
- return `${key}${sep}${PLACEHOLDER}`;
- });
+ out = out.replace(
+ COLON_VALUE_RE,
+ (match, key: string, sep: string, value: string) => {
+ if (value.includes(PLACEHOLDER)) return match;
+ if (value.startsWith('"') && value.endsWith('"')) {
+ return `${key}${sep}"${PLACEHOLDER}"`;
+ }
+ if (value.startsWith("'") && value.endsWith("'")) {
+ return `${key}${sep}'${PLACEHOLDER}'`;
+ }
+ return `${key}${sep}${PLACEHOLDER}`;
+ },
+ );
return out;
}
@@ -172,7 +234,10 @@ export interface NormaliseTextFieldOptions {
* Trim is left to the caller β€” the writer for a given field decides
* whether leading / trailing whitespace is significant.
*/
-export function normaliseTextField(value: unknown, opts: NormaliseTextFieldOptions): string {
+export function normaliseTextField(
+ value: unknown,
+ opts: NormaliseTextFieldOptions,
+): string {
if (typeof value !== "string") return "";
let s = value.replace(FORBIDDEN_C0_RE, "");
s = s.replace(UNICODE_LINE_SEP_RE, "\n");
@@ -195,7 +260,10 @@ export function normaliseTextField(value: unknown, opts: NormaliseTextFieldOptio
* writers (`writeSignal`, `appendApplyEvidence`) to keep field
* sanitisation consistent across surfaces.
*/
-export function sanitiseTextField(value: unknown, opts: NormaliseTextFieldOptions): string {
+export function sanitiseTextField(
+ value: unknown,
+ opts: NormaliseTextFieldOptions,
+): string {
if (typeof value !== "string") return "";
return normaliseTextField(redactRawOutput(value), opts);
}
diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.ts
index 5ae32dbf..a30748d6 100644
--- a/src/mcp/brain-tools.ts
+++ b/src/mcp/brain-tools.ts
@@ -19,6 +19,7 @@
* - `brain_agent_diff` β€” read-only comparison between source agents.
* - `brain_doctor` β€” invariant / schema health check.
* - `brain_backlinks` β€” read-only inbound reference lookup.
+ * - `brain_pinned_context` β€” current-task scratchpad read/write/clear.
* - `brain_context` β€” pull-bootstrap of `Brain/active.md`.
*
* The five Brain commands that remain CLI-only on purpose
@@ -39,12 +40,9 @@ import { isAbsolute, relative, resolve } from "node:path";
import { existsSync, readFileSync } from "node:fs";
-import { resolveAgentName } from "../core/config.ts";
+import { resolveAgentName, resolveLinkOutputFormat } from "../core/config.ts";
import { brainActivePath, brainDirs } from "../core/brain/paths.ts";
-import {
- regenerateActive,
- type RegenerateActiveResult,
-} from "../core/brain/active.ts";
+import { regenerateActive, type RegenerateActiveResult } from "../core/brain/active.ts";
import { parseFrontmatter } from "../core/vault.ts";
import {
appendApplyEvidence,
@@ -63,10 +61,7 @@ import { findStaleEntries } from "../core/brain/temporal/stale-watch.ts";
import { buildDailyBrief } from "../core/brain/temporal/daily-brief.ts";
import { buildWeeklySynthesis } from "../core/brain/temporal/weekly-brief.ts";
import { loadTemporalConfigSafe } from "../core/brain/policy.ts";
-import {
- isBrainLogEventKind,
- type BrainLogEventKind,
-} from "../core/brain/types.ts";
+import { isBrainLogEventKind, type BrainLogEventKind } from "../core/brain/types.ts";
import { packContext } from "../core/brain/context-pack.ts";
import { collectMaintenanceActions } from "../core/brain/maintenance/collect.ts";
import { normaliseWikilinkTarget } from "../core/brain/wikilink.ts";
@@ -82,10 +77,7 @@ import {
queryByPreference,
queryByTopic,
} from "../core/brain/query.ts";
-import {
- diffAgentSources,
- type AgentSourceDiffMode,
-} from "../core/brain/agent-source/diff.ts";
+import { diffAgentSources, type AgentSourceDiffMode } from "../core/brain/agent-source/diff.ts";
import { queryAgentSources } from "../core/brain/agent-source/query.ts";
import type { AgentSourceContributionKind } from "../core/brain/agent-source/types.ts";
import { writeSignal } from "../core/brain/signal.ts";
@@ -107,6 +99,13 @@ import {
import { appendLogEvent } from "../core/brain/log.ts";
import type { BrainLogEntry } from "../core/brain/log.ts";
import { appendBrainNote } from "../core/brain/note.ts";
+import {
+ appendPinnedContext,
+ clearPinnedContext,
+ readPinnedContext,
+ writePinnedContext,
+ type PinnedContext,
+} from "../core/brain/pinned.ts";
import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "./protocol.ts";
import type { ServerContext, ToolDefinition } from "./tools.ts";
@@ -195,9 +194,7 @@ async function toolBrainFeedback(
},
});
} catch (err) {
- process.stderr.write(
- `warning: append feedback log failed: ${(err as Error).message}\n`,
- );
+ process.stderr.write(`warning: append feedback log failed: ${(err as Error).message}\n`);
}
let prefResult: { path: string; id: string } | null = null;
@@ -271,9 +268,7 @@ async function toolBrainDream(
const dryRun = coerceBool(args, "dry_run");
const nowDate = coerceIsoDate(args, "now");
const agentArg = coerceStr(args, "agent", false);
- const agent =
- normalizeAgentArgument(agentArg) ??
- resolveAgentName(ctx.configPath ?? undefined);
+ const agent = normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);
const summary = dream(ctx.vault, {
dryRun,
@@ -313,9 +308,7 @@ async function toolBrainDream(
snapshot_path: summary.snapshot_path
? vaultRelativeSafe(ctx.vault, summary.snapshot_path)
: null,
- log_path: summary.log_path
- ? vaultRelativeSafe(ctx.vault, summary.log_path)
- : null,
+ log_path: summary.log_path ? vaultRelativeSafe(ctx.vault, summary.log_path) : null,
};
}
@@ -326,10 +319,7 @@ async function toolBrainReviewCandidates(
args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
const nowDate = coerceIsoDate(args, "now");
- const report = buildReviewCandidates(
- ctx.vault,
- nowDate ? { now: nowDate } : {},
- );
+ const report = buildReviewCandidates(ctx.vault, nowDate ? { now: nowDate } : {});
return {
would_create: [...report.would_create],
would_promote: [...report.would_promote],
@@ -381,9 +371,7 @@ async function toolBrainApplyEvidence(
const agentArg = coerceStr(args, "agent", false);
const note = coerceStr(args, "note", false);
- const agent =
- normalizeAgentArgument(agentArg) ??
- resolveAgentName(ctx.configPath ?? undefined);
+ const agent = normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);
const input: AppendApplyEvidenceInput = {
pref_id: prefId,
@@ -452,9 +440,7 @@ async function toolBrainNote(
// any other failure is an I/O / filesystem fault from `appendLogEvent`
// and must not be reported as a client-side INVALID_PARAMS.
const message = (err as Error).message ?? String(err);
- const code = message.startsWith("brain_note:")
- ? INVALID_PARAMS
- : INTERNAL_ERROR;
+ const code = message.startsWith("brain_note:") ? INVALID_PARAMS : INTERNAL_ERROR;
throw new MCPError(code, message);
}
return {
@@ -467,6 +453,64 @@ async function toolBrainNote(
// ----- brain_context (v0.10.10) --------------------------------------------
+type PinnedContextOperation = "read" | "write" | "append" | "clear";
+
+function coercePinnedContextOperation(args: Record<string, unknown>): PinnedContextOperation {
+ const operation = coerceStr(args, "operation", false) ?? "read";
+ if (
+ operation !== "read" &&
+ operation !== "write" &&
+ operation !== "append" &&
+ operation !== "clear"
+ ) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_pinned_context operation must be one of: read, write, append, clear",
+ );
+ }
+ return operation;
+}
+
+function serializePinnedContext(
+ ctx: ServerContext,
+ pinned: PinnedContext,
+ operation?: PinnedContextOperation,
+): Record<string, unknown> {
+ return {
+ ...(operation ? { operation } : {}),
+ present: pinned.present,
+ path: vaultRelativeSafe(ctx.vault, pinned.path),
+ absolute_path: pinned.path,
+ content: pinned.content,
+ };
+}
+
+async function toolBrainPinnedContext(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const operation = coercePinnedContextOperation(args);
+ let pinned: PinnedContext;
+ if (operation === "read") {
+ pinned = readPinnedContext(ctx.vault);
+ } else if (operation === "write") {
+ pinned = writePinnedContext(ctx.vault, coerceStr(args, "content", true)!);
+ } else if (operation === "append") {
+ pinned = appendPinnedContext(ctx.vault, coerceStr(args, "content", true)!);
+ } else {
+ pinned = clearPinnedContext(ctx.vault);
+ }
+ return serializePinnedContext(ctx, pinned, operation);
+}
+
+function appendPinnedToContextContent(activeContent: string, pinnedContent: string): string {
+ if (pinnedContent.length === 0) return activeContent;
+ const pinnedBlock = `## Pinned context\n\n${pinnedContent}`;
+ const trimmedActive = activeContent.trimEnd();
+ if (trimmedActive.length === 0) return `${pinnedBlock}\n`;
+ return `${trimmedActive}\n\n${pinnedBlock}\n`;
+}
+
type BrainContextCounts = RegenerateActiveResult["counts"];
const EMPTY_CONTEXT_COUNTS: BrainContextCounts = {
@@ -491,11 +535,10 @@ const EMPTY_CONTEXT_COUNTS: BrainContextCounts = {
* rewrite; the on-disk body is
* returned verbatim.
*/
-async function toolBrainContext(
- ctx: ServerContext,
-): Promise<Record<string, unknown>> {
+async function toolBrainContext(ctx: ServerContext): Promise<Record<string, unknown>> {
const dirs = brainDirs(ctx.vault);
const activePath = brainActivePath(ctx.vault);
+ const pinned = readPinnedContext(ctx.vault);
if (!existsSync(dirs.brain)) {
return {
vault_path: ctx.vault,
@@ -504,6 +547,7 @@ async function toolBrainContext(
content: "",
counts: EMPTY_CONTEXT_COUNTS,
generated_at: null,
+ pinned: serializePinnedContext(ctx, pinned),
};
}
@@ -536,6 +580,7 @@ async function toolBrainContext(
generatedAt = null;
}
}
+ content = appendPinnedToContextContent(content, pinned.content);
// Optional vault-root instruction file (v0.10.17). Absent file =
// field omitted so hosts that strip unknown fields stay
@@ -555,6 +600,7 @@ async function toolBrainContext(
content,
counts,
generated_at: generatedAt,
+ pinned: serializePinnedContext(ctx, pinned),
...(error ? { error } : {}),
...(vaultInstruction
? {
@@ -582,6 +628,7 @@ async function toolBrainDigest(
...(since ? { since } : {}),
...(until ? { until } : {}),
format,
+ linkOutputFormat: resolveLinkOutputFormat(ctx.configPath ?? undefined),
});
return {
@@ -762,8 +809,7 @@ async function toolBrainDoctor(
// Decide a single ok flag β€” `strict` only changes the CLI exit code,
// so we mirror that semantic here: with `strict`, warnings demote ok
// to false. Errors always do.
- const ok =
- result.errors.length === 0 && (!strict || result.warnings.length === 0);
+ const ok = result.errors.length === 0 && (!strict || result.warnings.length === 0);
return {
format,
@@ -773,17 +819,13 @@ async function toolBrainDoctor(
severity: i.severity,
code: i.code,
message: i.message,
- ...(i.path !== undefined
- ? { path: vaultRelativeSafe(ctx.vault, i.path) }
- : {}),
+ ...(i.path !== undefined ? { path: vaultRelativeSafe(ctx.vault, i.path) } : {}),
})),
warnings: result.warnings.map((i) => ({
severity: i.severity,
code: i.code,
message: i.message,
- ...(i.path !== undefined
- ? { path: vaultRelativeSafe(ctx.vault, i.path) }
- : {}),
+ ...(i.path !== undefined ? { path: vaultRelativeSafe(ctx.vault, i.path) } : {}),
})),
// v0.10.15: ranked maintenance actions surfaced as a parallel
// signal to errors/warnings. The list is independent of `strict`
@@ -802,16 +844,12 @@ async function toolBrainDoctor(
// surface, so it stays absent here). `instruction_file_warnings`
// surfaces vault-root instruction files exceeding the configured
// ceiling.
- ...(result.trust_verdict !== undefined
- ? { trust_verdict: result.trust_verdict }
- : {}),
- instruction_file_warnings: (result.instruction_file_warnings ?? []).map(
- (w) => ({
- path: w.path,
- lines: w.lines,
- ceiling: w.ceiling,
- }),
- ),
+ ...(result.trust_verdict !== undefined ? { trust_verdict: result.trust_verdict } : {}),
+ instruction_file_warnings: (result.instruction_file_warnings ?? []).map((w) => ({
+ path: w.path,
+ lines: w.lines,
+ ceiling: w.ceiling,
+ })),
};
}
@@ -865,9 +903,7 @@ function serializeSignal(s: BrainSignal): Record<string, unknown> {
};
}
-function serializePreference(
- p: BrainPreference | BrainRetired,
-): Record<string, unknown> {
+function serializePreference(p: BrainPreference | BrainRetired): Record<string, unknown> {
if (p.kind === "brain-retired") {
return {
kind: p.kind,
@@ -876,9 +912,7 @@ function serializePreference(
retired_at: p.retired_at,
retired_reason: p.retired_reason,
retired_by: p.retired_by,
- ...(p.superseded_by !== undefined
- ? { superseded_by: p.superseded_by }
- : {}),
+ ...(p.superseded_by !== undefined ? { superseded_by: p.superseded_by } : {}),
created_at: p.created_at,
topic: p.topic,
...(p.scope !== undefined ? { scope: p.scope } : {}),
@@ -964,6 +998,51 @@ export function vaultRelativeSafe(vault: string, target: string): string {
// ----- Tool registration ---------------------------------------------------
+const PINNED_CONTEXT_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {
+ type: "object",
+ required: ["present", "path", "absolute_path", "content"],
+ properties: {
+ operation: { type: "string", enum: ["read", "write", "append", "clear"] },
+ present: { type: "boolean" },
+ path: { type: "string" },
+ absolute_path: { type: "string" },
+ content: { type: "string" },
+ },
+ additionalProperties: false,
+};
+
+const BRAIN_CONTEXT_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {
+ type: "object",
+ required: ["vault_path", "present", "active_path", "content", "counts", "generated_at", "pinned"],
+ properties: {
+ vault_path: { type: "string" },
+ present: { type: "boolean" },
+ active_path: { type: "string" },
+ content: { type: "string" },
+ counts: {
+ type: "object",
+ required: ["confirmed", "quarantine", "retired_recent", "most_applied_30d"],
+ properties: {
+ confirmed: { type: "integer" },
+ quarantine: { type: "integer" },
+ retired_recent: { type: "integer" },
+ most_applied_30d: { type: "integer" },
+ },
+ additionalProperties: false,
+ },
+ generated_at: {},
+ pinned: PINNED_CONTEXT_OUTPUT_SCHEMA,
+ },
+};
+
+const BRAIN_QUERY_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {
+ type: "object",
+ required: ["mode"],
+ properties: {
+ mode: { type: "string", enum: ["preference", "topic", "since"] },
+ },
+};
+
// ----- brain_operator_summary (v0.10.16) -----------------------------------
/**
@@ -1014,10 +1093,7 @@ async function toolBrainOperatorSummary(
} else if (typeof includeDreamRaw === "boolean") {
includeDream = includeDreamRaw;
} else {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_operator_summary: include_dream must be a boolean",
- );
+ throw new MCPError(INVALID_PARAMS, "brain_operator_summary: include_dream must be a boolean");
}
let dreamSummary;
@@ -1069,10 +1145,7 @@ async function toolBrainUnlinkedMentions(
): Promise<Record<string, unknown>> {
const idRaw = args["id"];
if (typeof idRaw !== "string" || idRaw.trim().length === 0) {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_unlinked_mentions: id must be a non-empty string",
- );
+ throw new MCPError(INVALID_PARAMS, "brain_unlinked_mentions: id must be a non-empty string");
}
const targetId = normaliseWikilinkTarget(idRaw);
// Limit coercion mirrors the v0.10.16 `brain_operator_summary`
@@ -1113,11 +1186,7 @@ async function toolBrainUnlinkedMentions(
);
}
}
- const mentions = findUnlinkedMentions(
- ctx.vault,
- targetId,
- limit !== undefined ? { limit } : {},
- );
+ const mentions = findUnlinkedMentions(ctx.vault, targetId, limit !== undefined ? { limit } : {});
return {
vault_path: ctx.vault,
target_id: targetId,
@@ -1142,10 +1211,7 @@ async function toolBrainConceptSynthesis(
): Promise<Record<string, unknown>> {
const idRaw = args["id"];
if (typeof idRaw !== "string" || idRaw.trim().length === 0) {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_concept_synthesis: id must be a non-empty string",
- );
+ throw new MCPError(INVALID_PARAMS, "brain_concept_synthesis: id must be a non-empty string");
}
const includeUnlinkedRaw = args["include_unlinked"];
let includeUnlinked = false;
@@ -1186,10 +1252,7 @@ async function toolBrainMocAudit(
): Promise<Record<string, unknown>> {
const idRaw = args["id"];
if (typeof idRaw !== "string" || idRaw.trim().length === 0) {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_moc_audit: id must be a non-empty string",
- );
+ throw new MCPError(INVALID_PARAMS, "brain_moc_audit: id must be a non-empty string");
}
const targetId = normaliseWikilinkTarget(idRaw);
try {
@@ -1213,42 +1276,26 @@ async function toolBrainMocAudit(
// ----- Temporal subsystem MCP wrappers (v0.10.18) --------------------------
-function coercePositiveInteger(
- tool: string,
- field: string,
- raw: unknown,
-): number | undefined {
+function coercePositiveInteger(tool: string, field: string, raw: unknown): number | undefined {
if (raw === undefined || raw === null) return undefined;
if (typeof raw === "number") {
if (!Number.isInteger(raw) || raw < 1) {
- throw new MCPError(
- INVALID_PARAMS,
- `${tool}: ${field} must be a positive integer`,
- );
+ throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a positive integer`);
}
return raw;
}
if (typeof raw === "string") {
const trimmed = raw.trim();
if (trimmed === "" || !/^[0-9]+$/.test(trimmed)) {
- throw new MCPError(
- INVALID_PARAMS,
- `${tool}: ${field} must be a positive integer`,
- );
+ throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a positive integer`);
}
const parsed = Number.parseInt(trimmed, 10);
if (parsed < 1) {
- throw new MCPError(
- INVALID_PARAMS,
- `${tool}: ${field} must be a positive integer`,
- );
+ throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a positive integer`);
}
return parsed;
}
- throw new MCPError(
- INVALID_PARAMS,
- `${tool}: ${field} must be a positive integer`,
- );
+ throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a positive integer`);
}
const ISO_DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
@@ -1284,19 +1331,13 @@ function coerceIsoTimestampOrDate(
return v;
}
-function coerceEventKind(
- tool: string,
- raw: unknown,
-): BrainLogEventKind | undefined {
+function coerceEventKind(tool: string, raw: unknown): BrainLogEventKind | undefined {
if (raw === undefined || raw === null) return undefined;
if (typeof raw !== "string") {
throw new MCPError(INVALID_PARAMS, `${tool}: kind must be a string`);
}
if (!isBrainLogEventKind(raw)) {
- throw new MCPError(
- INVALID_PARAMS,
- `${tool}: kind must be a known BrainLogEventKind`,
- );
+ throw new MCPError(INVALID_PARAMS, `${tool}: kind must be a known BrainLogEventKind`);
}
return raw;
}
@@ -1310,20 +1351,11 @@ async function toolBrainTimeline(
ctx: ServerContext,
args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
- const prefId =
- typeof args["pref_id"] === "string" ? args["pref_id"] : undefined;
+ const prefId = typeof args["pref_id"] === "string" ? args["pref_id"] : undefined;
const topic = typeof args["topic"] === "string" ? args["topic"] : undefined;
const kind = coerceEventKind("brain_timeline", args["kind"]);
- const since = coerceIsoTimestampOrDate(
- "brain_timeline",
- "since",
- args["since"],
- );
- const until = coerceIsoTimestampOrDate(
- "brain_timeline",
- "until",
- args["until"],
- );
+ const since = coerceIsoTimestampOrDate("brain_timeline", "since", args["since"]);
+ const until = coerceIsoTimestampOrDate("brain_timeline", "until", args["until"]);
const limit = coercePositiveInteger("brain_timeline", "limit", args["limit"]);
const index = buildTimelineIndex(ctx.vault, {
@@ -1422,12 +1454,7 @@ async function toolBrainDailyBrief(
args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
const dateRaw = args["date"];
- const dateCoerced = coerceIsoTimestampOrDate(
- "brain_daily_brief",
- "date",
- dateRaw,
- "date-only",
- );
+ const dateCoerced = coerceIsoTimestampOrDate("brain_daily_brief", "date", dateRaw, "date-only");
const date = dateCoerced ?? new Date().toISOString().slice(0, 10);
const cfg = loadTemporalConfigSafe(ctx.vault);
const index = buildTimelineIndex(ctx.vault, {});
@@ -1490,18 +1517,11 @@ async function toolBrainContextPack(
args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
const maxRaw = args["max_tokens"];
- const maxTokens =
- typeof maxRaw === "number"
- ? maxRaw
- : Number.parseInt(String(maxRaw ?? ""), 10);
+ const maxTokens = typeof maxRaw === "number" ? maxRaw : Number.parseInt(String(maxRaw ?? ""), 10);
if (!Number.isFinite(maxTokens) || maxTokens <= 0) {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_context_pack: max_tokens must be a positive integer",
- );
+ throw new MCPError(INVALID_PARAMS, "brain_context_pack: max_tokens must be a positive integer");
}
- const query =
- typeof args["query"] === "string" ? (args["query"] as string) : undefined;
+ const query = typeof args["query"] === "string" ? (args["query"] as string) : undefined;
const report = packContext(ctx.vault, {
maxTokens,
...(query ? { query } : {}),
@@ -1535,8 +1555,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
properties: {
topic: {
type: "string",
- description:
- "Stable kebab-slug for the rule, e.g. `no-internal-abbrev`.",
+ description: "Stable kebab-slug for the rule, e.g. `no-internal-abbrev`.",
},
signal: {
type: "string",
@@ -1546,8 +1565,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
principle: {
type: "string",
- description:
- "One-line, agent-readable formulation of the rule (imperative voice).",
+ description: "One-line, agent-readable formulation of the rule (imperative voice).",
},
scope: {
type: "string",
@@ -1557,18 +1575,15 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
source: {
type: "array",
items: { type: "string" },
- description:
- "Optional wikilinks to the artifacts or notes that triggered the signal.",
+ description: "Optional wikilinks to the artifacts or notes that triggered the signal.",
},
agent: {
type: "string",
- description:
- "Optional agent identity override; defaults to the server-resolved name.",
+ description: "Optional agent identity override; defaults to the server-resolved name.",
},
raw: {
type: "string",
- description:
- "Optional free-form raw quote (rendered under `## Raw` in the signal file).",
+ description: "Optional free-form raw quote (rendered under `## Raw` in the signal file).",
},
force_confirmed: {
type: "boolean",
@@ -1648,8 +1663,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
agent: {
type: "string",
- description:
- "Optional agent identity override; defaults to the server-resolved name.",
+ description: "Optional agent identity override; defaults to the server-resolved name.",
},
note: {
type: "string",
@@ -1675,8 +1689,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
agent: {
type: "string",
- description:
- "Optional agent identity override; defaults to the server-resolved name.",
+ description: "Optional agent identity override; defaults to the server-resolved name.",
},
},
required: ["text"],
@@ -1684,15 +1697,38 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
handler: toolBrainNote,
},
+ {
+ name: "brain_pinned_context",
+ description:
+ "Read, write, append, or clear the transient current-task scratchpad at `Brain/pinned.md`. Use for facts that should survive context rotation but should not become permanent preferences.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["read", "write", "append", "clear"],
+ description: "Operation to perform. Defaults to read.",
+ },
+ content: {
+ type: "string",
+ description: "Pinned context body for write/append operations.",
+ },
+ },
+ additionalProperties: false,
+ },
+ outputSchema: PINNED_CONTEXT_OUTPUT_SCHEMA,
+ handler: toolBrainPinnedContext,
+ },
{
name: "brain_context",
description:
- "Pull the current Brain/active.md body plus active-preference counts. Use at session start when SessionStart hook is unavailable (Cursor, Aider, raw Claude API). Read-only.",
+ "Pull the current Brain/active.md body, pinned current-task context, and active-preference counts. Use at session start when SessionStart hook is unavailable (Cursor, Aider, raw Claude API). Read-only.",
inputSchema: {
type: "object",
properties: {},
additionalProperties: false,
},
+ outputSchema: BRAIN_CONTEXT_OUTPUT_SCHEMA,
handler: toolBrainContext,
},
{
@@ -1704,8 +1740,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
properties: {
since: {
type: "string",
- description:
- "Inclusive lower bound (ISO-8601). Defaults to `until - 24h`.",
+ description: "Inclusive lower bound (ISO-8601). Defaults to `until - 24h`.",
},
until: {
type: "string",
@@ -1735,13 +1770,11 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
topic: {
type: "string",
- description:
- "Topic slug to aggregate signals + active/retired preference + log events.",
+ description: "Topic slug to aggregate signals + active/retired preference + log events.",
},
since: {
type: "string",
- description:
- "ISO-8601 timestamp; returns every Brain log event with timestamp >= since.",
+ description: "ISO-8601 timestamp; returns every Brain log event with timestamp >= since.",
},
format: {
type: "string",
@@ -1752,6 +1785,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
additionalProperties: false,
},
+ outputSchema: BRAIN_QUERY_OUTPUT_SCHEMA,
handler: toolBrainQuery,
},
{
@@ -1764,8 +1798,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
agents: {
type: "array",
items: { type: "string" },
- description:
- "Agent ids to query. Omit or pass [] to query all known agents.",
+ description: "Agent ids to query. Omit or pass [] to query all known agents.",
},
topic: {
type: "string",
@@ -1808,8 +1841,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
agents: {
type: "array",
items: { type: "string" },
- description:
- "Agent ids to compare. Omit or pass [] to compare all known agents.",
+ description: "Agent ids to compare. Omit or pass [] to compare all known agents.",
},
topic: {
type: "string",
@@ -1829,8 +1861,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
type: "integer",
minimum: 1,
maximum: 500,
- description:
- "Maximum contributions returned before comparison. Defaults to 50.",
+ description: "Maximum contributions returned before comparison. Defaults to 50.",
},
},
additionalProperties: false,
@@ -1846,8 +1877,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
properties: {
strict: {
type: "boolean",
- description:
- "When true, warnings demote `ok` to false (CLI exit-code parity).",
+ description: "When true, warnings demote `ok` to false (CLI exit-code parity).",
},
format: {
type: "string",
@@ -1906,13 +1936,11 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
max_tokens: {
type: "integer",
minimum: 1,
- description:
- "Strict upper bound on the returned slice's token count.",
+ description: "Strict upper bound on the returned slice's token count.",
},
query: {
type: "string",
- description:
- "Optional case/Unicode-insensitive substring filter on topic + principle.",
+ description: "Optional case/Unicode-insensitive substring filter on topic + principle.",
},
},
required: ["max_tokens"],
@@ -1953,8 +1981,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
properties: {
id: {
type: "string",
- description:
- "Target id (e.g. `pref-foo`). Wikilink decoration is stripped if present.",
+ description: "Target id (e.g. `pref-foo`). Wikilink decoration is stripped if present.",
},
include_unlinked: {
type: "boolean",
@@ -1976,8 +2003,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
properties: {
id: {
type: "string",
- description:
- "Hub note id (e.g. `pref-foo`). Wikilink decoration is stripped if present.",
+ description: "Hub note id (e.g. `pref-foo`). Wikilink decoration is stripped if present.",
},
},
required: ["id"],
@@ -1994,8 +2020,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
properties: {
pref_id: {
type: "string",
- description:
- "Restrict to events for this preference / retired / signal id.",
+ description: "Restrict to events for this preference / retired / signal id.",
},
topic: {
type: "string",
@@ -2003,24 +2028,20 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
kind: {
type: "string",
- description:
- "Restrict to events of this BrainLogEventKind (e.g. `apply-evidence`).",
+ description: "Restrict to events of this BrainLogEventKind (e.g. `apply-evidence`).",
},
since: {
type: "string",
- description:
- "Inclusive lower bound (ISO date or ISO timestamp). Defaults to epoch.",
+ description: "Inclusive lower bound (ISO date or ISO timestamp). Defaults to epoch.",
},
until: {
type: "string",
- description:
- "Exclusive upper bound (ISO date or ISO timestamp). Defaults to now.",
+ description: "Exclusive upper bound (ISO date or ISO timestamp). Defaults to now.",
},
limit: {
type: "integer",
minimum: 1,
- description:
- "Maximum number of events to return after filtering. Omit for no cap.",
+ description: "Maximum number of events to return after filtering. Omit for no cap.",
},
},
additionalProperties: false,
@@ -2036,8 +2057,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
properties: {
pref_id: {
type: "string",
- description:
- "Target preference id (e.g. `pref-foo`). Mutually exclusive with `topic`.",
+ description: "Target preference id (e.g. `pref-foo`). Mutually exclusive with `topic`.",
},
topic: {
type: "string",
@@ -2069,8 +2089,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
properties: {
date: {
type: "string",
- description:
- "ISO date (`YYYY-MM-DD`) the brief targets. Defaults to today UTC.",
+ description: "ISO date (`YYYY-MM-DD`) the brief targets. Defaults to today UTC.",
},
},
additionalProperties: false,
@@ -2109,8 +2128,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
top_actions: {
type: "integer",
minimum: 0,
- description:
- "Cap on the ranked maintenance action list. Defaults to 5.",
+ description: "Cap on the ranked maintenance action list. Defaults to 5.",
},
},
additionalProperties: false,
diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.ts
index 9ea6fac9..7c2c4f2e 100644
--- a/src/mcp/instructions.ts
+++ b/src/mcp/instructions.ts
@@ -2,8 +2,8 @@
* Server-supplied instructions returned in `initialize.instructions`.
*
* The Brain observing-memory layer is the canonical writable surface:
- * three writer tools (`brain_feedback`, `brain_apply_evidence`,
- * `brain_note`) plus the read-only `brain_context` reader live on the
+ * four writer tools (`brain_feedback`, `brain_apply_evidence`,
+ * `brain_note`, `brain_pinned_context`) plus the read-only `brain_context` reader live on the
* always-loaded writer scope; the remaining `brain_*` surface ships on
* the deferred full server.
*/
@@ -22,7 +22,7 @@ export interface BuildInstructionsOpts {
const WRITER_INSTRUCTIONS = `Open Second Brain β€” always-loaded MCP surface.
-Four tools live here (three writers + one reader; the server's name is
+Five tools live here (four writers + one reader; the server's name is
preserved for backward compatibility with existing client configs):
- brain_feedback β€” record one new taste signal the user just expressed.
- brain_apply_evidence β€” record applied | violated | outdated against an
@@ -30,8 +30,12 @@ preserved for backward compatibility with existing client configs):
- brain_note β€” record one narrative milestone (release shipped,
PR merged, fact discovered) that fits neither
category.
+ - brain_pinned_context β€” read/write/append/clear Brain/pinned.md for
+ current-task facts that should survive context
+ rotation without becoming permanent preferences.
- brain_context β€” pull the current Brain/active.md body plus
- active-preference counts. Read-only. Use at session
+ pinned context and active-preference counts.
+ Read-only. Use at session
start when the host runtime lacks a SessionStart
hook (Cursor, Aider, raw Claude API). Runtimes that
already inject active.md via a hook can skip this.
@@ -42,7 +46,7 @@ and the scheduled learning pass) lives on the sibling
"open-second-brain" MCP server (deferred). Use ToolSearch to reach it.
Prefer the writer-server copies of brain_feedback / brain_apply_evidence /
-brain_note over any duplicate exposed by the full server β€” both call the same
+brain_note / brain_pinned_context over any duplicate exposed by the full server β€” both call the same
handler, but the writer copy is always available without ToolSearch.`;
export function buildInstructions(opts: BuildInstructionsOpts | string): string {
@@ -75,6 +79,13 @@ export function buildInstructions(opts: BuildInstructionsOpts | string): string
"`note` in `Brain/log/<today>.md` (and the JSONL sidecar). " +
"This is the Brain-native replacement for the retired " +
"`event_log_append` tool.\n" +
+ " - brain_pinned_context β€” read/write/append/clear " +
+ "`Brain/pinned.md` for current-task facts that should survive " +
+ "context rotation without becoming permanent preferences.\n" +
+ " - brain_context β€” read-only session bootstrap that returns " +
+ "`Brain/active.md`, pinned current-task context, and active " +
+ "preference counts. Use it at session start when the host runtime " +
+ "does not inject active.md via a hook.\n" +
" - brain_dream β€” runs the deterministic learning pass " +
"(clusters signals, promotes preferences, retires stale rules). " +
"Usually scheduled via cron, not invoked interactively.\n" +
diff --git a/src/mcp/output-contract.ts b/src/mcp/output-contract.ts
new file mode 100644
index 00000000..40875729
--- /dev/null
+++ b/src/mcp/output-contract.ts
@@ -0,0 +1,125 @@
+export type OutputSchemaType =
+ | "object"
+ | "array"
+ | "string"
+ | "number"
+ | "integer"
+ | "boolean"
+ | "null";
+
+export interface OutputSchema {
+ readonly type?: OutputSchemaType;
+ readonly required?: ReadonlyArray<string>;
+ readonly properties?: Readonly<Record<string, OutputSchema>>;
+ readonly items?: OutputSchema;
+ readonly enum?: ReadonlyArray<unknown>;
+ readonly additionalProperties?: boolean | OutputSchema;
+}
+
+export function validateOutputContract(
+ schema: OutputSchema,
+ value: unknown,
+ path = "$",
+): string[] {
+ const errors: string[] = [];
+
+ if (
+ schema.enum &&
+ !schema.enum.some((expected) => Object.is(expected, value))
+ ) {
+ errors.push(
+ `${path}: expected one of ${schema.enum.map(String).join(", ")}`,
+ );
+ return errors;
+ }
+
+ if (schema.type && !matchesType(value, schema.type)) {
+ errors.push(`${path}: expected ${schema.type}`);
+ return errors;
+ }
+
+ if (schema.type === "object" || schema.properties || schema.required) {
+ if (!isRecord(value)) {
+ if (!schema.type) errors.push(`${path}: expected object`);
+ return errors;
+ }
+
+ for (const requiredKey of schema.required ?? []) {
+ if (!hasOwn(value, requiredKey)) {
+ errors.push(`${path}: missing required property '${requiredKey}'`);
+ }
+ }
+
+ const properties = schema.properties ?? {};
+ for (const [key, childSchema] of Object.entries(properties)) {
+ if (hasOwn(value, key)) {
+ errors.push(
+ ...validateOutputContract(childSchema, value[key], `${path}.${key}`),
+ );
+ }
+ }
+
+ const additional = schema.additionalProperties;
+ if (additional === false) {
+ for (const key of Object.keys(value)) {
+ if (!hasOwn(properties, key))
+ errors.push(`${path}: unexpected property '${key}'`);
+ }
+ } else if (typeof additional === "object") {
+ for (const [key, childValue] of Object.entries(value)) {
+ if (!hasOwn(properties, key)) {
+ errors.push(
+ ...validateOutputContract(additional, childValue, `${path}.${key}`),
+ );
+ }
+ }
+ }
+ }
+
+ if (schema.type === "array" || schema.items) {
+ if (!Array.isArray(value)) {
+ if (!schema.type) errors.push(`${path}: expected array`);
+ return errors;
+ }
+ if (schema.items) {
+ value.forEach((item, index) => {
+ errors.push(
+ ...validateOutputContract(schema.items!, item, `${path}[${index}]`),
+ );
+ });
+ }
+ }
+
+ return errors;
+}
+
+export function assertOutputContract(
+ toolName: string,
+ schema: OutputSchema | undefined,
+ value: unknown,
+): void {
+ if (!schema) return;
+ const errors = validateOutputContract(schema, value);
+ if (errors.length > 0) {
+ throw new Error(`${toolName} output contract failed: ${errors.join("; ")}`);
+ }
+}
+
+function matchesType(value: unknown, type: OutputSchemaType): boolean {
+ if (type === "null") return value === null;
+ if (type === "array") return Array.isArray(value);
+ if (type === "object") return isRecord(value);
+ if (type === "integer")
+ return typeof value === "number" && Number.isInteger(value);
+ if (type === "number")
+ return typeof value === "number" && Number.isFinite(value);
+ return typeof value === type;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function hasOwn(value: object, key: string): boolean {
+ return Object.prototype.hasOwnProperty.call(value, key);
+}
diff --git a/src/mcp/search-tools.ts b/src/mcp/search-tools.ts
index cd23cd5c..7899984f 100644
--- a/src/mcp/search-tools.ts
+++ b/src/mcp/search-tools.ts
@@ -43,6 +43,41 @@ const SEARCH_INPUT_SCHEMA: Record<string, unknown> = {
additionalProperties: false,
};
+const SEARCH_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {
+ type: "object",
+ required: ["results", "warnings", "total"],
+ properties: {
+ results: {
+ type: "array",
+ items: {
+ type: "object",
+ required: [
+ "path",
+ "title",
+ "content",
+ "score",
+ "startLine",
+ "endLine",
+ "searchType",
+ "reasons",
+ ],
+ properties: {
+ path: { type: "string" },
+ title: { type: "string" },
+ content: { type: "string" },
+ score: { type: "number" },
+ startLine: { type: "integer" },
+ endLine: { type: "integer" },
+ searchType: { type: "string" },
+ reasons: { type: "array", items: { type: "string" } },
+ },
+ },
+ },
+ warnings: { type: "array", items: { type: "string" } },
+ total: { type: "integer" },
+ },
+};
+
function searchTimeoutError(ms: number): MCPError {
return new MCPError(INTERNAL_ERROR, `search timeout after ${ms}ms`);
}
@@ -187,6 +222,7 @@ export const SEARCH_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
description:
"Full-text search across the vault. Optional semantic layer when configured. Read-only.",
inputSchema: SEARCH_INPUT_SCHEMA,
+ outputSchema: SEARCH_OUTPUT_SCHEMA,
handler: toolBrainSearch,
},
]);
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 6fd44400..d83776b9 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -25,6 +25,7 @@ import {
type ToolDefinition,
type ToolScope,
} from "./tools.ts";
+import { assertOutputContract } from "./output-contract.ts";
export interface MCPServerOptions {
readonly vault: string;
@@ -75,7 +76,7 @@ export class MCPServer {
/** Public method for CLI tool-call bridge β€” the legacy code reached into `_tools`. */
async callTool(name: string, args: Record<string, unknown>): Promise<Record<string, unknown>> {
const tool = findTool(this.tools, name);
- return toolResult(await tool.handler(this.context, args));
+ return toolResult(tool, await tool.handler(this.context, args));
}
/** Process one JSON-RPC request or notification. Returns null for notifications. */
@@ -166,6 +167,7 @@ export class MCPServer {
name: t.name,
description: t.description,
inputSchema: t.inputSchema,
+ ...(t.outputSchema ? { outputSchema: t.outputSchema } : {}),
})),
};
}
@@ -200,7 +202,7 @@ export class MCPServer {
const args = argsRaw as Record<string, unknown>;
try {
const structured = await tool.handler(this.context, args);
- return toolResult(structured);
+ return toolResult(tool, structured);
} catch (exc) {
if (exc instanceof MCPError) throw exc;
const message = (exc as Error).message ?? String(exc);
@@ -212,7 +214,8 @@ export class MCPServer {
}
}
-function toolResult(structured: unknown): Record<string, unknown> {
+function toolResult(tool: ToolDefinition, structured: unknown): Record<string, unknown> {
+ assertOutputContract(tool.name, tool.outputSchema, structured);
const text = JSON.stringify(structured, sortedReplacer, 2);
return {
content: [{ type: "text", text }],
diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts
index ec8f700e..09f736a4 100644
--- a/src/mcp/tools.ts
+++ b/src/mcp/tools.ts
@@ -32,6 +32,7 @@ import { vaultRelative } from "../core/path-safety.ts";
import { listVaultPages } from "../core/vault.ts";
import { INVALID_PARAMS, METHOD_NOT_FOUND, MCPError } from "./protocol.ts";
import { coerceStr, coerceInt } from "./coerce.ts";
+import type { OutputSchema } from "./output-contract.ts";
export interface ServerContext {
readonly vault: string;
@@ -43,6 +44,7 @@ export interface ToolDefinition {
readonly name: string;
readonly description: string;
readonly inputSchema: Record<string, unknown>;
+ readonly outputSchema?: OutputSchema;
readonly handler: (
ctx: ServerContext,
args: Record<string, unknown>,
@@ -187,6 +189,7 @@ const WRITER_TOOL_NAMES: ReadonlySet<string> = new Set([
"brain_context",
"brain_feedback",
"brain_note",
+ "brain_pinned_context",
]);
export function buildToolTable(scope: ToolScope = "full"): ToolDefinition[] {
diff --git a/tests/cli/mcp-scope-arg.test.ts b/tests/cli/mcp-scope-arg.test.ts
index c4582beb..3271cdd6 100644
--- a/tests/cli/mcp-scope-arg.test.ts
+++ b/tests/cli/mcp-scope-arg.test.ts
@@ -56,6 +56,7 @@ describe("o2b mcp --scope arg validation", () => {
"brain_context",
"brain_feedback",
"brain_note",
+ "brain_pinned_context",
]);
});
});
diff --git a/tests/cli/mcp-writer-probe.test.ts b/tests/cli/mcp-writer-probe.test.ts
index 4e038a5e..c14fe24b 100644
--- a/tests/cli/mcp-writer-probe.test.ts
+++ b/tests/cli/mcp-writer-probe.test.ts
@@ -38,6 +38,7 @@ describe("o2b mcp --writer-only alias", () => {
"brain_context",
"brain_feedback",
"brain_note",
+ "brain_pinned_context",
]);
} finally {
if (tmp) rmSync(tmp, { recursive: true, force: true });
diff --git a/tests/core/brain.pinned.test.ts b/tests/core/brain.pinned.test.ts
new file mode 100644
index 00000000..148bec3c
--- /dev/null
+++ b/tests/core/brain.pinned.test.ts
@@ -0,0 +1,65 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { brainPinnedPath } from "../../src/core/brain/paths.ts";
+import {
+ appendPinnedContext,
+ clearPinnedContext,
+ readPinnedContext,
+ writePinnedContext,
+} from "../../src/core/brain/pinned.ts";
+import { PRIVATE_REGION_PLACEHOLDER } from "../../src/core/redactor.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-pinned-"));
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("pinned context paths", () => {
+ test("uses Brain/pinned.md under the vault", () => {
+ expect(brainPinnedPath(vault)).toBe(join(vault, "Brain", "pinned.md"));
+ });
+});
+
+describe("pinned context core", () => {
+ test("reads missing pinned context as empty", () => {
+ const pinned = readPinnedContext(vault);
+ expect(pinned.present).toBe(false);
+ expect(pinned.content).toBe("");
+ expect(pinned.path).toBe(brainPinnedPath(vault));
+ });
+
+ test("writes sanitised content atomically", () => {
+ const pinned = writePinnedContext(
+ vault,
+ "Remember api_key=abc\n<private>do not store this</private>",
+ );
+ expect(pinned.present).toBe(true);
+ expect(pinned.content).toContain("api_key=***REDACTED***");
+ expect(pinned.content).toContain(PRIVATE_REGION_PLACEHOLDER);
+ expect(pinned.content).not.toContain("do not store this");
+ expect(readFileSync(brainPinnedPath(vault), "utf8")).toBe(`${pinned.content}\n`);
+ });
+
+ test("appends content with a blank-line separator", () => {
+ writePinnedContext(vault, "First fact");
+ const pinned = appendPinnedContext(vault, "Second fact");
+ expect(pinned.content).toBe("First fact\n\nSecond fact");
+ });
+
+ test("clear leaves an empty pinned file", () => {
+ writePinnedContext(vault, "Temporary fact");
+ const pinned = clearPinnedContext(vault);
+ expect(pinned.present).toBe(true);
+ expect(pinned.content).toBe("");
+ expect(existsSync(brainPinnedPath(vault))).toBe(true);
+ expect(readFileSync(brainPinnedPath(vault), "utf8")).toBe("");
+ });
+});
diff --git a/tests/core/brain.wikilink.test.ts b/tests/core/brain.wikilink.test.ts
index f5e766c6..248929a8 100644
Binary files a/tests/core/brain.wikilink.test.ts and b/tests/core/brain.wikilink.test.ts differ
diff --git a/tests/core/config.test.ts b/tests/core/config.test.ts
index 2fd7b190..5139feaf 100644
--- a/tests/core/config.test.ts
+++ b/tests/core/config.test.ts
@@ -9,6 +9,7 @@ import {
parseSimpleYaml,
redactMapping,
resolveAgentName,
+ resolveLinkOutputFormat,
resolveTimezone,
resolveVault,
setConfigValue,
@@ -26,6 +27,7 @@ beforeEach(() => {
"VAULT_DIR",
"VAULT_AGENT_NAME",
"VAULT_TIMEZONE",
+ "OBSIDIAN_LINK_FORMAT",
]) {
savedEnv[k] = process.env[k];
delete process.env[k];
@@ -49,13 +51,17 @@ describe("defaultConfigPath", () => {
test("uses XDG_CONFIG_HOME when set without override", () => {
process.env["XDG_CONFIG_HOME"] = tmp;
- expect(defaultConfigPath()).toBe(join(tmp, "open-second-brain", "config.yaml"));
+ expect(defaultConfigPath()).toBe(
+ join(tmp, "open-second-brain", "config.yaml"),
+ );
});
});
describe("parseSimpleYaml", () => {
test("parses key: value lines", () => {
- const data = parseSimpleYaml("instance_name: Test Brain\nruntime: hermes\n");
+ const data = parseSimpleYaml(
+ "instance_name: Test Brain\nruntime: hermes\n",
+ );
expect(data["instance_name"]).toBe("Test Brain");
expect(data["runtime"]).toBe("hermes");
});
@@ -128,8 +134,12 @@ describe("setConfigValue", () => {
test("rejects values with disallowed characters", () => {
const p = join(tmp, "config.yaml");
- expect(() => setConfigValue("vault", 'evil"value', p)).toThrow(/disallowed character/);
- expect(() => setConfigValue("vault", "with\nnewline", p)).toThrow(/disallowed character/);
+ expect(() => setConfigValue("vault", 'evil"value', p)).toThrow(
+ /disallowed character/,
+ );
+ expect(() => setConfigValue("vault", "with\nnewline", p)).toThrow(
+ /disallowed character/,
+ );
});
});
@@ -199,6 +209,38 @@ describe("resolveAgentName", () => {
});
});
+describe("resolveLinkOutputFormat", () => {
+ test("defaults to wikilink", () => {
+ expect(resolveLinkOutputFormat(join(tmp, "missing.yaml"))).toBe("wikilink");
+ });
+
+ test("reads markdown from config", () => {
+ const cfg = join(tmp, "config.yaml");
+ writeFileSync(cfg, 'link_output_format: "markdown"\n');
+ expect(resolveLinkOutputFormat(cfg)).toBe("markdown");
+ });
+
+ test("invalid config falls back to wikilink", () => {
+ const cfg = join(tmp, "config.yaml");
+ writeFileSync(cfg, 'link_output_format: "html"\n');
+ expect(resolveLinkOutputFormat(cfg)).toBe("wikilink");
+ });
+
+ test("OBSIDIAN_LINK_FORMAT env wins over config", () => {
+ process.env["OBSIDIAN_LINK_FORMAT"] = "markdown";
+ const cfg = join(tmp, "config.yaml");
+ writeFileSync(cfg, 'link_output_format: "wikilink"\n');
+ expect(resolveLinkOutputFormat(cfg)).toBe("markdown");
+ });
+
+ test("empty OBSIDIAN_LINK_FORMAT env falls back to config", () => {
+ process.env["OBSIDIAN_LINK_FORMAT"] = " ";
+ const cfg = join(tmp, "config.yaml");
+ writeFileSync(cfg, 'link_output_format: "markdown"\n');
+ expect(resolveLinkOutputFormat(cfg)).toBe("markdown");
+ });
+});
+
describe("resolveTimezone", () => {
test("validates IANA timezone names", () => {
expect(validateTimezoneName("UTC")).toEqual({ ok: true, error: null });
diff --git a/tests/core/redactor.test.ts b/tests/core/redactor.test.ts
index f5e3b6d1..504d42c9 100644
--- a/tests/core/redactor.test.ts
+++ b/tests/core/redactor.test.ts
@@ -1,10 +1,56 @@
import { describe, expect, test } from "bun:test";
-import { normaliseTextField, redactRawOutput, sanitiseTextField } from "../../src/core/redactor.ts";
+import {
+ PRIVATE_REGION_PLACEHOLDER,
+ normaliseTextField,
+ redactRawOutput,
+ sanitiseTextField,
+ stripPrivateRegions,
+} from "../../src/core/redactor.ts";
+
+describe("stripPrivateRegions", () => {
+ test("strips balanced private regions across lines", () => {
+ const input = "before <private>secret\nbody token=abc</private> after";
+ expect(stripPrivateRegions(input)).toBe(
+ `before ${PRIVATE_REGION_PLACEHOLDER} after`,
+ );
+ });
+
+ test("matches private tags case-insensitively", () => {
+ const input = "A <PRIVATE>hidden</PrIvAtE> B";
+ expect(stripPrivateRegions(input)).toBe(
+ `A ${PRIVATE_REGION_PLACEHOLDER} B`,
+ );
+ });
+
+ test("strips from an unclosed private tag to the end", () => {
+ const input = "keep <private>hide forever";
+ expect(stripPrivateRegions(input)).toBe(
+ `keep ${PRIVATE_REGION_PLACEHOLDER}`,
+ );
+ });
+
+ test("strips nested private regions atomically", () => {
+ const input = "before <private>a<private>b</private>c</private> after";
+ expect(stripPrivateRegions(input)).toBe(
+ `before ${PRIVATE_REGION_PLACEHOLDER} after`,
+ );
+ });
+
+ test("runs before assignment redaction in redactRawOutput", () => {
+ const input = "visible api_key=keep <private>api_key=secret</private>";
+ const out = redactRawOutput(input);
+ expect(out).toContain("api_key=***REDACTED***");
+ expect(out).toContain(PRIVATE_REGION_PLACEHOLDER);
+ expect(out).not.toContain("secret");
+ });
+});
describe("redactRawOutput (cross-module backward compat)", () => {
test("masks api_key in env-style assignment", () => {
- expect(redactRawOutput("api_key=abcd1234")).toContain("api_key=***REDACTED***");
+ expect(redactRawOutput("api_key=abcd1234")).toContain(
+ "api_key=***REDACTED***",
+ );
});
test("masks token in YAML-style colon assignment", () => {
@@ -35,12 +81,16 @@ describe("normaliseTextField", () => {
test("folds U+2028 / U+2029 to \\n", () => {
// U+2028 line separator, U+2029 paragraph separator.
const input = "line1
line2
line3";
- expect(normaliseTextField(input, { maxLen: 100 })).toBe("line1\nline2\nline3");
+ expect(normaliseTextField(input, { maxLen: 100 })).toBe(
+ "line1\nline2\nline3",
+ );
});
test("singleLine collapses \\n / \\r / \\t runs to single space", () => {
const input = "a\n\nb\tc\r\nd";
- expect(normaliseTextField(input, { maxLen: 100, singleLine: true })).toBe("a b c d");
+ expect(normaliseTextField(input, { maxLen: 100, singleLine: true })).toBe(
+ "a b c d",
+ );
});
test("non-singleLine normalises CRLF/CR to LF", () => {
diff --git a/tests/mcp/brain-context.test.ts b/tests/mcp/brain-context.test.ts
index 19b253d4..7e825757 100644
--- a/tests/mcp/brain-context.test.ts
+++ b/tests/mcp/brain-context.test.ts
@@ -90,12 +90,18 @@ describe("brain_context tool registration", () => {
expect(tools.find((t) => t.name === "brain_context")).toBeDefined();
});
- test("writer scope still hosts the three Brain writers", () => {
+ test("writer scope still hosts the Brain writers plus context", () => {
const names = buildToolTable("writer")
.map((t) => t.name)
.toSorted();
expect(names).toEqual(
- ["brain_apply_evidence", "brain_context", "brain_feedback", "brain_note"].toSorted(),
+ [
+ "brain_apply_evidence",
+ "brain_context",
+ "brain_feedback",
+ "brain_note",
+ "brain_pinned_context",
+ ].toSorted(),
);
});
});
diff --git a/tests/mcp/brain.test.ts b/tests/mcp/brain.test.ts
index cc711611..d2f9773a 100644
--- a/tests/mcp/brain.test.ts
+++ b/tests/mcp/brain.test.ts
@@ -20,7 +20,13 @@ import { join } from "node:path";
import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
import { buildToolTable } from "../../src/mcp/tools.ts";
import { bootstrapBrain } from "../../src/core/brain/init.ts";
-import { brainDirs, logJsonlPath, logPath, preferencePath } from "../../src/core/brain/paths.ts";
+import {
+ brainDirs,
+ brainPinnedPath,
+ logJsonlPath,
+ logPath,
+ preferencePath,
+} from "../../src/core/brain/paths.ts";
import { writeSignal } from "../../src/core/brain/signal.ts";
import { writePreference } from "../../src/core/brain/preference.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
@@ -410,6 +416,31 @@ describe("brain_digest", () => {
expect(s.content).toContain("Confirmed");
});
+ test("uses configured markdown link output in Markdown digest", async () => {
+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\nlink_output_format: markdown\n`);
+ writePreference(vault, {
+ slug: "confirmed-rule",
+ topic: "confirmed-rule",
+ principle: "Confirmed test rule.",
+ created_at: "2026-05-14T09:00:00Z",
+ unconfirmed_until: "2026-05-14T09:00:00Z",
+ status: "confirmed",
+ evidenced_by: [],
+ confirmed_at: "2026-05-14T09:00:00Z",
+ applied_count: 1,
+ scope: "process",
+ });
+ const server = makeServer();
+ await initialize(server);
+ const r = await call(server, "brain_digest", {
+ since: "2026-05-14T00:00:00Z",
+ until: "2026-05-14T23:59:59Z",
+ });
+ const s = r.result.structuredContent;
+ expect(s.content).toContain("[Confirmed test rule.](Brain/preferences/pref-confirmed-rule.md)");
+ expect(s.content).not.toContain("[[pref-confirmed-rule|Confirmed test rule.]]");
+ });
+
test("format=json returns valid JSON content", async () => {
const server = makeServer();
await initialize(server);
@@ -783,12 +814,71 @@ describe("brain_note tool schema visibility", () => {
"brain_feedback",
"brain_apply_evidence",
"brain_note",
+ "brain_pinned_context",
// v0.10.10 added the `brain_context` reader to the same scope
// so runtimes without a SessionStart hook can fetch active.md
// without going through ToolSearch.
"brain_context",
]),
);
- expect(writer).toHaveLength(4);
+ expect(writer).toHaveLength(5);
+ });
+});
+
+describe("brain_pinned_context", () => {
+ test("reads missing pinned context as an empty payload", async () => {
+ const server = makeServer();
+ await initialize(server);
+ const r = (await call(server, "brain_pinned_context", { operation: "read" })) as any;
+ expect(r.result.isError).toBe(false);
+ const pinned = r.result.structuredContent;
+ expect(pinned.operation).toBe("read");
+ expect(pinned.present).toBe(false);
+ expect(pinned.content).toBe("");
+ expect(pinned.path).toBe("Brain/pinned.md");
+ expect(pinned.absolute_path).toBe(brainPinnedPath(vault));
+ });
+
+ test("writes, appends, and clears pinned context", async () => {
+ const server = makeServer();
+ await initialize(server);
+
+ const written = (await call(server, "brain_pinned_context", {
+ operation: "write",
+ content: "Remember api_key=abc <private>hidden</private>",
+ })) as any;
+ expect(written.result.structuredContent.content).toContain("api_key=***REDACTED***");
+ expect(written.result.structuredContent.content).toContain("***PRIVATE***");
+ expect(written.result.structuredContent.content).not.toContain("hidden");
+
+ const appended = (await call(server, "brain_pinned_context", {
+ operation: "append",
+ content: "Second fact",
+ })) as any;
+ expect(appended.result.structuredContent.content).toContain("\n\nSecond fact");
+
+ const cleared = (await call(server, "brain_pinned_context", { operation: "clear" })) as any;
+ expect(cleared.result.structuredContent.content).toBe("");
+ expect(readFileSync(brainPinnedPath(vault), "utf8")).toBe("");
+ });
+
+ test("brain_context includes pinned content as structured data and text", async () => {
+ const server = makeServer();
+ await initialize(server);
+ await call(server, "brain_pinned_context", {
+ operation: "write",
+ content: "Current task: fix MCP boundary tests.",
+ });
+
+ const r = (await call(server, "brain_context", {})) as any;
+ const context = r.result.structuredContent;
+ expect(context.pinned).toEqual({
+ present: true,
+ path: "Brain/pinned.md",
+ absolute_path: brainPinnedPath(vault),
+ content: "Current task: fix MCP boundary tests.",
+ });
+ expect(context.content).toContain("## Pinned context");
+ expect(context.content).toContain("Current task: fix MCP boundary tests.");
});
});
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index 9fbc3783..dc9aee67 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -19,12 +19,7 @@ const savedEnv: Record<string, string | undefined> = {};
beforeEach(() => {
tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-test-"));
- for (const k of [
- "VAULT_AGENT_NAME",
- "VAULT_TIMEZONE",
- "VAULT_DIR",
- "OPEN_SECOND_BRAIN_CONFIG",
- ]) {
+ for (const k of ["VAULT_AGENT_NAME", "VAULT_TIMEZONE", "VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG"]) {
savedEnv[k] = process.env[k];
delete process.env[k];
}
@@ -189,6 +184,7 @@ describe("tool listing", () => {
"brain_review_candidates",
"brain_apply_evidence",
"brain_note",
+ "brain_pinned_context",
"brain_context",
"brain_digest",
"brain_query",
@@ -278,9 +274,7 @@ describe("tool calls", () => {
expect(s.vault.ignore_source).toBeDefined();
expect(["_brain.yaml", "defaults"]).toContain(s.vault.ignore_source);
expect(Array.isArray(s.vault.rules)).toBe(true);
- expect(
- s.vault.rules.some((r: { raw: string }) => r.raw === ".obsidian"),
- ).toBe(true);
+ expect(s.vault.rules.some((r: { raw: string }) => r.raw === ".obsidian")).toBe(true);
expect(typeof s.vault.included.files).toBe("number");
expect(typeof s.vault.included.dirs).toBe("number");
expect(typeof s.vault.excluded.dirs).toBe("number");
@@ -341,9 +335,7 @@ describe("tool calls", () => {
const s = r.result.structuredContent;
expect(s.limit).toBe(5);
expect(s.total_pages).toBeGreaterThanOrEqual(1);
- expect(
- s.pages.some((p: { title: string }) => p.title.includes("Sandbox")),
- ).toBe(true);
+ expect(s.pages.some((p: { title: string }) => p.title.includes("Sandbox"))).toBe(true);
});
// `second_brain_capture` and `event_log_append` are no longer
@@ -385,6 +377,29 @@ describe("tool calls", () => {
const r = (await callTool(server, "not_a_tool")) as any;
expect(r.error.code).toBe(-32601);
});
+
+ test("tool output contract failure becomes a tool-level error", async () => {
+ const server = new MCPServer({ vault: tmp });
+ await initialize(server);
+ (server as any).tools = [
+ {
+ name: "bad_contract",
+ description: "test tool",
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
+ outputSchema: {
+ type: "object",
+ required: ["ok"],
+ properties: { ok: { type: "boolean" } },
+ additionalProperties: false,
+ },
+ handler: () => ({ ok: "yes" }),
+ },
+ ];
+ const r = (await callTool(server, "bad_contract")) as any;
+ expect(r.result.isError).toBe(true);
+ expect(r.result.structuredContent).toBeUndefined();
+ expect(r.result.content[0].text).toContain("bad_contract output contract failed");
+ });
});
describe("stdio loop", () => {
@@ -418,14 +433,16 @@ describe("stdio loop", () => {
const list = JSON.parse(lines[1]!);
expect(init.id).toBe(1);
expect(list.id).toBe(2);
- // v0.15.0: 3 core + 23 Brain (brain_health added in v0.14.0
+ // v0.16.0: 3 core + 24 Brain (brain_health added in v0.14.0
// Semantic Brain Health; brain_review_candidates added in v0.12.0
// Brain Integrity Suite; brain_timeline / brain_belief_evolution /
// brain_stale_scan / brain_daily_brief / brain_weekly_synthesis
// added v0.10.18)
// brain_agent_query / brain_agent_diff added in v0.15.0)
- // + 8 Pay Memory + 1 Search = 35.
- expect(list.result.tools.length).toBe(35);
+ // brain_agent_query / brain_agent_diff added in v0.15.0;
+ // brain_pinned_context added in v0.16.0)
+ // + 8 Pay Memory + 1 Search = 36.
+ expect(list.result.tools.length).toBe(36);
});
test("returns parse error for invalid JSON", async () => {
@@ -495,6 +512,7 @@ describe("serveStdioFromString respects scope+name", () => {
"brain_context",
"brain_feedback",
"brain_note",
+ "brain_pinned_context",
]);
});
});
diff --git a/tests/mcp/output-contract.test.ts b/tests/mcp/output-contract.test.ts
new file mode 100644
index 00000000..223e379b
--- /dev/null
+++ b/tests/mcp/output-contract.test.ts
@@ -0,0 +1,147 @@
+import { describe, expect, test } from "bun:test";
+
+import {
+ assertOutputContract,
+ validateOutputContract,
+ type OutputSchema,
+} from "../../src/mcp/output-contract.ts";
+import { JSONRPC_VERSION, MCPServer } from "../../src/mcp/index.ts";
+import { buildToolTable } from "../../src/mcp/tools.ts";
+
+describe("validateOutputContract", () => {
+ test("accepts objects that satisfy required properties", () => {
+ const schema: OutputSchema = {
+ type: "object",
+ required: ["ok"],
+ properties: { ok: { type: "boolean" } },
+ additionalProperties: false,
+ };
+ expect(validateOutputContract(schema, { ok: true })).toEqual([]);
+ });
+
+ test("reports missing required properties", () => {
+ const schema: OutputSchema = {
+ type: "object",
+ required: ["ok"],
+ properties: { ok: { type: "boolean" } },
+ };
+ expect(validateOutputContract(schema, {})).toEqual([
+ "$: missing required property 'ok'",
+ ]);
+ });
+
+ test("does not satisfy required properties via prototype chain", () => {
+ const schema: OutputSchema = {
+ type: "object",
+ required: ["ok"],
+ properties: { ok: { type: "boolean" } },
+ additionalProperties: false,
+ };
+ const value = Object.create({ ok: true }) as Record<string, unknown>;
+ expect(validateOutputContract(schema, value)).toEqual([
+ "$: missing required property 'ok'",
+ ]);
+ });
+
+ test("reports unexpected properties when additionalProperties is false", () => {
+ const schema: OutputSchema = {
+ type: "object",
+ properties: { ok: { type: "boolean" } },
+ additionalProperties: false,
+ };
+ expect(validateOutputContract(schema, { ok: true, extra: 1 })).toEqual([
+ "$: unexpected property 'extra'",
+ ]);
+ });
+
+ test("treats inherited schema properties as undeclared", () => {
+ const schema: OutputSchema = {
+ type: "object",
+ properties: {},
+ additionalProperties: false,
+ };
+ expect(validateOutputContract(schema, { toString: "owned" })).toEqual([
+ "$: unexpected property 'toString'",
+ ]);
+ });
+
+ test("rejects non-finite numbers for number type", () => {
+ const schema: OutputSchema = { type: "number" };
+ expect(validateOutputContract(schema, Number.NaN)).toEqual([
+ "$: expected number",
+ ]);
+ expect(validateOutputContract(schema, Infinity)).toEqual([
+ "$: expected number",
+ ]);
+ expect(validateOutputContract(schema, -Infinity)).toEqual([
+ "$: expected number",
+ ]);
+ expect(validateOutputContract(schema, 1.5)).toEqual([]);
+ });
+
+ test("validates arrays, items, and enum values", () => {
+ const schema: OutputSchema = {
+ type: "object",
+ required: ["items"],
+ properties: {
+ items: {
+ type: "array",
+ items: {
+ type: "object",
+ required: ["kind"],
+ properties: { kind: { type: "string", enum: ["a", "b"] } },
+ },
+ },
+ },
+ };
+ expect(validateOutputContract(schema, { items: [{ kind: "c" }] })).toEqual([
+ "$.items[0].kind: expected one of a, b",
+ ]);
+ });
+});
+
+describe("assertOutputContract", () => {
+ test("throws with tool name and validation details", () => {
+ const schema: OutputSchema = {
+ type: "object",
+ required: ["ok"],
+ properties: { ok: { type: "boolean" } },
+ };
+ expect(() =>
+ assertOutputContract("demo_tool", schema, { ok: "yes" }),
+ ).toThrow(/demo_tool output contract failed: \$\.ok: expected boolean/);
+ });
+});
+
+describe("registered output contracts", () => {
+ test("covers the first agent-facing structured surfaces", () => {
+ const tools = new Map(
+ buildToolTable("full").map((tool) => [tool.name, tool]),
+ );
+ for (const name of [
+ "brain_context",
+ "brain_pinned_context",
+ "brain_query",
+ "brain_search",
+ ]) {
+ expect(tools.get(name)?.outputSchema).toBeDefined();
+ }
+ });
+
+ test("tools/list advertises output schemas for contracted tools", async () => {
+ const server = new MCPServer({ vault: "/tmp/o2b-output-contract-test" });
+ const response = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "tools/list",
+ })) as any;
+ const tools = new Map(
+ (
+ response.result.tools as Array<{ name: string; outputSchema?: unknown }>
+ ).map((tool) => [tool.name, tool]),
+ );
+ expect(tools.get("brain_context")?.outputSchema).toBeDefined();
+ expect(tools.get("brain_pinned_context")?.outputSchema).toBeDefined();
+ expect(tools.get("brain_feedback")?.outputSchema).toBeUndefined();
+ });
+});
diff --git a/tests/mcp/scope-filter.test.ts b/tests/mcp/scope-filter.test.ts
index 7117b211..f0508813 100644
--- a/tests/mcp/scope-filter.test.ts
+++ b/tests/mcp/scope-filter.test.ts
@@ -13,7 +13,7 @@ describe("buildToolTable scope filter", () => {
expect(full.length).toBeGreaterThanOrEqual(15);
});
- test("writer scope returns the three writers plus brain_context (v0.10.10)", () => {
+ test("writer scope returns writers plus brain_context (v0.16.0)", () => {
const writer = buildToolTable("writer");
const names = writer.map((t) => t.name).toSorted();
expect(names).toEqual([
@@ -21,6 +21,7 @@ describe("buildToolTable scope filter", () => {
"brain_context",
"brain_feedback",
"brain_note",
+ "brain_pinned_context",
]);
});