Skip to content

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

TypeScript

feat: Agent Surface Suite - skills over MCP, two-pass tool catalog, surface profiles, session lifecycle (#68)

Sol Aitken707197a79775
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index a3e2bcc9..23a7998d 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.36.0",
+ "version": "0.37.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 8f155531..9d4bf4d6 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.36.0",
+ "version": "0.37.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 c35382cb..cd22cbb2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,77 @@ 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.37.0] - 2026-06-03
+
+Agent Surface Suite: eight changes in two themes. Theme A makes the
+MCP tool and skill surface adaptive - skills become discoverable over
+MCP, a two-pass catalog keeps schemas out of the prompt until needed,
+named profiles curate the surface per host, and relevant skills can
+auto-attach to a turn. Theme B closes the session lifecycle - capture
+filters by role, search focus binds to a session and auto-clears, a
+finished session leaves an operator-readable handoff note, and every
+workstream gets a versioned current-intention chain. All
+behaviour-changing pieces are off by default.
+
+### Added
+
+- **Skills as callable MCP tools.** `list_skills` returns the agent
+ skills Open Second Brain ships in `skills/` (plus vault-local
+ `Brain/skills/`, which shadow shipped ones by name) with one-line
+ descriptions; `get_skill` fetches SKILL.md content or a
+ traversal-guarded auxiliary file inside the skill directory. Any
+ MCP-connected agent can now self-discover and load skills without
+ shell access.
+- **Two-pass tool catalog hydration.** A new `catalog` scope
+ (`o2b mcp --scope catalog`) advertises a compact first pass - the
+ capability diagnostic, the five always-loaded Brain tools, and
+ `tool_hydrate` - while every other tool stays callable but
+ unadvertised. `tool_hydrate` with no arguments returns the sorted
+ compact catalog (name, one-line description, group); with a `names`
+ batch it returns full input/output schemas, reporting unknown names
+ per-name. Schema tokens stay out of the prompt until the agent
+ actually needs the tool.
+- **Adaptive tool-surface profiles.** Five named profiles (`full`,
+ `writer`, `catalog`, `recall`, `minimal`) resolve to a scope plus
+ capability window, selected via the `mcp_tool_profile` config key or
+ `o2b mcp --tool-profile`. An unknown profile fails OPEN to the full
+ surface with a logged note; hard-window profiles always retain the
+ `second_brain_capabilities` diagnostic so withheld tools stay
+ discoverable with reasons.
+- **Deterministic skill auto-attach.** `skills_attach` scores skills
+ against the current turn text with a shared BM25-style lexical
+ scorer (name > tags > description field weights, no LLM) and returns
+ a char-budgeted block of top matches with `get_skill` load hints.
+ Gated by `skill_auto_attach` (default off); the native Hermes
+ provider's prefetch appends the block through one fail-soft bridge
+ call.
+- **Config-level capture role filtering.** `session_capture_roles`
+ (comma-separated subset of `user,assistant,system,tool,meta`)
+ supplies the default `--filter-role` set for `brain import-session`.
+ Absent captures every role; an explicit flag wins; an unknown role
+ fails fast.
+- **Session-scoped search focus.** `o2b search focus set|status|clear
+ --session <id>` binds a focus to one session's file under
+ `search-focus/` beside the global file; a bound session focus wins
+ over the global one, `brain_search` gains an optional
+ `focus_session` input, and SessionEnd lifecycle capture auto-clears
+ the ending session's focus. When `search_focus_context_pack` is true
+ (default off), `brain_context_pack` promotes focus-matching memories
+ within their tier.
+- **Operator-readable handoff notes.** `o2b brain handoff
+ <session-file>` (and, when `session_handoff` is true, SessionEnd
+ lifecycle capture) writes `Brain/handoffs/<date>-<scope>.md` with
+ request, completed work, changed files, learned context, and next
+ steps - extracted by deterministic regex from the recorded turns, no
+ LLM.
+- **Scoped current-intention chains.** `o2b brain intention
+ set|show|list|move` (and the consolidated `brain_intention` MCP
+ tool) maintain per-workstream now-documents at
+ `Brain/intentions/<scope>.md`: every update bumps `version` and
+ appends the superseded text to an in-file history trail; `move`
+ retires the chain into `Brain/intentions/history/`. `Brain/pinned.md`
+ stays the scope-free scratchpad.
+
## [0.36.0] - 2026-06-03
Embedding Provider Suite: four changes to the semantic layer that make
@@ -4113,6 +4184,7 @@ plugin config (vault field)`, and exits with a clear
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[0.37.0]: https://github.com/itechmeat/open-second-brain/compare/v0.36.0...v0.37.0
[0.36.0]: https://github.com/itechmeat/open-second-brain/compare/v0.35.0...v0.36.0
[0.35.0]: https://github.com/itechmeat/open-second-brain/compare/v0.34.0...v0.35.0
[0.34.0]: https://github.com/itechmeat/open-second-brain/compare/v0.33.0...v0.34.0
diff --git a/README.md b/README.md
index 188091d9..219e4af0 100644
--- a/README.md
+++ b/README.md
@@ -114,7 +114,7 @@ The capabilities you actually feel day to day:
These are the headline capabilities. The full surface also includes: importing Claude Code memory directories, daily logging-discipline cron with a complexity-to-thinking warning, cross-project pointers for shared vaults, transient pinned session context through `brain_pinned_context` / `Brain/pinned.md`, source-agent query and comparison (`brain_agent_query`, `brain_agent_diff`, `o2b brain agent-query`, `o2b brain agent-diff`), the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, an operator dashboard, configurable Markdown-link presentation output, MCP output-contract checks for core agent-facing tools, private-region stripping with `<private>...</private>`, the v0.12.0 Brain Integrity Suite (content-hash drift detection, durable workrun checkpoints, destructive-from-confirmed retire gate, and the `brain_review_candidates` MCP tool that previews what the next dream pass would do without writing anything), the v0.13.0 Hybrid Search and Recall Quality suite (explainable recall, MMR diversity, link-graph traversal, entity-boosted retrieval, header-anchored chunking), the v0.14.0 Semantic Brain Health and Self-Maintenance suite (cross-preference contradiction detection, concept-gap and stale-claim surfacing, per-preference edit-history, a clean/watch/investigate reconciliation verdict via `brain_health`, and dependency-ordered `doctor --remediate`), the v0.17.0 Brain Lifecycle Review Suite (`intent-review`, `retention`, `monthly`, lifecycle schemas, and discipline complexity ratio), and the v0.18.0 MCP context economy (a per-tool preview budget that returns a bounded inline preview and parks the full payload in a vault-local artifact the agent fetches on demand with `brain_artifact_get`, plus a `recall_hint` one-liner on search results), and the v0.19.0 typed graph semantics (typed frontmatter relationships - `related` / `extends` / `contradicts` / `superseded_by` - that surface inline on search results, a `visibility:` scoping axis for `brain_search`, and a `brain_mcp_landscape` view of the Model Context Protocol servers configured across the vault), and the v0.20.0 Recall and Ranking Quality suite (a configurable Weibull recency-decay curve, structural query-intent classification that re-weights ranking by query shape, language-agnostic synonym expansion via local co-occurrence, per-memory and total recall character budgets for `brain_context_pack`, a persistent query cache that self-invalidates on a corpus-generation change, and a `brain_pre_compress_pack` tool that returns a budgeted top-preferences addendum for a host runtime to inject before context compression), and the v0.21.0 Brain Lifecycle Suite (a per-preference mutation audit trail keyed by preference id - create / promote / update / retire / merge with revision + content-hash before/after, via `o2b brain audit` and `brain_audit`; a multi-phase `dream` pipeline that names its close / reconcile / synthesize / heal / log seams and reports a structured per-phase summary without rewriting the proven internals; deterministic reconcile-phase domain classification that buckets contradictions into claims / entity / decisions / source-freshness, auto-resolves only the decisive source-freshness case, and surfaces the rest as open questions instead of forcing a merge; a budgeted `o2b brain morning-brief` / `brain_morning_brief` session-start summary of top preferences, recent open questions, and recent notes; language-agnostic ISO-8601 temporal extraction that fills preference validity windows from signal text; and opt-in heal-phase vault enrichment that links exact title mentions across user pages), and the v0.22.0 Vault portability + session economy suite (a deterministic lossless session codec - `expand(compress(x)) === x` for all input, opt-in on the signal store and exposed as `o2b brain codec`; an `o2b brain sources` / `brain_sources` read-only dashboard of signals by agent and source type; vault-map `{{role}}` tokens resolved via an optional `Brain/_vault-map.yaml` and wired into scan-inline read paths and graph import; named multi-vault profiles with `o2b vault profile` + a `brain_switch_vault` tool, activated by a pointer in config; and `o2b brain graph-export` / `graph-import` for moving a vault's knowledge graph between layouts with skip/overwrite/merge conflict modes). Browse [`docs/cli-reference.md`](docs/cli-reference.md) for every verb and [`docs/how-it-works.md`](docs/how-it-works.md) for the mental model.
-The v0.26.0 surface adds audited schema mutation/admin tools, real-time lifecycle capture hooks for prompt markers and `brain_feedback` tool calls, CJK-aware FTS recall, and `brain_watchdog` / `o2b brain watchdog` recovery probes. The v0.27.0 surface adds recall-control and trust tools: structured search query documents, session focus, MCP `brain_recall_gate`, polarity-aware context lanes, and opt-in evidence packs for CLI/MCP search. The v0.28.0 surface adds a deterministic prompt-injection guard for automatically surfaced Brain context, agent-blind `$secret:NAME` references, and preview foundations for source-scoped forget, privacy-scanned knowledge packs, and oversized payload externalization. The v0.29.0 surface adds opt-in context receipts and recall telemetry, read-only context budget presets, pre-compaction extraction, and a continuity-backed session recall DAG. The v0.33.0 surface adds the Recall Trust Suite: relation-aware recall polarity for typed memory edges, an explicit retrieval feedback loop with bounded learned weights (`o2b search feedback` / `weights`, MCP `brain_recall_feedback`), time-aware recall (`--since` / `--until` with natural-language ranges), verified multi-record recall (per-token union records, IDF-weighted coverage, rare-term abstention), and a search-completeness verdict with a false-absence guard. The v0.34.0 surface adds the Token Diet: a budgeted SessionStart injection of `Brain/active.md` (default 8,000 chars, `active.inject_budget_chars`) with the post-compaction path moved to the supported SessionStart `compact` matcher, a once-per-session post-write reminder cadence, frontmatter escape-amplification fixed at the parser with a one-shot `brain upgrade --apply` repair for already-corrupted preference files, three consolidated read tools (`brain_brief`, `brain_analytics`, `schema_inspect`) with 18 hidden deprecated aliases, registry description caps with a contract guard, preview budgets by default, and a `scripts/measure-token-surface.ts` report. The v0.35.0 surface adds the Memory Integrity Suite: a canonical entity registry under `Brain/entities/` (one Markdown entity per `(category, name)` with alias resolution, archive/restore, typed relations, `o2b brain entity` CLI verbs, a read-only `brain_entity` MCP tool, doctor duplicate/relation lints, and alias-aware search boost with `entity_canonical` explanations), per-device Brain log shards (`Brain/log/<date>.<deviceId>.jsonl` + `.md` keyed by a device-local id, merged reads through `readLogDay`/`listLogDates`, no more Syncthing write conflicts, legacy days untouched), capture boundaries (a `sessions:` block with ignored/stateless session globs and message suppression regexes, applied before any extraction at both live-hook and import seams, counted but never stored raw; keep suppression regexes simple - they run on every message, and a catastrophic-backtracking pattern slows capture), and deterministic regex fact extraction (seven precision-first families over user turns, `source_type: extracted` signals with family-scoped dedup and canonical entity anchors). The v0.36.0 surface adds the Embedding Provider Suite: an offline `local` embedding provider (deterministic feature hashing, no cloud, no key, no model download - set `embedding_provider: local` for a privacy-first recall path), a CLI provider registry (`o2b search provider add | list | show | remove`, persisted to `Brain/search/embedding-providers.json` storing only environment-variable names, resolved after the built-ins so a configured key is never shadowed), an embedding cost gate (`embedding_cost_gate_usd`, default 0 = off; refuses an over-budget run unless `o2b search index --force-cost`) with the active `<provider>:<model>:<dimension>` signature and a refresh-cost estimate in `o2b search status`, and an opt-in Reciprocal Rank Fusion mode (`search_fusion_mode: rrf`, `search_rrf_k` default 60) that fuses the keyword and semantic lanes by rank position instead of weighted magnitude while the default `linear` mode stays bit-identical and storage remains SQLite + sqlite-vec + FTS5.
+The v0.26.0 surface adds audited schema mutation/admin tools, real-time lifecycle capture hooks for prompt markers and `brain_feedback` tool calls, CJK-aware FTS recall, and `brain_watchdog` / `o2b brain watchdog` recovery probes. The v0.27.0 surface adds recall-control and trust tools: structured search query documents, session focus, MCP `brain_recall_gate`, polarity-aware context lanes, and opt-in evidence packs for CLI/MCP search. The v0.28.0 surface adds a deterministic prompt-injection guard for automatically surfaced Brain context, agent-blind `$secret:NAME` references, and preview foundations for source-scoped forget, privacy-scanned knowledge packs, and oversized payload externalization. The v0.29.0 surface adds opt-in context receipts and recall telemetry, read-only context budget presets, pre-compaction extraction, and a continuity-backed session recall DAG. The v0.33.0 surface adds the Recall Trust Suite: relation-aware recall polarity for typed memory edges, an explicit retrieval feedback loop with bounded learned weights (`o2b search feedback` / `weights`, MCP `brain_recall_feedback`), time-aware recall (`--since` / `--until` with natural-language ranges), verified multi-record recall (per-token union records, IDF-weighted coverage, rare-term abstention), and a search-completeness verdict with a false-absence guard. The v0.34.0 surface adds the Token Diet: a budgeted SessionStart injection of `Brain/active.md` (default 8,000 chars, `active.inject_budget_chars`) with the post-compaction path moved to the supported SessionStart `compact` matcher, a once-per-session post-write reminder cadence, frontmatter escape-amplification fixed at the parser with a one-shot `o2b brain upgrade --apply` repair for already-corrupted preference files, three consolidated read tools (`brain_brief`, `brain_analytics`, `schema_inspect`) with 18 hidden deprecated aliases, registry description caps with a contract guard, preview budgets by default, and a `scripts/measure-token-surface.ts` report. The v0.35.0 surface adds the Memory Integrity Suite: a canonical entity registry under `Brain/entities/` (one Markdown entity per `(category, name)` with alias resolution, archive/restore, typed relations, `o2b brain entity` CLI verbs, a read-only `brain_entity` MCP tool, doctor duplicate/relation lints, and alias-aware search boost with `entity_canonical` explanations), per-device Brain log shards (`Brain/log/<date>.<deviceId>.jsonl` + `.md` keyed by a device-local id, merged reads through `readLogDay`/`listLogDates`, no more Syncthing write conflicts, legacy days untouched), capture boundaries (a `sessions:` block with ignored/stateless session globs and message suppression regexes, applied before any extraction at both live-hook and import seams, counted but never stored raw; keep suppression regexes simple - they run on every message, and a catastrophic-backtracking pattern slows capture), and deterministic regex fact extraction (seven precision-first families over user turns, `source_type: extracted` signals with family-scoped dedup and canonical entity anchors). The v0.36.0 surface adds the Embedding Provider Suite: an offline `local` embedding provider (deterministic feature hashing, no cloud, no key, no model download - set `embedding_provider: local` for a privacy-first recall path), a CLI provider registry (`o2b search provider add | list | show | remove`, persisted to `Brain/search/embedding-providers.json` storing only environment-variable names, resolved after the built-ins so a configured key is never shadowed), an embedding cost gate (`embedding_cost_gate_usd`, default 0 = off; refuses an over-budget run unless `o2b search index --force-cost`) with the active `<provider>:<model>:<dimension>` signature and a refresh-cost estimate in `o2b search status`, and an opt-in Reciprocal Rank Fusion mode (`search_fusion_mode: rrf`, `search_rrf_k` default 60) that fuses the keyword and semantic lanes by rank position instead of weighted magnitude while the default `linear` mode stays bit-identical and storage remains SQLite + sqlite-vec + FTS5. The v0.37.0 surface adds the Agent Surface Suite: skills as callable MCP tools (`list_skills` / `get_skill` over the shipped `skills/` plus vault-local `Brain/skills/`), two-pass tool catalog hydration (a compact `catalog` scope where `tool_hydrate` returns the sorted catalog and per-name full schemas while every tool stays callable), five named tool-surface profiles with fail-open fallback (`mcp_tool_profile` / `o2b mcp --tool-profile`), deterministic BM25-style skill auto-attach (`skills_attach`, gated by `skill_auto_attach`), config-level capture role filtering (`session_capture_roles`), session-scoped search focus with SessionEnd auto-clear and gated context-pack promotion (`--session`, `focus_session`, `search_focus_context_pack`), operator-readable handoff notes (`o2b brain handoff`, gated SessionEnd generation via `session_handoff`), and scoped current-intention chains with a move-to-history lifecycle (`o2b brain intention`, MCP `brain_intention`).
## CLI
diff --git a/docs/brainstorm/agent-surface-suite/cli-output/claude.md b/docs/brainstorm/agent-surface-suite/cli-output/claude.md
new file mode 100644
index 00000000..c4d3577a
--- /dev/null
+++ b/docs/brainstorm/agent-surface-suite/cli-output/claude.md
@@ -0,0 +1,37 @@
+### Variant 1: Two theme kernels (catalog kernel + session-scope kernel)
+
+- **Approach**: Build exactly two shared modules. A **catalog/scoring kernel** emits uniform descriptor records (name, one-line desc, group/toolset, tags, checksum) over both MCP tools and `skills/` entries, plus one deterministic BM25 scorer; it feeds two-pass hydration, `list_skills`/`get_skill`, skill auto-attach, and the adaptive tool-surface selector. A **session-scope kernel** owns a session-id-keyed scope record with lifecycle hooks; it feeds role-filtered capture, handoff notes, per-session focus binding, and intention chains. The two kernels stay decoupled across the theme boundary.
+- **Trade-offs**:
+ - Pro: honors the "share kernels where natural" constraint with one kernel per theme β€” no eight disconnected features, no single god-module.
+ - Pro: tool-surface work stays request-local (compatible with the static-per-process MCP server and the hidden-tool precedent); session state is isolated and fail-soft.
+ - Pro: the two kernels are independently testable and parallelizable across the PR's eight units.
+ - Con: tool descriptors vs skill descriptors must be reconciled into one schema, which is some up-front design tax.
+ - Con: BM25 scorer is reused for two different inputs (turn-vs-tool, turn-vs-skill), risking subtle tuning divergence if not parameterized cleanly.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 2: Unified per-session context spine
+
+- **Approach**: Make a single `SessionContext` object the backbone for all eight units, keyed by session id and surfaced through the existing provider `system_prompt_block()` / `brain_context_pack`. Tool-surface profiles, skill auto-attach, focus, intention chain, capture filter, and handoff all read and write that one per-session state, so a turn's advertised tools, injected skills, and recalled memory are decided in one place.
+- **Trade-offs**:
+ - Pro: maximal coherence β€” focus, intention, skills, and tool surface all flow through one injection point with consistent token budgeting.
+ - Pro: per-session binding (focus, intention) gets a natural home and clean auto-clear on session end.
+ - Con: forces request-local, stateless Theme A work (which the static MCP server cannot vary per session anyway β€” no `listChanged`) into a session-stateful frame it does not fit; tool-surface adaptation would be misleadingly "session-bound."
+ - Con: a central spine touched by all eight units is a merge-and-regression hotspot and contradicts the "everything off by default, bit-identical defaults" guarantee being easy to prove per-unit.
+ - Con: highest blast radius if the shared object misbehaves.
+- **Complexity**: large
+- **Risk**: high
+
+### Variant 3: Thin additive layers over existing surfaces
+
+- **Approach**: Ship each unit as a minimal independent layer on what already exists β€” a `session_capture_roles` config key, `list_skills`/`get_skill` reading `skills/`, auto-attach as a new context-pack lane, the tool-surface selector as a dry-run/advisor first using the hidden-tool flag, handoff as a CLI+Stop-hook artifact, per-session focus as extra keys on `session-focus.json`, intention as a versioned sibling of `pinned.ts`. Share only two trivial utilities: a scoped-session-id resolver and one lexical scorer, used opportunistically rather than as mandatory kernels.
+- **Trade-offs**:
+ - Pro: lowest risk, fastest to land, cleanest match to house style (additive, fail-soft, off by default, easy per-unit defaults proof).
+ - Pro: defers the riskiest piece (active per-turn tool filtering) behind a dry-run advisor, which the static server constraint favors anyway.
+ - Con: weakest on the "avoid eight disconnected mini-features" constraint β€” sharing is incidental, so skill discovery could be implemented twice (once for `get_skill`, once for auto-attach).
+ - Con: descriptor metadata and scoring logic risk duplication and drift across units.
+- **Complexity**: small
+- **Risk**: low
+
+### Recommended: Variant 1
+**Rationale**: It is the only option that directly satisfies the epic's explicit "share kernels where natural" instruction β€” one skill/tool catalog+scorer, one session-scope concept β€” without the over-coupling of Variant 2, which fights the static-per-process MCP server and the off-by-default guarantee by forcing request-local tool work into session state. Compared to Variant 3 it avoids duplicating skill discovery and scoring across units while staying within the same additive, fail-soft, deterministic constraints, and its two-kernel split cleanly mirrors the two themes so the eight units remain independently testable and parallelizable.
diff --git a/docs/brainstorm/agent-surface-suite/cli-output/prompt.md b/docs/brainstorm/agent-surface-suite/cli-output/prompt.md
new file mode 100644
index 00000000..06100645
--- /dev/null
+++ b/docs/brainstorm/agent-surface-suite/cli-output/prompt.md
@@ -0,0 +1,339 @@
+You are brainstorming architectural variants for the following epic. Do not write code. Do not write a final design. Only produce variants and a recommendation.
+
+# Task
+
+Epic: Agent Surface Suite - one multi-task PR shipping eight related atomic units in two themes.
+
+Theme A - MCP tool surface and skills economy:
+1. Two-pass Brain tool catalog hydration (t_e8011a89)
+2. Skills as callable MCP tools: list_skills / get_skill (t_251c6490)
+3. Skill auto-attach in system prompt by deterministic relevance scoring (t_10b86707)
+4. Adaptive Brain MCP tool-surface profiles with full-tool fallback (t_20dcb192)
+
+Theme B - session lifecycle continuity:
+5. Role-based capture filtering for session sync (t_e2346fe9)
+6. Operator-readable session handoff notes (t_28afa4d2)
+7. Session-scoped focus: per-session binding, auto-clear, context-pack wiring (t_5b478e47)
+8. Scoped current-intention chains with move-to-history lifecycle (t_6d78f69e)
+
+Full task bodies follow.
+
+## Task t_e8011a89 (priority 3): [upstream:hermes-tool-slimmer] Two-pass Brain tool catalog hydration for large capability sets
+
+**Source**: https://github.com/alias8818/hermes-tool-slimmer
+**Upstream files studied**: `README.md`, `CHANGELOG.md`, `docs/quickstart.md`, `docs/hermes-core-integration.md`, `src/hermes_tool_slimmer/two_pass.py`, `src/hermes_tool_slimmer/integration.py`, `src/hermes_tool_slimmer/index_store.py`, `src/hermes_tool_slimmer/schemas.py`, `tests/test_two_pass.py`, `tests/test_index_metrics_anthropic.py`
+
+## What
+Hermes Tool Slimmer's experimental two-pass mode replaces a large eager schema list with a compact deterministic catalog and a hydration tool. The first pass exposes only always-included tools plus `tool_slimmer_hydrate_tools`; that tool describes available tools by name, one-line description, toolset, and tags. The model requests multiple full schemas in one batch, and the next model call exposes those hydrated schemas, optionally cached by session. The implementation keeps safety/fallback tools separate, respects disabled policy, sorts catalogs deterministically, limits catalog size, verifies live-schema checksums, and rejects stale or probe-only live snapshots by default.
+
+## Why useful for OSB
+As OSB accumulates more Brain capabilities, a binary choice between exposing every tool or a tiny static subset becomes awkward. Agents need discoverability for rare Second Brain operations such as schema repair, backlinks, watchdog checks, source ingestion, payment assets, or future graph/admin tools, but most turns only need a few core recall tools. A compact Brain tool catalog with explicit hydration would preserve discoverability while keeping full schemas out of the prompt until the agent actually needs them.
+
+## Current OSB status
+- **Verdict**: not_in_osb_useful
+- **Local evidence**: OSB exposes concrete MCP tools and a capability diagnostic surface, and it has output artifact fetch for oversized results. I did not find a compact catalog/hydration mode where rare OSB tool schemas are deferred, requested in a batch, and cached by session for later turns.
+- **Related existing work, not a duplicate**: MCP preview budgets and artifact fetch handle large results after execution. Context-pack ordering and repeated-context dedup optimize Brain content in prompts. This task targets the MCP tool-schema catalog itself before execution and before context-pack assembly.
+
+## Proposal
+Add a progressive Brain tool catalog mode for compatible OSB host adapters. The first version can be a dry-run/catalog surface plus integration tests; an active mode can follow where the host supports request-local schema filtering. The catalog should be deterministic, privacy-safe, and explainable, and it should hydrate full schemas only through an explicit tool-name batch request.
+
+## Acceptance criteria
+- OSB can render a compact catalog of currently eligible tools with name, short description, group/toolset, tags, and checksum.
+- A hydration request can name several tools and receive a bounded next-turn schema set without executing those tools.
+- Hydrated tools are scoped to a session or request and never become sticky global state.
+- Disabled tools, withheld capability windows, and scope restrictions are enforced both in the catalog and during hydration.
+- Stale live-schema snapshots are rejected by checksum/age, and probe events without session identity do not update production catalogs.
+- Tests cover deterministic catalog ordering, hydration batching, session cache behavior, disabled-policy enforcement, missing hydrator fallback, and stale snapshot rejection.
+
+> Validator comment: osb-triage-validator @ 2026-06-03T10:04Z:
+- sanity: clean
+- cluster: no cluster
+- priority: set to 3: overriding origin-unknown priority 1 (no reprioritized event in history) - not_in_osb_useful but clear scope, two-pass tool catalog with hydration fits one week of work.
+
+## Task t_251c6490 (priority 3): [upstream:core] Expose skills as callable MCP tools (list_skills, get_skill)
+
+**Source**: https://github.com/RedPlanetHQ/core/releases/tag/0.7.15
+**Repo**: RedPlanetHQ/core (1600β˜…)
+**Released**: 0.7.15 (2026-06-01T12:15:14Z)
+
+## What
+RedPlanet core exposes skills as MCP tools: list_skills and get_skill become callable via the MCP protocol. Connected agents can discover available skills and fetch their content without shell access. PR #886.
+
+## Why useful for OSB
+OSB has a rich skill system (skill_view, skills_list, skill_manage) accessible via Hermes CLI but NOT exposed as MCP tools. Connected agents (Claude Code, Codex, etc.) talking to OSB via MCP cannot discover or load skills β€” they must guess skill names or ask the user. Exposing skills as MCP tools would let any MCP-connected agent self-discover available skills, read their content, and follow their instructions without prior knowledge.
+
+## Status in OSB
+- **Verdict**: present_weaker
+- **Codegraph hints**: src/mcp/server.ts:76 (tools method), src/mcp/tools.ts:60 (ToolDefinition), src/mcp/tools.ts:283 (ToolScope). Skills live in ~/.hermes/skills/ and ~/.hermes/profiles/*/skills/, loaded by skill_view/skills_list CLI. No MCP tool surface for skill discovery or retrieval.
+
+## Notes
+The list_skills tool would return skill names + descriptions (like skills_list output). The get_skill tool would accept a skill name and optional file_path (like skill_view). This bridges the gap between OSB's skill system and MCP-connected agents.
+
+> Validator comment: Validation pass 2026-06-02: scope caveat - skill_view/skills_list and ~/.hermes/skills/ belong to the Hermes host, not to Open Second Brain. An OSB-side list_skills/get_skill MCP surface would either need OSB to own a skills directory concept, or this belongs upstream in Hermes (expose skills via the memory-provider/MCP surface). Decide ownership before implementation; the upstream pattern (RedPlanetHQ/core 0.7.15) is still a good reference.
+
+> Validator comment: osb-triage-validator @ 2026-06-03T10:05Z:
+- sanity: clean
+- cluster: no cluster
+- priority: set to 3: overriding origin-unknown priority 3 (no reprioritized event in history) - present_weaker with concrete hints (src/mcp/server.ts:76, tools.ts:60/283), clear scope, fits one week of work.
+
+## Task t_10b86707 (priority 3): [upstream:yantrikdb-hermes-plugin] Skill auto-attach in system prompt without explicit search
+
+**Source**: https://github.com/yantrikos/yantrikdb-hermes-plugin/releases/tag/v0.5.0
+**Repo**: yantrikos/yantrikdb-hermes-plugin (27β˜…)
+**Released**: v0.5.0 (2026-05-31T07:10:31Z)
+
+## What
+YantrikDB v0.5 introduced automatic skill attachment: skills surface in the system prompt on every turn without requiring an explicit skill_search call. The plugin scans active skills against the current turn context and injects relevant skill guidance proactively. First Hermes memory provider to do this.
+
+## Why useful for OSB
+OSB skills are loaded on-demand via skill_view when the agent decides to load one. There is no automatic per-turn skill relevance scoring that proactively surfaces applicable skills. Auto-attaching skills would reduce the cognitive load on the agent to remember which skills exist and when to load them, ensuring relevant procedural guidance is always present in context without explicit discovery calls.
+
+## Status in OSB
+- **Verdict**: present_weaker
+- **Codegraph hints**: Skills are in ~/.hermes/skills/ and loaded via skill_view/skills_list. No per-turn skill relevance scoring or auto-attachment mechanism exists. brain_context_pack injects memories but not skills. The procedural memory index (brain_procedural_memory) tracks usage but does not drive auto-injection.
+
+## Notes
+Implementation could use BM25 or embedding-based scoring of skill content against the current turn message, with a token-budget cap similar to context_pack. The yantrikdb approach uses the system_prompt_block hook for injection β€” OSB could integrate via the same hook or via brain_context_pack.
+
+> Validator comment: Validation pass 2026-06-02: same ownership caveat as t_251c6490 - the skills being auto-attached live in the Hermes host, not in OSB. Note v0.32.0 shipped the native Hermes memory provider with system_prompt_block(), which is exactly the injection point the upstream plugin uses; an OSB implementation would score skills per-turn and extend that block (deterministic BM25-style scoring preferred, no LLM in the loop).
+
+> Validator comment: osb-triage-validator @ 2026-06-03T10:04Z:
+- sanity: clean
+- cluster: no cluster
+- priority: set to 3: overriding origin-unknown priority 2 (no reprioritized event in history) - present_weaker with clear hints, skill auto-attach via BM25 scoring fits one week of work.
+
+## Task t_20dcb192 (priority 2): [upstream:hermes-tool-slimmer] Adaptive Brain MCP tool-surface profiles with full-tool fallback
+
+**Source**: https://github.com/alias8818/hermes-tool-slimmer
+**Upstream files studied**: `README.md`, `CHANGELOG.md`, `docs/quickstart.md`, `docs/hermes-core-integration.md`, `docs/dashboard-plugin.md`, `docs/privacy.md`, `src/hermes_tool_slimmer/selector.py`, `src/hermes_tool_slimmer/integration.py`, `src/hermes_tool_slimmer/config.py`, `src/hermes_tool_slimmer/policy.py`, `src/hermes_tool_slimmer/tools.py`, `tests/test_selector.py`, `tests/test_config.py`
+
+## What
+Hermes Tool Slimmer selects a request-local tool schema subset before the model call. It ranks eligible schemas with deterministic BM25 plus explicit boosts, keeps `always_include` tools hot, respects disabled tools/toolsets and MCP/native origin policy, applies platform profiles such as CLI, Slack, Telegram, cron, and webhook, skips low-information turns, enforces minimum estimated reduction guardrails, supports dry-run mode, and fails open to the original schema list on selector errors. It also keeps a `tool_slimmer_request_full_tools` fallback available so a model can recover the full schema set on the next turn instead of inventing substitute workflows.
+
+## Why useful for OSB
+OSB's MCP surface is growing: core Brain tools, search, schema administration, watchdog probes, pay-memory tools, future source connectors, and host-specific integrations all compete for the same model tool-schema budget. OSB currently has static tool scopes and runtime capability reporting, plus output preview budgets for large tool results, but it does not adapt the advertised Brain tool surface to the current task, host, or entry point. A profile-aware selector would make OSB more comfortable as a Second Brain for agents: the right memory tools stay visible, irrelevant or risky tools are quieter, and the full Brain surface remains recoverable when needed.
+
+## Current OSB status
+- **Verdict**: present_weaker
+- **Local evidence**: CodeGraph and local reads show `ToolScope` (`full`/`writer`), `ToolCapabilityReport`, MCP preview budgets, and `brain_artifact_get`. Those manage static availability and output size. I did not find a per-turn, query-aware MCP tool-surface selector, platform profile overlay, dry-run decision path, or full-tool fallback recovery mechanism for OSB's own tools.
+- **Related existing work, not a duplicate**: `t_89da8db4` protects context from oversized tool results after a tool runs. This task reduces request-side schema overhead before the model chooses tools. Runtime capability verification reports what can be exposed; this task decides what should be exposed for this turn and entry point.
+
+## Proposal
+Add an optional OSB tool-surface selection layer for hosts that support request-local tool filtering, plus a CLI/dry-run advisor for hosts that do not. Keep the default MCP server behavior unchanged unless enabled. The selector should use OSB tool metadata, task text, host/platform, configured profiles, and safety policy to propose a small Brain tool set while keeping explicit recovery available.
+
+## Acceptance criteria
+- OSB can compute a request-local tool subset for a user message without mutating the canonical MCP tool registry.
+- Config supports always-include, disabled tools, disabled tool groups, platform profiles, minimum reduction guardrails, dry-run mode, and fail-open behavior.
+- A full-tool fallback path is always available when slimming is active, and tests cover the retry lifecycle after fallback is requested.
+- Selection explanations include selected tools, skipped tools, score details, guardrail skip reason, and estimated schema bytes/tokens before and after.
+- Existing scope/capability checks still run before selection, so slimming cannot expose tools that OSB would otherwise withhold.
+- Tests cover low-information prompts, disabled-tool policy, platform profiles, no-match behavior, selector exceptions, and compatibility with the current static `full`/`writer` scopes.
+
+> Validator comment: osb-triage-validator @ 2026-06-03T10:05Z:
+- sanity: clean
+- cluster: no cluster
+- priority: set to 2: overriding origin-unknown priority 2 (no reprioritized event in history) - present_weaker, tool-surface selector needs design before implementation.
+
+## Task t_e2346fe9 (priority 3): [upstream:mnemosyne] Role-based autosave filtering for selective memory sync
+
+**Source**: https://github.com/AxDSan/mnemosyne/releases/tag/v3.3.0
+**Repo**: AxDSan/mnemosyne (629β˜…)
+**Released**: v3.3.0 (2026-06-01T02:21:51Z)
+
+## What
+Mnemosyne v3.3.0 introduced sync_roles config for role-based autosave filtering. The provider filters which conversation content gets persisted based on role configuration, enabling selective memory sync (e.g., only user messages and tool outputs, not raw assistant reasoning).
+
+## Why useful for OSB
+OSB session capture imports full conversation turns including assistant reasoning, tool calls, and intermediate thinking. A role-based filter would let operators configure which turn types become Brain evidence β€” for example, capturing user requests and final answers but excluding verbose intermediate reasoning or tool call internals. This would reduce noise in the Brain and focus memory on the most actionable content.
+
+## Status in OSB
+- **Verdict**: present_weaker
+- **Codegraph hints**: src/core/brain/sessions/types.ts:27 (SessionTurn), src/core/brain/sessions/import.ts:117 (importSession). Session import processes all turn types without role-based filtering. The session ignore patterns (from existing task t_0532ed5a) filter by session-level patterns, not by turn role.
+
+## Notes
+Could be implemented as a config key in _brain.yaml (session_capture.role_filter) that specifies which TurnSignal roles to persist. The Mnemosyne approach uses a config file (sync_roles) β€” OSB could follow the same pattern with YAML-based role allowlists/denylists.
+
+> Validator comment: osb-triage-validator @ 2026-06-03T10:04Z:
+- sanity: clean
+- cluster: no cluster
+- priority: set to 3: overriding origin-unknown priority 2 (no reprioritized event in history) - present_weaker with clear hints (sessions/types.ts:27, import.ts:117), role-based filter is a straightforward config addition.
+
+## Task t_28afa4d2 (priority 2): [upstream:ClawMem] Operator-readable session handoff notes
+
+**Source**: https://github.com/yoloshii/ClawMem
+**Upstream files studied**: `README.md`, `src/hooks/handoff-generator.ts`, `src/observer.ts`, `src/profile.ts`
+
+## What
+ClawMem generates a handoff note when an agent session ends. The hook reads the transcript tail, extracts a structured summary when possible, falls back to deterministic regex extraction when not, and saves a Markdown note with sections for request, investigation, learned context, completed work, files changed, and what the next session should do. Later session bootstrap/profile code can reuse these notes to keep continuity without replaying an entire transcript.
+
+## Why useful for OSB
+OSB already has session import adapters, conversation fact extraction, morning briefs, pre-compress packs, and a proposed session summary DAG. Those are valuable for recall and compression, but they do not give the operator a concise, inspectable end-of-session handoff artifact that answers: what changed, what was learned, where did we stop, and what should the next agent pick up first? Handoffs are especially useful when work crosses context compaction, agent changes, or a human pause between sessions.
+
+## Current OSB status
+- **Verdict**: not_in_osb_useful
+- **Local evidence**: Existing OSB session work focuses on importing turns, extracting facts, preserving lossless source, and generating session-start summaries. I did not find a dedicated stop-session handoff note format linked to session IDs and designed for human/operator review.
+- **Related existing work, not a duplicate**: `t_772706ee` is about a lossless summary DAG with drill-down recall. This task is about a small, durable, operator-readable handoff document that records state and next steps at the end of a work session.
+
+## Proposal
+Add a handoff generator that can be run from session-stop hooks, manually from the CLI, or after importing a transcript. Store handoffs as filesystem-first Brain artifacts linked to the session timeline and make the latest relevant handoff available to session-start context.
+
+## Suggested design
+- Add `brain handoff generate --session <id> --transcript <path>` plus an MCP/session-hook entry point.
+- Store generated notes under a stable path such as `Brain/sessions/handoffs/YYYY-MM-DD-SESSION.md` with frontmatter linking source agent, transcript hash, files changed, source turns, and generation mode.
+- Prefer structured extraction from existing session/fact pipelines, then fall back to deterministic transcript heuristics when extraction is unavailable.
+- Include sections for request, current state, decisions, files changed, unresolved blockers, next steps, and validation status.
+- Link handoffs from session index/timeline queries and optionally include the most recent relevant handoff in `brain_morning_brief` or session bootstrap.
+
+## Acceptance criteria
+- [ ] A session-stop or manual command creates a valid Markdown handoff without requiring full transcript replay.
+- [ ] The handoff links back to the source session/transcript and lists changed files when available.
+- [ ] The next session can retrieve the latest relevant handoff through CLI/MCP.
+- [ ] Duplicate stop-hook invocations do not create unbounded duplicate handoffs for the same session.
+- [ ] Tests cover structured extraction, fallback extraction, idempotency, and missing-transcript handling.
+
+## Out of scope
+- Replacing full session import or lossless transcript storage.
+- Treating generated handoffs as confirmed preferences without review.
+- Summarizing every historical session by default.
+
+> Validator comment: osb-triage-validator @ 2026-06-03T10:04Z:
+- sanity: clean
+- cluster: no cluster
+- priority: set to 2: overriding origin-unknown priority 1 (no reprioritized event in history) - not_in_osb_useful, handoff note generator fits one week of focused work, clear scope.
+
+## Task t_5b478e47 (priority 2): [follow-up:t_ff693b7f] Session-scoped focus: per-session binding, auto-clear, and context-pack/bootstrap wiring
+
+## Remaining scope (after PR #54 foundation slice)
+
+PR #54 shipped global search focus steering (`o2b search focus set/status/clear`, persisted focus file, ranking boost/demotion, MCP `focus_query`/`focus_path_prefix`). The original upstream scope (ClawMem session-scoped focus topic) still needs:
+
+- **Per-session-ID binding** β€” focus keyed to a session identifier rather than a single global file.
+- **Auto-clear on session end** β€” focus lifecycle tied to session teardown, not manual `clear`.
+- **Context-pack / session-bootstrap wiring** β€” focus automatically influences `brain_context_pack` and session bootstrap, not only explicit search calls.
+
+## Foundation shipped
+
+Global focus steering in PR #54 (v0.27.0). Build on `o2b search focus` and the MCP focus inputs.
+
+## Source
+
+Foundation: PR #54. Original assessment: t_ff693b7f (closed as foundation slice).
+
+> Validator comment: osb-triage-validator @ 2026-06-03T10:05Z:
+- sanity: clean
+- cluster: no cluster
+- priority: set to 2: overriding origin-unknown priority 2 (no reprioritized event in history) - follow-up task, inherits not-until-parent semantics from t_ff693b7f.
+
+## Task t_6d78f69e (priority 2): [upstream:keep] Scoped current-intention chains with move-to-history lifecycle
+
+**Source**: https://github.com/generalbusiness-ai/keep
+**Upstream files studied**: `README.md`, `SKILL.md`, `docs/KEEP-NOW.md`, `docs/VERSIONING.md`, `docs/KEEP-MOVE.md`, `docs/AGENT-GUIDE.md`, `keep/workstream.py`, `keep/integrations.py`
+
+## What
+Keep has a `now` document for the current working intention. Every update creates a version, and `--auto-scope` routes parallel sessions into per-workstream chains such as `now:project/branch` instead of one global scratchpad. When work pivots or completes, `keep move` can transfer selected versions into a named history item, optionally filtered by tags, so the active intention stays clean while the past trajectory remains searchable and inspectable.
+
+## Why useful for OSB
+OSB already imports agent sessions, supports focus steering, and can create handoff notes, but it lacks a first-class current-intention chain that agents update during work and then deliberately retire into named project histories. A Second Brain benefits from knowing not only final outcomes, but also the evolving intention trail: what was being attempted, where the work pivoted, which project/branch the work belonged to, and what should be carried into the next session.
+
+## Current OSB status
+- **Verdict**: present_weaker
+- **Local evidence**: Existing tasks cover session import, focus topics, handoff notes, pre-compaction decision capture, and session summary DAGs. I did not find a scoped `now`-style Brain document with version history, auto-derived workstream identity, and an explicit move/archive lifecycle for selected intention versions.
+- **Related existing work, not a duplicate**: a focus topic steers retrieval for one session; this task creates a durable, versioned intention chain that can be resumed, filtered, and moved into project history.
+
+## Proposal
+Add OSB-native current-intention chains under the Brain, with scoped IDs derived from project/worktree/branch or explicit operator scope. Provide CLI/MCP commands to read, update, list history, and move selected versions into a named note or session handoff.
+
+## Suggested design
+- Add `brain now` or equivalent MCP operations for get/set/history/move.
+- Store scoped chains as Markdown/YAML documents with version records or append-only sidecars.
+- Derive default scope from repository root and branch, with an explicit override for non-git work.
+- Surface current intention, previous intention, open loops, and related Brain items in context packs.
+- Support tag-filtered move so mixed sessions can split project-specific versions into separate histories.
+
+## Acceptance criteria
+- [ ] Agents can update a scoped current-intention chain without clobbering other workstreams.
+- [ ] Intention history is inspectable and searchable by time, scope, and tags.
+- [ ] Selected versions can be moved into a named Brain note while preserving provenance.
+- [ ] Session/context packs can include the active intention and recent intention history.
+- [ ] Tests cover auto-scope derivation, explicit scope override, move semantics, and mixed-project filtering.
+
+> Validator comment: osb-triage-validator @ 2026-06-03T10:05Z:
+- sanity: clean
+- cluster: no cluster
+- priority: set to 2: overriding origin-unknown priority 2 (no reprioritized event in history) - present_weaker, current-intention chains need design discussion before implementation.
+
+
+# Project context
+
+Open Second Brain - local-first second-brain memory layer for AI agents. TypeScript on Bun (plus a thin Python Hermes provider in plugins/hermes/provider.py). Storage: plain Markdown vault + SQLite (search index). MCP server over stdio JSON-RPC in src/mcp/.
+
+Recent commits:
+eda202d feat: Embedding Provider Suite - local embedder, provider registry, cost gate, RRF fusion (#67)
+dee5ab7 feat: Memory Integrity Suite - canonical entities, conflict-free log shards, capture boundaries, fact extraction (#66)
+5066e71 feat: Token Diet - budgeted injection, reminder cadence, consolidated MCP surface (#65)
+c494fd8 feat(search): Recall Trust Suite - relation polarity, learned weights, time-aware and verified recall (#64)
+23ff4fb refactor(hermes): single intentional self-bootstrap for the plugin entrypoint (#63)
+0952dfc feat: become a native Hermes memory provider (#62)
+6fbab0b feat: hands-off post-upgrade migration (v0.31.2) (#61)
+496dd2d fix: make plugin updates self-healing (v0.31.1) (#60)
+09c0592 chore(release): v0.31.0 (#59)
+b81335c Feat/procedural attention suite (#58)
+1f3a218 Feat/self learning skill proposals (#57)
+0162d13 feat(brain): add context continuity and receipts suite (#56)
+3b7b3a5 feat(brain): add safety governance foundations (#55)
+794ee45 feat(search): ship recall control and trust surfaces (#54)
+40d4e2b feat: cjk schema lifecycle recovery - CJK search, schema admin, lifecycle hooks, watchdog (#53)
+f62918c feat: runtime schema packs foundation - schema vocabulary, artifact taxonomy, schema inspection (#52)
+14d1ee1 feat: brain model semantics foundation - typed preference relations, memory labels, dry-run backfill (#51)
+3a5d5c3 feat: agent capability CLI integration - runtime MCP capabilities, inherited JSON, completions (#50)
+a085bfa feat: vault portability + session economy - codec, sources dashboard, vault-map tokens, multi-vault profiles, graph export/import (#49)
+73e4a28 feat: brain lifecycle suite - mutation audit, multi-phase dream, reconcile domains, morning brief, temporal extraction, heal enrichment (#48)
+
+Related files (verified current state):
+- src/mcp/tools.ts - buildToolTable(scope) assembles ToolDefinition[]; ToolScope = "full" | "writer"; ToolDefinition has optional `hidden` flag: hidden tools stay callable via tools/call but are omitted from tools/list (token-diet precedent, shipped v0.35.0).
+- src/mcp/capabilities.ts - evaluateToolCapabilities applies RuntimeCapabilityWindow {allowedTools, disabledTools, maxTools}; report lists available/withheld with reasons; second_brain_capabilities diagnostic tool always available.
+- src/mcp/server.ts - MCPServer constructor takes scope + capabilityWindow; handleToolsList filters hidden; instructions built per scope.
+- src/mcp/instructions.ts - per-scope initialize.instructions text.
+- skills/ - the repo ALREADY ships five agent skills as skills/<name>/SKILL.md (brain-memory, codegraph-partner, embeddings-setup, open-second-brain, schema-author). Ownership question from the task comments is resolved: Open Second Brain owns these plugin skills; list_skills/get_skill can serve them (plus optional vault-level skill roots).
+- plugins/hermes/provider.py - native Hermes memory provider; system_prompt_block() returns brain_context content; prefetch(query) gates recall via brain_recall_gate then calls brain_context_pack; all via bridge tool calls into the TS core.
+- src/core/brain/sessions/import.ts - ImportSessionOptions ALREADY has filterRoles + filterTextIncludes (per-call); what is missing is a config-level default (e.g. session_capture_roles in the vault config) applied by capture paths and the import CLI when no explicit flag is given.
+- src/core/brain/sessions/types.ts - SessionTurn.role: "user" | "assistant" | "system" | "tool" | "meta"; adapters: claude, codex, hermes.
+- src/core/search/session-focus.ts - search focus today is ONE global file (search-focus.json next to the index) with query/pathPrefix/expiresAt; ranker boost via scoreSessionFocusTarget; CLI o2b search focus set/status/clear; MCP brain_search focus_query/focus_path_prefix inputs (PR #54 foundation).
+- src/core/brain/pinned.ts - Brain/pinned.md scratchpad (read/write/append/clear) via brain_pinned_context tool - the closest existing surface to a "now" document, currently a single unversioned global file.
+- src/core/brain/context-pack.ts - budgeted context pack with lanes (directives/constraints/consider), tiers, receipts.
+- src/core/brain/session-lifecycle.ts - captureSessionLifecycleEvent invoked by hooks/session-capture.ts; hooks.json wires SessionStart, UserPromptSubmit, PostToolUse, Stop, SessionEnd events for Claude Code/Codex.
+- src/core/config.ts - parseSimpleYaml flat string config (_brain.yaml style); discoverConfig; resolveVault/resolveAgentName.
+- src/cli/command-manifest.ts - typed command tree for help/completions.
+- src/core/search/index.ts - resolveSearchConfig precedent for config key parsing with env overrides.
+
+Conventions:
+- Conventional commits; one feature per commit; TDD (failing test first).
+- bun test (3,379 tests), tsc typecheck, oxlint (baseline 111 warnings, must not grow), oxfmt.
+- Everything that could change existing behaviour ships off by default; defaults are bit-identical to the previous release.
+- Closed unions stay closed; new config keys are parsed fail-fast with SearchError/CliError; runtime surfaces fail soft (a broken optional file never crashes a session).
+- Deterministic logic preferred: no LLM in the loop for scoring/extraction (BM25-style lexical scoring, regex extraction are the house style).
+- No new external dependencies. Bun + node: builtins only.
+- MCP server is static per process: no listChanged notifications; the hidden-tool flag is the shipped mechanism for callable-but-not-advertised.
+
+Constraints:
+- Do not change existing public APIs or MCP tool contracts; additive only.
+- Hermes-host internals (~/.hermes/skills) are out of scope; skill surfaces serve the repo's own skills/ directory plus optional configured roots.
+- The eight units must share kernels where natural (e.g. one skill-discovery module feeding both list_skills/get_skill and auto-attach scoring; one session-scope concept feeding focus binding and handoff notes) - avoid eight disconnected mini-features.
+- Python provider changes minimal: call new TS tools over the existing bridge; no new Python logic beyond a tool call.
+
+# 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-surface-suite/design.md b/docs/brainstorm/agent-surface-suite/design.md
new file mode 100644
index 00000000..8a68d480
--- /dev/null
+++ b/docs/brainstorm/agent-surface-suite/design.md
@@ -0,0 +1,75 @@
+# Agent Surface Suite - adaptive tool catalog, skills over MCP, session lifecycle continuity
+
+**Status:** approved
+**Author:** claude-dev-agent (via feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+Open Second Brain's MCP surface keeps growing (Brain tools, search, schema admin, watchdog, pay-memory), and every connected agent pays the full schema list on every turn even when it needs three tools. At the same time the project ships five agent skills in `skills/` that MCP-connected agents cannot discover at all. On the session side, capture imports every turn role indiscriminately, search focus is one global file with no session binding, the current-task scratchpad (`Brain/pinned.md`) is a single unversioned global document, and a finished session leaves no operator-readable handoff artifact.
+
+## Scope
+
+Eight atomic units over two shared kernels.
+
+Kernel A - surface descriptor and scoring kernel (`src/core/surface/`):
+
+- `descriptor.ts` - one uniform `SurfaceDescriptor` record (kind `tool` | `skill`, name, one-line description, group, tags) built from `ToolDefinition[]` and from skill scans.
+- `lexical-score.ts` - one deterministic BM25-style scorer over descriptor fields (name boost, description, tags), no LLM, parameterised so tool-vs-skill tuning cannot drift.
+- `skills.ts` - skill discovery: scan the repo `skills/` root plus optional `<vault>/Brain/skills/`, parse `SKILL.md` (first `# heading` as title, first paragraph as description), path-traversal-guarded file access inside a skill directory.
+
+Theme A features on Kernel A:
+
+1. **Skills as MCP tools** (t_251c6490) - `list_skills` (names + descriptions + paths) and `get_skill` (SKILL.md content, optional `file_path` for auxiliary files inside the skill directory) in a new `src/mcp/skill-tools.ts`, registered in `buildToolTable`.
+2. **Two-pass tool catalog hydration** (t_e8011a89) - new `ToolScope` member `"catalog"`: `tools/list` advertises only the diagnostic tool, the writer five, and a new `tool_hydrate` tool; every other tool keeps `hidden: true` semantics (callable via `tools/call`, not advertised). `tool_hydrate` with no args returns the compact deterministic catalog (sorted descriptors); with `names: [...]` it returns the full `inputSchema`/`outputSchema` for the requested tools. This is the closest faithful mapping of upstream two-pass hydration onto a static-per-process MCP server (no `listChanged`).
+3. **Adaptive tool-surface profiles** (t_20dcb192) - named profiles in `src/mcp/profiles.ts` (`full`, `writer`, `catalog`, `recall`, `minimal`) each resolving to a scope plus a `RuntimeCapabilityWindow`; selected via config key `mcp_tool_profile` or `o2b mcp --tool-profile <name>`. Unknown profile fails OPEN to the full surface with a withheld-reason note in the capability report. Every non-full profile always retains `second_brain_capabilities` and `tool_hydrate` so the agent can discover and reach withheld tools instead of inventing substitutes (the upstream `request_full_tools` recovery contract, adapted to a static server).
+4. **Skill auto-attach** (t_10b86707) - `skill-attach.ts` scores skills against the current turn text with the Kernel A scorer and returns a token-budgeted block of top-k skill summaries. Exposed as MCP tool `skills_attach` (input: `query`, optional `max_skills`); gated by config key `skill_auto_attach` (default off -> `{enabled: false, block: ""}`). `plugins/hermes/provider.py` `prefetch()` adds one fail-soft bridge call to `skills_attach` and appends the returned block - the injection point the upstream plugin uses, with zero new Python logic.
+
+Kernel B - session-scope kernel (`src/core/brain/session-scope.ts`):
+
+- `resolveSessionScope(raw)` - normalise a session identifier or workstream label into a safe scope slug (lowercase, `[a-z0-9-]`, length-capped); shared by focus binding, intention chains, and handoff note naming.
+
+Theme B features on Kernel B:
+
+5. **Role-based capture filtering** (t_e2346fe9) - config key `session_capture_roles` (comma-separated subset of `user,assistant,system,tool,meta`; absent/empty = capture all, bit-identical). Parsed by a new `resolveSessionCaptureRoles(configPath)` in `src/core/config.ts`; the import CLI and the session-capture hook pass it as the `ImportSessionOptions.filterRoles` default when no explicit flag is given. Core `importSession` stays pure - the config read happens at the CLI/hook seam.
+6. **Operator-readable handoff notes** (t_28afa4d2) - `src/core/brain/handoff.ts`: `buildHandoffNote(turns, opts)` deterministically extracts Request (first user turn), Completed work, Files changed (paths in Write/Edit tool calls), Learned context (fact-shaped lines), and Next steps (next/todo/remaining-shaped lines) via regex - no LLM. Writes `Brain/handoffs/<date>-<scope>.md`. CLI verb `o2b brain handoff <session-file>` reuses the session adapters; the SessionEnd lifecycle path generates one automatically when config `session_handoff` is `true` (default off).
+7. **Session-scoped focus** (t_5b478e47) - `session-focus.ts` gains an optional scope: per-session focus files at `search-focus/<scope>.json` beside the global `search-focus.json`; session focus wins over global when both exist. `o2b search focus set|status|clear --session <id>`; MCP `brain_search` gains optional `focus_session` input. SessionEnd lifecycle capture auto-clears that session's focus file. Context-pack wiring: when config `search_focus_context_pack` is `true` (default off), `brain_context_pack` boosts candidates with `scoreSessionFocusTarget` using the active focus.
+8. **Scoped intention chains** (t_6d78f69e) - `src/core/brain/intentions.ts`: per-scope now-documents at `Brain/intentions/<scope>.md` with frontmatter (`scope`, `version`, `updated_at`) and an append-only `## History` trail of prior versions (timestamped one-liners); `move-to-history` retires a chain to `Brain/intentions/history/<scope>-<date>.md` and clears the active file. CLI `o2b brain intention set|show|list|move`; one consolidated MCP tool `brain_intention` (operation: `set` | `show` | `list` | `move`) mirroring the `brain_pinned_context` pattern. `Brain/pinned.md` stays untouched as the scope-free default.
+
+## Out of scope
+
+- Hermes-host skill directories (`~/.hermes/skills/`) - the skill surface serves only the repo `skills/` root and the optional vault root.
+- Live per-turn re-advertising of MCP tools (`listChanged`) - the server stays static per process; hydration returns schemas as data.
+- LLM-based scoring, classification, or summarisation anywhere in the suite.
+- Embedding-based skill relevance (the BM25-style scorer is the deliberate v1; an embedding lane can register later).
+- Per-session binding for `Brain/pinned.md` (intention chains are the scoped surface; pinned stays global).
+- Watching live transcripts (anticipatory cache, t_4cee9df5) - separate task.
+
+## Chosen approach
+
+Consultant Variant 1 (two theme kernels), accepted without override. One catalog/scoring kernel feeds two-pass hydration, the skill tools, auto-attach, and the profile selector, so descriptors and relevance scoring cannot drift between features. One session-scope kernel gives focus binding, intention chains, and handoff naming the same identifier semantics. The kernels stay decoupled across the theme boundary; each of the eight units remains independently testable and off by default.
+
+## Design decisions
+
+- **`hidden` flag is the hydration substrate** - the v0.35.0 token-diet mechanism (callable but unadvertised) already implements "schema not in the prompt until requested"; the catalog scope reuses it instead of inventing a second visibility channel.
+- **Unknown profile fails open** - upstream Tool Slimmer fails open to the original schema list on selector errors; a typo in `mcp_tool_profile` must degrade to the full surface (with a report entry), never lock an agent out.
+- **`skills_attach` gates inside the tool, not in Python** - the Hermes provider always makes the (fail-soft) call; the TS side returns an empty block unless `skill_auto_attach` is on. The Python diff stays at one call, and the default Hermes injection is bit-identical.
+- **Config reads stay at the seams** - `importSession` and `buildHandoffNote` stay pure; CLI verbs and lifecycle hooks resolve config and pass plain options. This keeps the core testable without config fixtures.
+- **Session focus wins over global** - a bound session focus is more specific; merging would average two intents. Absent a session file the global file applies, so PR #54 behaviour is unchanged.
+- **Intention history is in-file then archived** - the active chain keeps a short timestamped trail (cheap diffing, single read); `move` archives the whole document. No SQLite involvement - intentions are operator-readable Markdown first.
+- **One consolidated `brain_intention` tool** - four CLI verbs collapse to one MCP tool with an `operation` input, matching `brain_pinned_context` and respecting the token diet.
+
+## File changes
+
+New (src): `src/core/surface/descriptor.ts`, `src/core/surface/lexical-score.ts`, `src/core/surface/skills.ts`, `src/core/surface/skill-attach.ts`, `src/mcp/skill-tools.ts`, `src/mcp/hydrate-tool.ts`, `src/mcp/profiles.ts`, `src/core/brain/session-scope.ts`, `src/core/brain/handoff.ts`, `src/core/brain/intentions.ts`.
+
+Modified (src): `src/mcp/tools.ts` (register skill/hydrate tools, `ToolScope` + `"catalog"`), `src/mcp/server.ts` (catalog advertising), `src/mcp/instructions.ts` (catalog-scope instructions), `src/cli/main.ts` (`--tool-profile`), `src/core/config.ts` (`resolveSessionCaptureRoles`, `resolveBoolFlag` helpers), `src/core/search/session-focus.ts` (scoped files), `src/core/search/search.ts` + `src/cli/search.ts` (`--session`), `src/mcp/search-tools.ts` (`focus_session`), `src/core/brain/context-pack.ts` (gated focus boost), `src/core/brain/session-lifecycle.ts` (SessionEnd: focus auto-clear + gated handoff), `src/cli/brain.ts` (handoff + intention verbs), `src/mcp/brain-tools.ts` (`brain_intention`), `src/cli/command-manifest.ts`, `plugins/hermes/provider.py` (one `skills_attach` call).
+
+New (tests): one suite per new module plus `tests/integration/agent-surface.integration.test.ts`.
+
+## Risks and open questions
+
+- **Catalog scope vs existing clients** - a client configured with `--tool-profile catalog` sees five advertised tools; agents unaware of `tool_hydrate` may under-use the Brain. Mitigation: catalog-scope `initialize.instructions` explain the hydration contract explicitly.
+- **`brain_search` input growth** - `focus_session` is one optional string; the schema cost is small but real. Accepted: session focus without a search-side key would be unreachable over MCP.
+- **Handoff extraction quality** - regex extraction will miss prose-shaped facts; acceptable for v1 (the note links the session file for full fidelity).
+- **SKILL.md heterogeneity** - descriptions derive from the first paragraph; a skill without one degrades to an empty description (never a crash).
diff --git a/docs/brainstorm/agent-surface-suite/plan.md b/docs/brainstorm/agent-surface-suite/plan.md
new file mode 100644
index 00000000..ebae8510
--- /dev/null
+++ b/docs/brainstorm/agent-surface-suite/plan.md
@@ -0,0 +1,63 @@
+# Agent Surface Suite - implementation plan
+
+## Tasks
+
+### Task 1: Kernel A - surface descriptors and lexical scorer
+- **Files**: `src/core/surface/descriptor.ts`, `src/core/surface/lexical-score.ts`, `tests/core/surface/descriptor.test.ts`, `tests/core/surface/lexical-score.test.ts`
+- **Acceptance**: `SurfaceDescriptor` builds deterministically (sorted) from `ToolDefinition[]`; BM25-style scorer ranks descriptors for a query with name-field boost; empty query / empty corpus return empty rankings; scoring is pure and reproducible.
+- **Depends on**: none
+
+### Task 2: Skill discovery module
+- **Files**: `src/core/surface/skills.ts`, `tests/core/surface/skills.test.ts`
+- **Acceptance**: scans repo `skills/` plus optional `<vault>/Brain/skills/`; parses SKILL.md title + first-paragraph description; missing/empty roots yield `[]` (fail-soft); `readSkillFile` rejects path traversal and absolute paths.
+- **Depends on**: Task 1 (descriptor shape)
+
+### Task 3: list_skills / get_skill MCP tools (t_251c6490)
+- **Files**: `src/mcp/skill-tools.ts`, `src/mcp/tools.ts`, `tests/mcp/skill-tools.test.ts`
+- **Acceptance**: `list_skills` returns name/description/path for repo skills; `get_skill` returns SKILL.md content, optional `file_path` reads auxiliary files inside the skill dir only; unknown skill -> tool error; registered in `buildToolTable` and visible in `tools/list`.
+- **Depends on**: Task 2
+
+### Task 4: Two-pass tool catalog hydration (t_e8011a89)
+- **Files**: `src/mcp/hydrate-tool.ts`, `src/mcp/tools.ts` (`ToolScope` + `"catalog"`), `src/mcp/server.ts`, `src/mcp/instructions.ts`, `tests/mcp/catalog-scope.test.ts`
+- **Acceptance**: scope `"catalog"`: `tools/list` advertises diagnostic + writer five + `tool_hydrate` only; every other tool remains callable via `tools/call`; `tool_hydrate` (no args) returns the sorted compact catalog; `tool_hydrate {names}` returns full schemas; unknown names reported per-name without failing the batch; `full`/`writer` scopes byte-identical to before.
+- **Depends on**: Task 1
+
+### Task 5: Adaptive tool-surface profiles (t_20dcb192)
+- **Files**: `src/mcp/profiles.ts`, `src/cli/main.ts` (`--tool-profile`), `src/core/config.ts` (`mcp_tool_profile`), `tests/mcp/profiles.test.ts`
+- **Acceptance**: named profiles full/writer/catalog/recall/minimal resolve to scope + capability window; unknown profile fails OPEN to full with a capability-report note; every non-full profile retains `second_brain_capabilities` + `tool_hydrate`; flag wins over config key; default (no key, no flag) bit-identical to today.
+- **Depends on**: Task 4
+
+### Task 6: Skill auto-attach (t_10b86707)
+- **Files**: `src/core/surface/skill-attach.ts`, `src/mcp/skill-tools.ts` (`skills_attach`), `src/core/config.ts` (`skill_auto_attach`), `plugins/hermes/provider.py`, `tests/core/surface/skill-attach.test.ts`, `tests/mcp/skills-attach-tool.test.ts`
+- **Acceptance**: scorer returns top-k skills over threshold within a token budget; `skills_attach` returns `{enabled:false, block:""}` when config off (default); enabled path returns deterministic block with skill names + descriptions + paths; provider.py prefetch appends the block fail-soft (Python diff is one call).
+- **Depends on**: Tasks 1, 2, 3
+
+### Task 7: Kernel B - session-scope resolver
+- **Files**: `src/core/brain/session-scope.ts`, `tests/core/brain/session-scope.test.ts`
+- **Acceptance**: `resolveSessionScope` normalises arbitrary session ids / workstream labels to `[a-z0-9-]` slugs, length-capped, deterministic; rejects empty input with a typed error.
+- **Depends on**: none
+
+### Task 8: Role-based capture filtering (t_e2346fe9)
+- **Files**: `src/core/config.ts` (`resolveSessionCaptureRoles`), `src/cli/brain.ts` / `src/cli/brain/` import-session verb, `src/core/brain/session-lifecycle.ts`, `tests/core/config.capture-roles.test.ts`, `tests/cli/import-session-roles.test.ts`
+- **Acceptance**: `session_capture_roles: "user,assistant"` filters import when no explicit flag; explicit `--filter-roles` flag wins; absent/empty key captures all roles (bit-identical); invalid role name -> fail-fast config error.
+- **Depends on**: none
+
+### Task 9: Session-scoped focus (t_5b478e47)
+- **Files**: `src/core/search/session-focus.ts`, `src/cli/search.ts` (`--session`), `src/mcp/search-tools.ts` (`focus_session`), `src/core/brain/context-pack.ts` (gated boost), `src/core/brain/session-lifecycle.ts` (auto-clear), `src/core/config.ts` (`search_focus_context_pack`), `tests/core/search/session-focus-scoped.test.ts`, `tests/core/brain/context-pack-focus.test.ts`
+- **Acceptance**: per-session focus file `search-focus/<scope>.json`; session focus wins over global; `focus set/status/clear --session` round-trips; SessionEnd lifecycle event clears the matching session focus; context-pack boost only when `search_focus_context_pack: "true"` (default off, pack byte-identical).
+- **Depends on**: Task 7
+
+### Task 10: Operator-readable handoff notes (t_28afa4d2)
+- **Files**: `src/core/brain/handoff.ts`, `src/cli/brain.ts` (`handoff` verb), `src/core/brain/session-lifecycle.ts` (gated SessionEnd generation), `src/core/config.ts` (`session_handoff`), `tests/core/brain/handoff.test.ts`
+- **Acceptance**: `buildHandoffNote` extracts request / completed work / files changed / learned context / next steps from `SessionTurn[]` by regex; writes `Brain/handoffs/<date>-<scope>.md`; CLI verb works on a real session fixture via the adapters; SessionEnd generation only when `session_handoff: "true"` (default off).
+- **Depends on**: Task 7
+
+### Task 11: Scoped intention chains (t_6d78f69e)
+- **Files**: `src/core/brain/intentions.ts`, `src/cli/brain.ts` (`intention` verb), `src/mcp/brain-tools.ts` (`brain_intention`), `src/cli/command-manifest.ts`, `tests/core/brain/intentions.test.ts`, `tests/mcp/brain-intention-tool.test.ts`
+- **Acceptance**: `set` creates/updates `Brain/intentions/<scope>.md` bumping `version` and appending a timestamped history line; `show`/`list` read; `move` archives to `Brain/intentions/history/<scope>-<date>.md` and removes the active file; MCP tool mirrors all four operations; `Brain/pinned.md` untouched.
+- **Depends on**: Task 7
+
+### Task 12: Integration test + command manifest + docs surface
+- **Files**: `tests/integration/agent-surface.integration.test.ts`, `src/cli/command-manifest.ts` (final entries)
+- **Acceptance**: one flow exercises catalog profile (`tools/list` small, hydrate, call hidden tool), `list_skills`/`skills_attach` on the real repo `skills/`, scoped focus + intention + handoff on a temp vault; full suite green.
+- **Depends on**: Tasks 1-11
diff --git a/docs/brainstorm/agent-surface-suite/variants.md b/docs/brainstorm/agent-surface-suite/variants.md
new file mode 100644
index 00000000..19796da6
--- /dev/null
+++ b/docs/brainstorm/agent-surface-suite/variants.md
@@ -0,0 +1,101 @@
+# Agent Surface Suite - brainstorm audit trail
+
+Consultant: Claude Code (`claude -p`), single pass, 2026-06-03. Prompt and raw
+output live in `cli-output/`. Three variants were requested for the epic as a
+whole (eight units, two themes); the consultant also returned exactly one
+recommendation.
+
+## Variant 1: Two theme kernels (catalog kernel + session-scope kernel)
+
+- **Approach**: Build exactly two shared modules. A catalog/scoring kernel
+ emits uniform descriptor records (name, one-line desc, group/toolset, tags,
+ checksum) over both MCP tools and `skills/` entries, plus one deterministic
+ BM25 scorer; it feeds two-pass hydration, `list_skills`/`get_skill`, skill
+ auto-attach, and the adaptive tool-surface selector. A session-scope kernel
+ owns a session-id-keyed scope record with lifecycle hooks; it feeds
+ role-filtered capture, handoff notes, per-session focus binding, and
+ intention chains. The two kernels stay decoupled across the theme boundary.
+- **Trade-offs**:
+ - Pro: honors the "share kernels where natural" constraint with one kernel
+ per theme - no eight disconnected features, no single god-module.
+ - Pro: tool-surface work stays request-local (compatible with the
+ static-per-process MCP server and the hidden-tool precedent); session
+ state is isolated and fail-soft.
+ - Pro: the two kernels are independently testable and parallelizable across
+ the PR's eight units.
+ - Con: tool descriptors vs skill descriptors must be reconciled into one
+ schema, which is some up-front design tax.
+ - Con: BM25 scorer is reused for two different inputs (turn-vs-tool,
+ turn-vs-skill), risking subtle tuning divergence if not parameterized
+ cleanly.
+- **Complexity**: medium
+- **Risk**: low
+
+## Variant 2: Unified per-session context spine
+
+- **Approach**: Make a single `SessionContext` object the backbone for all
+ eight units, keyed by session id and surfaced through the existing provider
+ `system_prompt_block()` / `brain_context_pack`. Tool-surface profiles, skill
+ auto-attach, focus, intention chain, capture filter, and handoff all read
+ and write that one per-session state, so a turn's advertised tools, injected
+ skills, and recalled memory are decided in one place.
+- **Trade-offs**:
+ - Pro: maximal coherence - focus, intention, skills, and tool surface all
+ flow through one injection point with consistent token budgeting.
+ - Pro: per-session binding (focus, intention) gets a natural home and clean
+ auto-clear on session end.
+ - Con: forces request-local, stateless Theme A work (which the static MCP
+ server cannot vary per session anyway - no `listChanged`) into a
+ session-stateful frame it does not fit; tool-surface adaptation would be
+ misleadingly "session-bound."
+ - Con: a central spine touched by all eight units is a merge-and-regression
+ hotspot and contradicts the "everything off by default, bit-identical
+ defaults" guarantee being easy to prove per-unit.
+ - Con: highest blast radius if the shared object misbehaves.
+- **Complexity**: large
+- **Risk**: high
+
+## Variant 3: Thin additive layers over existing surfaces
+
+- **Approach**: Ship each unit as a minimal independent layer on what already
+ exists - a `session_capture_roles` config key, `list_skills`/`get_skill`
+ reading `skills/`, auto-attach as a new context-pack lane, the tool-surface
+ selector as a dry-run/advisor first using the hidden-tool flag, handoff as a
+ CLI+Stop-hook artifact, per-session focus as extra keys on
+ `session-focus.json`, intention as a versioned sibling of `pinned.ts`. Share
+ only two trivial utilities: a scoped-session-id resolver and one lexical
+ scorer, used opportunistically rather than as mandatory kernels.
+- **Trade-offs**:
+ - Pro: lowest risk, fastest to land, cleanest match to house style
+ (additive, fail-soft, off by default, easy per-unit defaults proof).
+ - Pro: defers the riskiest piece (active per-turn tool filtering) behind a
+ dry-run advisor, which the static server constraint favors anyway.
+ - Con: weakest on the "avoid eight disconnected mini-features" constraint -
+ sharing is incidental, so skill discovery could be implemented twice (once
+ for `get_skill`, once for auto-attach).
+ - Con: descriptor metadata and scoring logic risk duplication and drift
+ across units.
+- **Complexity**: small
+- **Risk**: low
+
+## Consultant recommendation
+
+Variant 1. "It is the only option that directly satisfies the epic's explicit
+'share kernels where natural' instruction - one skill/tool catalog+scorer, one
+session-scope concept - without the over-coupling of Variant 2, which fights
+the static-per-process MCP server and the off-by-default guarantee by forcing
+request-local tool work into session state. Compared to Variant 3 it avoids
+duplicating skill discovery and scoring across units while staying within the
+same additive, fail-soft, deterministic constraints, and its two-kernel split
+cleanly mirrors the two themes so the eight units remain independently
+testable and parallelizable."
+
+## Orchestrator decision
+
+Variant 1, accepted as recommended (no override). Two refinements applied in
+the design doc: (a) the descriptor checksum field is deferred - the static
+server has no live-schema snapshot to verify against, so the checksum carries
+no information yet; (b) Variant 3's "fail open on unknown profile" idea is
+folded into the profile selector, since the upstream Tool Slimmer contract
+fails open on selector errors and that matches the project's fail-soft
+runtime convention.
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index cb191dd5..a37b364a 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -15,7 +15,7 @@ o2b doctor Run vault + adapter checks
o2b index Rebuild the Markdown page index
o2b export-config Write a redacted config snapshot
o2b secrets list|status Inspect $secret:NAME references without printing values
-o2b mcp Run the MCP tool server (stdio); --scope full|writer, --probe, --allow-tool, --disable-tool, --max-tools
+o2b mcp Run the MCP tool server (stdio); --scope full|writer|catalog, --tool-profile full|writer|catalog|recall|minimal, --probe, --allow-tool, --disable-tool, --max-tools
o2b tool-call Invoke an MCP tool handler from the CLI
o2b help --json Print the command/flag manifest as JSON
o2b completions --shell zsh Print completions for bash|zsh|fish|elvish|nushell|powershell
@@ -113,6 +113,8 @@ o2b brain import-session <path> --recall [--recall-session-id <id>] [--reca
o2b brain session-grep --query <text> [--session-id <id>] [--limit <n>] [--snippet-chars <n>] [--json]
o2b brain session-describe --session-id <id> [--json]
o2b brain session-expand <record-id> [--raw-limit <n>] [--cursor <offset>] [--json]
+o2b brain handoff <session-file> [--session-id <id>] [--format auto|claude|codex|hermes] [--json] - write Brain/handoffs/<date>-<scope>.md (since v0.37.0)
+o2b brain intention set|show|list|move [--scope S] [--text T] [--json] - scoped current-intention chains under Brain/intentions/ (since v0.37.0)
```
Receipts, telemetry, transforms, and session recall import are opt-in. Receipt and telemetry records store redaction-safe payloads, source references, hashes, counters, and bounded snippets rather than raw private prompt context; session recall stores redacted turn text only when explicitly imported for later expansion.
@@ -176,9 +178,9 @@ o2b search feedback Record explicit recall feedback for one result
under Brain/search/feedback/, learned weights refresh deterministically)
o2b search weights Show base weights, learned multipliers, event count, and bounds
--reset removes the derived learned-weights file (events kept)
-o2b search focus set Persist a 120-minute ranking focus (--query Q and/or --path P; --ttl-minutes N)
+o2b search focus set Persist a 120-minute ranking focus (--query Q and/or --path P; --ttl-minutes N; --session S binds it to one session, since v0.37.0)
o2b search focus status Show the active focus; --json emits { active, focus }
-o2b search focus clear Clear the persisted focus file next to the search index
+o2b search focus clear Clear the persisted focus file next to the search index (--session S clears one session's focus)
o2b search reindex Rebuild the SQLite + FTS5 index from scratch
(required after upgrading to v0.13.0 recall schema or v0.26.0 CJK FTS content)
--force-cost bypasses the embedding cost gate for this run (since v0.36.0)
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index 169f1e84..4ac6ab7d 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -199,6 +199,26 @@ Four independent paths land a signal in `Brain/inbox/`:
- **Session import** - `o2b brain import-session <path>` reads a Claude Code / Codex CLI / Hermes session JSONL and extracts both `@osb` markers from message text and replays of `brain_feedback` tool-use calls. Useful when MCP was not available at recording time or the agent did not make the call live.
- **Lifecycle hook** - Claude Code / Codex hooks call `o2b brain session-hook` through `hooks/session-capture.ts`. `UserPromptSubmit` prompt markers and `PostToolUse` `brain_feedback` inputs are captured immediately through the same signal dedup hash, while SessionStart / Stop / SessionEnd / PostCompact observations append non-blocking lifecycle audit/log rows.
+Session capture is role-filterable (since v0.37.0): `session_capture_roles`
+in the config (comma-separated subset of `user,assistant,system,tool,meta`)
+supplies the default `--filter-role` set for `brain import-session`; an
+explicit flag wins, an absent key captures every role, and an unknown role
+name fails fast.
+
+SessionEnd carries two more lifecycle duties (since v0.37.0). It clears the
+ending session's bound search focus (`search-focus/<scope>.json`) so a
+finished session's steering never leaks into the next one - cleanup runs
+regardless of the capture boundary. And when `session_handoff` is `"true"`
+(default off), it writes an operator-readable handoff note to
+`Brain/handoffs/<date>-<scope>.md` - request, completed work, changed files,
+learned context, next steps - extracted from the recorded transcript by
+deterministic regex (`o2b brain handoff <session-file>` is the manual
+equivalent). Alongside the scope-free `Brain/pinned.md` scratchpad, scoped
+current-intention chains live at `Brain/intentions/<scope>.md`
+(`o2b brain intention set|show|list|move`, MCP `brain_intention`): every
+update bumps `version` and appends the superseded text to an in-file history
+trail, and `move` retires the chain into `Brain/intentions/history/`.
+
All four paths share a normalised payload hash so the same rule captured twice from different surfaces dedups automatically. Pinned preferences are exempt from automatic retire (`stale-no-evidence`, `expired-unconfirmed`, `rebutted`); only `o2b brain reject` can retire them.
`o2b brain watchdog` is the recovery surface for this layout. It checks the
diff --git a/docs/mcp.md b/docs/mcp.md
index aefbdb83..08113b09 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -233,6 +233,47 @@ tool counts, an `available[]` list, and a `withheld[]` list. Withheld reasons
are stable strings such as `disabled by runtime capability window`, `not allowed
by runtime capability window`, and `outside runtime capability max tool window`.
+## Tool-surface profiles and the two-pass catalog (since v0.37.0)
+
+Named profiles bundle a scope plus capability window so hosts stop
+hand-rolling allow/deny flag lists:
+
+```bash
+o2b mcp --vault /path/to/vault --tool-profile catalog
+o2b mcp --vault /path/to/vault --tool-profile recall --probe
+```
+
+Profiles: `full` (default), `writer`, `catalog`, `recall` (memory
+read/write surface, no admin tools), and `minimal` (writers + context +
+search). The `mcp_tool_profile` config key (env:
+`OPEN_SECOND_BRAIN_MCP_TOOL_PROFILE`) selects one without flags; an
+explicit `--scope` or window flag wins over the profile's fields. An
+unknown profile name FAILS OPEN to the full surface with a stderr note -
+a typo can never lock an agent out. Hard-window profiles always retain
+`second_brain_capabilities`, so withheld tools stay discoverable with
+reasons.
+
+The `catalog` scope is the two-pass surface: `tools/list` advertises
+only the capability diagnostic, the five always-loaded Brain tools, and
+`tool_hydrate`; every other tool stays callable through `tools/call`.
+Call `tool_hydrate` with no arguments for the compact catalog (name,
+one-line description, group), then with `names: [...]` for the full
+input/output schemas of exactly the tools you need - unknown names are
+reported per-name without failing the batch.
+
+## Skill surface (since v0.37.0)
+
+`list_skills` returns the agent skills shipped in the plugin's
+`skills/` directory plus vault-local `Brain/skills/` (vault entries
+shadow shipped ones by name). `get_skill` fetches a skill's SKILL.md by
+name; an optional `file_path` reads an auxiliary file and is
+path-traversal-guarded to the skill directory. `skills_attach` scores
+skills against the current turn text with a deterministic BM25-style
+scorer and returns a char-budgeted block of top matches; it returns
+`enabled: false` with an empty block unless the `skill_auto_attach`
+config key is `"true"`, so default per-turn injection is unchanged. The
+native Hermes provider calls it from `prefetch()` fail-soft.
+
## Hermes integration
Hermes discovers MCP servers from `~/.hermes/config.yaml` under the
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 1dca35c4..2511c74a 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.36.0",
+ "version": "0.37.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index a1f967ce..bcfcefb4 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.36.0",
+ "version": "0.37.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 963c149c..5078d54c 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.36.0"
+version: "0.37.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index c17f4a6f..5e9fafb9 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.36.0",
+ "version": "0.37.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 963c149c..5078d54c 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.36.0"
+version: "0.37.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/hermes/provider.py b/plugins/hermes/provider.py
index 0e775af3..b799cfa5 100644
--- a/plugins/hermes/provider.py
+++ b/plugins/hermes/provider.py
@@ -177,6 +177,14 @@ class OpenSecondBrainMemoryProvider(MemoryProvider):
recalled = self._text(pack)
if recalled:
parts.append(recalled)
+ # Skill auto-attach (Agent Surface Suite): the TS side gates on the
+ # skill_auto_attach config key and returns an empty block when off,
+ # so the default injection stays byte-identical. Fail-soft like every
+ # other lifecycle bridge call.
+ attach = self._structured(self._safe_call("skills_attach", {"query": query}))
+ skills_block = str(attach.get("block", "") or "")
+ if attach.get("enabled") and skills_block:
+ parts.append(skills_block)
reminder = config.build_reminder()
if reminder:
parts.append(reminder)
diff --git a/pyproject.toml b/pyproject.toml
index a45e5e4a..ee6d295d 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.36.0"
+version = "0.37.0"
description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/src/cli/brain.ts b/src/cli/brain.ts
index 6f02f8bf..9c1ba0e1 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -50,6 +50,8 @@ import {
cmdBrainScanInline,
cmdBrainEntity,
cmdBrainImportSession,
+ cmdBrainHandoff,
+ cmdBrainIntention,
cmdBrainSessionHook,
cmdBrainImportClaudeMemory,
cmdBrainPageDedup,
@@ -172,6 +174,10 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promis
return await cmdBrainScanInline(rest);
case "import-session":
return await cmdBrainImportSession(rest);
+ case "handoff":
+ return await cmdBrainHandoff(rest);
+ case "intention":
+ return await cmdBrainIntention(rest);
case "entity":
return await cmdBrainEntity(rest);
case "session-hook":
diff --git a/src/cli/brain/verbs/handoff.ts b/src/cli/brain/verbs/handoff.ts
new file mode 100644
index 00000000..cc39d4e1
--- /dev/null
+++ b/src/cli/brain/verbs/handoff.ts
@@ -0,0 +1,66 @@
+/**
+ * `o2b brain handoff <session-file>` (Agent Surface Suite, t_28afa4d2):
+ * render an operator-readable handoff note from a recorded session.
+ */
+
+import { existsSync, readFileSync } from "node:fs";
+import { basename } from "node:path";
+
+import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import { writeHandoffNote } from "../../../core/brain/handoff.ts";
+import {
+ detectAdapter,
+ getAdapter,
+ isSessionAdapterId,
+} from "../../../core/brain/sessions/registry.ts";
+import type { SessionTurn } from "../../../core/brain/sessions/types.ts";
+import { fail, normalizeFlagString, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainHandoff(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ format: { type: "string" },
+ "session-id": { type: "string" },
+ agent: { type: "string" },
+ json: { type: "boolean" },
+ });
+ if (positional.length < 1) return fail("brain handoff requires a <session-file> argument");
+ const sessionPath = positional[0]!;
+ if (!existsSync(sessionPath)) return fail(`session file does not exist: ${sessionPath}`);
+
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const agent = normalizeFlagString(flags["agent"]) ?? resolveAgentName(config);
+ const sessionId = normalizeFlagString(flags["session-id"]) ?? basename(sessionPath);
+
+ // CLI error boundary: read/parse/write failures land as fail(...)
+ // (controlled exit), never an uncaught exception.
+ try {
+ const formatRaw = flags["format"] as string | undefined;
+ let adapter;
+ if (formatRaw !== undefined && formatRaw !== "auto") {
+ if (!isSessionAdapterId(formatRaw)) return fail(`unknown --format: ${formatRaw}`);
+ adapter = getAdapter(formatRaw);
+ } else {
+ const text = readFileSync(sessionPath, "utf8");
+ const nl = text.indexOf("\n");
+ adapter = detectAdapter(nl < 0 ? text : text.slice(0, nl));
+ if (adapter === null) {
+ return fail(`could not autodetect session format for ${sessionPath}; pass --format`);
+ }
+ }
+
+ const turns: SessionTurn[] = [];
+ for await (const turn of adapter.iterate(sessionPath)) turns.push(turn);
+
+ const result = writeHandoffNote(vault, { turns, sessionId, agent });
+ if (flags["json"]) {
+ okJson({ ok: true, path: result.path, scope: result.scope, turns: turns.length });
+ return 0;
+ }
+ ok(`handoff note written: ${result.path} (${turns.length} turns)`);
+ return 0;
+ } catch (err) {
+ return fail((err as Error).message ?? String(err));
+ }
+}
diff --git a/src/cli/brain/verbs/import-session.ts b/src/cli/brain/verbs/import-session.ts
index 8a392423..fa760e5d 100644
--- a/src/cli/brain/verbs/import-session.ts
+++ b/src/cli/brain/verbs/import-session.ts
@@ -1,5 +1,9 @@
import { statSync } from "node:fs";
-import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import {
+ defaultConfigPath,
+ resolveAgentName,
+ resolveSessionCaptureRoles,
+} from "../../../core/config.ts";
import { importSession, importSessionPath } from "../../../core/brain/sessions/import.ts";
import { SessionImportError, type SessionAdapterId } from "../../../core/brain/sessions/types.ts";
import {
@@ -54,7 +58,17 @@ export async function cmdBrainImportSession(argv: string[]): Promise<number> {
"--recall-summary-group-size",
);
const ingestScope = normalizeFlagString(flags["ingest-scope"] as string | undefined);
- const filterRoles = normalizeRoleFilter(flags["filter-role"] as string[] | undefined);
+ const explicitRoles = normalizeRoleFilter(flags["filter-role"] as string[] | undefined);
+ // Config-level default (t_e2346fe9): session_capture_roles applies
+ // only when no explicit --filter-role flag is given; flag wins.
+ let filterRoles = explicitRoles;
+ if (explicitRoles.length === 0) {
+ try {
+ filterRoles = resolveSessionCaptureRoles(config) ?? [];
+ } catch (err) {
+ return fail((err as Error).message);
+ }
+ }
const filterText = normalizeFlagString(flags["filter-text"] as string | undefined);
const formatRaw = flags["format"] as string | undefined;
diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.ts
index efb61af7..db82b1cb 100644
--- a/src/cli/brain/verbs/index.ts
+++ b/src/cli/brain/verbs/index.ts
@@ -36,6 +36,8 @@ export { cmdBrainUpgrade } from "./upgrade.ts";
export { cmdBrainSnapshotDiff, handleBrainSnapshotSubcommand } from "./snapshot.ts";
export { cmdBrainScanInline } from "./scan-inline.ts";
export { cmdBrainImportSession } from "./import-session.ts";
+export { cmdBrainHandoff } from "./handoff.ts";
+export { cmdBrainIntention } from "./intention.ts";
export { cmdBrainEntity } from "./entity.ts";
export { cmdBrainSessionHook } from "./session-hook.ts";
export { cmdBrainImportClaudeMemory } from "./import-claude-memory.ts";
diff --git a/src/cli/brain/verbs/intention.ts b/src/cli/brain/verbs/intention.ts
new file mode 100644
index 00000000..07d19579
--- /dev/null
+++ b/src/cli/brain/verbs/intention.ts
@@ -0,0 +1,102 @@
+/**
+ * `o2b brain intention <set|show|list|move>` (Agent Surface Suite,
+ * t_6d78f69e): scoped current-intention chains with a move-to-history
+ * lifecycle.
+ */
+
+import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import {
+ listIntentions,
+ moveIntentionToHistory,
+ setIntention,
+ showIntention,
+} from "../../../core/brain/intentions.ts";
+import { fail, normalizeFlagString, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainIntention(argv: string[]): Promise<number> {
+ const action = argv[0];
+ if (!action || !["set", "show", "list", "move"].includes(action)) {
+ return fail("usage: o2b brain intention <set|show|list|move> [--scope S] [--text T]");
+ }
+ const { flags } = parse(argv.slice(1), {
+ vault: { type: "string" },
+ scope: { type: "string" },
+ text: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const scope = normalizeFlagString(flags["scope"]);
+ const json = flags["json"] === true;
+
+ if (action === "list") {
+ let intentions;
+ try {
+ intentions = listIntentions(vault);
+ } catch (err) {
+ return fail((err as Error).message ?? String(err));
+ }
+ if (json) {
+ okJson({
+ ok: true,
+ intentions: intentions.map((c) => ({
+ scope: c.scope,
+ version: c.version,
+ updated_at: c.updatedAt,
+ text: c.text,
+ })),
+ });
+ return 0;
+ }
+ if (intentions.length === 0) {
+ ok("no active intentions");
+ return 0;
+ }
+ for (const c of intentions) ok(`${c.scope} v${c.version} (${c.updatedAt}): ${c.text}`);
+ return 0;
+ }
+
+ if (scope === null) return fail(`brain intention ${action} requires --scope`);
+
+ try {
+ if (action === "set") {
+ const text = normalizeFlagString(flags["text"]);
+ if (text === null) return fail("brain intention set requires --text");
+ const chain = setIntention(vault, { scope, text, agent: resolveAgentName(config) });
+ if (json) okJson({ ok: true, scope: chain.scope, version: chain.version, path: chain.path });
+ else ok(`intention ${chain.scope} v${chain.version}: ${chain.text}`);
+ return 0;
+ }
+ if (action === "show") {
+ const chain = showIntention(vault, scope);
+ if (chain === null) {
+ if (json) okJson({ ok: true, present: false, scope });
+ else ok(`no active intention for scope: ${scope}`);
+ return 0;
+ }
+ if (json) {
+ okJson({
+ ok: true,
+ present: true,
+ scope: chain.scope,
+ version: chain.version,
+ updated_at: chain.updatedAt,
+ text: chain.text,
+ history: chain.history,
+ path: chain.path,
+ });
+ } else {
+ ok(`${chain.scope} v${chain.version} (${chain.updatedAt}): ${chain.text}`);
+ for (const line of chain.history) ok(` history: ${line}`);
+ }
+ return 0;
+ }
+ // move
+ const moved = moveIntentionToHistory(vault, { scope });
+ if (json) okJson({ ok: true, scope: moved.scope, archive_path: moved.archivePath });
+ else ok(`intention ${moved.scope} moved to history: ${moved.archivePath}`);
+ return 0;
+ } catch (err) {
+ return fail((err as Error).message);
+ }
+}
diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.ts
index 71bb1104..d839c37e 100644
--- a/src/cli/command-manifest.ts
+++ b/src/cli/command-manifest.ts
@@ -55,6 +55,7 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
flag("repo", "string"),
flag("scope", "string"),
flag("writer-only", "boolean"),
+ flag("tool-profile", "string"),
flag("probe", "boolean"),
flag("allow-tool", "string-array"),
flag("disable-tool", "string-array"),
@@ -149,6 +150,8 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
command("mcp-landscape", "List MCP servers configured across the vault"),
command("scan-inline", "Capture inline @osb markers"),
command("import-session", "Replay registered agent sessions"),
+ command("handoff", "Write an operator-readable session handoff note"),
+ command("intention", "Manage scoped current-intention chains"),
command("entity", "Canonical entity registry: set, get, list, relate, archive"),
command("session-hook", "Capture runtime lifecycle hook payloads"),
command("import-claude-memory", "Import Claude memory feedback"),
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 870481a4..4101faaa 100644
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -15,6 +15,7 @@ import {
defaultConfigPath,
discoverConfig,
redactMapping,
+ resolveMcpToolProfile,
setConfigValue,
validateTimezoneName,
} from "../core/config.ts";
@@ -66,6 +67,7 @@ import { serveStdio } from "../mcp/stdio.ts";
import { SERVER_VERSION } from "../mcp/protocol.ts";
import { buildToolTable } from "../mcp/tools.ts";
import { evaluateToolCapabilities, type RuntimeCapabilityWindow } from "../mcp/capabilities.ts";
+import { resolveToolSurface, toolSurfaceProfileNames } from "../mcp/profiles.ts";
// ── Subcommands ─────────────────────────────────────────────────────────────
@@ -392,6 +394,7 @@ async function cmdMcp(argv: string[]): Promise<number> {
repo: { type: "string" },
scope: { type: "string" },
"writer-only": { type: "boolean" },
+ "tool-profile": { type: "string" },
probe: { type: "boolean" },
json: { type: "boolean" },
"allow-tool": { type: "string-array" },
@@ -405,23 +408,46 @@ async function cmdMcp(argv: string[]): Promise<number> {
// contradictory pair (e.g. `--scope full --writer-only`) is
// rejected to avoid silent surprises.
const writerOnly = Boolean(flags["writer-only"]);
- const rawScope = (flags["scope"] as string | undefined) ?? (writerOnly ? "writer" : "full");
- if (rawScope !== "full" && rawScope !== "writer") {
+ const explicitScope =
+ (flags["scope"] as string | undefined) ?? (writerOnly ? "writer" : undefined);
+ if (
+ explicitScope !== undefined &&
+ explicitScope !== "full" &&
+ explicitScope !== "writer" &&
+ explicitScope !== "catalog"
+ ) {
process.stderr.write(
- `o2b mcp: invalid --scope value: ${rawScope}; expected one of: full, writer\n`,
+ `o2b mcp: invalid --scope value: ${explicitScope}; expected one of: full, writer, catalog\n`,
);
return 2;
}
- if (writerOnly && rawScope !== "writer") {
- process.stderr.write(`o2b mcp: --writer-only conflicts with --scope ${rawScope}\n`);
+ if (writerOnly && explicitScope !== "writer") {
+ process.stderr.write(`o2b mcp: --writer-only conflicts with --scope ${explicitScope}\n`);
return 2;
}
- const scope = rawScope;
- const serverName = scope === "writer" ? "open-second-brain-writer" : "open-second-brain";
- const capabilityWindow = parseCapabilityWindow(flags);
const config = (flags["config"] as string | undefined) ?? defaultConfigPath();
+ // Named tool-surface profile: flag wins over the config key; an
+ // unknown name FAILS OPEN to the full surface (logged, never fatal).
+ const profileName =
+ (flags["tool-profile"] as string | undefined) ?? resolveMcpToolProfile(config);
+ const explicitWindow = parseCapabilityWindow(flags);
+ const surface = resolveToolSurface({
+ profileName,
+ ...(explicitScope !== undefined ? { explicitScope } : {}),
+ ...(explicitWindow !== undefined ? { explicitWindow } : {}),
+ });
+ if (surface.unknownProfile !== undefined) {
+ process.stderr.write(
+ `o2b mcp: unknown tool profile "${surface.unknownProfile}"; ` +
+ `failing open to the full surface (known: ${toolSurfaceProfileNames().join(", ")})\n`,
+ );
+ }
+ const scope = surface.scope;
+ const serverName = scope === "writer" ? "open-second-brain-writer" : "open-second-brain";
+ const capabilityWindow = surface.window;
+
if (flags["probe"]) {
return await runMcpProbe({
vault: flags["vault"] as string | undefined,
@@ -482,7 +508,7 @@ function parseCapabilityWindow(
async function runMcpProbe(args: {
vault: string | undefined;
config: string;
- scope: "full" | "writer";
+ scope: "full" | "writer" | "catalog";
serverName: string;
json: boolean;
capabilityWindow: RuntimeCapabilityWindow | undefined;
diff --git a/src/cli/search.ts b/src/cli/search.ts
index 22de5e7a..3a8c89d0 100644
--- a/src/cli/search.ts
+++ b/src/cli/search.ts
@@ -145,7 +145,9 @@ function resolveConfig(
async function cmdSearchFocus(argv: ReadonlyArray<string>): Promise<number> {
const action = argv[0];
if (!action || !["set", "status", "clear"].includes(action)) {
- throw new CliError("usage: o2b search focus <set|status|clear> [--query Q] [--path P]");
+ throw new CliError(
+ "usage: o2b search focus <set|status|clear> [--query Q] [--path P] [--session S]",
+ );
}
const { flags } = parseFlags(argv.slice(1), {
vault: { type: "string" },
@@ -153,10 +155,14 @@ async function cmdSearchFocus(argv: ReadonlyArray<string>): Promise<number> {
db: { type: "string" },
query: { type: "string" },
path: { type: "string" },
+ session: { type: "string" },
"ttl-minutes": { type: "string", default: "120" },
json: { type: "boolean" },
});
const cfg = resolveConfig(flags);
+ // Session-scoped focus (t_5b478e47): --session binds the focus to
+ // one session's file under search-focus/ instead of the global file.
+ const session = typeof flags["session"] === "string" ? (flags["session"] as string) : undefined;
if (action === "set") {
const ttlMinutes = Number(flags["ttl-minutes"] ?? "120");
@@ -168,18 +174,18 @@ async function cmdSearchFocus(argv: ReadonlyArray<string>): Promise<number> {
},
Date.now(),
);
- writeSessionFocus(cfg, focus);
+ writeSessionFocus(cfg, focus, session);
writeFocusResponse(focus, flags["json"] === true);
return 0;
}
if (action === "clear") {
- clearSessionFocus(cfg);
+ clearSessionFocus(cfg, session);
writeFocusResponse(null, flags["json"] === true);
return 0;
}
- writeFocusResponse(readSessionFocus(cfg), flags["json"] === true);
+ writeFocusResponse(readSessionFocus(cfg, Date.now(), session), flags["json"] === true);
return 0;
}
diff --git a/src/core/brain/context-pack.ts b/src/core/brain/context-pack.ts
index c72dc28b..67fdc048 100644
--- a/src/core/brain/context-pack.ts
+++ b/src/core/brain/context-pack.ts
@@ -41,6 +41,11 @@ import {
type ContextLanesReport,
} from "./context-lanes.ts";
import { buildAttentionContextBlock } from "./attention-flows.ts";
+import {
+ scoreSessionFocusTarget,
+ sessionFocusIsActive,
+ type SearchSessionFocus,
+} from "../search/session-focus.ts";
const TIER_ORDER: ReadonlyArray<PageTier> = [
PAGE_TIER.core,
@@ -105,6 +110,14 @@ export interface ContextPackOptions {
readonly transforms?: ContextTransformOptions;
/** Optional declarative attention-flow ids to include as a synthetic context item. */
readonly attentionFlowIds?: ReadonlyArray<string>;
+ /**
+ * Active search focus (Agent Surface Suite, t_5b478e47). When set
+ * and unexpired, focus-matching memories are promoted WITHIN their
+ * tier; a peripheral page can never outrank a core one. Omitted or
+ * null keeps the legacy ordering byte-identical. Callers gate this
+ * on the `search_focus_context_pack` config key.
+ */
+ readonly sessionFocus?: SearchSessionFocus | null;
}
interface Candidate {
@@ -218,10 +231,27 @@ export function packContext(vault: string, opts: ContextPackOptions): ContextPac
const query = opts.query ? normalizeForDedup(opts.query) : null;
const candidates = collectCandidates(vault);
+ // Focus boost (within-tier only): computed once per candidate, 0 for
+ // every candidate when no active focus is supplied, so the default
+ // sort stays byte-identical.
+ const focus = sessionFocusIsActive(opts.sessionFocus) ? opts.sessionFocus! : null;
+ const focusScore = new Map<string, number>();
+ if (focus !== null) {
+ for (const c of candidates) {
+ focusScore.set(
+ c.id,
+ scoreSessionFocusTarget({ path: c.path, title: c.topic, content: c.body }, focus),
+ );
+ }
+ }
+
candidates.sort((a, b) => {
const tierA = TIER_ORDER.indexOf(a.tier);
const tierB = TIER_ORDER.indexOf(b.tier);
if (tierA !== tierB) return tierA - tierB;
+ const focusA = focusScore.get(a.id) ?? 0;
+ const focusB = focusScore.get(b.id) ?? 0;
+ if (focusA !== focusB) return focusB - focusA;
if (a.createdAtMs !== b.createdAtMs) return b.createdAtMs - a.createdAtMs;
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
});
diff --git a/src/core/brain/handoff.ts b/src/core/brain/handoff.ts
new file mode 100644
index 00000000..bfea2150
--- /dev/null
+++ b/src/core/brain/handoff.ts
@@ -0,0 +1,146 @@
+/**
+ * Operator-readable session handoff notes (Agent Surface Suite,
+ * t_28afa4d2).
+ *
+ * A handoff answers four questions a session leaves behind: what was
+ * asked, what got done, what was learned, and what the next session
+ * should pick up first. Extraction is deterministic regex over the
+ * normalised turns - no LLM - so the note is reproducible and cheap;
+ * the source session file remains the lossless record.
+ */
+
+import { mkdirSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { isoDate, isoSecond } from "./time.ts";
+import { resolveSessionScope } from "./session-scope.ts";
+import type { SessionTurn } from "./sessions/types.ts";
+
+export interface HandoffNoteOptions {
+ /** Raw session id or workstream label; normalised to a scope slug. */
+ readonly sessionId: string;
+ readonly agent: string;
+ readonly now?: Date;
+}
+
+export interface WriteHandoffNoteInput extends HandoffNoteOptions {
+ readonly turns: ReadonlyArray<SessionTurn>;
+}
+
+export interface HandoffNoteResult {
+ readonly path: string;
+ readonly scope: string;
+ readonly content: string;
+}
+
+const MAX_LINES_PER_SECTION = 5;
+const MAX_REQUEST_CHARS = 500;
+
+const COMPLETED_RE = /\b(done|completed|shipped|merged|fixed|implemented|created|added)\b/iu;
+const LEARNED_RE = /\b(learned|discovered|turns out|note that|important|gotcha)\b/iu;
+const NEXT_RE = /\b(next step|next session|todo|remaining|follow-up|later|pick up)\b/iu;
+
+/** Tool names whose input.file_path marks a changed file. */
+const WRITE_TOOLS = new Set(["Write", "Edit", "MultiEdit", "apply_patch", "NotebookEdit"]);
+
+function lines(text: string): string[] {
+ return text
+ .split("\n")
+ .map((line) => line.trim())
+ .filter((line) => line.length > 0);
+}
+
+function collectMatching(
+ turns: ReadonlyArray<SessionTurn>,
+ roles: ReadonlySet<SessionTurn["role"]>,
+ re: RegExp,
+): string[] {
+ const out: string[] = [];
+ for (const turn of turns) {
+ if (!roles.has(turn.role) || !turn.text) continue;
+ for (const line of lines(turn.text)) {
+ if (!re.test(line)) continue;
+ if (!out.includes(line)) out.push(line);
+ if (out.length >= MAX_LINES_PER_SECTION) return out;
+ }
+ }
+ return out;
+}
+
+function collectChangedFiles(turns: ReadonlyArray<SessionTurn>): string[] {
+ const out: string[] = [];
+ for (const turn of turns) {
+ for (const call of turn.toolCalls ?? []) {
+ if (!WRITE_TOOLS.has(call.name)) continue;
+ const filePath = call.input["file_path"] ?? call.input["path"];
+ if (typeof filePath !== "string" || filePath.length === 0) continue;
+ if (!out.includes(filePath)) out.push(filePath);
+ }
+ }
+ return out;
+}
+
+function section(title: string, entries: ReadonlyArray<string>): string {
+ const body =
+ entries.length === 0 ? "(none captured)" : entries.map((entry) => `- ${entry}`).join("\n");
+ return `## ${title}\n\n${body}`;
+}
+
+/** Render the handoff note body (without frontmatter). Pure. */
+export function buildHandoffNote(
+ turns: ReadonlyArray<SessionTurn>,
+ opts: HandoffNoteOptions,
+): string {
+ const firstUser = turns.find((turn) => turn.role === "user" && turn.text);
+ const request = firstUser?.text?.trim().slice(0, MAX_REQUEST_CHARS) ?? "(none captured)";
+ const assistantRoles = new Set<SessionTurn["role"]>(["assistant"]);
+ const anyRoles = new Set<SessionTurn["role"]>(["user", "assistant"]);
+
+ const completed = collectMatching(turns, assistantRoles, COMPLETED_RE);
+ const learned = collectMatching(turns, anyRoles, LEARNED_RE);
+ const nextSteps = collectMatching(turns, anyRoles, NEXT_RE);
+ const files = collectChangedFiles(turns);
+
+ return [
+ `# Handoff - ${opts.sessionId}`,
+ "",
+ `Agent ${opts.agent}, ${turns.length} turn(s).`,
+ "",
+ `## Request\n\n${request}`,
+ "",
+ section("Completed work", completed),
+ "",
+ section("Files changed", files),
+ "",
+ section("Learned context", learned),
+ "",
+ section("Next steps", nextSteps),
+ "",
+ ].join("\n");
+}
+
+/** Build and persist the note at `Brain/handoffs/<date>-<scope>.md`. */
+export function writeHandoffNote(vault: string, input: WriteHandoffNoteInput): HandoffNoteResult {
+ const now = input.now ?? new Date();
+ const scope = resolveSessionScope(input.sessionId);
+ const dir = join(vault, "Brain", "handoffs");
+ mkdirSync(dir, { recursive: true });
+ const path = join(dir, `${isoDate(now)}-${scope}.md`);
+ const body = buildHandoffNote(input.turns, input);
+ // JSON.stringify-quote the caller-supplied scalars: YAML-significant
+ // characters or newlines in a session id / agent name must not be
+ // able to break or inject frontmatter fields.
+ const content = [
+ "---",
+ `session_id: ${JSON.stringify(input.sessionId)}`,
+ `scope: ${scope}`,
+ `agent: ${JSON.stringify(input.agent)}`,
+ `created_at: ${isoSecond(now)}`,
+ `turns: ${input.turns.length}`,
+ "---",
+ "",
+ body,
+ ].join("\n");
+ writeFileSync(path, content);
+ return Object.freeze({ path, scope, content });
+}
diff --git a/src/core/brain/intentions.ts b/src/core/brain/intentions.ts
new file mode 100644
index 00000000..f9eb511b
--- /dev/null
+++ b/src/core/brain/intentions.ts
@@ -0,0 +1,186 @@
+/**
+ * Scoped current-intention chains (Agent Surface Suite, t_6d78f69e).
+ *
+ * A per-workstream "now" document: `Brain/intentions/<scope>.md` holds
+ * the current intention, every update bumps `version` and appends the
+ * superseded text to an in-file `## History` trail, and `move`
+ * retires the whole chain into `Brain/intentions/history/` so the
+ * active directory only ever shows live work. Markdown first - the
+ * chain is operator-readable without any tooling. `Brain/pinned.md`
+ * stays untouched as the scope-free scratchpad.
+ */
+
+import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync } from "node:fs";
+import { join } from "node:path";
+
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { parseFrontmatter } from "../vault.ts";
+import { resolveSessionScope } from "./session-scope.ts";
+import { isoDate, isoSecond } from "./time.ts";
+
+export interface IntentionChain {
+ readonly scope: string;
+ readonly version: number;
+ readonly updatedAt: string;
+ readonly agent: string;
+ /** Current intention text (without the history trail). */
+ readonly text: string;
+ /** History lines, newest first. */
+ readonly history: ReadonlyArray<string>;
+ readonly path: string;
+}
+
+export interface SetIntentionInput {
+ readonly scope: string;
+ readonly text: string;
+ readonly agent: string;
+ readonly now?: Date;
+}
+
+export interface MoveIntentionInput {
+ readonly scope: string;
+ readonly now?: Date;
+}
+
+export interface MoveIntentionResult {
+ readonly scope: string;
+ readonly archivePath: string;
+}
+
+const HISTORY_HEADER = "## History";
+const HISTORY_SNIPPET_CHARS = 120;
+
+function intentionsDir(vault: string): string {
+ return join(vault, "Brain", "intentions");
+}
+
+function intentionPath(vault: string, scope: string): string {
+ return join(intentionsDir(vault), `${scope}.md`);
+}
+
+function renderChain(chain: Omit<IntentionChain, "path">): string {
+ const history =
+ chain.history.length === 0
+ ? ""
+ : `\n${HISTORY_HEADER}\n\n${chain.history.map((line) => `- ${line}`).join("\n")}\n`;
+ // The agent name is caller-supplied: JSON.stringify-quote it so
+ // YAML-significant characters cannot corrupt the chain file
+ // (parseFrontmatter strips the quotes on read).
+ return [
+ "---",
+ `scope: ${chain.scope}`,
+ `version: ${chain.version}`,
+ `updated_at: ${chain.updatedAt}`,
+ `agent: ${JSON.stringify(chain.agent)}`,
+ "---",
+ "",
+ chain.text,
+ history,
+ ].join("\n");
+}
+
+function parseChain(vault: string, scope: string): IntentionChain | null {
+ const path = intentionPath(vault, scope);
+ if (!existsSync(path)) return null;
+ const [meta, body] = parseFrontmatter(path);
+ const versionRaw = meta["version"];
+ const version =
+ typeof versionRaw === "string" && /^[0-9]+$/.test(versionRaw)
+ ? Number.parseInt(versionRaw, 10)
+ : 1;
+ // Match the trail as a real heading line, not a substring, so
+ // intention text that merely mentions "## History" is never split.
+ const headerMatch = /^## History$/mu.exec(body);
+ const headerIndex = headerMatch?.index ?? -1;
+ const text = (headerIndex < 0 ? body : body.slice(0, headerIndex)).trim();
+ const history: string[] = [];
+ if (headerIndex >= 0) {
+ for (const line of body.slice(headerIndex + HISTORY_HEADER.length).split("\n")) {
+ const trimmed = line.trim();
+ if (trimmed.startsWith("- ")) history.push(trimmed.slice(2));
+ }
+ }
+ return Object.freeze({
+ scope,
+ version,
+ updatedAt: typeof meta["updated_at"] === "string" ? meta["updated_at"] : "",
+ agent: typeof meta["agent"] === "string" ? meta["agent"] : "",
+ text,
+ history: Object.freeze(history),
+ path,
+ });
+}
+
+/** Create or update the scoped intention; prior text lands in history. */
+export function setIntention(vault: string, input: SetIntentionInput): IntentionChain {
+ const scope = resolveSessionScope(input.scope);
+ const now = input.now ?? new Date();
+ const text = input.text.trim();
+ if (text.length === 0) throw new Error("intention text must not be empty");
+ const prior = parseChain(vault, scope);
+ const history =
+ prior === null
+ ? []
+ : [
+ `v${prior.version} (${prior.updatedAt}): ${prior.text.replace(/\s+/gu, " ").slice(0, HISTORY_SNIPPET_CHARS)}`,
+ ...prior.history,
+ ];
+ const chain = {
+ scope,
+ version: (prior?.version ?? 0) + 1,
+ updatedAt: isoSecond(now),
+ agent: input.agent,
+ text,
+ history: Object.freeze(history),
+ };
+ mkdirSync(intentionsDir(vault), { recursive: true });
+ const path = intentionPath(vault, scope);
+ atomicWriteFileSync(path, renderChain(chain));
+ return Object.freeze({ ...chain, path });
+}
+
+/** Current chain for a scope, or null. */
+export function showIntention(vault: string, scope: string): IntentionChain | null {
+ return parseChain(vault, resolveSessionScope(scope));
+}
+
+/** Active chains sorted by scope. History entries are excluded. */
+export function listIntentions(vault: string): IntentionChain[] {
+ const dir = intentionsDir(vault);
+ if (!existsSync(dir)) return [];
+ const out: IntentionChain[] = [];
+ for (const name of readdirSync(dir)) {
+ if (!name.endsWith(".md")) continue;
+ const chain = parseChain(vault, name.replace(/\.md$/u, ""));
+ if (chain !== null) out.push(chain);
+ }
+ return out.toSorted((a, b) => (a.scope < b.scope ? -1 : a.scope > b.scope ? 1 : 0));
+}
+
+/** Retire a chain into Brain/intentions/history/ and clear the active file. */
+export function moveIntentionToHistory(
+ vault: string,
+ input: MoveIntentionInput,
+): MoveIntentionResult {
+ const scope = resolveSessionScope(input.scope);
+ const now = input.now ?? new Date();
+ const activePath = intentionPath(vault, scope);
+ if (!existsSync(activePath)) {
+ throw new Error(`no active intention for scope: ${scope}`);
+ }
+ const historyDir = join(intentionsDir(vault), "history");
+ mkdirSync(historyDir, { recursive: true });
+ const base = `${scope}-${isoDate(now)}`;
+ let archivePath = join(historyDir, `${base}.md`);
+ for (let suffix = 2; existsSync(archivePath); suffix++) {
+ archivePath = join(historyDir, `${base}-${suffix}.md`);
+ }
+ try {
+ renameSync(activePath, archivePath);
+ } catch {
+ // Cross-device fallback: copy then remove.
+ atomicWriteFileSync(archivePath, readFileSync(activePath, "utf8"));
+ rmSync(activePath, { force: true });
+ }
+ return Object.freeze({ scope, archivePath });
+}
diff --git a/src/core/brain/session-lifecycle.ts b/src/core/brain/session-lifecycle.ts
index 1d6fb75d..cc723a74 100644
--- a/src/core/brain/session-lifecycle.ts
+++ b/src/core/brain/session-lifecycle.ts
@@ -1,4 +1,5 @@
-import { join } from "node:path";
+import { existsSync, readFileSync } from "node:fs";
+import { basename, join } from "node:path";
import { appendAuditRecord } from "../reliability/audit.ts";
import { appendLogEvent } from "./log.ts";
@@ -11,6 +12,12 @@ import { writeSignal } from "./signal.ts";
import { isoDate, isoSecond } from "./time.ts";
import { BRAIN_LOG_EVENT_KIND, BRAIN_SIGNAL_SOURCE_TYPE } from "./types.ts";
import { validateBrainFeedbackInput } from "./sessions/validate-feedback.ts";
+import { resolveSearchConfig } from "../search/index.ts";
+import { clearSessionFocus, sessionFocusPath } from "../search/session-focus.ts";
+import { resolveSessionHandoff } from "../config.ts";
+import { writeHandoffNote, type HandoffNoteResult } from "./handoff.ts";
+import { detectAdapter } from "./sessions/registry.ts";
+import type { SessionTurn } from "./sessions/types.ts";
export interface CaptureSessionLifecycleOptions {
readonly agent: string;
@@ -33,6 +40,10 @@ export interface CaptureSessionLifecycleResult {
readonly facts_deduped: number;
readonly audit_path: string;
readonly log_path?: string;
+ /** True when a SessionEnd event cleared that session's bound focus. */
+ readonly focus_cleared?: boolean;
+ /** Path of the handoff note a SessionEnd event produced (gated). */
+ readonly handoff_path?: string;
}
interface NormalizedPayload {
@@ -101,6 +112,47 @@ export async function captureSessionLifecycleEvent(
captureToolFeedback(vault, normalized, opts, now, ensureDedup(), counters);
}
+ // Session-scoped focus lifecycle (Agent Surface Suite, t_5b478e47):
+ // a finished session's bound focus must not leak into the next one.
+ // Deliberately NOT gated on the capture boundary (unlike the handoff
+ // below): removing the session's own steering state is cleanup, not
+ // memory capture, so it applies even for stateless sessions.
+ // Fail-soft - focus cleanup can never block lifecycle capture.
+ let focusCleared = false;
+ if (normalized.event === "SessionEnd" && normalized.sessionId !== undefined && !opts.dryRun) {
+ try {
+ const searchConfig = resolveSearchConfig({ vault });
+ // Clear by file presence, not by activity: an already-expired
+ // focus file is still stale state worth removing.
+ if (existsSync(sessionFocusPath(searchConfig, normalized.sessionId))) {
+ clearSessionFocus(searchConfig, normalized.sessionId);
+ focusCleared = true;
+ }
+ } catch {
+ // ignore - lifecycle capture must survive a broken search config
+ }
+ }
+
+ // Handoff note on SessionEnd (Agent Surface Suite, t_28afa4d2):
+ // gated by the session_handoff config key (default off) and the
+ // capture boundary; reads the recorded transcript through the
+ // session adapters. Fail-soft like the rest of lifecycle capture.
+ let handoffPath: string | undefined;
+ if (
+ normalized.event === "SessionEnd" &&
+ normalized.transcriptPath !== undefined &&
+ mayWrite &&
+ !opts.dryRun &&
+ resolveSessionHandoff()
+ ) {
+ try {
+ handoffPath = (await writeHandoffNoteFromTranscript(vault, normalized, opts.agent, now))
+ ?.path;
+ } catch {
+ // ignore - a malformed transcript never blocks lifecycle capture
+ }
+ }
+
let logPath: string | undefined;
if (mayWrite && !opts.dryRun) {
logPath = appendLifecycleLog(vault, normalized, opts.agent, now, counters);
@@ -134,9 +186,35 @@ export async function captureSessionLifecycleEvent(
facts_deduped: counters.facts_deduped,
audit_path: auditPath,
...(logPath ? { log_path: logPath } : {}),
+ ...(focusCleared ? { focus_cleared: true } : {}),
+ ...(handoffPath !== undefined ? { handoff_path: handoffPath } : {}),
};
}
+/** Read the recorded transcript via the session adapters and write a handoff note. */
+async function writeHandoffNoteFromTranscript(
+ vault: string,
+ normalized: NormalizedPayload,
+ agent: string,
+ now: Date,
+): Promise<HandoffNoteResult | null> {
+ const path = normalized.transcriptPath!;
+ if (!existsSync(path)) return null;
+ const text = readFileSync(path, "utf8");
+ const nl = text.indexOf("\n");
+ const adapter = detectAdapter(nl < 0 ? text : text.slice(0, nl));
+ if (adapter === null) return null;
+ const turns: SessionTurn[] = [];
+ for await (const turn of adapter.iterate(path)) turns.push(turn);
+ if (turns.length === 0) return null;
+ return writeHandoffNote(vault, {
+ turns,
+ sessionId: normalized.sessionId ?? basename(path),
+ agent,
+ now,
+ });
+}
+
function normalizePayload(payload: unknown): NormalizedPayload {
if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
return { event: "unknown", malformed: 1 };
diff --git a/src/core/brain/session-scope.ts b/src/core/brain/session-scope.ts
new file mode 100644
index 00000000..7d59842e
--- /dev/null
+++ b/src/core/brain/session-scope.ts
@@ -0,0 +1,41 @@
+/**
+ * Session-scope kernel (Agent Surface Suite).
+ *
+ * One normalisation for every per-session surface: session-scoped
+ * search focus files, intention chains, and handoff note names all key
+ * on the same `[a-z0-9-]` slug, so a session identifier from any host
+ * (Claude Code UUIDs, Codex paths, operator-chosen workstream labels)
+ * maps to one stable, filesystem- and wikilink-safe scope.
+ */
+
+export class SessionScopeError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "SessionScopeError";
+ }
+}
+
+export const SESSION_SCOPE_MAX_LENGTH = 64;
+
+/**
+ * Normalise a raw session id or workstream label into a scope slug:
+ * lowercase, non-alphanumerics collapsed to single dashes, edge dashes
+ * trimmed, length-capped. Deterministic and idempotent. Empty or
+ * separator-only input is a caller bug and throws.
+ */
+export function resolveSessionScope(raw: string): string {
+ // Plain toLowerCase: scope slugs become cross-host filenames, so
+ // locale-dependent casing (Turkish dotless-i) must never vary them.
+ const slug = raw
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/gu, "-")
+ .replace(/^-+|-+$/gu, "")
+ .slice(0, SESSION_SCOPE_MAX_LENGTH)
+ .replace(/-+$/gu, "");
+ if (slug.length === 0) {
+ throw new SessionScopeError(
+ `session scope requires at least one alphanumeric: ${JSON.stringify(raw)}`,
+ );
+ }
+ return slug;
+}
diff --git a/src/core/config.ts b/src/core/config.ts
index a0eb04d2..f4e1bcce 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -253,6 +253,87 @@ export function resolveLinkOutputFormat(configPath?: string): LinkOutputFormat {
return raw === "markdown" ? "markdown" : "wikilink";
}
+/**
+ * Named MCP tool-surface profile (Agent Surface Suite). Returns the raw
+ * configured name or null; validation against the known profile set
+ * happens in the resolver, which fails open on unknown names.
+ */
+export function resolveMcpToolProfile(configPath?: string): string | null {
+ const env = process.env["OPEN_SECOND_BRAIN_MCP_TOOL_PROFILE"]?.trim();
+ if (env) return env;
+ const raw = discoverConfig(configPath).data["mcp_tool_profile"]?.trim();
+ return raw ? raw : null;
+}
+
+/**
+ * Skill auto-attach gate (Agent Surface Suite). Default OFF: the
+ * skills_attach tool returns an empty block unless the operator sets
+ * `skill_auto_attach: "true"` (or the matching env override), so the
+ * default per-turn injection stays bit-identical.
+ */
+export function resolveSkillAutoAttach(configPath?: string): boolean {
+ const env = process.env["OPEN_SECOND_BRAIN_SKILL_AUTO_ATTACH"]?.trim();
+ const raw = env || discoverConfig(configPath).data["skill_auto_attach"]?.trim();
+ return raw === "true" || raw === "1";
+}
+
+/**
+ * Context-pack focus wiring gate (Agent Surface Suite, t_5b478e47).
+ * Default OFF: brain_context_pack ignores the active search focus
+ * unless `search_focus_context_pack: "true"`, keeping the default
+ * pack byte-identical.
+ */
+export function resolveSearchFocusContextPack(configPath?: string): boolean {
+ const env = process.env["OPEN_SECOND_BRAIN_SEARCH_FOCUS_CONTEXT_PACK"]?.trim();
+ const raw = env || discoverConfig(configPath).data["search_focus_context_pack"]?.trim();
+ return raw === "true" || raw === "1";
+}
+
+/**
+ * SessionEnd handoff-note gate (Agent Surface Suite, t_28afa4d2).
+ * Default OFF: lifecycle capture writes no handoff note unless
+ * `session_handoff: "true"`.
+ */
+export function resolveSessionHandoff(configPath?: string): boolean {
+ const env = process.env["OPEN_SECOND_BRAIN_SESSION_HANDOFF"]?.trim();
+ const raw = env || discoverConfig(configPath).data["session_handoff"]?.trim();
+ return raw === "true" || raw === "1";
+}
+
+export const SESSION_CAPTURE_ROLES = ["user", "assistant", "system", "tool", "meta"] as const;
+
+export type SessionCaptureRole = (typeof SESSION_CAPTURE_ROLES)[number];
+
+function isSessionCaptureRole(value: string): value is SessionCaptureRole {
+ return (SESSION_CAPTURE_ROLES as ReadonlyArray<string>).includes(value);
+}
+
+/**
+ * Config-level default for session-capture role filtering (Agent
+ * Surface Suite, t_e2346fe9). `session_capture_roles` is a
+ * comma-separated subset of user/assistant/system/tool/meta; absent or
+ * empty means "capture every role" (null = no filter, bit-identical to
+ * the pre-key behaviour). An unknown role name fails fast - a silent
+ * typo here would silently drop memory.
+ */
+export function resolveSessionCaptureRoles(configPath?: string): SessionCaptureRole[] | null {
+ const env = process.env["OPEN_SECOND_BRAIN_SESSION_CAPTURE_ROLES"]?.trim();
+ const raw = env || discoverConfig(configPath).data["session_capture_roles"]?.trim();
+ if (!raw) return null;
+ const roles: SessionCaptureRole[] = [];
+ for (const part of raw.split(",")) {
+ const role = part.trim().toLowerCase();
+ if (role.length === 0) continue;
+ if (!isSessionCaptureRole(role)) {
+ throw new Error(
+ `session_capture_roles: unknown role "${role}" (expected a subset of ${SESSION_CAPTURE_ROLES.join(", ")})`,
+ );
+ }
+ if (!roles.includes(role)) roles.push(role);
+ }
+ return roles.length > 0 ? roles : null;
+}
+
/** Replace values for keys whose name suggests a secret with `[REDACTED]`. */
export function redactMapping<T extends Record<string, unknown>>(data: T): Record<string, unknown> {
const redacted: Record<string, unknown> = {};
diff --git a/src/core/search/search.ts b/src/core/search/search.ts
index 97bd19e5..1121e108 100644
--- a/src/core/search/search.ts
+++ b/src/core/search/search.ts
@@ -34,7 +34,7 @@ import { deriveExpansionTerms, tokenizeForExpansion, DEFAULT_EXPANSION } from ".
import { filterByProperties } from "./property-filter.ts";
import { applyRelationPolarity } from "./relation-polarity.ts";
import { rankResults } from "./ranker.ts";
-import { readSessionFocus } from "./session-focus.ts";
+import { readActiveSessionFocus } from "./session-focus.ts";
import { mtimeInRange, resolveTimeRange } from "./time-range.ts";
import { expandByTraversal, type TraversalOptions } from "./traversal.ts";
import { Store } from "./store.ts";
@@ -195,7 +195,9 @@ export async function search(
const warnings: string[] = [];
const structured = opts.structuredQuery;
const sessionFocus =
- opts.sessionFocus === undefined ? readSessionFocus(config, Date.now()) : opts.sessionFocus;
+ opts.sessionFocus === undefined
+ ? readActiveSessionFocus(config, opts.focusSession, Date.now())
+ : opts.sessionFocus;
const keywordQuery = structuredKeywordQuery(query, structured);
const semanticLaneQuery = structuredSemanticQuery(structured);
// Time-aware recall (recall-trust-suite): resolve since/until up front
diff --git a/src/core/search/session-focus.ts b/src/core/search/session-focus.ts
index 019dfb40..60d506b7 100644
--- a/src/core/search/session-focus.ts
+++ b/src/core/search/session-focus.ts
@@ -1,6 +1,7 @@
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
+import { resolveSessionScope } from "../brain/session-scope.ts";
import { resolveIndexPath } from "./paths.ts";
import { SearchError, type ResolvedSearchConfig } from "./types.ts";
@@ -25,6 +26,7 @@ export interface SessionFocusTarget {
const DEFAULT_TTL_MINUTES = 120;
const MAX_TTL_MINUTES = 24 * 60;
const FOCUS_FILE = "search-focus.json";
+const FOCUS_DIR = "search-focus";
function normalizePathPrefix(pathPrefix: string | null | undefined): string | null {
if (pathPrefix === undefined || pathPrefix === null) return null;
@@ -78,15 +80,24 @@ export function sessionFocusIsActive(
return focus.expiresAt === null || focus.expiresAt > nowMs;
}
-export function sessionFocusPath(config: ResolvedSearchConfig): string {
- return join(dirname(resolveIndexPath(config.vault, config.dbPath)), FOCUS_FILE);
+/**
+ * Focus file location. With no scope: the PR #54 global file. With a
+ * session scope (Agent Surface Suite, t_5b478e47): one file per scope
+ * slug under `search-focus/`, so concurrent sessions never clobber
+ * each other's focus.
+ */
+export function sessionFocusPath(config: ResolvedSearchConfig, sessionScope?: string): string {
+ const dir = dirname(resolveIndexPath(config.vault, config.dbPath));
+ if (sessionScope === undefined) return join(dir, FOCUS_FILE);
+ return join(dir, FOCUS_DIR, `${resolveSessionScope(sessionScope)}.json`);
}
export function readSessionFocus(
config: ResolvedSearchConfig,
nowMs = Date.now(),
+ sessionScope?: string,
): SearchSessionFocus | null {
- const path = sessionFocusPath(config);
+ const path = sessionFocusPath(config, sessionScope);
if (!existsSync(path)) return null;
try {
const parsed = JSON.parse(readFileSync(path, "utf8")) as SearchSessionFocus;
@@ -103,17 +114,39 @@ export function readSessionFocus(
}
}
-export function writeSessionFocus(config: ResolvedSearchConfig, focus: SearchSessionFocus): void {
- const path = sessionFocusPath(config);
+export function writeSessionFocus(
+ config: ResolvedSearchConfig,
+ focus: SearchSessionFocus,
+ sessionScope?: string,
+): void {
+ const path = sessionFocusPath(config, sessionScope);
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, JSON.stringify(focus, null, 2) + "\n");
}
-export function clearSessionFocus(config: ResolvedSearchConfig): void {
- const path = sessionFocusPath(config);
+export function clearSessionFocus(config: ResolvedSearchConfig, sessionScope?: string): void {
+ const path = sessionFocusPath(config, sessionScope);
if (existsSync(path)) rmSync(path, { force: true });
}
+/**
+ * The focus that applies to a turn: the session's own focus when one
+ * is bound and unexpired, else the global focus. The two are never
+ * merged - a bound session focus is more specific than the global one,
+ * and averaging two intents would steer toward neither.
+ */
+export function readActiveSessionFocus(
+ config: ResolvedSearchConfig,
+ sessionId: string | undefined,
+ nowMs = Date.now(),
+): SearchSessionFocus | null {
+ if (sessionId !== undefined) {
+ const scoped = readSessionFocus(config, nowMs, sessionId);
+ if (scoped !== null) return scoped;
+ }
+ return readSessionFocus(config, nowMs);
+}
+
function focusTokens(query: string): string[] {
const tokens = new Set<string>();
for (const token of query.toLocaleLowerCase().split(/[^\p{L}\p{N}_-]+/u)) {
diff --git a/src/core/search/types.ts b/src/core/search/types.ts
index 19697665..088aa7c4 100644
--- a/src/core/search/types.ts
+++ b/src/core/search/types.ts
@@ -216,6 +216,13 @@ export interface SearchOptions {
readonly structuredQuery?: StructuredRecallQueryDocument;
/** Optional per-query or persisted session focus steering. Undefined means load persisted focus. */
readonly sessionFocus?: SearchSessionFocus | null;
+ /**
+ * Session id for scoped focus resolution (Agent Surface Suite,
+ * t_5b478e47). Applies only when `sessionFocus` is undefined: the
+ * persisted focus lookup checks `search-focus/<scope>.json` first
+ * and falls back to the global focus file.
+ */
+ readonly focusSession?: string;
/** Opt-in verified evidence pack diagnostics. Omitted preserves the legacy search outcome shape. */
readonly evidencePack?: boolean;
/**
diff --git a/src/core/surface/descriptor.ts b/src/core/surface/descriptor.ts
new file mode 100644
index 00000000..086b62ce
--- /dev/null
+++ b/src/core/surface/descriptor.ts
@@ -0,0 +1,101 @@
+/**
+ * Surface descriptor kernel (Agent Surface Suite).
+ *
+ * One uniform record describes anything an agent can discover at
+ * runtime - MCP tools and repository skills alike. The two-pass tool
+ * catalog, the skill tools, skill auto-attach, and the tool-surface
+ * profiles all consume this shape, so name/description/group semantics
+ * cannot drift between features.
+ */
+
+export type SurfaceKind = "tool" | "skill";
+
+export interface SurfaceDescriptor {
+ readonly kind: SurfaceKind;
+ /** Stable identifier - MCP tool name or skill directory name. */
+ readonly name: string;
+ /** One-line description (first non-empty line of the source text). */
+ readonly description: string;
+ /** Coarse grouping: tool-name prefix family, or "skill". */
+ readonly group: string;
+ readonly tags: ReadonlyArray<string>;
+}
+
+/** Minimal structural slice of an MCP ToolDefinition we depend on. */
+export interface DescribableTool {
+ readonly name: string;
+ readonly description: string;
+}
+
+/** Minimal structural slice of a discovered skill entry. */
+export interface DescribableSkill {
+ readonly name: string;
+ readonly description: string;
+ readonly path: string;
+}
+
+/** First non-empty line, trimmed. Empty input stays empty. */
+export function firstLine(text: string): string {
+ for (const line of text.split("\n")) {
+ const trimmed = line.trim();
+ if (trimmed.length > 0) return trimmed;
+ }
+ return "";
+}
+
+const GROUP_PREFIXES: ReadonlyArray<string> = Object.freeze([
+ "brain",
+ "schema",
+ "payment",
+ "asset",
+]);
+
+/**
+ * Derive a coarse group from a tool name. Prefix families map to their
+ * prefix ("brain_*" -> "brain"); everything else is "core". The special
+ * "second_brain_*" diagnostics deliberately land in "core" - they are
+ * server-level, not Brain-domain.
+ */
+export function surfaceGroup(toolName: string): string {
+ if (toolName.startsWith("second_brain_")) return "core";
+ const head = toolName.split("_", 1)[0] ?? "";
+ return GROUP_PREFIXES.includes(head) ? head : "core";
+}
+
+function freezeDescriptor(d: SurfaceDescriptor): SurfaceDescriptor {
+ return Object.freeze({ ...d, tags: Object.freeze([...d.tags]) });
+}
+
+/** Build sorted, frozen descriptors for a tool table. */
+export function toolDescriptors(
+ tools: ReadonlyArray<DescribableTool>,
+): ReadonlyArray<SurfaceDescriptor> {
+ const out = tools.map((t) =>
+ freezeDescriptor({
+ kind: "tool",
+ name: t.name,
+ description: firstLine(t.description),
+ group: surfaceGroup(t.name),
+ tags: [],
+ }),
+ );
+ out.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
+ return Object.freeze(out);
+}
+
+/** Build sorted, frozen descriptors for discovered skills. */
+export function skillDescriptors(
+ skills: ReadonlyArray<DescribableSkill>,
+): ReadonlyArray<SurfaceDescriptor> {
+ const out = skills.map((s) =>
+ freezeDescriptor({
+ kind: "skill",
+ name: s.name,
+ description: firstLine(s.description),
+ group: "skill",
+ tags: [],
+ }),
+ );
+ out.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
+ return Object.freeze(out);
+}
diff --git a/src/core/surface/lexical-score.ts b/src/core/surface/lexical-score.ts
new file mode 100644
index 00000000..ae5d29aa
--- /dev/null
+++ b/src/core/surface/lexical-score.ts
@@ -0,0 +1,118 @@
+/**
+ * Deterministic BM25-style lexical scorer over surface descriptors
+ * (Agent Surface Suite). No LLM, no embeddings - tokenized term
+ * matching with field weights, reproducible across processes.
+ *
+ * Field weighting follows the house convention from search ranking:
+ * a name-token match is the strongest relevance signal, tags sit
+ * between name and description. Weights are applied as term-frequency
+ * multipliers so one BM25 core serves both turn-vs-tool and
+ * turn-vs-skill scoring without divergent formulas.
+ */
+
+import type { SurfaceDescriptor } from "./descriptor.ts";
+
+export interface ScoredDescriptor {
+ readonly descriptor: SurfaceDescriptor;
+ readonly score: number;
+}
+
+export interface LexicalScoreOptions {
+ /** Term-frequency multiplier for name tokens. Default 3. */
+ readonly nameWeight?: number;
+ /** Term-frequency multiplier for tag tokens. Default 2. */
+ readonly tagWeight?: number;
+ /** BM25 k1 (term-frequency saturation). Default 1.2. */
+ readonly k1?: number;
+ /** BM25 b (length normalisation). Default 0.75. */
+ readonly b?: number;
+}
+
+const DEFAULTS = Object.freeze({ nameWeight: 3, tagWeight: 2, k1: 1.2, b: 0.75 });
+
+/**
+ * Lowercase, split on non-alphanumerics, drop 1-char tokens. Plain
+ * toLowerCase keeps tokenisation identical across host locales.
+ */
+export function tokenize(text: string): string[] {
+ const out: string[] = [];
+ for (const raw of text.toLowerCase().split(/[^\p{L}\p{N}]+/u)) {
+ if (raw.length >= 2) out.push(raw);
+ }
+ return out;
+}
+
+interface DescriptorDoc {
+ readonly descriptor: SurfaceDescriptor;
+ /** token -> weighted term frequency */
+ readonly tf: ReadonlyMap<string, number>;
+ readonly length: number;
+}
+
+function buildDoc(
+ descriptor: SurfaceDescriptor,
+ opts: Required<LexicalScoreOptions>,
+): DescriptorDoc {
+ const tf = new Map<string, number>();
+ let length = 0;
+ const add = (tokens: string[], weight: number): void => {
+ for (const token of tokens) {
+ tf.set(token, (tf.get(token) ?? 0) + weight);
+ length += weight;
+ }
+ };
+ add(tokenize(descriptor.name), opts.nameWeight);
+ add(tokenize(descriptor.tags.join(" ")), opts.tagWeight);
+ add(tokenize(descriptor.description), 1);
+ return { descriptor, tf, length };
+}
+
+/**
+ * Rank descriptors against a free-text query. Zero-score entries are
+ * dropped; ties break by descriptor name ascending so output is fully
+ * deterministic.
+ */
+export function scoreDescriptors(
+ query: string,
+ descriptors: ReadonlyArray<SurfaceDescriptor>,
+ options: LexicalScoreOptions = {},
+): ScoredDescriptor[] {
+ const opts = { ...DEFAULTS, ...options };
+ const queryTokens = [...new Set(tokenize(query))];
+ if (queryTokens.length === 0 || descriptors.length === 0) return [];
+
+ const docs = descriptors.map((d) => buildDoc(d, opts));
+ const n = docs.length;
+ const avgLength = docs.reduce((sum, doc) => sum + doc.length, 0) / n || 1;
+
+ // Document frequency per query token (over weighted-tf presence).
+ const df = new Map<string, number>();
+ for (const token of queryTokens) {
+ let count = 0;
+ for (const doc of docs) if (doc.tf.has(token)) count++;
+ df.set(token, count);
+ }
+
+ const scored: ScoredDescriptor[] = [];
+ for (const doc of docs) {
+ let score = 0;
+ for (const token of queryTokens) {
+ const tf = doc.tf.get(token);
+ if (tf === undefined) continue;
+ const docFreq = df.get(token) ?? 0;
+ // BM25+ style idf floor: keeps a term present in every document
+ // from zeroing out, which matters in tiny descriptor corpora.
+ const idf = Math.log(1 + (n - docFreq + 0.5) / (docFreq + 0.5));
+ const norm = tf + opts.k1 * (1 - opts.b + opts.b * (doc.length / avgLength));
+ score += idf * ((tf * (opts.k1 + 1)) / norm);
+ }
+ if (score > 0) scored.push({ descriptor: doc.descriptor, score });
+ }
+
+ scored.sort(
+ (a, b) =>
+ b.score - a.score ||
+ (a.descriptor.name < b.descriptor.name ? -1 : a.descriptor.name > b.descriptor.name ? 1 : 0),
+ );
+ return scored;
+}
diff --git a/src/core/surface/skill-attach.ts b/src/core/surface/skill-attach.ts
new file mode 100644
index 00000000..4e440773
--- /dev/null
+++ b/src/core/surface/skill-attach.ts
@@ -0,0 +1,77 @@
+/**
+ * Skill auto-attach (Agent Surface Suite, t_10b86707).
+ *
+ * Deterministic per-turn skill relevance: score discovered skills
+ * against the current turn text with the shared lexical scorer and
+ * render a small Markdown block of the top matches. No LLM in the
+ * loop; the same query and skill set always produce the same block.
+ * The char budget drops whole trailing entries - a half-rendered
+ * skill line would read as a different skill.
+ */
+
+import { skillDescriptors } from "./descriptor.ts";
+import { scoreDescriptors } from "./lexical-score.ts";
+import type { SkillEntry } from "./skills.ts";
+
+export interface SkillAttachItem {
+ readonly name: string;
+ readonly description: string;
+ readonly path: string;
+ readonly score: number;
+}
+
+export interface SkillAttachment {
+ /** Markdown block ("## Relevant skills" + bullets), "" when empty. */
+ readonly block: string;
+ readonly items: ReadonlyArray<SkillAttachItem>;
+}
+
+export interface BuildSkillAttachmentOptions {
+ /** Current turn text to score against. */
+ readonly query: string;
+ readonly skills: ReadonlyArray<SkillEntry>;
+ /** Maximum skills to attach. Default 3. */
+ readonly maxSkills?: number;
+ /** Char budget for the rendered block. Default 1200. */
+ readonly maxChars?: number;
+}
+
+const DEFAULT_MAX_SKILLS = 3;
+const DEFAULT_MAX_CHARS = 1200;
+const BLOCK_HEADER = "## Relevant skills";
+
+function renderLine(item: SkillAttachItem): string {
+ return `- ${item.name} - ${item.description} (load with get_skill: ${item.name})`;
+}
+
+export function buildSkillAttachment(opts: BuildSkillAttachmentOptions): SkillAttachment {
+ const maxSkills = opts.maxSkills ?? DEFAULT_MAX_SKILLS;
+ const maxChars = opts.maxChars ?? DEFAULT_MAX_CHARS;
+ const byName = new Map(opts.skills.map((s) => [s.name, s]));
+ const ranked = scoreDescriptors(opts.query, skillDescriptors(opts.skills)).slice(0, maxSkills);
+
+ const items: SkillAttachItem[] = [];
+ const lines: string[] = [];
+ let used = BLOCK_HEADER.length + 2; // header + blank line
+ for (const { descriptor, score } of ranked) {
+ const skill = byName.get(descriptor.name);
+ if (skill === undefined) continue;
+ const item: SkillAttachItem = Object.freeze({
+ name: skill.name,
+ description: skill.description,
+ path: skill.path,
+ score,
+ });
+ const line = renderLine(item);
+ if (used + line.length + 1 > maxChars) break;
+ used += line.length + 1;
+ items.push(item);
+ lines.push(line);
+ }
+
+ if (items.length === 0) return Object.freeze({ block: "", items: Object.freeze([]) });
+ return Object.freeze({
+ block: `${BLOCK_HEADER}\n\n${lines.join("\n")}`,
+ items: Object.freeze(items),
+ });
+}
diff --git a/src/core/surface/skills.ts b/src/core/surface/skills.ts
new file mode 100644
index 00000000..485c5a13
--- /dev/null
+++ b/src/core/surface/skills.ts
@@ -0,0 +1,146 @@
+/**
+ * Skill discovery (Agent Surface Suite).
+ *
+ * Open Second Brain ships agent skills as `skills/<name>/SKILL.md`
+ * inside the plugin checkout; an operator can add vault-local skills
+ * under `<vault>/Brain/skills/`. Discovery is read-only and fail-soft:
+ * a missing root or an unreadable skill directory yields nothing and
+ * never crashes a session. File access inside a skill directory is
+ * path-traversal-guarded - agents read skill content, not the host
+ * filesystem.
+ */
+
+import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
+import { isAbsolute, join, resolve, sep } from "node:path";
+
+import { parseFrontmatter } from "../vault.ts";
+import { firstLine } from "./descriptor.ts";
+
+export type SkillErrorCode = "NOT_FOUND" | "INVALID_PATH";
+
+export class SkillError extends Error {
+ readonly code: SkillErrorCode;
+ constructor(code: SkillErrorCode, message: string) {
+ super(message);
+ this.name = "SkillError";
+ this.code = code;
+ }
+}
+
+export interface SkillEntry {
+ /** Frontmatter `name`, falling back to the directory name. */
+ readonly name: string;
+ /** Frontmatter `description`, falling back to the first body line. */
+ readonly description: string;
+ /** Absolute path to the skill directory. */
+ readonly path: string;
+ /** Absolute path to the SKILL.md file. */
+ readonly skillFile: string;
+}
+
+export interface SkillRootsOptions {
+ /** Plugin checkout root containing `skills/`. */
+ readonly repoRoot?: string | null;
+ /** Vault root; vault-local skills live at `Brain/skills/`. */
+ readonly vault?: string | null;
+}
+
+export const SKILL_FILE_NAME = "SKILL.md";
+
+/** Existing skill roots in precedence order (repo first, vault last). */
+export function skillRoots(opts: SkillRootsOptions): string[] {
+ const candidates: string[] = [];
+ if (opts.repoRoot) candidates.push(join(opts.repoRoot, "skills"));
+ if (opts.vault) candidates.push(join(opts.vault, "Brain", "skills"));
+ return candidates.filter((root) => {
+ try {
+ return statSync(root).isDirectory();
+ } catch {
+ return false;
+ }
+ });
+}
+
+function readSkillEntry(root: string, dir: string): SkillEntry | null {
+ const path = join(root, dir);
+ const skillFile = join(path, SKILL_FILE_NAME);
+ if (!existsSync(skillFile)) return null;
+ const [meta, body] = parseFrontmatter(skillFile);
+ const metaName = typeof meta["name"] === "string" ? meta["name"].trim() : "";
+ const metaDescription = typeof meta["description"] === "string" ? meta["description"].trim() : "";
+ return Object.freeze({
+ name: metaName.length > 0 ? metaName : dir,
+ description: metaDescription.length > 0 ? metaDescription : firstBodyLine(body),
+ path,
+ skillFile,
+ });
+}
+
+/** First non-empty, non-heading line of the SKILL.md body. */
+function firstBodyLine(body: string): string {
+ for (const line of body.split("\n")) {
+ const trimmed = line.trim();
+ if (trimmed.length === 0 || trimmed.startsWith("#")) continue;
+ return firstLine(trimmed);
+ }
+ return "";
+}
+
+/**
+ * Discover skills across roots. A later root overrides an earlier one
+ * on name collision (vault-local skills shadow shipped ones). Output
+ * is sorted by name. Fail-soft: unreadable roots/directories skip.
+ */
+export function discoverSkills(roots: ReadonlyArray<string>): SkillEntry[] {
+ const byName = new Map<string, SkillEntry>();
+ for (const root of roots) {
+ let dirs: string[];
+ try {
+ dirs = readdirSync(root).filter((d) => {
+ try {
+ return statSync(join(root, d)).isDirectory();
+ } catch {
+ return false;
+ }
+ });
+ } catch {
+ continue;
+ }
+ for (const dir of dirs) {
+ try {
+ const entry = readSkillEntry(root, dir);
+ if (entry !== null) byName.set(entry.name, entry);
+ } catch {
+ // One malformed skill never hides the rest.
+ }
+ }
+ }
+ return [...byName.values()].toSorted((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
+}
+
+/**
+ * Read a file inside a skill directory. Default: SKILL.md. A relative
+ * `filePath` may name an auxiliary file (reference docs, templates)
+ * but can never escape the skill directory.
+ */
+export function readSkillFile(entry: SkillEntry, filePath?: string): string {
+ if (filePath === undefined) return readFileSync(entry.skillFile, "utf8");
+ if (isAbsolute(filePath)) {
+ throw new SkillError("INVALID_PATH", "skill file path must be relative");
+ }
+ const abs = resolve(entry.path, filePath);
+ if (abs !== entry.path && !abs.startsWith(entry.path + sep)) {
+ throw new SkillError("INVALID_PATH", "skill file path must stay inside the skill directory");
+ }
+ if (!existsSync(abs)) {
+ throw new SkillError("NOT_FOUND", `skill file not found: ${filePath}`);
+ }
+ // Re-check after symlink resolution: a link inside the skill
+ // directory must not smuggle reads outside it.
+ const realDir = realpathSync(entry.path);
+ const realTarget = realpathSync(abs);
+ if (realTarget !== realDir && !realTarget.startsWith(realDir + sep)) {
+ throw new SkillError("INVALID_PATH", "skill file path must stay inside the skill directory");
+ }
+ return readFileSync(realTarget, "utf8");
+}
diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.ts
index f55e3f10..added9e2 100644
--- a/src/mcp/brain-tools.ts
+++ b/src/mcp/brain-tools.ts
@@ -40,7 +40,13 @@ import { isAbsolute, join, relative, resolve } from "node:path";
import { existsSync, readFileSync } from "node:fs";
-import { resolveAgentName, resolveLinkOutputFormat } from "../core/config.ts";
+import {
+ resolveAgentName,
+ resolveLinkOutputFormat,
+ resolveSearchFocusContextPack,
+} from "../core/config.ts";
+import { resolveSearchConfig } from "../core/search/index.ts";
+import { readActiveSessionFocus } from "../core/search/session-focus.ts";
import { brainActivePath, brainDirs } from "../core/brain/paths.ts";
import { regenerateActive, type RegenerateActiveResult } from "../core/brain/active.ts";
import { parseFrontmatter } from "../core/vault.ts";
@@ -70,6 +76,12 @@ import { buildWeeklySynthesis } from "../core/brain/temporal/weekly-brief.ts";
import { loadTemporalConfigSafe } from "../core/brain/policy.ts";
import { isBrainLogEventKind, type BrainLogEventKind } from "../core/brain/types.ts";
import { packContext } from "../core/brain/context-pack.ts";
+import {
+ listIntentions,
+ moveIntentionToHistory,
+ setIntention,
+ showIntention,
+} from "../core/brain/intentions.ts";
import { buildPreCompressPack } from "../core/brain/pre-compress-pack.ts";
import {
getContextReceipt,
@@ -1805,6 +1817,57 @@ async function toolBrainWeeklySynthesis(
};
}
+// ----- brain_intention (Agent Surface Suite) --------------------------------
+
+function toolBrainIntention(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Record<string, unknown> {
+ const operation = coerceStr(args, "operation", true)!;
+ if (operation === "list") {
+ return {
+ intentions: listIntentions(ctx.vault).map((chain) => ({
+ scope: chain.scope,
+ version: chain.version,
+ updated_at: chain.updatedAt,
+ text: chain.text,
+ })),
+ };
+ }
+ const scope = coerceStr(args, "scope", true)!;
+ if (operation === "set") {
+ const text = coerceStr(args, "text", true)!;
+ const chain = setIntention(ctx.vault, {
+ scope,
+ text,
+ agent: resolveAgentName(ctx.configPath ?? undefined),
+ });
+ return { operation, scope: chain.scope, version: chain.version, path: chain.path };
+ }
+ if (operation === "show") {
+ const chain = showIntention(ctx.vault, scope);
+ if (chain === null) return { operation, scope, present: false };
+ return {
+ operation,
+ scope: chain.scope,
+ present: true,
+ version: chain.version,
+ updated_at: chain.updatedAt,
+ text: chain.text,
+ history: chain.history,
+ path: chain.path,
+ };
+ }
+ if (operation === "move") {
+ const moved = moveIntentionToHistory(ctx.vault, { scope });
+ return { operation, scope: moved.scope, archive_path: moved.archivePath };
+ }
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_intention operation must be one of: set, show, list, move",
+ );
+}
+
// ----- brain_context_pack (v0.10.15) ---------------------------------------
/**
@@ -1834,8 +1897,29 @@ async function toolBrainContextPack(
const maxTotalChars = optionalPositiveInt(args, "max_total_chars", "brain_context_pack");
const receipt = receiptOptionsFromArgs("brain_context_pack", args, "context_pack", "mcp");
const telemetry = telemetryOptionsFromArgs("brain_context_pack", args, "mcp");
+ // Focus wiring (Agent Surface Suite, t_5b478e47): gated on the
+ // search_focus_context_pack config key (default off) so the default
+ // pack stays byte-identical. Fail-soft - a broken search config
+ // never breaks the pack.
+ let sessionFocus: ReturnType<typeof readActiveSessionFocus> = null;
+ if (resolveSearchFocusContextPack(ctx.configPath ?? undefined)) {
+ // Argument validation stays OUTSIDE the fail-soft block: an invalid
+ // focus_session is a caller error (INVALID_PARAMS), not a config
+ // read to swallow.
+ const focusSession = coerceStr(args, "focus_session", false) ?? undefined;
+ try {
+ const searchConfig = resolveSearchConfig({
+ vault: ctx.vault,
+ configPath: ctx.configPath ?? undefined,
+ });
+ sessionFocus = readActiveSessionFocus(searchConfig, focusSession);
+ } catch {
+ sessionFocus = null;
+ }
+ }
const report = packContext(ctx.vault, {
maxTokens,
+ ...(sessionFocus !== null ? { sessionFocus } : {}),
...(query ? { query } : {}),
...(includeLanes ? { includeLanes: true } : {}),
...(receipt !== undefined ? { receipt } : {}),
@@ -2834,6 +2918,37 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
outputSchema: PINNED_CONTEXT_OUTPUT_SCHEMA,
handler: toolBrainPinnedContext,
},
+ {
+ name: "brain_intention",
+ description:
+ "Scoped current-intention chains under Brain/intentions/: set updates a workstream's now-document (prior text lands in its history trail), show/list read, move retires the chain into history/.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["set", "show", "list", "move"],
+ description: "Operation to perform.",
+ },
+ scope: {
+ type: "string",
+ minLength: 1,
+ maxLength: 128,
+ description: "Workstream or session label (normalised to a scope slug).",
+ },
+ text: {
+ type: "string",
+ minLength: 1,
+ maxLength: 4000,
+ description: "Intention text for the set operation.",
+ },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ previewBudget: MCP_PREVIEW_BUDGET,
+ handler: toolBrainIntention,
+ },
{
name: "brain_context",
description:
@@ -3160,6 +3275,13 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
type: "string",
description: "Optional case/Unicode-insensitive substring filter on topic + principle.",
},
+ focus_session: {
+ type: "string",
+ minLength: 1,
+ maxLength: 128,
+ description:
+ "Session id whose bound search focus boosts matching memories (requires search_focus_context_pack).",
+ },
max_chars_per_memory: {
type: "integer",
minimum: 1,
diff --git a/src/mcp/hydrate-tool.ts b/src/mcp/hydrate-tool.ts
new file mode 100644
index 00000000..bdc1861d
--- /dev/null
+++ b/src/mcp/hydrate-tool.ts
@@ -0,0 +1,81 @@
+/**
+ * Two-pass tool catalog hydration (Agent Surface Suite, t_e8011a89).
+ *
+ * Under the `catalog` scope the server advertises a compact first-pass
+ * surface; every other tool keeps the token-diet `hidden` semantics -
+ * callable via `tools/call`, absent from `tools/list`. `tool_hydrate`
+ * is the second pass: with no arguments it returns the deterministic
+ * sorted catalog (name, one-line description, group), and with a
+ * `names` batch it returns the full input/output schemas for exactly
+ * the requested tools. Unknown names are reported per-name; one typo
+ * never fails the batch.
+ *
+ * The MCP server is static per process (no `listChanged`), so hydrated
+ * schemas arrive as tool-result data rather than a mutated tools/list -
+ * the closest faithful mapping of upstream two-pass hydration onto
+ * this transport.
+ */
+
+import { toolDescriptors } from "../core/surface/descriptor.ts";
+import { coerceStrList } from "./coerce.ts";
+import type { ToolDefinition } from "./tools.ts";
+
+export const TOOL_HYDRATE_NAME = "tool_hydrate";
+
+/**
+ * Build the `tool_hydrate` definition over a late-bound tool table.
+ * The getter indirection avoids a module cycle: `tools.ts` assembles
+ * the table and hands it to this builder, which only dereferences it
+ * inside the handler (by which time the table is complete, including
+ * this very tool).
+ */
+export function buildHydrateTool(getTable: () => ReadonlyArray<ToolDefinition>): ToolDefinition {
+ return {
+ name: TOOL_HYDRATE_NAME,
+ description:
+ "Two-pass tool discovery: no arguments returns the compact tool catalog (name, one-line description, group); names returns full schemas for the requested tools. Hidden tools stay callable via tools/call.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ names: {
+ type: "array",
+ items: { type: "string" },
+ description: "Tool names to hydrate full schemas for. Omit to get the catalog.",
+ },
+ },
+ additionalProperties: false,
+ },
+ handler: (_ctx, args) => {
+ const table = getTable();
+ const names = coerceStrList(args, "names");
+ if (names.length === 0) {
+ const catalog = toolDescriptors(table);
+ return {
+ count: catalog.length,
+ catalog: catalog.map((d) => ({
+ name: d.name,
+ description: d.description,
+ group: d.group,
+ })),
+ };
+ }
+ const byName = new Map(table.map((t) => [t.name, t]));
+ const hydrated: Record<string, unknown>[] = [];
+ const unknown: string[] = [];
+ for (const name of names) {
+ const tool = byName.get(name);
+ if (tool === undefined) {
+ unknown.push(name);
+ continue;
+ }
+ hydrated.push({
+ name: tool.name,
+ description: tool.description,
+ inputSchema: tool.inputSchema,
+ ...(tool.outputSchema ? { outputSchema: tool.outputSchema } : {}),
+ });
+ }
+ return { tools: hydrated, unknown };
+ },
+ };
+}
diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.ts
index f0aa12f0..bf381151 100644
--- a/src/mcp/instructions.ts
+++ b/src/mcp/instructions.ts
@@ -49,12 +49,31 @@ Prefer the writer-server copies of brain_feedback / brain_apply_evidence /
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.`;
+const CATALOG_INSTRUCTIONS = `Open Second Brain β€” two-pass catalog MCP surface.
+
+This server advertises a compact first-pass tool set: the capability
+diagnostic, the five always-loaded Brain writers/readers, and
+tool_hydrate. Every other Open Second Brain tool stays CALLABLE via
+tools/call β€” it is only omitted from tools/list to keep schema tokens
+out of your prompt until needed.
+
+Second pass: call tool_hydrate with no arguments to get the compact
+catalog (name, one-line description, group) of every tool in this
+process, then call tool_hydrate with names: [...] to fetch the full
+input/output schemas for the tools you actually need. After hydration,
+invoke those tools directly by name through tools/call β€” no further
+registration step exists or is needed.
+
+Do not invent substitute workflows for a capability you cannot see:
+hydrate the catalog first; the tool is almost certainly already here.`;
+
export function buildInstructions(opts: BuildInstructionsOpts | string): string {
// Legacy call-site compat: plain string β†’ full-surface branch.
const agent = typeof opts === "string" ? opts : opts.agent;
const scope = typeof opts === "string" ? undefined : opts.scope;
if (scope === "writer") return WRITER_INSTRUCTIONS;
+ if (scope === "catalog") return CATALOG_INSTRUCTIONS;
// Deliberately terse (token-diet): per-tool detail lives in the tool
// descriptions and docs/mcp.md; this text carries only the contract
diff --git a/src/mcp/profiles.ts b/src/mcp/profiles.ts
new file mode 100644
index 00000000..49e27ec2
--- /dev/null
+++ b/src/mcp/profiles.ts
@@ -0,0 +1,145 @@
+/**
+ * Adaptive tool-surface profiles (Agent Surface Suite, t_20dcb192).
+ *
+ * A profile names a curated MCP surface: a ToolScope plus an optional
+ * RuntimeCapabilityWindow. Hosts pick one via the `mcp_tool_profile`
+ * config key or `o2b mcp --tool-profile <name>` instead of hand-rolling
+ * allow/deny flag lists per platform.
+ *
+ * Contract (mirrors upstream Hermes Tool Slimmer): selection FAILS
+ * OPEN - an unknown profile name degrades to the full surface (with
+ * the unknown name surfaced for logging), never locks an agent out.
+ * Hard-window profiles (`recall`, `minimal`) always retain the
+ * `second_brain_capabilities` diagnostic, which reports every withheld
+ * tool with its reason; schema hydration via `tool_hydrate` stays on
+ * the `catalog` and `full` surfaces, where every catalogued tool is
+ * actually callable.
+ */
+
+import type { RuntimeCapabilityWindow } from "./capabilities.ts";
+import type { ToolScope } from "./tools.ts";
+
+export interface ToolSurfaceProfile {
+ readonly name: string;
+ readonly description: string;
+ readonly scope: ToolScope;
+ readonly window?: RuntimeCapabilityWindow;
+}
+
+/** The always-loaded Brain writer/reader set (writer scope parity). */
+const WRITER_SET = [
+ "brain_apply_evidence",
+ "brain_context",
+ "brain_feedback",
+ "brain_note",
+ "brain_pinned_context",
+] as const;
+
+export const TOOL_SURFACE_PROFILES: Readonly<Record<string, ToolSurfaceProfile>> = Object.freeze({
+ full: Object.freeze({
+ name: "full",
+ description: "Every tool advertised (default).",
+ scope: "full",
+ }),
+ writer: Object.freeze({
+ name: "writer",
+ description: "Always-loaded Brain writers plus the context reader.",
+ scope: "writer",
+ }),
+ catalog: Object.freeze({
+ name: "catalog",
+ description: "Two-pass surface: compact first pass, schemas via tool_hydrate.",
+ scope: "catalog",
+ }),
+ recall: Object.freeze({
+ name: "recall",
+ description: "Memory read/write surface for recall-heavy hosts; no admin tools.",
+ scope: "full",
+ window: Object.freeze({
+ allowedTools: Object.freeze([
+ ...WRITER_SET,
+ "brain_search",
+ "brain_recall_gate",
+ "brain_recall_feedback",
+ "brain_context_pack",
+ "brain_artifact_get",
+ ]),
+ }),
+ }),
+ minimal: Object.freeze({
+ name: "minimal",
+ description: "Floor surface for constrained hosts: writers, context, search.",
+ scope: "full",
+ window: Object.freeze({
+ allowedTools: Object.freeze([...WRITER_SET, "brain_search"]),
+ }),
+ }),
+});
+
+export function toolSurfaceProfileNames(): string[] {
+ return Object.keys(TOOL_SURFACE_PROFILES);
+}
+
+export interface ResolveToolSurfaceOptions {
+ /** Profile name from --tool-profile or the mcp_tool_profile key. */
+ readonly profileName?: string | null;
+ /** Explicit --scope value; wins over the profile's scope. */
+ readonly explicitScope?: ToolScope;
+ /** Explicit window flags; fields win over the profile's window. */
+ readonly explicitWindow?: RuntimeCapabilityWindow;
+}
+
+export interface ResolvedToolSurface {
+ readonly scope: ToolScope;
+ readonly window?: RuntimeCapabilityWindow;
+ /** The profile that applied ("full" when none/unknown). */
+ readonly profile: string;
+ /** Set when the requested profile did not exist (fail-open marker). */
+ readonly unknownProfile?: string;
+}
+
+function mergeWindows(
+ profile: RuntimeCapabilityWindow | undefined,
+ explicit: RuntimeCapabilityWindow | undefined,
+): RuntimeCapabilityWindow | undefined {
+ if (profile === undefined) return explicit;
+ if (explicit === undefined) return profile;
+ return {
+ ...((explicit.allowedTools ?? profile.allowedTools)
+ ? { allowedTools: explicit.allowedTools ?? profile.allowedTools! }
+ : {}),
+ ...((explicit.disabledTools ?? profile.disabledTools)
+ ? { disabledTools: explicit.disabledTools ?? profile.disabledTools! }
+ : {}),
+ ...((explicit.maxTools ?? profile.maxTools) !== undefined
+ ? { maxTools: (explicit.maxTools ?? profile.maxTools)! }
+ : {}),
+ };
+}
+
+/** Resolve the effective surface. Unknown profiles fail OPEN to full. */
+export function resolveToolSurface(opts: ResolveToolSurfaceOptions): ResolvedToolSurface {
+ const requested = opts.profileName?.trim() || null;
+ if (requested === null) {
+ return {
+ scope: opts.explicitScope ?? "full",
+ ...(opts.explicitWindow ? { window: opts.explicitWindow } : {}),
+ profile: opts.explicitScope ?? "full",
+ };
+ }
+ const profile = TOOL_SURFACE_PROFILES[requested];
+ if (profile === undefined) {
+ return {
+ scope: opts.explicitScope ?? "full",
+ ...(opts.explicitWindow ? { window: opts.explicitWindow } : {}),
+ profile: "full",
+ unknownProfile: requested,
+ };
+ }
+ const window = mergeWindows(profile.window, opts.explicitWindow);
+ return {
+ scope: opts.explicitScope ?? profile.scope,
+ ...(window ? { window } : {}),
+ profile: profile.name,
+ };
+}
diff --git a/src/mcp/registry-guard.ts b/src/mcp/registry-guard.ts
index 5ebfc4b2..59b01535 100644
--- a/src/mcp/registry-guard.ts
+++ b/src/mcp/registry-guard.ts
@@ -125,6 +125,8 @@ export const PREVIEW_BUDGET_EXEMPT: Readonly<Record<string, string>> = Object.fr
brain_procedural_graph: "bounded graph summary",
brain_recurrence: "bounded recurrence records; learn/forget are writes",
brain_agent_diff: "bounded two-agent comparison",
+ get_skill: "explicit full-content fetch; truncating the skill the agent asked for defeats it",
+ tool_hydrate: "the two-pass schema escape hatch; truncating hydration would defeat itself",
// Deprecated aliases (token-diet): the consolidated tool carries the
// budget; the alias keeps its predecessor's budget status until
diff --git a/src/mcp/search-tools.ts b/src/mcp/search-tools.ts
index 201592f3..acd3c116 100644
--- a/src/mcp/search-tools.ts
+++ b/src/mcp/search-tools.ts
@@ -39,6 +39,12 @@ const SEARCH_INPUT_SCHEMA: Record<string, unknown> = {
query_document: { type: "string", minLength: 1, maxLength: 4000 },
focus_query: { type: "string", minLength: 1, maxLength: 1000 },
focus_path_prefix: { type: "string", minLength: 1, maxLength: 256 },
+ focus_session: {
+ type: "string",
+ minLength: 1,
+ maxLength: 128,
+ description: "Session id whose bound focus applies (falls back to the global focus).",
+ },
evidence_pack: { type: "boolean" },
include_superseded: {
type: "boolean",
@@ -287,6 +293,7 @@ async function toolBrainSearch(
pathPrefix: focusPathPrefix ?? null,
})
: undefined;
+ const focusSession = coerceStringOptional(args, "focus_session", 128);
const properties = parsePropertiesArgument(args["properties"]);
const visibility = parseVisibilityArgument(args["visibility"]);
@@ -309,6 +316,7 @@ async function toolBrainSearch(
...(visibility !== undefined ? { visibility } : {}),
...(structuredQuery !== undefined ? { structuredQuery } : {}),
...(sessionFocus !== undefined ? { sessionFocus } : {}),
+ ...(focusSession !== undefined ? { focusSession } : {}),
...(evidencePack ? { evidencePack: true } : {}),
...(includeSuperseded ? { includeSuperseded: true } : {}),
...(since !== undefined ? { since } : {}),
diff --git a/src/mcp/skill-tools.ts b/src/mcp/skill-tools.ts
new file mode 100644
index 00000000..51eebc6b
--- /dev/null
+++ b/src/mcp/skill-tools.ts
@@ -0,0 +1,146 @@
+/**
+ * Skill surface MCP tools (Agent Surface Suite).
+ *
+ * `list_skills` / `get_skill` let any MCP-connected agent discover and
+ * load the skills Open Second Brain ships in `skills/` (plus optional
+ * vault-local skills under `Brain/skills/`) without shell access or
+ * prior knowledge of skill names. `skills_attach` is the deterministic
+ * per-turn relevance surface: gated by the `skill_auto_attach` config
+ * key (default off), it scores skills against the current turn text
+ * with the shared lexical scorer and returns a char-budgeted block.
+ */
+
+import { resolveSkillAutoAttach } from "../core/config.ts";
+import { buildSkillAttachment } from "../core/surface/skill-attach.ts";
+import { discoverSkills, readSkillFile, skillRoots, SkillError } from "../core/surface/skills.ts";
+import { coerceInt, coerceStr } from "./coerce.ts";
+import { MCP_PREVIEW_BUDGET } from "./preview-budget.ts";
+import { INVALID_PARAMS, MCPError } from "./protocol.ts";
+import type { ServerContext, ToolDefinition } from "./tools.ts";
+
+function rootsFor(ctx: ServerContext): string[] {
+ return skillRoots({ repoRoot: ctx.repoRoot, vault: ctx.vault });
+}
+
+function toolListSkills(ctx: ServerContext): Record<string, unknown> {
+ const skills = discoverSkills(rootsFor(ctx));
+ return {
+ count: skills.length,
+ skills: skills.map((s) => ({
+ name: s.name,
+ description: s.description,
+ path: s.path,
+ })),
+ };
+}
+
+function toolGetSkill(ctx: ServerContext, args: Record<string, unknown>): Record<string, unknown> {
+ const name = coerceStr(args, "name", true)!;
+ const filePath = coerceStr(args, "file_path", false) ?? undefined;
+ const skills = discoverSkills(rootsFor(ctx));
+ const skill = skills.find((s) => s.name === name);
+ if (skill === undefined) {
+ const known = skills.map((s) => s.name).join(", ") || "(none)";
+ throw new MCPError(INVALID_PARAMS, `unknown skill: ${name}. Known skills: ${known}`);
+ }
+ let content: string;
+ try {
+ content = readSkillFile(skill, filePath);
+ } catch (err) {
+ if (err instanceof SkillError) throw new MCPError(INVALID_PARAMS, err.message);
+ throw err;
+ }
+ return {
+ name: skill.name,
+ description: skill.description,
+ path: skill.path,
+ ...(filePath !== undefined ? { file_path: filePath } : {}),
+ content,
+ };
+}
+
+function toolSkillsAttach(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Record<string, unknown> {
+ const query = coerceStr(args, "query", true)!;
+ const maxSkills = coerceInt(args, "max_skills", 3, 1, 10);
+ if (!resolveSkillAutoAttach(ctx.configPath ?? undefined)) {
+ return { enabled: false, block: "", skills: [] };
+ }
+ const attachment = buildSkillAttachment({
+ query,
+ skills: discoverSkills(rootsFor(ctx)),
+ maxSkills,
+ });
+ return {
+ enabled: true,
+ block: attachment.block,
+ skills: attachment.items.map((item) => ({
+ name: item.name,
+ description: item.description,
+ path: item.path,
+ score: item.score,
+ })),
+ };
+}
+
+export const SKILL_TOOLS: ReadonlyArray<ToolDefinition> = [
+ {
+ name: "list_skills",
+ description:
+ "List agent skills shipped with Open Second Brain (and vault-local Brain/skills/) with one-line descriptions. Read-only.",
+ inputSchema: {
+ type: "object",
+ properties: {},
+ additionalProperties: false,
+ },
+ previewBudget: MCP_PREVIEW_BUDGET,
+ handler: (ctx) => toolListSkills(ctx),
+ },
+ {
+ name: "get_skill",
+ description:
+ "Fetch a skill's SKILL.md content by name; optional file_path reads an auxiliary file inside the same skill directory. Read-only.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ name: {
+ type: "string",
+ description: "Skill name as returned by list_skills.",
+ },
+ file_path: {
+ type: "string",
+ description: "Optional relative path to an auxiliary file inside the skill directory.",
+ },
+ },
+ required: ["name"],
+ additionalProperties: false,
+ },
+ handler: (ctx, args) => toolGetSkill(ctx, args),
+ },
+ {
+ name: "skills_attach",
+ description:
+ "Score available skills against the current turn text and return a char-budgeted block of relevant skill summaries. Returns enabled:false unless skill_auto_attach is configured.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ query: {
+ type: "string",
+ description: "Current turn text to score skills against.",
+ },
+ max_skills: {
+ type: "integer",
+ minimum: 1,
+ maximum: 10,
+ description: "Maximum number of skills to attach (default 3).",
+ },
+ },
+ required: ["query"],
+ additionalProperties: false,
+ },
+ previewBudget: MCP_PREVIEW_BUDGET,
+ handler: (ctx, args) => toolSkillsAttach(ctx, args),
+ },
+];
diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts
index 75c8d75a..1220483d 100644
--- a/src/mcp/tools.ts
+++ b/src/mcp/tools.ts
@@ -33,6 +33,8 @@ import { SEARCH_TOOLS, buildSearchStatusBlock } from "./search-tools.ts";
import { SCHEMA_TOOLS } from "./schema-tools.ts";
import { WATCHDOG_TOOLS } from "./watchdog-tools.ts";
import { PAY_MEMORY_TOOLS } from "./pay-memory-tools.ts";
+import { SKILL_TOOLS } from "./skill-tools.ts";
+import { buildHydrateTool, TOOL_HYDRATE_NAME } from "./hydrate-tool.ts";
import { normalizeAgentArgument, PLACEHOLDER_AGENT_VALUES } from "../core/agent-identity.ts";
import { vaultRelative } from "../core/path-safety.ts";
import { listVaultPages } from "../core/vault.ts";
@@ -263,7 +265,7 @@ const CAPABILITIES_OUTPUT_SCHEMA: OutputSchema = {
"withheld",
],
properties: {
- scope: { type: "string", enum: ["full", "writer"] },
+ scope: { type: "string", enum: ["full", "writer", "catalog"] },
server_name: { type: "string" },
static_tool_count: { type: "integer" },
available_tool_count: { type: "integer" },
@@ -286,7 +288,7 @@ const CAPABILITIES_OUTPUT_SCHEMA: OutputSchema = {
},
};
-export type ToolScope = "full" | "writer";
+export type ToolScope = "full" | "writer" | "catalog";
/**
* Deprecated delegating alias (token-diet, t_3920db77): the tool name
@@ -326,6 +328,15 @@ const WRITER_TOOL_NAMES: ReadonlySet<string> = new Set([
"brain_pinned_context",
]);
+// First-pass surface of the two-pass catalog scope (Agent Surface
+// Suite): the always-available diagnostic, the writer set, and the
+// hydration tool. Everything else stays callable but unadvertised.
+const CATALOG_ADVERTISED_NAMES: ReadonlySet<string> = new Set([
+ CAPABILITY_DIAGNOSTIC_TOOL,
+ ...WRITER_TOOL_NAMES,
+ TOOL_HYDRATE_NAME,
+]);
+
export function buildToolTable(scope: ToolScope = "full"): ToolDefinition[] {
const all: ToolDefinition[] = [
{
@@ -414,9 +425,19 @@ export function buildToolTable(scope: ToolScope = "full"): ToolDefinition[] {
...SCHEMA_TOOLS,
...WATCHDOG_TOOLS,
...PAY_MEMORY_TOOLS,
+ ...SKILL_TOOLS,
];
+ if (scope === "writer") return all.filter((t) => WRITER_TOOL_NAMES.has(t.name));
+ // The hydrate tool closes over the finished table (itself included)
+ // so its catalog and schema lookups always reflect this process's
+ // real surface.
+ all.push(buildHydrateTool(() => all));
if (scope === "full") return all;
- return all.filter((t) => WRITER_TOOL_NAMES.has(t.name));
+ // Catalog scope: the compact first-pass set stays advertised; every
+ // other tool keeps `hidden` semantics - callable, not listed.
+ return all.map((t) =>
+ CATALOG_ADVERTISED_NAMES.has(t.name) || t.hidden === true ? t : { ...t, hidden: true },
+ );
}
export function findTool(tools: ReadonlyArray<ToolDefinition>, name: string): ToolDefinition {
diff --git a/tests/cli/import-session-roles.test.ts b/tests/cli/import-session-roles.test.ts
new file mode 100644
index 00000000..cfbd811f
--- /dev/null
+++ b/tests/cli/import-session-roles.test.ts
@@ -0,0 +1,71 @@
+/**
+ * Config-level role filtering for session capture (t_e2346fe9): the
+ * `session_capture_roles` key supplies the default `--filter-role`
+ * set; an explicit flag always wins.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let config: string;
+const FIXTURE = join(process.cwd(), "tests/fixtures/sessions/claude-minimal.jsonl");
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-roles-cli-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });
+ config = join(tmp, "config.yaml");
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function writeConfig(extra = ""): void {
+ writeFileSync(config, `vault: "${vault}"\n${extra}`);
+}
+
+async function importJson(extraArgs: string[] = []): Promise<Record<string, unknown>> {
+ const r = await runCli(
+ ["brain", "import-session", FIXTURE, "--vault", vault, "--json", ...extraArgs],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ const parsed = JSON.parse(r.stdout) as { files: Array<Record<string, unknown>> };
+ return parsed.files[0]!;
+}
+
+test("session_capture_roles filters turns when no flag is given", async () => {
+ writeConfig('session_capture_roles: "assistant"\n');
+ const file = await importJson();
+ // The claude fixture has user turns; with an assistant-only default
+ // they are filtered out instead of scanned for facts/markers.
+ expect(file["filtered_turns"] as number).toBeGreaterThan(0);
+});
+
+test("absent key keeps capture-all behaviour (bit-identical default)", async () => {
+ writeConfig();
+ const file = await importJson();
+ expect(file["filtered_turns"]).toBe(0);
+});
+
+test("an explicit --filter-role flag wins over the config default", async () => {
+ writeConfig('session_capture_roles: "assistant"\n');
+ const withFlag = await importJson(["--filter-role", "user", "--filter-role", "assistant"]);
+ expect(withFlag["filtered_turns"]).toBe(0);
+});
+
+test("an invalid config role fails fast with a clear error", async () => {
+ writeConfig('session_capture_roles: "user,reviewer"\n');
+ const r = await runCli(["brain", "import-session", FIXTURE, "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).not.toBe(0);
+ expect(r.stderr + r.stdout).toContain("session_capture_roles");
+});
diff --git a/tests/core/brain/context-pack-focus.test.ts b/tests/core/brain/context-pack-focus.test.ts
new file mode 100644
index 00000000..34ca42eb
--- /dev/null
+++ b/tests/core/brain/context-pack-focus.test.ts
@@ -0,0 +1,71 @@
+import { test, expect, beforeEach, afterEach } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { packContext } from "../../../src/core/brain/context-pack.ts";
+import { normalizeSessionFocus } from "../../../src/core/search/session-focus.ts";
+import { resolveSearchFocusContextPack } from "../../../src/core/config.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-pack-focus-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function writePref(slug: string, principle: string, createdAt: string): void {
+ writeFileSync(
+ join(vault, "Brain", "preferences", `pref-${slug}.md`),
+ [
+ "---",
+ `id: pref-${slug}`,
+ `topic: ${slug}`,
+ `principle: ${principle}`,
+ "tier: core",
+ `created_at: ${createdAt}`,
+ "---",
+ "",
+ principle,
+ "",
+ ].join("\n"),
+ );
+}
+
+test("an active session focus promotes matching memories within their tier", () => {
+ // Without focus the newer pref sorts first; the focus flips the order.
+ writePref("unrelated", "Always write tests first", "2026-01-02T00:00:00Z");
+ writePref("embeddings", "Prefer local embedding providers for recall", "2026-01-01T00:00:00Z");
+
+ const plain = packContext(vault, { maxTokens: 10_000 });
+ expect(plain.items.map((i) => i.id)).toEqual(["pref-unrelated", "pref-embeddings"]);
+
+ const focused = packContext(vault, {
+ maxTokens: 10_000,
+ // Focus must be unexpired relative to the real clock the pack uses.
+ sessionFocus: normalizeSessionFocus({ query: "embedding providers recall" }, Date.now()),
+ });
+ expect(focused.items.map((i) => i.id)).toEqual(["pref-embeddings", "pref-unrelated"]);
+});
+
+test("a null or expired focus leaves the pack byte-identical", () => {
+ writePref("a", "Alpha principle", "2026-01-02T00:00:00Z");
+ writePref("b", "Beta principle", "2026-01-01T00:00:00Z");
+ const plain = packContext(vault, { maxTokens: 10_000 });
+ const withNull = packContext(vault, { maxTokens: 10_000, sessionFocus: null });
+ expect(withNull.items.map((i) => i.id)).toEqual(plain.items.map((i) => i.id));
+});
+
+test("resolveSearchFocusContextPack defaults off and reads the config key", () => {
+ const tmp = mkdtempSync(join(tmpdir(), "osb-pack-focus-cfg-"));
+ const config = join(tmp, "config.yaml");
+ writeFileSync(config, `vault: "${vault}"\n`);
+ expect(resolveSearchFocusContextPack(config)).toBe(false);
+ writeFileSync(config, `vault: "${vault}"\nsearch_focus_context_pack: "true"\n`);
+ expect(resolveSearchFocusContextPack(config)).toBe(true);
+ rmSync(tmp, { recursive: true, force: true });
+});
diff --git a/tests/core/brain/handoff.test.ts b/tests/core/brain/handoff.test.ts
new file mode 100644
index 00000000..98e633f0
--- /dev/null
+++ b/tests/core/brain/handoff.test.ts
@@ -0,0 +1,120 @@
+import { test, expect, beforeEach, afterEach } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { buildHandoffNote, writeHandoffNote } from "../../../src/core/brain/handoff.ts";
+import type { SessionTurn } from "../../../src/core/brain/sessions/types.ts";
+
+const NOW = new Date("2026-06-03T12:00:00Z");
+
+function turn(
+ role: SessionTurn["role"],
+ text: string,
+ toolCalls?: SessionTurn["toolCalls"],
+): SessionTurn {
+ return Object.freeze({
+ turnId: `t-${role}-${text.slice(0, 8)}`,
+ timestamp: "2026-06-03T11:00:00Z",
+ role,
+ text,
+ ...(toolCalls ? { toolCalls } : {}),
+ });
+}
+
+const TURNS: SessionTurn[] = [
+ turn("user", "Please add a cost gate to the embedding indexer and document it."),
+ turn(
+ "assistant",
+ "I implemented the cost gate and added tests. Note that the gate only fires when positive.\nNext step: wire the docs.",
+ [
+ { name: "Write", input: { file_path: "src/core/search/indexer.ts" } },
+ { name: "Edit", input: { file_path: "docs/cli-reference.md" } },
+ ],
+ ),
+ turn("assistant", "Done: docs updated. TODO: announce in the changelog later."),
+];
+
+test("buildHandoffNote extracts the five sections deterministically", () => {
+ const note = buildHandoffNote(TURNS, { sessionId: "Sess 42", agent: "test-agent", now: NOW });
+ expect(note).toContain("## Request");
+ expect(note).toContain("add a cost gate");
+ expect(note).toContain("## Completed work");
+ expect(note).toContain("Done: docs updated");
+ expect(note).toContain("## Files changed");
+ expect(note).toContain("src/core/search/indexer.ts");
+ expect(note).toContain("docs/cli-reference.md");
+ expect(note).toContain("## Learned context");
+ expect(note).toContain("gate only fires when positive");
+ expect(note).toContain("## Next steps");
+ expect(note).toContain("announce in the changelog");
+ // Deterministic: same input, same note.
+ expect(buildHandoffNote(TURNS, { sessionId: "Sess 42", agent: "test-agent", now: NOW })).toBe(
+ note,
+ );
+});
+
+test("empty sections render an explicit placeholder, never vanish", () => {
+ const note = buildHandoffNote([turn("user", "hi")], {
+ sessionId: "s",
+ agent: "a",
+ now: NOW,
+ });
+ expect(note).toContain("## Completed work");
+ expect(note).toContain("(none captured)");
+});
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-handoff-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+test("SessionEnd lifecycle writes a handoff only when session_handoff is on", async () => {
+ const { captureSessionLifecycleEvent } =
+ await import("../../../src/core/brain/session-lifecycle.ts");
+ const fixture = join(process.cwd(), "tests/fixtures/sessions/claude-minimal.jsonl");
+ const payload = {
+ hook_event_name: "SessionEnd",
+ session_id: "end-1",
+ transcript_path: fixture,
+ };
+
+ // Default off: no handoff note.
+ delete process.env["OPEN_SECOND_BRAIN_SESSION_HANDOFF"];
+ const off = await captureSessionLifecycleEvent(vault, payload, { agent: "a" });
+ expect(off.handoff_path).toBeUndefined();
+ expect(existsSync(join(vault, "Brain", "handoffs"))).toBe(false);
+
+ // Gated on: one note per session end.
+ process.env["OPEN_SECOND_BRAIN_SESSION_HANDOFF"] = "true";
+ try {
+ const on = await captureSessionLifecycleEvent(vault, payload, { agent: "a" });
+ expect(on.handoff_path).toBeDefined();
+ expect(existsSync(on.handoff_path!)).toBe(true);
+ expect(readFileSync(on.handoff_path!, "utf8")).toContain("## Request");
+ } finally {
+ delete process.env["OPEN_SECOND_BRAIN_SESSION_HANDOFF"];
+ }
+});
+
+test("writeHandoffNote lands Brain/handoffs/<date>-<scope>.md with frontmatter", () => {
+ const result = writeHandoffNote(vault, {
+ turns: TURNS,
+ sessionId: "Sess 42",
+ agent: "test-agent",
+ now: NOW,
+ });
+ expect(result.path.endsWith(join("Brain", "handoffs", "2026-06-03-sess-42.md"))).toBe(true);
+ expect(existsSync(result.path)).toBe(true);
+ const content = readFileSync(result.path, "utf8");
+ // Caller-supplied scalars are JSON-quoted against YAML injection.
+ expect(content).toContain('session_id: "Sess 42"');
+ expect(content).toContain('agent: "test-agent"');
+ expect(content).toContain("## Request");
+});
diff --git a/tests/core/brain/intentions.test.ts b/tests/core/brain/intentions.test.ts
new file mode 100644
index 00000000..aec556e6
--- /dev/null
+++ b/tests/core/brain/intentions.test.ts
@@ -0,0 +1,94 @@
+import { test, expect, beforeEach, afterEach } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ listIntentions,
+ moveIntentionToHistory,
+ setIntention,
+ showIntention,
+} from "../../../src/core/brain/intentions.ts";
+
+const NOW = new Date("2026-06-03T12:00:00Z");
+const LATER = new Date("2026-06-03T13:30:00Z");
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-intentions-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+test("setIntention creates a scoped now-document at version 1", () => {
+ const chain = setIntention(vault, {
+ scope: "feat/agent-surface",
+ text: "Ship the surface suite",
+ agent: "test-agent",
+ now: NOW,
+ });
+ expect(chain.scope).toBe("feat-agent-surface");
+ expect(chain.version).toBe(1);
+ expect(chain.path.endsWith(join("Brain", "intentions", "feat-agent-surface.md"))).toBe(true);
+ expect(readFileSync(chain.path, "utf8")).toContain("Ship the surface suite");
+});
+
+test("updating bumps the version and appends the prior text to history", () => {
+ setIntention(vault, { scope: "ws", text: "First intention", agent: "a", now: NOW });
+ const chain = setIntention(vault, { scope: "ws", text: "Pivoted plan", agent: "a", now: LATER });
+ expect(chain.version).toBe(2);
+ const content = readFileSync(chain.path, "utf8");
+ expect(content).toContain("Pivoted plan");
+ expect(content).toContain("## History");
+ expect(content).toContain("v1");
+ expect(content).toContain("First intention");
+});
+
+test("showIntention returns the current chain and null for unknown scopes", () => {
+ setIntention(vault, { scope: "ws", text: "Current work", agent: "a", now: NOW });
+ const chain = showIntention(vault, "ws");
+ expect(chain?.text).toBe("Current work");
+ expect(chain?.version).toBe(1);
+ expect(showIntention(vault, "ghost")).toBeNull();
+});
+
+test("listIntentions lists active chains sorted by scope", () => {
+ setIntention(vault, { scope: "zeta", text: "Z work", agent: "a", now: NOW });
+ setIntention(vault, { scope: "alpha", text: "A work", agent: "a", now: NOW });
+ const all = listIntentions(vault);
+ expect(all.map((c) => c.scope)).toEqual(["alpha", "zeta"]);
+});
+
+test("moveIntentionToHistory archives the chain and clears the active file", () => {
+ setIntention(vault, { scope: "ws", text: "Done soon", agent: "a", now: NOW });
+ const moved = moveIntentionToHistory(vault, { scope: "ws", now: LATER });
+ expect(moved.archivePath).toContain(join("Brain", "intentions", "history"));
+ expect(existsSync(moved.archivePath)).toBe(true);
+ expect(showIntention(vault, "ws")).toBeNull();
+ expect(readFileSync(moved.archivePath, "utf8")).toContain("Done soon");
+});
+
+test("moving an unknown scope throws a clear error", () => {
+ expect(() => moveIntentionToHistory(vault, { scope: "ghost", now: NOW })).toThrow(
+ "no active intention",
+ );
+});
+
+test("archive collisions get a numeric suffix instead of clobbering", () => {
+ setIntention(vault, { scope: "ws", text: "First run", agent: "a", now: NOW });
+ const first = moveIntentionToHistory(vault, { scope: "ws", now: LATER });
+ setIntention(vault, { scope: "ws", text: "Second run", agent: "a", now: LATER });
+ const second = moveIntentionToHistory(vault, { scope: "ws", now: LATER });
+ expect(second.archivePath).not.toBe(first.archivePath);
+ expect(existsSync(first.archivePath)).toBe(true);
+ expect(existsSync(second.archivePath)).toBe(true);
+});
+
+test("Brain/pinned.md is never touched by intention operations", () => {
+ setIntention(vault, { scope: "ws", text: "Work", agent: "a", now: NOW });
+ expect(existsSync(join(vault, "Brain", "pinned.md"))).toBe(false);
+});
diff --git a/tests/core/brain/session-lifecycle-focus.test.ts b/tests/core/brain/session-lifecycle-focus.test.ts
new file mode 100644
index 00000000..4e99ae38
--- /dev/null
+++ b/tests/core/brain/session-lifecycle-focus.test.ts
@@ -0,0 +1,55 @@
+import { test, expect, beforeEach, afterEach } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { captureSessionLifecycleEvent } from "../../../src/core/brain/session-lifecycle.ts";
+import {
+ normalizeSessionFocus,
+ readSessionFocus,
+ writeSessionFocus,
+} from "../../../src/core/search/session-focus.ts";
+import { resolveSearchConfig } from "../../../src/core/search/index.ts";
+
+const NOW = 1_750_000_000_000;
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-lifecycle-focus-"));
+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+test("SessionEnd auto-clears that session's scoped focus only", async () => {
+ const cfg = resolveSearchConfig({ vault });
+ writeSessionFocus(cfg, normalizeSessionFocus({ query: "mine" }, NOW), "sess-end-1");
+ writeSessionFocus(cfg, normalizeSessionFocus({ query: "other" }, NOW), "sess-end-2");
+ writeSessionFocus(cfg, normalizeSessionFocus({ query: "global" }, NOW));
+
+ const result = await captureSessionLifecycleEvent(
+ vault,
+ { hook_event_name: "SessionEnd", session_id: "sess-end-1" },
+ { agent: "test-agent" },
+ );
+
+ expect(result.focus_cleared).toBe(true);
+ expect(readSessionFocus(cfg, NOW, "sess-end-1")).toBeNull();
+ expect(readSessionFocus(cfg, NOW, "sess-end-2")?.query).toBe("other");
+ expect(readSessionFocus(cfg, NOW)?.query).toBe("global");
+});
+
+test("non-SessionEnd events never clear focus", async () => {
+ const cfg = resolveSearchConfig({ vault });
+ writeSessionFocus(cfg, normalizeSessionFocus({ query: "mine" }, NOW), "sess-live");
+ const result = await captureSessionLifecycleEvent(
+ vault,
+ { hook_event_name: "UserPromptSubmit", session_id: "sess-live", prompt: "hello" },
+ { agent: "test-agent" },
+ );
+ expect(result.focus_cleared).toBeUndefined();
+ expect(readSessionFocus(cfg, NOW, "sess-live")?.query).toBe("mine");
+});
diff --git a/tests/core/brain/session-scope.test.ts b/tests/core/brain/session-scope.test.ts
new file mode 100644
index 00000000..9426f0be
--- /dev/null
+++ b/tests/core/brain/session-scope.test.ts
@@ -0,0 +1,34 @@
+import { test, expect } from "bun:test";
+
+import { resolveSessionScope, SessionScopeError } from "../../../src/core/brain/session-scope.ts";
+
+test("normalises arbitrary session ids to safe slugs", () => {
+ expect(resolveSessionScope("Sess_01 (Claude)")).toBe("sess-01-claude");
+ expect(resolveSessionScope("dc6dd88a-dd62-448e-b4d0-e65a2accab69")).toBe(
+ "dc6dd88a-dd62-448e-b4d0-e65a2accab69",
+ );
+ expect(resolveSessionScope("feat/agent-surface")).toBe("feat-agent-surface");
+});
+
+test("collapses runs of separators and trims edge dashes", () => {
+ expect(resolveSessionScope("a//b__c d")).toBe("a-b-c-d");
+ expect(resolveSessionScope("--edge--")).toBe("edge");
+});
+
+test("caps the slug length deterministically", () => {
+ const long = "x".repeat(200);
+ const scope = resolveSessionScope(long);
+ expect(scope.length).toBeLessThanOrEqual(64);
+ expect(resolveSessionScope(long)).toBe(scope);
+});
+
+test("rejects empty and separator-only input with a typed error", () => {
+ expect(() => resolveSessionScope("")).toThrow(SessionScopeError);
+ expect(() => resolveSessionScope(" ")).toThrow(SessionScopeError);
+ expect(() => resolveSessionScope("///")).toThrow(SessionScopeError);
+});
+
+test("is idempotent: a resolved scope resolves to itself", () => {
+ const scope = resolveSessionScope("My Workstream #42");
+ expect(resolveSessionScope(scope)).toBe(scope);
+});
diff --git a/tests/core/config.capture-roles.test.ts b/tests/core/config.capture-roles.test.ts
new file mode 100644
index 00000000..44596dd1
--- /dev/null
+++ b/tests/core/config.capture-roles.test.ts
@@ -0,0 +1,46 @@
+import { test, expect, beforeEach, afterEach } from "bun:test";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { resolveSessionCaptureRoles } from "../../src/core/config.ts";
+
+let tmp: string;
+let config: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "osb-capture-roles-"));
+ config = join(tmp, "config.yaml");
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ delete process.env["OPEN_SECOND_BRAIN_SESSION_CAPTURE_ROLES"];
+});
+
+test("absent key captures all roles (null = no filter)", () => {
+ writeFileSync(config, `vault: "${tmp}"\n`);
+ expect(resolveSessionCaptureRoles(config)).toBeNull();
+ expect(resolveSessionCaptureRoles(join(tmp, "ghost.yaml"))).toBeNull();
+});
+
+test("comma-separated roles parse, trim, and dedupe", () => {
+ writeFileSync(config, `vault: "${tmp}"\nsession_capture_roles: "user, assistant,user"\n`);
+ expect(resolveSessionCaptureRoles(config)).toEqual(["user", "assistant"]);
+});
+
+test("an empty value is treated as no filter", () => {
+ writeFileSync(config, `vault: "${tmp}"\nsession_capture_roles: ""\n`);
+ expect(resolveSessionCaptureRoles(config)).toBeNull();
+});
+
+test("an invalid role name fails fast", () => {
+ writeFileSync(config, `vault: "${tmp}"\nsession_capture_roles: "user,reviewer"\n`);
+ expect(() => resolveSessionCaptureRoles(config)).toThrow("session_capture_roles");
+});
+
+test("the env override wins over the config key", () => {
+ writeFileSync(config, `vault: "${tmp}"\nsession_capture_roles: "user"\n`);
+ process.env["OPEN_SECOND_BRAIN_SESSION_CAPTURE_ROLES"] = "tool,meta";
+ expect(resolveSessionCaptureRoles(config)).toEqual(["tool", "meta"]);
+});
diff --git a/tests/core/search/session-focus-scoped.test.ts b/tests/core/search/session-focus-scoped.test.ts
new file mode 100644
index 00000000..14cbfb6a
--- /dev/null
+++ b/tests/core/search/session-focus-scoped.test.ts
@@ -0,0 +1,81 @@
+import { test, expect, beforeEach, afterEach } from "bun:test";
+import { existsSync } from "node:fs";
+import { join, dirname } from "node:path";
+
+import {
+ clearSessionFocus,
+ normalizeSessionFocus,
+ readActiveSessionFocus,
+ readSessionFocus,
+ sessionFocusPath,
+ writeSessionFocus,
+} from "../../../src/core/search/session-focus.ts";
+import { createTempVault, makeConfig } from "../../helpers/search-fixtures.ts";
+import type { ResolvedSearchConfig } from "../../../src/core/search/types.ts";
+
+const NOW = 1_750_000_000_000;
+
+let cfg: ResolvedSearchConfig;
+let cleanup: () => void;
+
+beforeEach(() => {
+ const t = createTempVault("focus-scoped");
+ cfg = makeConfig({ vault: t.vault, dbPath: t.dbPath });
+ cleanup = t.cleanup;
+});
+
+afterEach(() => {
+ cleanup();
+});
+
+function focus(query: string) {
+ return normalizeSessionFocus({ query }, NOW);
+}
+
+test("a scoped focus file lives under search-focus/<scope>.json", () => {
+ const path = sessionFocusPath(cfg, "sess-1");
+ expect(path.endsWith(join("search-focus", "sess-1.json"))).toBe(true);
+ expect(dirname(sessionFocusPath(cfg))).toBe(dirname(dirname(path)));
+});
+
+test("scoped write/read round-trips without touching the global file", () => {
+ writeSessionFocus(cfg, focus("scoped topic"), "sess-1");
+ expect(readSessionFocus(cfg, NOW, "sess-1")?.query).toBe("scoped topic");
+ expect(readSessionFocus(cfg, NOW)).toBeNull();
+ expect(existsSync(sessionFocusPath(cfg))).toBe(false);
+});
+
+test("readActiveSessionFocus prefers the session focus over the global one", () => {
+ writeSessionFocus(cfg, focus("global topic"));
+ writeSessionFocus(cfg, focus("session topic"), "sess-1");
+ expect(readActiveSessionFocus(cfg, "sess-1", NOW)?.query).toBe("session topic");
+});
+
+test("readActiveSessionFocus falls back to global when the session has none", () => {
+ writeSessionFocus(cfg, focus("global topic"));
+ expect(readActiveSessionFocus(cfg, "sess-2", NOW)?.query).toBe("global topic");
+ expect(readActiveSessionFocus(cfg, undefined, NOW)?.query).toBe("global topic");
+});
+
+test("an expired session focus falls back to the global focus", () => {
+ writeSessionFocus(cfg, focus("global topic"));
+ writeSessionFocus(cfg, normalizeSessionFocus({ query: "stale", ttlMinutes: 1 }, NOW), "sess-1");
+ const later = NOW + 10 * 60 * 1000;
+ expect(readActiveSessionFocus(cfg, "sess-1", later)?.query).toBe("global topic");
+});
+
+test("clearing a scope removes only that scope's file", () => {
+ writeSessionFocus(cfg, focus("global topic"));
+ writeSessionFocus(cfg, focus("one"), "sess-1");
+ writeSessionFocus(cfg, focus("two"), "sess-2");
+ clearSessionFocus(cfg, "sess-1");
+ expect(readSessionFocus(cfg, NOW, "sess-1")).toBeNull();
+ expect(readSessionFocus(cfg, NOW, "sess-2")?.query).toBe("two");
+ expect(readSessionFocus(cfg, NOW)?.query).toBe("global topic");
+});
+
+test("a raw session id is normalised to its scope slug", () => {
+ writeSessionFocus(cfg, focus("normalised"), "My Session #42");
+ expect(readSessionFocus(cfg, NOW, "my-session-42")?.query).toBe("normalised");
+ expect(readActiveSessionFocus(cfg, "My Session #42", NOW)?.query).toBe("normalised");
+});
diff --git a/tests/core/surface/descriptor.test.ts b/tests/core/surface/descriptor.test.ts
new file mode 100644
index 00000000..fef62403
--- /dev/null
+++ b/tests/core/surface/descriptor.test.ts
@@ -0,0 +1,73 @@
+import { test, expect } from "bun:test";
+
+import {
+ toolDescriptors,
+ skillDescriptors,
+ firstLine,
+ surfaceGroup,
+ type SurfaceDescriptor,
+} from "../../../src/core/surface/descriptor.ts";
+
+const TOOLS = [
+ {
+ name: "second_brain_status",
+ description: "Report Open Second Brain configuration and vault status.",
+ },
+ {
+ name: "brain_feedback",
+ description: "Record one Brain taste signal.\nLong second line that must not leak.",
+ },
+ { name: "schema_inspect", description: "Inspect Brain schema vocabulary." },
+ { name: "brain_search", description: "Hybrid keyword + semantic vault search." },
+];
+
+test("toolDescriptors emits one sorted descriptor per tool", () => {
+ const out = toolDescriptors(TOOLS);
+ expect(out.map((d) => d.name)).toEqual([
+ "brain_feedback",
+ "brain_search",
+ "schema_inspect",
+ "second_brain_status",
+ ]);
+ for (const d of out) expect(d.kind).toBe("tool");
+});
+
+test("descriptions are first-line only", () => {
+ const out = toolDescriptors(TOOLS);
+ const feedback = out.find((d) => d.name === "brain_feedback")!;
+ expect(feedback.description).toBe("Record one Brain taste signal.");
+});
+
+test("surfaceGroup derives a group from the name prefix", () => {
+ expect(surfaceGroup("brain_feedback")).toBe("brain");
+ expect(surfaceGroup("schema_inspect")).toBe("schema");
+ expect(surfaceGroup("payment_policy_check")).toBe("payment");
+ expect(surfaceGroup("second_brain_status")).toBe("core");
+ expect(surfaceGroup("vault_health")).toBe("core");
+});
+
+test("skillDescriptors maps skill entries with the skill group", () => {
+ const out = skillDescriptors([
+ { name: "brain-memory", description: "Memory discipline skill.", path: "skills/brain-memory" },
+ { name: "schema-author", description: "", path: "skills/schema-author" },
+ ]);
+ expect(out).toHaveLength(2);
+ expect(out[0]!.kind).toBe("skill");
+ expect(out[0]!.group).toBe("skill");
+ expect(out[0]!.name).toBe("brain-memory");
+});
+
+test("firstLine trims and collapses to the first non-empty line", () => {
+ expect(firstLine(" hello world \n second")).toBe("hello world");
+ expect(firstLine("\n\nlate start\nrest")).toBe("late start");
+ expect(firstLine("")).toBe("");
+});
+
+test("descriptor list is frozen and deterministic across calls", () => {
+ const a = toolDescriptors(TOOLS);
+ const b = toolDescriptors(TOOLS);
+ expect(a).toEqual(b);
+ expect(Object.isFrozen(a)).toBe(true);
+ const d: SurfaceDescriptor = a[0]!;
+ expect(Object.isFrozen(d)).toBe(true);
+});
diff --git a/tests/core/surface/lexical-score.test.ts b/tests/core/surface/lexical-score.test.ts
new file mode 100644
index 00000000..f6928141
--- /dev/null
+++ b/tests/core/surface/lexical-score.test.ts
@@ -0,0 +1,77 @@
+import { test, expect } from "bun:test";
+
+import { tokenize, scoreDescriptors } from "../../../src/core/surface/lexical-score.ts";
+import type { SurfaceDescriptor } from "../../../src/core/surface/descriptor.ts";
+
+function d(name: string, description: string, tags: string[] = []): SurfaceDescriptor {
+ return Object.freeze({
+ kind: "tool" as const,
+ name,
+ description,
+ group: "test",
+ tags: Object.freeze(tags),
+ });
+}
+
+const CORPUS = [
+ d("brain_search", "Hybrid keyword and semantic vault search.", ["search", "recall"]),
+ d("brain_feedback", "Record one Brain taste signal into the inbox.", ["memory", "signal"]),
+ d("vault_health", "Run vault, config, and plugin manifest health checks.", ["diagnostics"]),
+ d("schema_inspect", "Inspect Brain schema vocabulary and graph.", ["schema"]),
+];
+
+test("tokenize lowercases, splits punctuation, drops 1-char tokens", () => {
+ expect(tokenize("Hybrid keyword+semantic, X search!")).toEqual([
+ "hybrid",
+ "keyword",
+ "semantic",
+ "search",
+ ]);
+});
+
+test("query matching a description ranks that descriptor first", () => {
+ const ranked = scoreDescriptors("semantic vault search", CORPUS);
+ expect(ranked[0]!.descriptor.name).toBe("brain_search");
+ expect(ranked[0]!.score).toBeGreaterThan(0);
+});
+
+test("a name-token match outranks a description-only match", () => {
+ const corpus = [
+ d("alpha_tool", "useful for searching widget catalogs", []),
+ d("widget_tool", "a generic helper", []),
+ ];
+ const ranked = scoreDescriptors("widget", corpus);
+ expect(ranked[0]!.descriptor.name).toBe("widget_tool");
+});
+
+test("zero-score descriptors are filtered out", () => {
+ const ranked = scoreDescriptors("nonexistent-term-xyz", CORPUS);
+ expect(ranked).toHaveLength(0);
+});
+
+test("empty query and empty corpus return empty rankings", () => {
+ expect(scoreDescriptors("", CORPUS)).toHaveLength(0);
+ expect(scoreDescriptors(" ", CORPUS)).toHaveLength(0);
+ expect(scoreDescriptors("search", [])).toHaveLength(0);
+});
+
+test("ties break by descriptor name ascending (deterministic)", () => {
+ const corpus = [d("zz_same", "identical body text", []), d("aa_same", "identical body text", [])];
+ const ranked = scoreDescriptors("identical body", corpus);
+ expect(ranked.map((r) => r.descriptor.name)).toEqual(["aa_same", "zz_same"]);
+});
+
+test("scoring is reproducible across calls", () => {
+ const a = scoreDescriptors("brain schema", CORPUS);
+ const b = scoreDescriptors("brain schema", CORPUS);
+ expect(a.map((r) => `${r.descriptor.name}:${r.score.toFixed(6)}`)).toEqual(
+ b.map((r) => `${r.descriptor.name}:${r.score.toFixed(6)}`),
+ );
+});
+
+test("tag tokens contribute to the score", () => {
+ const corpus = [d("plain_tool", "does things", []), d("tagged_tool", "does things", ["recall"])];
+ const ranked = scoreDescriptors("recall", corpus);
+ expect(ranked).toHaveLength(1);
+ expect(ranked[0]!.descriptor.name).toBe("tagged_tool");
+});
diff --git a/tests/core/surface/skill-attach.test.ts b/tests/core/surface/skill-attach.test.ts
new file mode 100644
index 00000000..3f140a1b
--- /dev/null
+++ b/tests/core/surface/skill-attach.test.ts
@@ -0,0 +1,68 @@
+import { test, expect } from "bun:test";
+
+import { buildSkillAttachment } from "../../../src/core/surface/skill-attach.ts";
+import type { SkillEntry } from "../../../src/core/surface/skills.ts";
+
+function entry(name: string, description: string): SkillEntry {
+ return Object.freeze({
+ name,
+ description,
+ path: `/skills/${name}`,
+ skillFile: `/skills/${name}/SKILL.md`,
+ });
+}
+
+const SKILLS = [
+ entry("brain-memory", "Record taste signals and apply-evidence events into the Brain."),
+ entry("embeddings-setup", "Configure embedding providers for semantic search."),
+ entry("schema-author", "Author Brain schema vocabulary packs."),
+];
+
+test("returns the most relevant skills for a turn query", () => {
+ const attachment = buildSkillAttachment({
+ query: "set up an embedding provider for semantic search",
+ skills: SKILLS,
+ });
+ expect(attachment.items.length).toBeGreaterThan(0);
+ expect(attachment.items[0]!.name).toBe("embeddings-setup");
+ expect(attachment.block).toContain("embeddings-setup");
+});
+
+test("irrelevant query yields an empty attachment", () => {
+ const attachment = buildSkillAttachment({ query: "qqq zzz xxyyzz", skills: SKILLS });
+ expect(attachment.items).toHaveLength(0);
+ expect(attachment.block).toBe("");
+});
+
+test("maxSkills caps the attachment size", () => {
+ const attachment = buildSkillAttachment({
+ query: "brain schema memory embedding search signals",
+ skills: SKILLS,
+ maxSkills: 1,
+ });
+ expect(attachment.items).toHaveLength(1);
+});
+
+test("maxChars budget drops whole trailing entries, never truncates mid-line", () => {
+ const attachment = buildSkillAttachment({
+ query: "brain schema memory embedding search signals",
+ skills: SKILLS,
+ maxChars: 120,
+ });
+ expect(attachment.block.length).toBeLessThanOrEqual(120);
+ for (const item of attachment.items) {
+ expect(attachment.block).toContain(item.name);
+ }
+});
+
+test("empty skill list and empty query fail soft", () => {
+ expect(buildSkillAttachment({ query: "anything", skills: [] }).items).toHaveLength(0);
+ expect(buildSkillAttachment({ query: "", skills: SKILLS }).items).toHaveLength(0);
+});
+
+test("the block is deterministic and headed", () => {
+ const a = buildSkillAttachment({ query: "brain memory signals", skills: SKILLS });
+ const b = buildSkillAttachment({ query: "brain memory signals", skills: SKILLS });
+ expect(a.block).toBe(b.block);
+ expect(a.block.startsWith("## Relevant skills")).toBe(true);
+});
diff --git a/tests/core/surface/skills.test.ts b/tests/core/surface/skills.test.ts
new file mode 100644
index 00000000..dba9165b
--- /dev/null
+++ b/tests/core/surface/skills.test.ts
@@ -0,0 +1,121 @@
+import { test, expect, beforeEach, afterEach } from "bun:test";
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ discoverSkills,
+ readSkillFile,
+ skillRoots,
+ SkillError,
+} from "../../../src/core/surface/skills.ts";
+
+let tmp: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "osb-skills-"));
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function writeSkill(root: string, dir: string, frontmatter: string | null, body: string): string {
+ const skillDir = join(root, dir);
+ mkdirSync(skillDir, { recursive: true });
+ const content = frontmatter === null ? body : `---\n${frontmatter}\n---\n\n${body}`;
+ writeFileSync(join(skillDir, "SKILL.md"), content);
+ return skillDir;
+}
+
+test("discoverSkills reads frontmatter name and description", () => {
+ const root = join(tmp, "skills");
+ writeSkill(
+ root,
+ "alpha",
+ 'name: alpha-skill\ndescription: "Does alpha things."',
+ "# Alpha\n\nBody.",
+ );
+ const skills = discoverSkills([root]);
+ expect(skills).toHaveLength(1);
+ expect(skills[0]!.name).toBe("alpha-skill");
+ expect(skills[0]!.description).toBe("Does alpha things.");
+});
+
+test("falls back to directory name and first body line without frontmatter", () => {
+ const root = join(tmp, "skills");
+ writeSkill(root, "bare", null, "# Bare Skill\n\nFirst real paragraph line.\n\nMore.");
+ const skills = discoverSkills([root]);
+ expect(skills[0]!.name).toBe("bare");
+ expect(skills[0]!.description).toBe("First real paragraph line.");
+});
+
+test("skills sort by name and a directory without SKILL.md is skipped", () => {
+ const root = join(tmp, "skills");
+ writeSkill(root, "zeta", "name: zeta\ndescription: z", "z");
+ writeSkill(root, "alpha", "name: alpha\ndescription: a", "a");
+ mkdirSync(join(root, "not-a-skill"), { recursive: true });
+ const skills = discoverSkills([root]);
+ expect(skills.map((s) => s.name)).toEqual(["alpha", "zeta"]);
+});
+
+test("a later root overrides an earlier one on name collision", () => {
+ const repo = join(tmp, "repo-skills");
+ const vault = join(tmp, "vault-skills");
+ writeSkill(repo, "shared", "name: shared\ndescription: repo copy", "r");
+ writeSkill(vault, "shared", "name: shared\ndescription: vault copy", "v");
+ const skills = discoverSkills([repo, vault]);
+ expect(skills).toHaveLength(1);
+ expect(skills[0]!.description).toBe("vault copy");
+});
+
+test("missing roots fail soft to an empty list", () => {
+ expect(discoverSkills([join(tmp, "nope")])).toEqual([]);
+ expect(discoverSkills([])).toEqual([]);
+});
+
+test("skillRoots returns existing repo and vault roots only", () => {
+ const repoRoot = join(tmp, "repo");
+ mkdirSync(join(repoRoot, "skills"), { recursive: true });
+ const vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain", "skills"), { recursive: true });
+ expect(skillRoots({ repoRoot, vault })).toEqual([
+ join(repoRoot, "skills"),
+ join(vault, "Brain", "skills"),
+ ]);
+ expect(skillRoots({ repoRoot: join(tmp, "ghost"), vault: null })).toEqual([]);
+});
+
+test("readSkillFile returns SKILL.md by default and auxiliary files by relative path", () => {
+ const root = join(tmp, "skills");
+ const dir = writeSkill(root, "rich", "name: rich\ndescription: r", "# Rich");
+ writeFileSync(join(dir, "extra.md"), "extra content");
+ const [skill] = discoverSkills([root]);
+ expect(readSkillFile(skill!)).toContain("# Rich");
+ expect(readSkillFile(skill!, "extra.md")).toBe("extra content");
+});
+
+test("readSkillFile rejects traversal and absolute paths", () => {
+ const root = join(tmp, "skills");
+ writeSkill(root, "guarded", "name: guarded\ndescription: g", "g");
+ const [skill] = discoverSkills([root]);
+ expect(() => readSkillFile(skill!, "../other/SKILL.md")).toThrow(SkillError);
+ expect(() => readSkillFile(skill!, "/etc/passwd")).toThrow(SkillError);
+});
+
+test("readSkillFile refuses a symlink that escapes the skill directory", () => {
+ const root = join(tmp, "skills");
+ const dir = writeSkill(root, "linked", "name: linked\ndescription: l", "l");
+ writeFileSync(join(tmp, "outside-secret.txt"), "secret");
+ const { symlinkSync } = require("node:fs") as typeof import("node:fs");
+ symlinkSync(join(tmp, "outside-secret.txt"), join(dir, "escape.md"));
+ const [skill] = discoverSkills([root]);
+ expect(() => readSkillFile(skill!, "escape.md")).toThrow(SkillError);
+});
+
+test("readSkillFile throws NOT_FOUND for a missing auxiliary file", () => {
+ const root = join(tmp, "skills");
+ writeSkill(root, "sparse", "name: sparse\ndescription: s", "s");
+ const [skill] = discoverSkills([root]);
+ expect(() => readSkillFile(skill!, "missing.md")).toThrow(SkillError);
+});
diff --git a/tests/e2e/agent-surface.integration.test.ts b/tests/e2e/agent-surface.integration.test.ts
new file mode 100644
index 00000000..e39ef622
--- /dev/null
+++ b/tests/e2e/agent-surface.integration.test.ts
@@ -0,0 +1,118 @@
+/**
+ * Agent Surface Suite end-to-end: one flow exercises the two-pass
+ * catalog (small tools/list, hydrate, call a hidden tool), the skill
+ * surface against the REAL repository skills/, and the session
+ * lifecycle trio (scoped focus, intention chain, handoff note) on a
+ * temp vault.
+ */
+
+import { test, expect, beforeAll, afterAll } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { MCPServer } from "../../src/mcp/server.ts";
+import { resolveToolSurface } from "../../src/mcp/profiles.ts";
+import { writeHandoffNote } from "../../src/core/brain/handoff.ts";
+import { setIntention, moveIntentionToHistory } from "../../src/core/brain/intentions.ts";
+import {
+ normalizeSessionFocus,
+ readActiveSessionFocus,
+ writeSessionFocus,
+} from "../../src/core/search/session-focus.ts";
+import { resolveSearchConfig } from "../../src/core/search/index.ts";
+
+let vault: string;
+const repoRoot = process.cwd();
+
+beforeAll(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-surface-e2e-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+});
+
+afterAll(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+async function rpc(server: MCPServer, id: number, method: string, params: unknown) {
+ return (await server.handleRequest({
+ jsonrpc: "2.0",
+ id,
+ method,
+ params: params as Record<string, unknown>,
+ }))! as { result?: any; error?: unknown };
+}
+
+test("catalog profile: compact list, hydrate schemas, call a hidden tool", async () => {
+ const surface = resolveToolSurface({ profileName: "catalog" });
+ const server = new MCPServer({ vault, repoRoot }, { scope: surface.scope });
+
+ const list = await rpc(server, 1, "tools/list", {});
+ expect(list.result.tools.length).toBe(7);
+
+ const catalog = await rpc(server, 2, "tools/call", { name: "tool_hydrate", arguments: {} });
+ const catalogPayload = catalog.result.structuredContent as { count: number };
+ expect(catalogPayload.count).toBeGreaterThan(50);
+
+ const hydrated = await rpc(server, 3, "tools/call", {
+ name: "tool_hydrate",
+ arguments: { names: ["list_skills"] },
+ });
+ const schemas = hydrated.result.structuredContent as { tools: Array<{ name: string }> };
+ expect(schemas.tools[0]!.name).toBe("list_skills");
+
+ // The hydrated (still unadvertised) tool is directly callable.
+ const skills = await rpc(server, 4, "tools/call", { name: "list_skills", arguments: {} });
+ const skillsPayload = skills.result.structuredContent as {
+ count: number;
+ skills: Array<{ name: string }>;
+ };
+ expect(skillsPayload.count).toBeGreaterThanOrEqual(5);
+ expect(skillsPayload.skills.map((s) => s.name)).toContain("brain-memory");
+});
+
+test("get_skill serves the real repository skill content", async () => {
+ const server = new MCPServer({ vault, repoRoot }, { scope: "full" });
+ const r = await rpc(server, 5, "tools/call", {
+ name: "get_skill",
+ arguments: { name: "open-second-brain" },
+ });
+ const payload = r.result.structuredContent as { content: string };
+ expect(payload.content).toContain("Open Second Brain");
+});
+
+test("session lifecycle trio: scoped focus, intention chain, handoff note", () => {
+ const cfg = resolveSearchConfig({ vault });
+ writeSessionFocus(cfg, normalizeSessionFocus({ query: "surface suite" }), "e2e-session");
+ expect(readActiveSessionFocus(cfg, "e2e-session")?.query).toBe("surface suite");
+
+ const chain = setIntention(vault, {
+ scope: "e2e-session",
+ text: "Finish the integration test",
+ agent: "e2e-agent",
+ });
+ expect(chain.version).toBe(1);
+
+ const handoff = writeHandoffNote(vault, {
+ turns: [
+ {
+ turnId: "t1",
+ timestamp: new Date().toISOString(),
+ role: "user",
+ text: "Wire the suite together.",
+ },
+ {
+ turnId: "t2",
+ timestamp: new Date().toISOString(),
+ role: "assistant",
+ text: "Done: suite wired. Next step: release.",
+ },
+ ],
+ sessionId: "e2e-session",
+ agent: "e2e-agent",
+ });
+ expect(existsSync(handoff.path)).toBe(true);
+
+ const moved = moveIntentionToHistory(vault, { scope: "e2e-session" });
+ expect(existsSync(moved.archivePath)).toBe(true);
+});
diff --git a/tests/mcp/brain-intention-tool.test.ts b/tests/mcp/brain-intention-tool.test.ts
new file mode 100644
index 00000000..472e32c6
--- /dev/null
+++ b/tests/mcp/brain-intention-tool.test.ts
@@ -0,0 +1,63 @@
+import { test, expect, beforeEach, afterEach } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";
+
+let tmp: string;
+let ctx: ServerContext;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "osb-intention-tool-"));
+ mkdirSync(join(tmp, "Brain"), { recursive: true });
+ ctx = { vault: tmp, configPath: null, repoRoot: null };
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function intentionTool() {
+ return findTool(buildToolTable("full"), "brain_intention");
+}
+
+test("set / show / list / move round-trip through the consolidated tool", async () => {
+ const tool = intentionTool();
+ const set = (await tool.handler(ctx, {
+ operation: "set",
+ scope: "ws-1",
+ text: "Ship the suite",
+ })) as { scope: string; version: number };
+ expect(set.scope).toBe("ws-1");
+ expect(set.version).toBe(1);
+
+ const show = (await tool.handler(ctx, { operation: "show", scope: "ws-1" })) as {
+ present: boolean;
+ text: string;
+ };
+ expect(show.present).toBe(true);
+ expect(show.text).toBe("Ship the suite");
+
+ const list = (await tool.handler(ctx, { operation: "list" })) as {
+ intentions: Array<{ scope: string }>;
+ };
+ expect(list.intentions.map((i) => i.scope)).toEqual(["ws-1"]);
+
+ const move = (await tool.handler(ctx, { operation: "move", scope: "ws-1" })) as {
+ archive_path: string;
+ };
+ expect(move.archive_path).toContain("history");
+
+ const after = (await tool.handler(ctx, { operation: "show", scope: "ws-1" })) as {
+ present: boolean;
+ };
+ expect(after.present).toBe(false);
+});
+
+test("invalid operations and missing arguments are rejected", () => {
+ const tool = intentionTool();
+ expect(() => tool.handler(ctx, { operation: "archive" })).toThrow();
+ expect(() => tool.handler(ctx, { operation: "set", scope: "ws" })).toThrow();
+ expect(() => tool.handler(ctx, { operation: "show" })).toThrow();
+});
diff --git a/tests/mcp/catalog-scope.test.ts b/tests/mcp/catalog-scope.test.ts
new file mode 100644
index 00000000..6d54d47c
--- /dev/null
+++ b/tests/mcp/catalog-scope.test.ts
@@ -0,0 +1,113 @@
+import { test, expect } from "bun:test";
+import { mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";
+import { MCPServer } from "../../src/mcp/server.ts";
+
+function ctx(): ServerContext {
+ return {
+ vault: mkdtempSync(join(tmpdir(), "osb-catalog-")),
+ configPath: null,
+ repoRoot: null,
+ };
+}
+
+const ADVERTISED = [
+ "second_brain_capabilities",
+ "brain_apply_evidence",
+ "brain_context",
+ "brain_feedback",
+ "brain_note",
+ "brain_pinned_context",
+ "tool_hydrate",
+];
+
+test("catalog scope advertises only the compact first-pass surface", () => {
+ const tools = buildToolTable("catalog");
+ const advertised = tools.filter((t) => t.hidden !== true).map((t) => t.name);
+ expect(advertised.toSorted()).toEqual([...ADVERTISED].toSorted());
+});
+
+test("catalog scope keeps every tool callable (hidden, not removed)", () => {
+ const full = buildToolTable("full");
+ const catalog = buildToolTable("catalog");
+ expect(catalog.length).toBe(full.length);
+ // A deep Brain tool stays resolvable for tools/call.
+ expect(() => findTool(catalog, "brain_search")).not.toThrow();
+});
+
+test("full and writer scopes do not advertise tool_hydrate semantics changes", () => {
+ const full = buildToolTable("full");
+ const hydrateInFull = full.find((t) => t.name === "tool_hydrate");
+ expect(hydrateInFull).toBeDefined();
+ const writer = buildToolTable("writer");
+ expect(writer.find((t) => t.name === "tool_hydrate")).toBeUndefined();
+});
+
+test("tool_hydrate with no args returns the sorted compact catalog", async () => {
+ const tools = buildToolTable("catalog");
+ const hydrate = findTool(tools, "tool_hydrate");
+ const result = (await hydrate.handler(ctx(), {})) as {
+ catalog: Array<{ name: string; description: string; group: string }>;
+ count: number;
+ };
+ expect(result.count).toBeGreaterThan(20);
+ const names = result.catalog.map((c) => c.name);
+ expect(names).toEqual([...names].toSorted());
+ expect(names).toContain("brain_search");
+ const search = result.catalog.find((c) => c.name === "brain_search")!;
+ expect(search.description.length).toBeGreaterThan(0);
+ expect(search.description).not.toContain("\n");
+});
+
+test("tool_hydrate with names returns full schemas and reports unknowns", async () => {
+ const tools = buildToolTable("catalog");
+ const hydrate = findTool(tools, "tool_hydrate");
+ const result = (await hydrate.handler(ctx(), {
+ names: ["brain_search", "no_such_tool"],
+ })) as {
+ tools: Array<{ name: string; description: string; inputSchema: unknown }>;
+ unknown: string[];
+ };
+ expect(result.tools).toHaveLength(1);
+ expect(result.tools[0]!.name).toBe("brain_search");
+ expect(result.tools[0]!.inputSchema).toBeDefined();
+ expect(result.unknown).toEqual(["no_such_tool"]);
+});
+
+test("catalog-scope server lists the compact surface but calls hidden tools", async () => {
+ const vault = mkdtempSync(join(tmpdir(), "osb-catalog-srv-"));
+ const server = new MCPServer({ vault }, { scope: "catalog" });
+ const listResponse = (await server.handleRequest({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "tools/list",
+ params: {},
+ }))! as { result: { tools: Array<{ name: string }> } };
+ const advertised = listResponse.result.tools.map((t) => t.name);
+ expect(advertised.toSorted()).toEqual([...ADVERTISED].toSorted());
+
+ // A hidden tool still executes through tools/call.
+ const callResponse = (await server.handleRequest({
+ jsonrpc: "2.0",
+ id: 2,
+ method: "tools/call",
+ params: { name: "second_brain_status", arguments: {} },
+ }))! as { result?: unknown; error?: unknown };
+ expect(callResponse.error).toBeUndefined();
+ expect(callResponse.result).toBeDefined();
+});
+
+test("initialize instructions for catalog scope explain the hydration contract", async () => {
+ const vault = mkdtempSync(join(tmpdir(), "osb-catalog-ins-"));
+ const server = new MCPServer({ vault }, { scope: "catalog" });
+ const response = (await server.handleRequest({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "initialize",
+ params: { protocolVersion: "2024-11-05" },
+ }))! as { result: { instructions: string } };
+ expect(response.result.instructions).toContain("tool_hydrate");
+});
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index ac6bc233..50eacf10 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -247,6 +247,12 @@ describe("tool listing", () => {
"schema_apply_mutations",
"schema_inspect",
"brain_watchdog",
+ // Agent Surface Suite: skill discovery + two-pass hydration.
+ "list_skills",
+ "get_skill",
+ "skills_attach",
+ "tool_hydrate",
+ "brain_intention",
].toSorted(),
);
// Explicit grep: legacy writable tools are no longer advertised.
@@ -493,8 +499,10 @@ describe("stdio loop", () => {
// + brain_recall_feedback (recall-trust-suite) = 71,
// + brain_brief / brain_analytics / schema_inspect (token-diet) = 74
// - 18 predecessors hidden as deprecated aliases (callable via
- // tools/call, not advertised) = 56.
- expect(list.result.tools.length).toBe(57);
+ // tools/call, not advertised) = 56 (+1 capability diagnostic = 57).
+ // + list_skills / get_skill / skills_attach / tool_hydrate /
+ // brain_intention (Agent Surface Suite) = 62.
+ expect(list.result.tools.length).toBe(62);
});
test("returns parse error for invalid JSON", async () => {
diff --git a/tests/mcp/profiles.test.ts b/tests/mcp/profiles.test.ts
new file mode 100644
index 00000000..86bce4c2
--- /dev/null
+++ b/tests/mcp/profiles.test.ts
@@ -0,0 +1,130 @@
+import { test, expect, beforeEach, afterEach } from "bun:test";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ TOOL_SURFACE_PROFILES,
+ resolveToolSurface,
+ toolSurfaceProfileNames,
+} from "../../src/mcp/profiles.ts";
+import { resolveMcpToolProfile } from "../../src/core/config.ts";
+import { buildToolTable } from "../../src/mcp/tools.ts";
+import { evaluateToolCapabilities } from "../../src/mcp/capabilities.ts";
+
+test("the five named profiles exist", () => {
+ expect(toolSurfaceProfileNames().toSorted()).toEqual([
+ "catalog",
+ "full",
+ "minimal",
+ "recall",
+ "writer",
+ ]);
+});
+
+test("full profile resolves to the unrestricted surface", () => {
+ const surface = resolveToolSurface({ profileName: "full" });
+ expect(surface.scope).toBe("full");
+ expect(surface.window).toBeUndefined();
+ expect(surface.unknownProfile).toBeUndefined();
+});
+
+test("catalog profile resolves to the catalog scope with no window", () => {
+ const surface = resolveToolSurface({ profileName: "catalog" });
+ expect(surface.scope).toBe("catalog");
+ expect(surface.window).toBeUndefined();
+});
+
+test("recall profile keeps the memory surface and withholds admin tools", () => {
+ const surface = resolveToolSurface({ profileName: "recall" });
+ expect(surface.scope).toBe("full");
+ const evaluated = evaluateToolCapabilities(buildToolTable(surface.scope), {
+ scope: surface.scope,
+ serverName: "test",
+ ...(surface.window ? { window: surface.window } : {}),
+ });
+ const names = evaluated.tools.map((t) => t.name);
+ expect(names).toContain("second_brain_capabilities");
+ expect(names).toContain("brain_search");
+ expect(names).toContain("brain_context_pack");
+ expect(names).toContain("brain_feedback");
+ expect(names).not.toContain("schema_apply_mutations");
+ expect(names).not.toContain("payment_memory_init");
+ const withheld = evaluated.report.withheld.map((w) => w.name);
+ expect(withheld).toContain("schema_apply_mutations");
+});
+
+test("minimal profile is the floor: writers, context, search, diagnostic", () => {
+ const surface = resolveToolSurface({ profileName: "minimal" });
+ const evaluated = evaluateToolCapabilities(buildToolTable(surface.scope), {
+ scope: surface.scope,
+ serverName: "test",
+ ...(surface.window ? { window: surface.window } : {}),
+ });
+ const names = evaluated.tools.map((t) => t.name).toSorted();
+ expect(names).toEqual([
+ "brain_apply_evidence",
+ "brain_context",
+ "brain_feedback",
+ "brain_note",
+ "brain_pinned_context",
+ "brain_search",
+ "second_brain_capabilities",
+ ]);
+});
+
+test("an unknown profile fails OPEN to the full surface and reports the name", () => {
+ const surface = resolveToolSurface({ profileName: "typo-profile" });
+ expect(surface.scope).toBe("full");
+ expect(surface.window).toBeUndefined();
+ expect(surface.unknownProfile).toBe("typo-profile");
+});
+
+test("no profile name resolves to explicit flags or the default full surface", () => {
+ expect(resolveToolSurface({}).scope).toBe("full");
+ expect(resolveToolSurface({ explicitScope: "writer" }).scope).toBe("writer");
+});
+
+test("an explicit scope wins over the profile scope", () => {
+ const surface = resolveToolSurface({ profileName: "catalog", explicitScope: "full" });
+ expect(surface.scope).toBe("full");
+});
+
+test("explicit window fields override profile window fields", () => {
+ const surface = resolveToolSurface({
+ profileName: "minimal",
+ explicitWindow: { allowedTools: ["brain_feedback"] },
+ });
+ expect(surface.window?.allowedTools).toEqual(["brain_feedback"]);
+});
+
+test("every named profile is defined with a description", () => {
+ for (const profile of Object.values(TOOL_SURFACE_PROFILES)) {
+ expect(profile.description.length).toBeGreaterThan(0);
+ }
+});
+
+// ── config key ───────────────────────────────────────────────────────────────
+
+let tmp: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "osb-profile-cfg-"));
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+test("resolveMcpToolProfile reads mcp_tool_profile from config", () => {
+ const config = join(tmp, "config.yaml");
+ writeFileSync(config, `vault: "${tmp}"\nmcp_tool_profile: "recall"\n`);
+ expect(resolveMcpToolProfile(config)).toBe("recall");
+});
+
+test("resolveMcpToolProfile returns null when absent or config missing", () => {
+ const config = join(tmp, "config.yaml");
+ writeFileSync(config, `vault: "${tmp}"\n`);
+ expect(resolveMcpToolProfile(config)).toBeNull();
+ expect(resolveMcpToolProfile(join(tmp, "ghost.yaml"))).toBeNull();
+});
diff --git a/tests/mcp/skill-tools.test.ts b/tests/mcp/skill-tools.test.ts
new file mode 100644
index 00000000..00fe08ed
--- /dev/null
+++ b/tests/mcp/skill-tools.test.ts
@@ -0,0 +1,84 @@
+import { test, expect, beforeEach, afterEach } from "bun:test";
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { SKILL_TOOLS } from "../../src/mcp/skill-tools.ts";
+import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";
+
+let tmp: string;
+let ctx: ServerContext;
+
+function writeSkill(repoRoot: string, dir: string, description: string, body: string): void {
+ const skillDir = join(repoRoot, "skills", dir);
+ mkdirSync(skillDir, { recursive: true });
+ writeFileSync(
+ join(skillDir, "SKILL.md"),
+ `---\nname: ${dir}\ndescription: ${description}\n---\n\n${body}`,
+ );
+}
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "osb-skill-tools-"));
+ const vault = join(tmp, "vault");
+ mkdirSync(vault, { recursive: true });
+ writeSkill(tmp, "demo-skill", "Demonstration skill.", "# Demo\n\nUse wisely.");
+ writeSkill(tmp, "other-skill", "Another skill.", "# Other");
+ ctx = { vault, configPath: null, repoRoot: tmp };
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function tool(name: string) {
+ return SKILL_TOOLS.find((t) => t.name === name)!;
+}
+
+test("list_skills returns sorted names with descriptions and paths", async () => {
+ const result = (await tool("list_skills").handler(ctx, {})) as {
+ skills: Array<{ name: string; description: string; path: string }>;
+ count: number;
+ };
+ expect(result.count).toBe(2);
+ expect(result.skills.map((s) => s.name)).toEqual(["demo-skill", "other-skill"]);
+ expect(result.skills[0]!.description).toBe("Demonstration skill.");
+ expect(result.skills[0]!.path).toContain("skills/demo-skill");
+});
+
+test("list_skills with no roots fails soft to an empty list", async () => {
+ const bare: ServerContext = { vault: join(tmp, "ghost"), configPath: null, repoRoot: null };
+ const result = (await tool("list_skills").handler(bare, {})) as { count: number };
+ expect(result.count).toBe(0);
+});
+
+test("get_skill returns SKILL.md content by name", async () => {
+ const result = (await tool("get_skill").handler(ctx, { name: "demo-skill" })) as {
+ name: string;
+ content: string;
+ };
+ expect(result.name).toBe("demo-skill");
+ expect(result.content).toContain("Use wisely.");
+});
+
+test("get_skill reads an auxiliary file inside the skill directory", async () => {
+ writeFileSync(join(tmp, "skills", "demo-skill", "ref.md"), "reference text");
+ const result = (await tool("get_skill").handler(ctx, {
+ name: "demo-skill",
+ file_path: "ref.md",
+ })) as { content: string };
+ expect(result.content).toBe("reference text");
+});
+
+test("get_skill rejects unknown skills and traversal paths", () => {
+ expect(() => tool("get_skill").handler(ctx, { name: "nope" })).toThrow("unknown skill");
+ expect(() =>
+ tool("get_skill").handler(ctx, { name: "demo-skill", file_path: "../other-skill/SKILL.md" }),
+ ).toThrow("inside the skill directory");
+});
+
+test("skill tools are registered in the full tool table", () => {
+ const tools = buildToolTable("full");
+ expect(() => findTool(tools, "list_skills")).not.toThrow();
+ expect(() => findTool(tools, "get_skill")).not.toThrow();
+});
diff --git a/tests/mcp/skills-attach-tool.test.ts b/tests/mcp/skills-attach-tool.test.ts
new file mode 100644
index 00000000..5da4383d
--- /dev/null
+++ b/tests/mcp/skills-attach-tool.test.ts
@@ -0,0 +1,72 @@
+import { test, expect, beforeEach, afterEach } from "bun:test";
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { SKILL_TOOLS } from "../../src/mcp/skill-tools.ts";
+import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";
+
+let tmp: string;
+let configPath: string;
+let ctx: ServerContext;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "osb-attach-tool-"));
+ const vault = join(tmp, "vault");
+ mkdirSync(vault, { recursive: true });
+ configPath = join(tmp, "config.yaml");
+ writeFileSync(configPath, `vault: "${vault}"\n`);
+ const skillDir = join(tmp, "skills", "embeddings-setup");
+ mkdirSync(skillDir, { recursive: true });
+ writeFileSync(
+ join(skillDir, "SKILL.md"),
+ "---\nname: embeddings-setup\ndescription: Configure embedding providers for semantic search.\n---\n\n# Embeddings",
+ );
+ ctx = { vault, configPath, repoRoot: tmp };
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function attach() {
+ return SKILL_TOOLS.find((t) => t.name === "skills_attach")!;
+}
+
+test("skills_attach is disabled by default (config key absent)", async () => {
+ const result = (await attach().handler(ctx, { query: "embedding search" })) as {
+ enabled: boolean;
+ block: string;
+ skills: unknown[];
+ };
+ expect(result.enabled).toBe(false);
+ expect(result.block).toBe("");
+ expect(result.skills).toHaveLength(0);
+});
+
+test("skills_attach returns a scored block when skill_auto_attach is true", async () => {
+ writeFileSync(configPath, `vault: "${ctx.vault}"\nskill_auto_attach: "true"\n`);
+ const result = (await attach().handler(ctx, { query: "configure embedding search" })) as {
+ enabled: boolean;
+ block: string;
+ skills: Array<{ name: string; score: number }>;
+ };
+ expect(result.enabled).toBe(true);
+ expect(result.block).toContain("embeddings-setup");
+ expect(result.skills[0]!.name).toBe("embeddings-setup");
+ expect(result.skills[0]!.score).toBeGreaterThan(0);
+});
+
+test("an irrelevant turn attaches nothing even when enabled", async () => {
+ writeFileSync(configPath, `vault: "${ctx.vault}"\nskill_auto_attach: "true"\n`);
+ const result = (await attach().handler(ctx, { query: "qqq zzz" })) as {
+ enabled: boolean;
+ block: string;
+ };
+ expect(result.enabled).toBe(true);
+ expect(result.block).toBe("");
+});
+
+test("skills_attach is registered in the full tool table", () => {
+ expect(() => findTool(buildToolTable("full"), "skills_attach")).not.toThrow();
+});
diff --git a/tests/python/test_memory_provider.py b/tests/python/test_memory_provider.py
index 2e939ebf..9fb27544 100644
--- a/tests/python/test_memory_provider.py
+++ b/tests/python/test_memory_provider.py
@@ -318,6 +318,38 @@ class ProviderLifecycleTests(unittest.TestCase):
self.assertIn("RECALLED", out)
self.assertIn("@pf-agent", out)
+ def test_prefetch_appends_skills_attach_block_when_enabled(self):
+ os.environ["VAULT_AGENT_NAME"] = "pf-agent"
+ bridge = FakeBrainBridge(
+ results={
+ "brain_recall_gate": {"structuredContent": {"retrieve": False}},
+ "skills_attach": {
+ "structuredContent": {
+ "enabled": True,
+ "block": "## Relevant skills\n\n- embeddings-setup - configure providers",
+ "skills": [{"name": "embeddings-setup"}],
+ }
+ },
+ }
+ )
+ provider = self._init(bridge, hermes_home="/tmp/hh")
+ out = provider.prefetch("configure embeddings", session_id="sess-1")
+ self.assertIn("## Relevant skills", out)
+ self.assertIn("embeddings-setup", out)
+
+ def test_prefetch_unchanged_when_skills_attach_disabled_or_missing(self):
+ os.environ["VAULT_AGENT_NAME"] = "pf-agent"
+ bridge = FakeBrainBridge(
+ results={
+ "brain_recall_gate": {"structuredContent": {"retrieve": False}},
+ "skills_attach": {"structuredContent": {"enabled": False, "block": ""}},
+ }
+ )
+ provider = self._init(bridge, hermes_home="/tmp/hh")
+ out = provider.prefetch("hello", session_id="sess-1")
+ self.assertNotIn("Relevant skills", out)
+ self.assertIn("@pf-agent", out)
+
def test_prefetch_reminder_only_when_gate_declines(self):
os.environ["VAULT_AGENT_NAME"] = "pf-agent"
bridge = FakeBrainBridge(