Skip to content

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

TypeScript

v0.10.10: Pull channels β€” brain_context tool, Most-applied (30d), o2b brain note, semantic hint

Sol Aitken0484a23e342d
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 035e441a..383cfcaa 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.9",
+ "version": "0.10.10",
"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 0b2bfc64..b3884629 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.9",
+ "version": "0.10.10",
"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 b3e7746c..57b7d13d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,76 @@ 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.10.10] - 2026-05-20
+
+Pull channels for runtimes without `SessionStart`. Adds an MCP
+`brain_context` tool, surfaces a `Most-applied (30d)` section in
+`Brain/active.md`, ships the `o2b brain note` CLI verb, and prints
+a semantic-search hint in `o2b status`. The always-loaded
+`open-second-brain-writer` MCP server now also hosts one read
+tool; the server name is preserved for backward compatibility and
+a rename is deferred (see
+`docs/plans/2026-05-20-v0.10.10-design.md` Β§12). Companion design
+and impl plan at `docs/plans/2026-05-20-v0.10.10-design.md` and
+`docs/plans/2026-05-20-v0.10.10-impl.md`.
+
+### Added
+
+- `brain_context` MCP tool β€” read-only pull-bootstrap of the
+ current `Brain/active.md` body plus active-preference counts.
+ Hosted in the always-loaded `open-second-brain-writer` MCP
+ server so MCP clients without a `SessionStart` hook (Cursor,
+ Aider, raw Claude API) can fetch the same shortcut card the
+ hook-aware runtimes get injected automatically.
+- `Most-applied (30d)` section in `Brain/active.md` β€” top ten
+ `confirmed` / `quarantine` preferences ranked by
+ `apply-evidence (result: applied)` events whose timestamp lies
+ inside the trailing 30-day window. Section is omitted when the
+ count is zero. The render is fully derived from `Brain/log/`;
+ no new persistent state is introduced.
+- `o2b brain note <text>` CLI verb β€” Brain-native milestone log
+ for cron jobs and shell scripts. Same on-disk contract as the
+ MCP `brain_note` tool: writes one `note` event to
+ `Brain/log/<today>.md` plus the JSONL sidecar. Supports
+ `--agent`, `--vault`, `--config`, and `--json`. Multi-line text
+ collapses to one line (matches the MCP contract).
+- `o2b status` semantic-search hint β€” when semantic search is
+ enabled in config but unusable (key missing) and search is not
+ disabled outright, the human output appends
+ `semantic: off (run 'o2b search check' for setup steps)` after
+ the `config_keys:` block. `--json` payload always carries the
+ new keys `semantic_enabled`, `embedding_key_present`, and
+ `semantic_hint` (last one is `null` when fully configured or
+ when search is disabled).
+- `appendBrainNote` core function in `src/core/brain/note.ts`.
+ Single source of truth shared by the MCP `brain_note` handler
+ and the new CLI verb so the on-disk shape cannot drift between
+ surfaces.
+- `computeMostApplied` core function in
+ `src/core/brain/most-applied.ts`. Pure read; the caller passes
+ the candidate preferences so retired rules never surface in
+ the active digest.
+- `resolveSemanticConfigState` helper in `src/cli/helpers.ts`.
+ Single source of truth for `o2b status` and the `o2b init`
+ search banner; collapses the duplicated truthy / key-present
+ logic onto one function.
+
+### Changed
+
+- `RegenerateActiveResult.counts` gains a `most_applied_30d`
+ field. Internal additive change; the existing
+ `{confirmed, quarantine, retired_recent}` triple keeps its
+ values and semantics.
+- Hook detector (`hooks/lib/detect.ts`) recognises
+ `o2b brain note` as a brain event needle, alongside
+ `o2b brain feedback` and `o2b brain apply-evidence`. The stop
+ guardrail clears for any of the three CLI verbs.
+- The always-loaded MCP server tool table grows from three
+ writers to four (three writers + `brain_context` reader). The
+ server's exposed name (`open-second-brain-writer` in
+ `.mcp.json`) is unchanged; renaming is deferred until a second
+ reader joins the always-load scope.
+
## [0.10.9] - 2026-05-20
Closes the "Vault Scope" feature: a single declarative exclusion
diff --git a/README.md b/README.md
index 84192b71..07c28484 100644
--- a/README.md
+++ b/README.md
@@ -127,6 +127,7 @@ o2b brain init Bootstrap Brain/{inbox,preferences,retired,log,.sn
o2b brain feedback Record one taste signal (--topic, --signal, --principle, ...)
o2b brain dream Run the deterministic consolidation pass (idempotent; usually cron'd)
o2b brain apply-evidence Record applied / violated against a preference for a durable artifact
+o2b brain note <text> Append a one-line narrative milestone to Brain/log/<today>.md (cron / shell mirror of brain_note)
o2b brain digest Render a Markdown or JSON summary of recent Brain transitions
o2b brain query Read helper: by preference, by topic, or by log timestamp
o2b brain reject (CLI-only) Retire a preference; requires --reason "<text>". Subsequent signals on the same topic are suppressed.
diff --git a/docs/architecture.md b/docs/architecture.md
index ecbe6330..9f4562e0 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -236,6 +236,17 @@ Agent runtime
Full design: [`docs/plans/2026-05-15-brain-observing-memory.md`](plans/2026-05-15-brain-observing-memory.md).
+As of v0.10.10 the always-loaded `open-second-brain-writer` MCP
+server hosts one read tool (`brain_context`) alongside the three
+writers (`brain_feedback`, `brain_apply_evidence`, `brain_note`).
+The reader exists for runtimes without a `SessionStart` hook
+(Cursor, Aider, raw Claude API) β€” they call it once at session
+start to pull the same `Brain/active.md` content the hook-aware
+runtimes get auto-injected. The MCP server name is preserved for
+backward compatibility with existing client `.mcp.json` entries;
+renaming is deferred until a second reader joins the always-load
+scope.
+
## Event log
The event log is append-only. It records operational events, not polished knowledge.
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index ed31a968..aed4b9a3 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -315,13 +315,17 @@ flowchart LR
Active -- SessionStart hook --> ClaudeStart["Claude Code / Codex<br/>session start"]
Active -- PostCompact hook --> ClaudeCompact["Claude Code / Codex<br/>after /compact"]
Active -- "osb://preferences/active" --> MCPHost["MCP host (Hermes, others)"]
+ Active -- "brain_context tool" --> PullRT["Cursor / Aider / raw API<br/>(no SessionStart hook)"]
```
- **`Brain/active.md`** is a derived Markdown digest: confirmed
- preferences (id, scope, confidence, principle), quarantined
- preferences with their applied / violated counters, and the three
- most recently retired entries. The writer is idempotent β€” if the
- rendered body matches the file on disk, no I/O happens.
+ preferences (id, scope, confidence, principle), a `Most-applied
+ (30d)` section ranking up to ten confirmed/quarantine rules by
+ `apply-evidence (result: applied)` events in the trailing
+ 30-day window, quarantined preferences with their applied /
+ violated counters, and the three most recently retired entries.
+ The writer is idempotent β€” if the rendered body matches the file
+ on disk, no I/O happens.
- **SessionStart hook** (`startup | resume | clear`) and
**PostCompact hook** (`manual | auto`) inject the body as
`additionalContext` so the agent sees current rules at the start of
@@ -349,6 +353,8 @@ are mirrored in MCP; destructive operations are CLI-only by design.
| Record taste signal | `o2b brain feedback` | `brain_feedback` | writes signal + log event (sanitised) |
| Consolidation pass | `o2b brain dream` | `brain_dream` | mutates preferences/retired, atomic snapshot, regenerates `Brain/active.md` |
| Record application | `o2b brain apply-evidence` | `brain_apply_evidence`| appends log event; `result ∈ {applied, violated, outdated}`; artifact supports `[[file:120-145]]` ranges |
+| Record milestone | `o2b brain note <text>` | `brain_note` | appends one `note` log event to `Brain/log/<today>.md` plus the JSONL sidecar. Multi-line collapses to one line. CLI mirror exists for cron / shell. |
+| Pull active context | β€” (use MCP) | `brain_context` | read-only; returns `Brain/active.md` body + counts. Always-loaded on the writer MCP server so runtimes without a `SessionStart` hook (Cursor, Aider, raw Claude API) can fetch it at session start. |
| Render summary | `o2b brain digest` | `brain_digest` | read-only; includes `top_applied` and `top_referenced` sections |
| Inspect state | `o2b brain query` | `brain_query` | read-only |
| Computed backlinks | `o2b brain backlinks <id>` | `brain_backlinks` | read-only; inverted reference map across `preferences/`, `retired/`, `log/` |
diff --git a/docs/plans/2026-05-20-v0.10.10-design.md b/docs/plans/2026-05-20-v0.10.10-design.md
new file mode 100644
index 00000000..18622ad7
--- /dev/null
+++ b/docs/plans/2026-05-20-v0.10.10-design.md
@@ -0,0 +1,512 @@
+# v0.10.10 β€” pull-channels for runtimes without SessionStart
+
+## 1. Problem
+
+The current `Brain/active.md` digest is reachable through two push
+paths (Claude Code `SessionStart` hook, Codex identity-reminder
+injection) and one MCP resource (`osb://preferences/active`). That
+leaves three concrete gaps:
+
+1. **MCP hosts that ignore resources.** Cursor, Aider, raw Claude API
+ and similar runtimes can call MCP *tools* but do not auto-load MCP
+ resources. Without a tool surface for the active digest, those
+ agents start every session blind to confirmed preferences.
+2. **`brain_note` has no non-MCP entrypoint.** Cron jobs and shell
+ scripts cannot reach the `Brain/log/<date>.md` `note` event kind
+ that `brain_note` writes. They have to fall back to `vault-log` /
+ `o2b append-event` (which write to `Daily/`), recreating the
+ pre-v0.10.8 split the Β§32 deprecation was supposed to close.
+3. **`o2b status` is silent about semantic search.** The CLI reports
+ config presence but never hints that the vector index is disabled.
+ Operators only discover that semantic is off when they specifically
+ try `o2b search status` or `o2b search check`.
+
+The shared theme is *pull*: when push channels are unavailable or
+inapplicable, the agent or operator needs a small, discoverable surface
+that returns the same information.
+
+A fourth, orthogonal request lands in the same release: surface the
+**Most-applied (30d)** preferences in `Brain/active.md`. The digest
+currently shows what preferences *exist* but not which ones are
+actually firing. A top-N section by `apply-evidence` events over a
+sliding 30-day window gives both the agent (via the injected file)
+and the operator (via reading active.md directly) a concrete signal
+of which confirmed rules carry weight right now.
+
+## 2. Goals
+
+- Ship an MCP tool `brain_context` in the always-loaded writer-server
+ scope that returns the current `Brain/active.md` body plus structured
+ counts. Discoverable without `ToolSearch`, callable without
+ arguments, idempotent.
+- Extend `Brain/active.md` with a new `## Most-applied (30d)` section
+ listing up to ten `confirmed` / `quarantine` preferences with the
+ highest count of `apply-evidence (result: applied)` events whose
+ `timestamp` falls inside the sliding 30-day window. Section is
+ omitted entirely when the count is zero.
+- Ship a CLI verb `o2b brain note "<text>"` that mirrors the MCP
+ `brain_note` tool one-to-one for cron jobs and shell scripts. The
+ CLI and the MCP handler share a single `appendBrainNote` core
+ function.
+- Extend `o2b status` with a single-line semantic-search hint. Print
+ `semantic: off (run 'o2b search check' for setup steps)` in
+ human-output and `semantic_enabled` / `embedding_key_present` /
+ `semantic_hint` keys in `--json` whenever `semantic_enabled` is
+ `false` *or* the embedding key is missing.
+
+## 3. Non-goals
+
+- Auto-discovery of agent runtime to decide whether to advertise
+ `brain_context` (Cursor vs Claude Code etc.). The tool is always
+ advertised; runtimes with a working SessionStart hook can ignore it.
+- Filter / pagination / scope arguments on `brain_context`. The tool
+ returns the full `active.md` body; callers that want a slice already
+ have `brain_query`.
+- Configurable `Most-applied` window or limit. The 30-day window and
+ the top-10 limit are baked in. If a user complaint surfaces, the
+ block can grow a `_brain.yaml` knob in a later release.
+- Multi-line `o2b brain note` (`--stdin` etc.). The MCP tool collapses
+ newlines into a single line; the CLI matches that contract.
+- Backfilling existing `Brain/log/<date>` files. The Most-applied
+ section reads whatever the log walker already returns.
+- A new MCP resource. `osb://preferences/active` already covers
+ resource-capable hosts; the tool exists for hosts that ignore
+ resources.
+- Renaming the always-loaded MCP server. It is still named
+ `open-second-brain-writer` even though one of its tools is now a
+ reader. The rename is not worth the breaking change on existing
+ client configs. A short comment in the file explains the
+ asymmetry.
+
+## 4. Architecture
+
+### 4.1 Module layout
+
+```
+src/core/brain/most-applied.ts (new) pure computation: log β†’ ranked entries
+src/core/brain/note.ts (new) shared appendBrainNote core
+src/core/brain/active.ts (edit) call most-applied, render section, expose count
+src/cli/brain/verbs/note.ts (new) CLI verb wrapping appendBrainNote
+src/cli/brain.ts (edit) dispatcher registers note verb
+src/cli/brain/help-text.ts (edit) help line for `o2b brain note`
+src/cli/main.ts (edit) cmdStatus emits semantic line
+src/cli/helpers.ts (edit) resolveSemanticConfigState helper
+src/mcp/brain-tools.ts (edit) toolBrainContext + toolBrainNote routed via core
+src/mcp/tools.ts (edit) WRITER_TOOL_NAMES adds brain_context
+src/mcp/instructions.ts (edit) writer-server description mentions brain_context
+hooks/lib/detect.ts (edit) BRAIN_EVENT_BASH_NEEDLES adds "o2b brain note "
+hooks/README.md (edit) note CLI mentioned as third clear-trigger
+docs/architecture.md (edit) writer-server now hosts one reader tool
+CHANGELOG.md (edit) new [0.10.10] entry
+```
+
+All edits are additive. The only non-additive surface is the
+extraction of the `brain_note` body into `appendBrainNote` β€” the MCP
+handler shrinks to a thin wrapper around the same function the CLI
+calls.
+
+### 4.2 Data flow
+
+```
+Brain/log/*.md|.jsonl ──► readLogDay (existing) ──► most-applied ──► render
+Brain/preferences/*.md ──► parsePreference (existing) β”€β”€β”˜
+Brain/retired/*.md ──► parseRetired (existing) ─────► render
+
+regenerateActive ──► renderBody ──► atomicWriteFileSync ──► active.md
+
+brain_context (MCP) ──► regenerateActive (self-heal) ──► read active.md + computeBrainStatus
+o2b brain note ──► appendBrainNote ──► appendLogEvent (existing)
+brain_note (MCP) ──► appendBrainNote ──► appendLogEvent (existing)
+o2b status ──► discoverConfig + resolveSemanticConfigState
+```
+
+There is no new persistent state. The Most-applied section is fully
+derived from existing log files at render time.
+
+## 5. `brain_context` MCP tool
+
+### 5.1 Surface
+
+```
+name: brain_context
+description: Pull the current Brain/active.md body plus active-preference
+ counts. Use at session start when SessionStart hook is
+ unavailable (Cursor, Aider, raw Claude API).
+inputSchema: { type: "object", properties: {}, additionalProperties: false }
+result:
+ {
+ vault_path: string, // ctx.vault, absolute
+ present: boolean, // Brain/ directory exists
+ active_path: string, // absolute path to Brain/active.md
+ content: string, // active.md as it lives on disk, "" if absent
+ counts: {
+ confirmed: number,
+ quarantine: number,
+ retired_recent: number,
+ most_applied_30d: number
+ },
+ generated_at: string | null, // active.md frontmatter; null when file absent
+ error?: string // present only when self-heal regen failed
+ }
+```
+
+### 5.2 Behaviour
+
+1. If `Brain/` is not present in the vault: return
+ `present: false`, `content: ""`, `counts` all zero,
+ `generated_at: null`. No error. New vaults are a valid state for
+ this tool to describe.
+2. Otherwise: call `regenerateActive(vault)`. That function is
+ idempotent β€” it writes only when the body differs from disk, so
+ calling it on every `brain_context` invocation costs at most the
+ preference + retired + log walk it would do during dream. Use the
+ returned `counts` directly. If the call throws (disk full,
+ permission error), return `present: true`, `content: ""`,
+ zero counts, `generated_at: null`, and the error message in
+ `error: string`.
+3. Read `Brain/active.md` from disk and parse its frontmatter to
+ pull `generated_at`. The file is guaranteed to exist after step
+ 2. Return the full body in `content`.
+
+The tool never *writes anything new* on its own β€” `regenerateActive`
+either no-ops (file body unchanged) or self-heals a missing /
+out-of-date file. Two consecutive calls against an unchanged Brain
+return byte-equal payloads (the `generated_at` reflects the file's
+frontmatter, not the wall clock at the second call).
+
+### 5.3 Scope
+
+Added to `WRITER_TOOL_NAMES` so it loads in the
+`open-second-brain-writer` MCP server (the always-loaded scope).
+A code comment at the set declaration explains why a read tool now
+lives in the "writer" scope (always-load semantics, not write
+semantics).
+
+### 5.4 Idempotence
+
+See Β§5.2 β€” the property falls out of `regenerateActive`'s existing
+no-op-on-equal-body contract.
+
+## 6. `Most-applied (30d)` section in `active.md`
+
+### 6.1 Computation: `computeMostApplied`
+
+Signature:
+
+```ts
+export interface MostAppliedEntry {
+ readonly preference: BrainPreference;
+ readonly applied_30d: number;
+}
+export function computeMostApplied(
+ vault: string,
+ preferences: ReadonlyArray<BrainPreference>,
+ opts?: { readonly now?: Date; readonly limit?: number },
+): ReadonlyArray<MostAppliedEntry>;
+```
+
+Algorithm:
+
+1. `now = opts.now ?? new Date()`. `limit = opts.limit ?? 10`.
+2. Window `[now - 30 * 24 * 3600 * 1000, now]` in milliseconds.
+3. Build a `Map<string, BrainPreference>` keyed by
+ `normaliseWikilinkTarget(pref.id)` from the `preferences` argument
+ (already filtered to `confirmed | quarantine` upstream).
+4. Walk `Brain/log/`. Use the same allow-list regex as `status.ts`
+ (`/^\d{4}-\d{2}-\d{2}\.md$/`). Compute the file's date prefix
+ integer (`YYYY-MM-DD`) and skip files whose date is more than one
+ day older than the window start (one-day slack covers UTC drift).
+5. For each remaining day: call `readLogDay(vault, date)` (existing
+ JSONL-preferred reader). Iterate `entries`:
+ - `e.eventType` must equal `BRAIN_LOG_EVENT_KIND.applyEvidence`.
+ - `e.result` must equal `"applied"`.
+ - `Date.parse(e.timestamp)` must lie inside the window.
+ - `normaliseWikilinkTarget(e.preference)` must hit the preference
+ map (otherwise the event belongs to a retired or unknown rule
+ and the section excludes it by design).
+6. Tally `Map<string, number>` keyed by the normalised preference id.
+7. Sort descending by count, tiebreaker `id` ascending. Take `limit`.
+8. Map back to `{ preference, applied_30d }`.
+
+Error handling: a parse failure on one log day calls
+`process.stderr.write` (matching `readLogDay`'s own warn-and-continue
+contract) and moves on. The function never throws.
+
+### 6.2 Render
+
+In `renderBody`, between `Confirmed` and `Quarantine`:
+
+```
+## Most-applied (30d) (<N>)
+
+- `pref-foo` (scope: <scope>, applied_30d: <n>) β€” <principle>
+- `pref-bar` (applied_30d: <n>) β€” <principle>
+…
+```
+
+Section is omitted when `N === 0`. The `scope:` segment is omitted
+when the preference has no scope.
+
+### 6.3 Counts plumbing
+
+`RegenerateActiveResult.counts` grows a fourth field:
+
+```ts
+readonly counts: {
+ readonly confirmed: number;
+ readonly quarantine: number;
+ readonly retired_recent: number;
+ readonly most_applied_30d: number; // NEW
+};
+```
+
+No external consumer of `RegenerateActiveResult.counts` exists today
+outside the function's tests, so the addition is safe.
+
+### 6.4 Idempotence
+
+`renderBody` already compares byte-for-byte against the on-disk body
+before writing. The Most-applied section is deterministic given
+the same logs and the same `now` β€” but `now` advances. Two render
+runs at different wall clocks against an unchanged log set produce
+the same body iff no `apply-evidence` event crossed the window
+boundary in between. That is the same idempotence model the rest of
+`active.md` already lives by (the frontmatter `generated_at`
+timestamp is the only intentional variance), so no special handling
+is needed.
+
+## 7. CLI: `o2b brain note`
+
+### 7.1 Core extraction
+
+The body of `toolBrainNote` (`src/mcp/brain-tools.ts:324-358`)
+collapses to four steps: validate text, sanitise, resolve agent,
+`appendLogEvent`. We extract those steps into
+`src/core/brain/note.ts`:
+
+```ts
+export interface AppendBrainNoteInput {
+ readonly vault: string;
+ readonly text: string;
+ readonly agent?: string;
+ readonly now?: Date;
+ readonly configPath?: string;
+}
+
+export interface AppendBrainNoteResult {
+ readonly logged_at: string;
+ readonly log_path: string; // vault-relative
+ readonly absolute_log_path: string;
+ readonly agent: string;
+}
+
+export function appendBrainNote(
+ input: AppendBrainNoteInput,
+): AppendBrainNoteResult;
+```
+
+The function throws plain `Error` on empty/missing text (the MCP
+wrapper translates that into `MCPError(INVALID_PARAMS, ...)`; the
+CLI wrapper translates it into a 2-exit with the same message).
+
+### 7.2 CLI surface
+
+```
+o2b brain note <text> [--agent <name>] [--vault <path>] [--config <path>] [--json]
+```
+
+- `<text>` β€” single positional argument, required. Empty / whitespace
+ only β†’ exit 2 with `error: brain note requires text`.
+- `--agent` β€” override identity. Defaults to
+ `resolveAgentName(config)`, same as the MCP handler.
+- `--vault` / `--config` β€” same shape as every other Brain verb.
+- `--json` β€” emit `{logged_at, log_path, absolute_log_path, agent}`
+ as a single JSON object to stdout. Default human form is
+ `logged note at <log_path>\n`.
+
+### 7.3 Hook detector
+
+`hooks/lib/detect.ts:BRAIN_EVENT_BASH_NEEDLES` adds the string
+`"o2b brain note "`. The trailing space prevents `o2b brain note-…`
+or `o2b brain notes` from matching. The `BRAIN_EVENT_NAME_SUFFIX`
+already covers the MCP-side `brain_note` tool name.
+
+### 7.4 Help text
+
+`src/cli/brain/help-text.ts` gains a `note` entry alongside
+`feedback`, `apply-evidence`, etc. The description points operators
+at the cron / shell-script use case.
+
+## 8. `o2b status` semantic hint
+
+### 8.1 Decision helper
+
+A new helper in `src/cli/helpers.ts`:
+
+```ts
+export interface SemanticConfigState {
+ readonly semantic_enabled: boolean;
+ readonly embedding_key_present: boolean;
+ readonly off: boolean; // (!enabled) || (!key)
+ readonly hint: string | null; // human-friendly one-liner, or null
+}
+
+export function resolveSemanticConfigState(
+ configData: Readonly<Record<string, unknown>>,
+ env: NodeJS.ProcessEnv,
+): SemanticConfigState;
+```
+
+Implementation matches the `truthy` predicate already in
+`writeSearchInitBlock`. Both `cmdInit` and `cmdStatus` start calling
+this helper; the duplicated truthy/key logic in
+`writeSearchInitBlock` collapses onto the same source.
+
+A small wrinkle: `o2b status` should not nag when search is disabled
+outright (`search_enabled: "false"`). The helper exposes
+`searchDisabledByConfig(configData)` so the caller can suppress the
+hint in that branch. (Alternatively, the helper itself reads
+`search_enabled` and returns `off: false, hint: null` when search is
+disabled β€” simpler, picked.)
+
+### 8.2 Human output
+
+After the existing `config_keys:` block:
+
+```
+semantic: off (run 'o2b search check' for setup steps)
+```
+
+Only when `off === true` AND `search_enabled !== "false"`. Otherwise
+nothing.
+
+### 8.3 JSON output
+
+The `--json` payload grows three keys, always present:
+
+```
+{
+ "config_path": "...",
+ "config_exists": true,
+ "config_keys": [...],
+ "vault": "...",
+ "semantic_enabled": false,
+ "embedding_key_present": false,
+ "semantic_hint": "run 'o2b search check' for setup steps"
+}
+```
+
+`semantic_hint` is `null` when `off === false`. Machine consumers can
+either read the booleans directly or display the prebuilt hint.
+
+## 9. Tests (TDD order)
+
+Each test file is written *before* the matching implementation. The
+order below matches the implementation order in Β§10.
+
+1. `tests/core/brain/most-applied.test.ts` β€” drives Β§6.1.
+2. `tests/core/brain/active.test.ts` extensions β€” drives Β§6.2,
+ Β§6.3.
+3. `tests/mcp/brain-context.test.ts` β€” drives Β§5.
+4. `tests/core/brain/note.test.ts` β€” drives Β§7.1.
+5. `tests/cli/brain-note.test.ts` (execFile-based) β€” drives Β§7.2.
+6. `tests/hooks/detect.test.ts` extensions β€” drives Β§7.3.
+7. `tests/cli/status.test.ts` β€” drives Β§8.
+8. `tests/e2e/v0.10.10-pull-channels.test.ts` β€” one happy-path
+ covering `o2b brain note` writing to `Brain/log/today.md` with
+ correct identity and the `note` event kind appearing in the JSONL
+ sidecar.
+
+Coverage targets:
+
+- `computeMostApplied`: window boundaries, retired exclusion,
+ quarantine inclusion, wikilink line-range normalisation, malformed
+ log day, empty vault.
+- `appendBrainNote`: multi-line collapse, length cap, empty text
+ rejection, agent resolution priority (explicit > config > env).
+- `brain_context`: present/absent Brain, present/absent active.md
+ with self-heal, idempotent payload, `most_applied_30d` count
+ reflected.
+- `o2b status`: human-output presence/absence under each of the four
+ state matrices (enabled Γ— key-present), JSON shape under same,
+ suppression when `search_enabled` is `false`.
+- `hooks/detect`: positive match for `o2b brain note "…"`, negative
+ match for `o2b brain notes`, `o2b brain not-quite`.
+
+## 10. Implementation order
+
+1. Tests in Β§9.1 (most-applied), implementation in
+ `src/core/brain/most-applied.ts`.
+2. Tests in Β§9.2 (active.md), wiring in `src/core/brain/active.ts`.
+3. Tests in Β§9.3 (brain_context), handler in
+ `src/mcp/brain-tools.ts`, registration in `src/mcp/tools.ts`,
+ instructions update in `src/mcp/instructions.ts`.
+4. Tests in Β§9.4 (appendBrainNote core), extraction from
+ `src/mcp/brain-tools.ts` into `src/core/brain/note.ts`. MCP
+ handler refactored to thin wrapper; existing MCP tests stay
+ green.
+5. Tests in Β§9.5 (CLI verb), implementation in
+ `src/cli/brain/verbs/note.ts`, dispatcher in `src/cli/brain.ts`,
+ help text.
+6. Tests in Β§9.6 (hook detector), needle list update.
+7. Tests in Β§9.7 (`o2b status`), helper extraction in
+ `src/cli/helpers.ts`, render update in `src/cli/main.ts`.
+8. E2E in Β§9.8.
+9. Documentation pass: `CHANGELOG.md`, `docs/architecture.md`,
+ `hooks/README.md`, `src/mcp/instructions.ts`,
+ `Projects/OpenSecondBrain/Features/_summary.md` (vault edit β€”
+ operator-confirmed).
+
+## 11. Vault summary update
+
+After implementation lands, the vault-side
+`Projects/OpenSecondBrain/Features/_summary.md` is updated in three
+small places (operator-confirmed edit, no automated cron writes):
+
+- Β§1 shipped-in header gains "+v0.10.10 Most-applied (30d) section".
+- "Π‘ΠΏΠΎΡ€Π½Ρ‹Π΅ / ΠΎΡ‚Π»ΠΎΠΆΠ΅Π½Π½Ρ‹Π΅" β€” the `brain_context` bullet is removed
+ (no longer disputed).
+- "Deferred work" β€” the Β§32B CLI bullet moves to a shipped reference
+ pointing at the v0.10.10 release notes.
+
+## 12. Deferred / out of scope for this release
+
+These appear in `Brain/` / `_summary.md` `## Deferred work` only if
+they remain open after this release ships. They are not part of the
+v0.10.10 scope:
+
+- Configurable Most-applied window (default 30d) or limit (default
+ 10) via `_brain.yaml`. Trigger: first operator request after
+ shipping.
+- Rename the always-loaded MCP server from
+ `open-second-brain-writer` to something neutral
+ (`open-second-brain-core` or similar). Trigger: a second reader
+ tool joins the writer scope.
+- `brain_context` filters (`scope`, `topic`). Trigger: a real agent
+ use case where the full active.md is too large.
+- `o2b brain note --stdin` for multi-line piping. Trigger: a real
+ cron / script that wants multi-line. (MCP `brain_note` does not
+ support multi-line either; the limitation is intentional.)
+- Surfacing the Most-applied section through `brain_digest` as a
+ second hot block alongside the existing `top_applied` (lifetime).
+ Trigger: a digest reader who specifically wants both lifetime and
+ windowed views in one render.
+
+## 13. Risks
+
+- **`now` injection in tests.** `computeMostApplied` accepts `now`
+ via `opts.now` because the window calculation otherwise reads the
+ system clock. Every caller in production passes the default
+ (`new Date()`). Tests inject a fixed `now` for deterministic
+ windowing. This is the same pattern `active.ts` already follows.
+- **Reading 30 log days on every `regenerateActive`.** Worst case is
+ 30 JSONL files Γ— ~50 entries each. `readLogDay` is JSONL-preferred
+ and already part of the dream hot path. No observable regression.
+- **Writer-server scope drift.** Adding a read tool to a server
+ named "writer" is a naming inconsistency. Mitigation: comment at
+ the `WRITER_TOOL_NAMES` declaration explaining the always-load
+ rationale. Rename is deferred β€” see Β§12.
+- **`o2b status` JSON shape grows three keys.** Existing consumers
+ do not depend on the JSON shape today (verified via the absence
+ of a `status --json` test outside `cli`). The three new keys are
+ always-present booleans / nullable string, additive only.
diff --git a/docs/plans/2026-05-20-v0.10.10-impl.md b/docs/plans/2026-05-20-v0.10.10-impl.md
new file mode 100644
index 00000000..6255bcf7
--- /dev/null
+++ b/docs/plans/2026-05-20-v0.10.10-impl.md
@@ -0,0 +1,2345 @@
+# v0.10.10 β€” pull-channels: Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+>
+> **Git policy for this project (operator-imposed):** the executing
+> agent MUST NOT run `git commit`, `git push`, branch creation, or any
+> other state-changing git command without an explicit per-action
+> confirmation from the operator. Every "Commit" step below ends with
+> `Pause: ask operator for permission to run the git command, paste
+> the exact command, wait for an explicit yes`. Do not auto-stage and
+> do not piggyback unrelated changes.
+
+**Goal:** Ship four small "pull channels" so that runtimes / cron jobs /
+operators without a `SessionStart` hook can still reach the agent's
+working memory: a `brain_context` MCP tool, a Most-applied (30d)
+section in `Brain/active.md`, a `o2b brain note` CLI verb, and a
+semantic-search hint line in `o2b status`.
+
+**Architecture:** Each feature reuses an existing module rather than
+introducing a new abstraction. `brain_context` is a thin read wrapper
+over `regenerateActive`. Most-applied lives in its own pure module
+(`src/core/brain/most-applied.ts`) and plugs into the existing
+`renderBody`. `o2b brain note` extracts the body of `toolBrainNote`
+into `src/core/brain/note.ts` so the MCP handler and the CLI share
+exactly one code path. The semantic hint lifts the existing truthy
+predicate from `writeSearchInitBlock` into
+`src/cli/helpers.ts:resolveSemanticConfigState` so both `o2b init` and
+`o2b status` consume the same source.
+
+**Tech Stack:** TypeScript (Node-style, run by Bun), `bun test`, no
+new runtime dependencies. Tests live under `tests/`, mirroring the
+existing structure (`tests/core/brain/`, `tests/cli/`, `tests/mcp/`,
+`tests/hooks/`, `tests/e2e/`). The full test suite is run with
+`bun test` from the repo root.
+
+**Spec:** `docs/plans/2026-05-20-v0.10.10-design.md`. Read it before
+starting β€” every section number below (`Β§5.2`, `Β§6.1`, …) refers to
+that document.
+
+---
+
+## Pre-flight
+
+These run once before Task 1.
+
+- [ ] **Verify the working tree is clean.**
+
+```bash
+cd /srv/projects/open-second-brain
+git status
+```
+
+Expected: branch is `master` or an existing feature branch, no unstaged
+changes, no untracked files in `src/` or `tests/`. If dirty: stop and
+ask the operator how to proceed.
+
+- [ ] **Verify baseline tests pass.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test
+```
+
+Expected: full suite green. If anything fails: stop and ask the
+operator β€” implementing on top of red tests would mask new
+regressions.
+
+- [ ] **Verify typecheck passes.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun run typecheck
+```
+
+Expected: zero errors.
+
+- [ ] **Read the spec.**
+
+Read `docs/plans/2026-05-20-v0.10.10-design.md` end-to-end. Every
+later step relies on section references from it.
+
+---
+
+## Task 1: `computeMostApplied` core function
+
+**Files:**
+- Create: `src/core/brain/most-applied.ts`
+- Test: `tests/core/brain/most-applied.test.ts`
+
+Implements Β§6.1 (window scan over `Brain/log/`, ranking by
+`apply-evidence (result: applied)` count, keyed by preference id).
+
+- [ ] **Step 1.1: Write the failing test file.**
+
+```ts
+// tests/core/brain/most-applied.test.ts
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { computeMostApplied } from "../../../src/core/brain/most-applied.ts";
+import type { BrainPreference } from "../../../src/core/brain/types.ts";
+import { BRAIN_PREFERENCE_STATUS } from "../../../src/core/brain/types.ts";
+
+function buildPref(id: string, overrides: Partial<BrainPreference> = {}): BrainPreference {
+ return {
+ id,
+ topic: id.replace(/^pref-/, ""),
+ principle: `principle for ${id}`,
+ signal: "positive",
+ scope: null,
+ pinned: false,
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ confidence: "medium",
+ confidence_value: 0.5,
+ applied_count: 0,
+ violated_count: 0,
+ created_at: "2026-04-01T00:00:00Z",
+ last_evidence_at: null,
+ evidenced_by: [],
+ contradicted_by: [],
+ unconfirmed_until: null,
+ primary_agent: null,
+ retired_reason: null,
+ ...overrides,
+ } as BrainPreference;
+}
+
+function writeLogDay(vault: string, date: string, body: string): void {
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+ writeFileSync(join(vault, "Brain", "log", `${date}.md`), body, "utf8");
+}
+
+const APPLY_BLOCK = (ts: string, prefWikilink: string) =>
+ [
+ `## ${ts.slice(11, 19)}Z - apply-evidence`,
+ `- timestamp: ${ts}`,
+ `- preference: ${prefWikilink}`,
+ `- artifact: [[src/foo.ts]]`,
+ `- agent: tester`,
+ `- result: applied`,
+ "",
+ ].join("\n");
+
+const LOG_HEADER = (date: string) =>
+ ["---", "kind: brain-log", `date: ${date}`, "tags: [project/open-second-brain, log]", "---", "", `# ${date}`, ""].join("\n");
+
+describe("computeMostApplied", () => {
+ let vault: string;
+ beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-most-applied-"));
+ });
+ afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ });
+
+ test("returns empty when log directory is missing", () => {
+ const result = computeMostApplied(vault, [], { now: new Date("2026-05-20T00:00:00Z") });
+ expect(result).toEqual([]);
+ });
+
+ test("counts only result=applied events inside the 30d window", () => {
+ const now = new Date("2026-05-20T00:00:00Z");
+ writeLogDay(
+ vault,
+ "2026-05-15",
+ LOG_HEADER("2026-05-15")
+ + APPLY_BLOCK("2026-05-15T10:00:00Z", "[[pref-a]]")
+ + APPLY_BLOCK("2026-05-15T10:05:00Z", "[[pref-a]]"),
+ );
+ // 31 days ago β€” out of window.
+ writeLogDay(
+ vault,
+ "2026-04-19",
+ LOG_HEADER("2026-04-19")
+ + APPLY_BLOCK("2026-04-19T10:00:00Z", "[[pref-a]]"),
+ );
+ const prefs = [buildPref("pref-a")];
+ const result = computeMostApplied(vault, prefs, { now });
+ expect(result.length).toBe(1);
+ expect(result[0]!.applied_30d).toBe(2);
+ });
+
+ test("ignores violated and outdated results", () => {
+ const now = new Date("2026-05-20T00:00:00Z");
+ const VIOL = APPLY_BLOCK("2026-05-15T10:00:00Z", "[[pref-a]]").replace("applied", "violated");
+ const OUTD = APPLY_BLOCK("2026-05-15T10:05:00Z", "[[pref-a]]").replace("applied", "outdated");
+ writeLogDay(vault, "2026-05-15", LOG_HEADER("2026-05-15") + VIOL + OUTD);
+ const result = computeMostApplied(vault, [buildPref("pref-a")], { now });
+ expect(result).toEqual([]);
+ });
+
+ test("excludes preferences whose status is not confirmed or quarantine (input contract)", () => {
+ const now = new Date("2026-05-20T00:00:00Z");
+ writeLogDay(
+ vault,
+ "2026-05-15",
+ LOG_HEADER("2026-05-15") + APPLY_BLOCK("2026-05-15T10:00:00Z", "[[pref-a]]"),
+ );
+ // Caller passes ONLY confirmed/quarantine preferences. Retired
+ // preferences are dropped by the caller before reaching this
+ // function, so an event referencing pref-a with no matching
+ // entry in the map is silently ignored.
+ const result = computeMostApplied(vault, [], { now });
+ expect(result).toEqual([]);
+ });
+
+ test("includes quarantine preferences", () => {
+ const now = new Date("2026-05-20T00:00:00Z");
+ writeLogDay(
+ vault,
+ "2026-05-15",
+ LOG_HEADER("2026-05-15") + APPLY_BLOCK("2026-05-15T10:00:00Z", "[[pref-q]]"),
+ );
+ const result = computeMostApplied(
+ vault,
+ [buildPref("pref-q", { status: BRAIN_PREFERENCE_STATUS.quarantine })],
+ { now },
+ );
+ expect(result.length).toBe(1);
+ expect(result[0]!.preference.id).toBe("pref-q");
+ expect(result[0]!.applied_30d).toBe(1);
+ });
+
+ test("sorts by count desc, then by id asc", () => {
+ const now = new Date("2026-05-20T00:00:00Z");
+ writeLogDay(
+ vault,
+ "2026-05-15",
+ LOG_HEADER("2026-05-15")
+ + APPLY_BLOCK("2026-05-15T10:00:00Z", "[[pref-a]]")
+ + APPLY_BLOCK("2026-05-15T10:01:00Z", "[[pref-a]]")
+ + APPLY_BLOCK("2026-05-15T10:02:00Z", "[[pref-b]]")
+ + APPLY_BLOCK("2026-05-15T10:03:00Z", "[[pref-c]]"),
+ );
+ const result = computeMostApplied(
+ vault,
+ [buildPref("pref-a"), buildPref("pref-b"), buildPref("pref-c")],
+ { now },
+ );
+ expect(result.map((r) => r.preference.id)).toEqual(["pref-a", "pref-b", "pref-c"]);
+ expect(result[0]!.applied_30d).toBe(2);
+ });
+
+ test("honours limit", () => {
+ const now = new Date("2026-05-20T00:00:00Z");
+ let body = LOG_HEADER("2026-05-15");
+ for (const id of ["a", "b", "c"]) {
+ body += APPLY_BLOCK("2026-05-15T10:00:00Z", `[[pref-${id}]]`);
+ }
+ writeLogDay(vault, "2026-05-15", body);
+ const result = computeMostApplied(
+ vault,
+ [buildPref("pref-a"), buildPref("pref-b"), buildPref("pref-c")],
+ { now, limit: 2 },
+ );
+ expect(result.length).toBe(2);
+ });
+
+ test("normalises wikilinks with line ranges", () => {
+ const now = new Date("2026-05-20T00:00:00Z");
+ writeLogDay(
+ vault,
+ "2026-05-15",
+ LOG_HEADER("2026-05-15") + APPLY_BLOCK("2026-05-15T10:00:00Z", "[[pref-a:42-58]]"),
+ );
+ const result = computeMostApplied(vault, [buildPref("pref-a")], { now });
+ expect(result.length).toBe(1);
+ expect(result[0]!.applied_30d).toBe(1);
+ });
+
+ test("survives a malformed log day", () => {
+ const now = new Date("2026-05-20T00:00:00Z");
+ writeLogDay(vault, "2026-05-14", "this is not a valid log file");
+ writeLogDay(
+ vault,
+ "2026-05-15",
+ LOG_HEADER("2026-05-15") + APPLY_BLOCK("2026-05-15T10:00:00Z", "[[pref-a]]"),
+ );
+ const result = computeMostApplied(vault, [buildPref("pref-a")], { now });
+ expect(result.length).toBe(1);
+ expect(result[0]!.applied_30d).toBe(1);
+ });
+
+ test("event exactly on window edge is included", () => {
+ const now = new Date("2026-05-20T00:00:00Z");
+ const windowStart = new Date(now.getTime() - 30 * 24 * 3600 * 1000);
+ const stamp = windowStart.toISOString().replace(/\.\d{3}Z$/, "Z");
+ const date = stamp.slice(0, 10);
+ writeLogDay(vault, date, LOG_HEADER(date) + APPLY_BLOCK(stamp, "[[pref-a]]"));
+ const result = computeMostApplied(vault, [buildPref("pref-a")], { now });
+ expect(result.length).toBe(1);
+ });
+});
+```
+
+- [ ] **Step 1.2: Run the test, confirm it fails.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test tests/core/brain/most-applied.test.ts
+```
+
+Expected: every test fails because the module does not exist yet.
+
+- [ ] **Step 1.3: Implement the module.**
+
+Create `src/core/brain/most-applied.ts` with:
+
+```ts
+/**
+ * `Brain/active.md` Most-applied (30d) section computation.
+ *
+ * Reads the last 30 days of `Brain/log/`, counts `apply-evidence`
+ * events with `result: applied` whose `timestamp` lies inside the
+ * window, attributes them to the matching preference, and returns
+ * a ranked list capped at `limit` entries.
+ *
+ * Pure read. The caller passes the candidate preferences (already
+ * filtered to `confirmed | quarantine` in `regenerateActive`), so
+ * this module does not re-read the preferences directory.
+ *
+ * Anchored in design doc Β§6.1 ("Most-applied (30d) section in
+ * `active.md`").
+ */
+
+import { existsSync, readdirSync } from "node:fs";
+
+import { brainDirs } from "./paths.ts";
+import { readLogDay } from "./log-jsonl.ts";
+import { normaliseWikilinkTarget } from "./wikilink.ts";
+import {
+ BRAIN_APPLY_RESULT,
+ BRAIN_LOG_EVENT_KIND,
+ BRAIN_PREFERENCE_STATUS,
+ type BrainPreference,
+} from "./types.ts";
+
+const WINDOW_MS = 30 * 24 * 3600 * 1000;
+const DAY_MS = 24 * 3600 * 1000;
+const DEFAULT_LIMIT = 10;
+const LOG_FILENAME_RE = /^(\d{4}-\d{2}-\d{2})\.md$/;
+
+export interface MostAppliedEntry {
+ readonly preference: BrainPreference;
+ readonly applied_30d: number;
+}
+
+export interface ComputeMostAppliedOptions {
+ /** Window anchor. Defaults to `new Date()`. */
+ readonly now?: Date;
+ /** Max entries returned. Defaults to 10. */
+ readonly limit?: number;
+}
+
+/**
+ * Compute the Most-applied list for the `active.md` section.
+ *
+ * @param vault Vault root.
+ * @param preferences Candidate preferences (confirmed | quarantine).
+ * Events referencing preferences outside this list
+ * are silently ignored by design β€” retired rules
+ * do not appear in `active.md`.
+ */
+export function computeMostApplied(
+ vault: string,
+ preferences: ReadonlyArray<BrainPreference>,
+ opts: ComputeMostAppliedOptions = {},
+): ReadonlyArray<MostAppliedEntry> {
+ const now = opts.now ?? new Date();
+ const limit = opts.limit ?? DEFAULT_LIMIT;
+ const dirs = brainDirs(vault);
+ if (!existsSync(dirs.log)) return [];
+
+ // `preferences` is filtered upstream to confirmed | quarantine, but
+ // we sanity-check the status here so a future caller passing a
+ // wider list cannot accidentally surface retired rules.
+ const prefByKey = new Map<string, BrainPreference>();
+ for (const p of preferences) {
+ if (
+ p.status !== BRAIN_PREFERENCE_STATUS.confirmed &&
+ p.status !== BRAIN_PREFERENCE_STATUS.quarantine
+ ) {
+ continue;
+ }
+ prefByKey.set(normaliseWikilinkTarget(p.id), p);
+ }
+ if (prefByKey.size === 0) return [];
+
+ const windowEndMs = now.getTime();
+ const windowStartMs = windowEndMs - WINDOW_MS;
+ // Day-level fence: include the day before window start to absorb
+ // UTC drift between the event timestamp and the file's date prefix.
+ const earliestDayPrefix = isoDayPrefix(new Date(windowStartMs - DAY_MS));
+
+ const counts = new Map<string, number>();
+ for (const name of readdirSync(dirs.log)) {
+ const m = LOG_FILENAME_RE.exec(name);
+ if (!m) continue;
+ const datePrefix = m[1]!;
+ if (datePrefix < earliestDayPrefix) continue;
+
+ let parsed;
+ try {
+ parsed = readLogDay(vault, datePrefix);
+ } catch (err) {
+ process.stderr.write(
+ `warning: most-applied: failed to read ${datePrefix}: ${(err as Error).message}\n`,
+ );
+ continue;
+ }
+ for (const e of parsed.entries) {
+ if (e.eventType !== BRAIN_LOG_EVENT_KIND.applyEvidence) continue;
+ const result = e.body["result"];
+ if (result !== BRAIN_APPLY_RESULT.applied) continue;
+ const tsMs = Date.parse(e.timestamp);
+ if (!Number.isFinite(tsMs)) continue;
+ if (tsMs < windowStartMs || tsMs > windowEndMs) continue;
+ const prefField = e.body["preference"];
+ if (typeof prefField !== "string") continue;
+ const key = normaliseWikilinkTarget(prefField);
+ if (!prefByKey.has(key)) continue;
+ counts.set(key, (counts.get(key) ?? 0) + 1);
+ }
+ }
+
+ const entries: MostAppliedEntry[] = [];
+ for (const [key, count] of counts) {
+ const pref = prefByKey.get(key)!;
+ entries.push({ preference: pref, applied_30d: count });
+ }
+ entries.sort((a, b) => {
+ if (b.applied_30d !== a.applied_30d) return b.applied_30d - a.applied_30d;
+ return a.preference.id.localeCompare(b.preference.id);
+ });
+ return entries.slice(0, limit);
+}
+
+function isoDayPrefix(d: Date): string {
+ return d.toISOString().slice(0, 10);
+}
+```
+
+> **DRY check:** `BRAIN_APPLY_RESULT.applied` is the canonical literal
+> for `"applied"`. If `src/core/brain/types.ts` does not export this
+> constant, use `e.body["result"] === "applied"` inline β€” do NOT
+> introduce a new constant for it.
+
+- [ ] **Step 1.4: Run the test, confirm it passes.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test tests/core/brain/most-applied.test.ts
+```
+
+Expected: all tests green.
+
+- [ ] **Step 1.5: Typecheck.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun run typecheck
+```
+
+Expected: zero errors.
+
+- [ ] **Step 1.6: Commit.**
+
+```bash
+git add src/core/brain/most-applied.ts tests/core/brain/most-applied.test.ts
+git commit -m "feat(brain): computeMostApplied β€” 30d apply-evidence ranker"
+```
+
+Pause: ask operator for permission to run the git command, paste the
+exact command, wait for an explicit yes.
+
+---
+
+## Task 2: Render Most-applied section in `active.md`
+
+**Files:**
+- Modify: `src/core/brain/active.ts`
+- Modify: `tests/core/brain/active.test.ts` (extend; create if missing)
+
+Implements Β§6.2, Β§6.3, Β§6.4.
+
+- [ ] **Step 2.1: Check whether `tests/core/brain/active.test.ts` exists.**
+
+```bash
+ls -1 /srv/projects/open-second-brain/tests/core/brain/active.test.ts 2>&1 || echo "absent"
+```
+
+If absent: create it in step 2.2 with the full scaffolding shown below.
+If present: append the new `describe("Most-applied (30d)", ...)` block
+without disturbing existing tests.
+
+- [ ] **Step 2.2: Write the failing Most-applied test block.**
+
+Add (or create the file with) the following block. If creating from
+scratch, prepend the same imports `most-applied.test.ts` uses, plus
+`regenerateActive` from the module under test.
+
+```ts
+// In tests/core/brain/active.test.ts
+import { describe, expect, test, beforeEach, afterEach } from "bun:test";
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { regenerateActive } from "../../../src/core/brain/active.ts";
+import { writePreference } from "../../../src/core/brain/preference.ts";
+import {
+ BRAIN_PREFERENCE_STATUS,
+ BRAIN_SIGNAL_SIGN,
+} from "../../../src/core/brain/types.ts";
+
+function bootstrap(vault: string): void {
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ "dream:\n unconfirmed_window_days: 7\n",
+ "utf8",
+ );
+}
+
+const LOG_HEADER = (date: string) =>
+ ["---", "kind: brain-log", `date: ${date}`, "tags: [project/open-second-brain, log]", "---", "", `# ${date}`, ""].join("\n");
+
+const APPLY_BLOCK = (ts: string, prefWikilink: string) =>
+ [
+ `## ${ts.slice(11, 19)}Z - apply-evidence`,
+ `- timestamp: ${ts}`,
+ `- preference: ${prefWikilink}`,
+ `- artifact: [[src/foo.ts]]`,
+ `- agent: tester`,
+ `- result: applied`,
+ "",
+ ].join("\n");
+
+describe("Most-applied (30d) section", () => {
+ let vault: string;
+ beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-active-most-applied-"));
+ bootstrap(vault);
+ });
+ afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ });
+
+ test("section absent when no applied events in window", () => {
+ writePreference(vault, {
+ id: "pref-a",
+ topic: "a",
+ principle: "principle a",
+ signal: BRAIN_SIGNAL_SIGN.positive,
+ scope: null,
+ pinned: false,
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ confidence: "medium",
+ confidence_value: 0.5,
+ applied_count: 0,
+ violated_count: 0,
+ created_at: "2026-05-01T00:00:00Z",
+ last_evidence_at: null,
+ evidenced_by: [],
+ contradicted_by: [],
+ unconfirmed_until: null,
+ primary_agent: null,
+ retired_reason: null,
+ });
+ const res = regenerateActive(vault, { now: new Date("2026-05-20T00:00:00Z") });
+ const body = readFileSync(res.path, "utf8");
+ expect(body).not.toContain("## Most-applied");
+ expect(res.counts.most_applied_30d).toBe(0);
+ });
+
+ test("section rendered when applied events exist", () => {
+ writePreference(vault, {
+ id: "pref-a",
+ topic: "a",
+ principle: "principle a",
+ signal: BRAIN_SIGNAL_SIGN.positive,
+ scope: "writing",
+ pinned: false,
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ confidence: "medium",
+ confidence_value: 0.5,
+ applied_count: 0,
+ violated_count: 0,
+ created_at: "2026-05-01T00:00:00Z",
+ last_evidence_at: null,
+ evidenced_by: [],
+ contradicted_by: [],
+ unconfirmed_until: null,
+ primary_agent: null,
+ retired_reason: null,
+ });
+ writeFileSync(
+ join(vault, "Brain", "log", "2026-05-15.md"),
+ LOG_HEADER("2026-05-15") + APPLY_BLOCK("2026-05-15T10:00:00Z", "[[pref-a]]"),
+ "utf8",
+ );
+ const res = regenerateActive(vault, { now: new Date("2026-05-20T00:00:00Z") });
+ const body = readFileSync(res.path, "utf8");
+ expect(body).toContain("## Most-applied (30d) (1)");
+ expect(body).toContain("`pref-a`");
+ expect(body).toContain("applied_30d: 1");
+ expect(res.counts.most_applied_30d).toBe(1);
+ });
+
+ test("idempotent: re-render produces byte-equal body", () => {
+ writePreference(vault, {
+ id: "pref-a",
+ topic: "a",
+ principle: "p",
+ signal: BRAIN_SIGNAL_SIGN.positive,
+ scope: null,
+ pinned: false,
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ confidence: "medium",
+ confidence_value: 0.5,
+ applied_count: 0,
+ violated_count: 0,
+ created_at: "2026-05-01T00:00:00Z",
+ last_evidence_at: null,
+ evidenced_by: [],
+ contradicted_by: [],
+ unconfirmed_until: null,
+ primary_agent: null,
+ retired_reason: null,
+ });
+ writeFileSync(
+ join(vault, "Brain", "log", "2026-05-15.md"),
+ LOG_HEADER("2026-05-15") + APPLY_BLOCK("2026-05-15T10:00:00Z", "[[pref-a]]"),
+ "utf8",
+ );
+ const r1 = regenerateActive(vault, { now: new Date("2026-05-20T00:00:00Z") });
+ const body1 = readFileSync(r1.path, "utf8");
+ const r2 = regenerateActive(vault, { now: new Date("2026-05-20T00:01:00Z") });
+ const body2 = readFileSync(r2.path, "utf8");
+ // frontmatter `generated_at` would differ if a rewrite happened;
+ // because the body did not change, regenerateActive must keep the
+ // file untouched.
+ expect(body2).toBe(body1);
+ expect(r2.changed).toBe(false);
+ });
+});
+```
+
+- [ ] **Step 2.3: Run the failing block.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test tests/core/brain/active.test.ts
+```
+
+Expected: the Most-applied block fails because the field
+`counts.most_applied_30d` does not exist yet and the section is not
+rendered.
+
+- [ ] **Step 2.4: Extend `RegenerateActiveResult.counts`.**
+
+Edit `src/core/brain/active.ts`. Find the `RegenerateActiveResult`
+interface (around line 57). Add the `most_applied_30d` field:
+
+```ts
+export interface RegenerateActiveResult {
+ readonly path: string;
+ readonly changed: boolean;
+ readonly counts: {
+ readonly confirmed: number;
+ readonly quarantine: number;
+ readonly retired_recent: number;
+ readonly most_applied_30d: number; // NEW
+ };
+}
+```
+
+- [ ] **Step 2.5: Call `computeMostApplied` from `regenerateActive`.**
+
+Edit `src/core/brain/active.ts`. Add the import near the top:
+
+```ts
+import { computeMostApplied, type MostAppliedEntry } from "./most-applied.ts";
+```
+
+In the `regenerateActive` body, after computing `confirmed` and
+`quarantine`:
+
+```ts
+ const mostApplied = computeMostApplied(
+ vault,
+ [...confirmed, ...quarantine],
+ { now },
+ );
+```
+
+Pass `mostApplied` into the render:
+
+```ts
+ const body = renderBody({
+ confirmed,
+ quarantine,
+ retiredRecent,
+ mostApplied, // NEW
+ });
+```
+
+Update the returned counts:
+
+```ts
+ return {
+ path,
+ changed,
+ counts: {
+ confirmed: confirmed.length,
+ quarantine: quarantine.length,
+ retired_recent: retiredRecent.length,
+ most_applied_30d: mostApplied.length, // NEW
+ },
+ };
+```
+
+- [ ] **Step 2.6: Extend `RenderInput` and `renderBody`.**
+
+Edit `src/core/brain/active.ts`. Extend `RenderInput`:
+
+```ts
+interface RenderInput {
+ readonly confirmed: ReadonlyArray<BrainPreference>;
+ readonly quarantine: ReadonlyArray<BrainPreference>;
+ readonly retiredRecent: ReadonlyArray<BrainRetired>;
+ readonly mostApplied: ReadonlyArray<MostAppliedEntry>; // NEW
+}
+```
+
+In `renderBody`, between the `Confirmed` section and the `Quarantine`
+section, insert:
+
+```ts
+ if (input.mostApplied.length > 0) {
+ out.push(`## Most-applied (30d) (${input.mostApplied.length})`);
+ out.push("");
+ for (const m of input.mostApplied) out.push(renderMostAppliedLine(m));
+ out.push("");
+ }
+```
+
+Add the renderer near the other `render*Line` helpers:
+
+```ts
+function renderMostAppliedLine(m: MostAppliedEntry): string {
+ const p = m.preference;
+ const tags: string[] = [];
+ if (p.scope) tags.push(`scope: ${p.scope}`);
+ tags.push(`applied_30d: ${m.applied_30d}`);
+ return `- \`${p.id}\` (${tags.join(", ")}) β€” ${p.principle}`;
+}
+```
+
+- [ ] **Step 2.7: Run the active.md tests, confirm they pass.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test tests/core/brain/active.test.ts tests/core/brain/most-applied.test.ts
+```
+
+Expected: green.
+
+- [ ] **Step 2.8: Run the full suite.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test
+```
+
+Expected: green. Any pre-existing test that asserted exact body bytes
+of `active.md` will likely surface here β€” fix it by appending the
+`Most-applied` expectation rather than weakening the assertion.
+
+- [ ] **Step 2.9: Typecheck.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun run typecheck
+```
+
+Expected: zero errors.
+
+- [ ] **Step 2.10: Commit.**
+
+```bash
+git add src/core/brain/active.ts tests/core/brain/active.test.ts
+git commit -m "feat(brain): Most-applied (30d) section in active.md"
+```
+
+Pause: ask operator for permission, paste the command, wait for yes.
+
+---
+
+## Task 3: Extract `appendBrainNote` core
+
+**Files:**
+- Create: `src/core/brain/note.ts`
+- Modify: `src/mcp/brain-tools.ts` (refactor `toolBrainNote`)
+- Test: `tests/core/brain/note.test.ts`
+
+Implements Β§7.1. No behaviour change for the MCP tool β€” existing tests
+in `tests/mcp/brain.test.ts` must remain green.
+
+- [ ] **Step 3.1: Write the failing test for the new core function.**
+
+```ts
+// tests/core/brain/note.test.ts
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { appendBrainNote } from "../../../src/core/brain/note.ts";
+
+function bootstrap(vault: string): void {
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ "dream:\n unconfirmed_window_days: 7\n",
+ "utf8",
+ );
+}
+
+describe("appendBrainNote", () => {
+ let vault: string;
+ beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-brain-note-"));
+ bootstrap(vault);
+ });
+ afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ });
+
+ test("writes a one-line note to today's log under kind=note", () => {
+ const now = new Date("2026-05-20T12:34:56Z");
+ const res = appendBrainNote({
+ vault,
+ text: "released v0.10.10",
+ agent: "tester",
+ now,
+ });
+ expect(res.agent).toBe("tester");
+ expect(res.logged_at).toBe("2026-05-20T12:34:56Z");
+ expect(res.log_path).toBe("Brain/log/2026-05-20.md");
+ const body = readFileSync(res.absolute_log_path, "utf8");
+ expect(body).toContain("## 12:34:56Z - note");
+ expect(body).toContain("- text: released v0.10.10");
+ expect(body).toContain("- agent: tester");
+ });
+
+ test("collapses multi-line text to one line", () => {
+ const res = appendBrainNote({
+ vault,
+ text: "line one\nline two\r\nline three",
+ agent: "tester",
+ now: new Date("2026-05-20T00:00:00Z"),
+ });
+ const body = readFileSync(res.absolute_log_path, "utf8");
+ expect(body).toContain("- text: line one line two line three");
+ });
+
+ test("rejects empty text", () => {
+ expect(() =>
+ appendBrainNote({ vault, text: " ", agent: "tester", now: new Date() }),
+ ).toThrow(/text is required/);
+ });
+
+ test("rejects whitespace-only text after sanitiser", () => {
+ expect(() =>
+ appendBrainNote({ vault, text: "\n\t \n", agent: "tester", now: new Date() }),
+ ).toThrow(/text is required/);
+ });
+});
+```
+
+- [ ] **Step 3.2: Run, confirm it fails.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test tests/core/brain/note.test.ts
+```
+
+Expected: file not found β†’ tests fail.
+
+- [ ] **Step 3.3: Create the core module.**
+
+Create `src/core/brain/note.ts`:
+
+```ts
+/**
+ * `appendBrainNote` β€” single source of truth for the `brain_note`
+ * event-kind write.
+ *
+ * Called by:
+ * - `src/mcp/brain-tools.ts:toolBrainNote` (MCP tool, agent path)
+ * - `src/cli/brain/verbs/note.ts:cmdBrainNote` (CLI verb, cron /
+ * shell path)
+ *
+ * Both surfaces share this body so the on-disk shape cannot drift
+ * between them. Sanitiser, agent resolution, and log append happen
+ * here; protocol-specific concerns (MCPError vs CLI exit code) stay
+ * in the wrappers.
+ *
+ * Anchored in design doc Β§7.1 ("Core extraction").
+ */
+
+import { resolve } from "node:path";
+
+import { sanitiseTextField } from "../redactor.ts";
+import { resolveAgentName } from "../config.ts";
+import { appendLogEvent } from "./log.ts";
+import { isoSecond } from "./time.ts";
+import { BRAIN_LOG_EVENT_KIND } from "./types.ts";
+import { vaultRelativeSafe } from "./paths.ts";
+
+const NOTE_TEXT_MAX_LEN = 4096;
+
+export interface AppendBrainNoteInput {
+ readonly vault: string;
+ readonly text: string;
+ readonly agent?: string;
+ readonly now?: Date;
+ readonly configPath?: string;
+}
+
+export interface AppendBrainNoteResult {
+ readonly logged_at: string;
+ /** Vault-relative POSIX path (`Brain/log/<date>.md`). */
+ readonly log_path: string;
+ /** Absolute filesystem path. */
+ readonly absolute_log_path: string;
+ /** Identity actually written into the log entry. */
+ readonly agent: string;
+}
+
+/**
+ * Append one `note` event to `Brain/log/<today>.md` (and the JSONL
+ * sidecar via `appendLogEvent`). Throws on empty text β€” wrappers
+ * translate the error to their protocol's idiom.
+ */
+export function appendBrainNote(
+ input: AppendBrainNoteInput,
+): AppendBrainNoteResult {
+ const sanitised = sanitiseTextField(input.text, {
+ maxLen: NOTE_TEXT_MAX_LEN,
+ singleLine: true,
+ }).trim();
+ if (!sanitised) {
+ throw new Error("brain_note: text is required");
+ }
+ const agent =
+ (input.agent && input.agent.trim().length > 0
+ ? input.agent
+ : resolveAgentName(input.configPath));
+ const timestamp = isoSecond(input.now ?? new Date());
+ const entry = {
+ timestamp,
+ eventType: BRAIN_LOG_EVENT_KIND.note,
+ body: { text: sanitised, agent },
+ } as const;
+ const res = appendLogEvent(input.vault, entry);
+ return {
+ logged_at: timestamp,
+ log_path: vaultRelativeSafe(input.vault, res.logPath),
+ absolute_log_path: resolve(res.logPath),
+ agent,
+ };
+}
+```
+
+> **Heads-up:** `vaultRelativeSafe` currently lives in
+> `src/mcp/brain-tools.ts:605`. The MCP layer should not be the home
+> of a path helper that the core now needs. Move
+> `vaultRelativeSafe` (and any tightly-coupled helper it uses) into
+> `src/core/brain/paths.ts`, re-export it from `src/mcp/brain-tools.ts`
+> for backward compatibility within the MCP layer, and update the
+> import in `note.ts` to point at the new home. If the move is more
+> than ~15 lines or pulls in unrelated MCP types, stop and ask the
+> operator before proceeding β€” keep this PR small.
+
+- [ ] **Step 3.4: Move `vaultRelativeSafe` to `paths.ts`.**
+
+In `src/core/brain/paths.ts`, append:
+
+```ts
+import { isAbsolute, relative, resolve } from "node:path";
+
+/**
+ * Compute the vault-relative POSIX path of `target` (an absolute or
+ * vault-relative filesystem path). Falls back to the absolute path
+ * when `target` resolves outside the vault, so callers never silently
+ * leak a `../` traversal through what looks like a relative path.
+ */
+export function vaultRelativeSafe(vault: string, target: string): string {
+ const absVault = resolve(vault);
+ const absTarget = isAbsolute(target) ? target : resolve(vault, target);
+ const rel = relative(absVault, absTarget);
+ if (rel.startsWith("..") || isAbsolute(rel)) return absTarget;
+ return rel.split(/[\\/]/).join("/");
+}
+```
+
+In `src/mcp/brain-tools.ts`, around line 605, replace the local
+`vaultRelativeSafe` definition with a re-export:
+
+```ts
+export { vaultRelativeSafe } from "../core/brain/paths.ts";
+```
+
+If the local definition has additional logic this re-export does not
+cover: stop and ask the operator before changing semantics.
+
+- [ ] **Step 3.5: Run the new core tests, confirm green.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test tests/core/brain/note.test.ts
+```
+
+Expected: green.
+
+- [ ] **Step 3.6: Refactor `toolBrainNote` to delegate.**
+
+Edit `src/mcp/brain-tools.ts:toolBrainNote` (around line 324).
+Replace the body with:
+
+```ts
+async function toolBrainNote(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const rawText = coerceStr(args, "text", true)!;
+ const agentArg = coerceStr(args, "agent", false);
+
+ let res;
+ try {
+ res = appendBrainNote({
+ vault: ctx.vault,
+ text: rawText,
+ ...(normalizeAgentArgument(agentArg) !== null
+ ? { agent: normalizeAgentArgument(agentArg)! }
+ : {}),
+ ...(ctx.configPath ? { configPath: ctx.configPath } : {}),
+ });
+ } catch (err) {
+ throw new MCPError(INVALID_PARAMS, (err as Error).message);
+ }
+ return {
+ logged_at: res.logged_at,
+ log_path: res.log_path,
+ absolute_log_path: res.absolute_log_path,
+ agent: res.agent,
+ };
+}
+```
+
+Add the import near the top:
+
+```ts
+import { appendBrainNote } from "../core/brain/note.ts";
+```
+
+Drop now-unused local symbols (`NOTE_TEXT_MAX_LEN`, the local
+sanitiser invocation, the local `appendLogEvent` call) from this
+file.
+
+- [ ] **Step 3.7: Run the full MCP brain suite, confirm green.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test tests/mcp/brain.test.ts tests/core/brain/note.test.ts
+```
+
+Expected: green. The existing MCP brain_note tests must still pass β€”
+the surface contract is byte-identical.
+
+- [ ] **Step 3.8: Full suite + typecheck.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test
+bun run typecheck
+```
+
+Expected: green / zero errors.
+
+- [ ] **Step 3.9: Commit.**
+
+```bash
+git add src/core/brain/note.ts src/core/brain/paths.ts src/mcp/brain-tools.ts tests/core/brain/note.test.ts
+git commit -m "refactor(brain): extract appendBrainNote core, share between MCP and CLI"
+```
+
+Pause: ask operator, wait for yes.
+
+---
+
+## Task 4: CLI verb `o2b brain note`
+
+**Files:**
+- Create: `src/cli/brain/verbs/note.ts`
+- Modify: `src/cli/brain/verbs/index.ts` (export)
+- Modify: `src/cli/brain.ts` (dispatch)
+- Modify: `src/cli/brain/help-text.ts` (BRAIN_HELP + VERB_HELP)
+- Test: `tests/cli/brain-note.test.ts`
+
+Implements Β§7.2.
+
+- [ ] **Step 4.1: Write the failing CLI test.**
+
+```ts
+// tests/cli/brain-note.test.ts
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { execFileSync } from "node:child_process";
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+const O2B = join(import.meta.dir, "..", "..", "scripts", "o2b");
+
+function runO2b(argv: string[], env: Record<string, string> = {}) {
+ return execFileSync(O2B, argv, {
+ encoding: "utf8",
+ env: { ...process.env, ...env },
+ });
+}
+
+describe("o2b brain note", () => {
+ let vault: string;
+ beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-cli-brain-note-"));
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ "dream:\n unconfirmed_window_days: 7\n",
+ "utf8",
+ );
+ });
+ afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ });
+
+ test("writes a note with the positional text", () => {
+ runO2b(["brain", "note", "released v0.10.10", "--vault", vault, "--agent", "tester"]);
+ const today = new Date().toISOString().slice(0, 10);
+ const body = readFileSync(join(vault, "Brain", "log", `${today}.md`), "utf8");
+ expect(body).toContain("- note");
+ expect(body).toContain("- text: released v0.10.10");
+ expect(body).toContain("- agent: tester");
+ });
+
+ test("--json emits the structured result", () => {
+ const out = runO2b([
+ "brain", "note", "json output check",
+ "--vault", vault, "--agent", "tester", "--json",
+ ]);
+ const parsed = JSON.parse(out);
+ expect(parsed.agent).toBe("tester");
+ expect(parsed.log_path).toMatch(/^Brain\/log\/\d{4}-\d{2}-\d{2}\.md$/);
+ expect(parsed.logged_at).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/);
+ expect(typeof parsed.absolute_log_path).toBe("string");
+ });
+
+ test("missing text exits non-zero with a clear message", () => {
+ let failed = false;
+ try {
+ execFileSync(O2B, ["brain", "note", "--vault", vault], {
+ encoding: "utf8",
+ env: process.env,
+ });
+ } catch (exc: any) {
+ failed = true;
+ expect(exc.status).toBe(2);
+ expect(String(exc.stderr ?? "")).toContain("brain note");
+ }
+ expect(failed).toBe(true);
+ });
+
+ test("empty positional text exits non-zero", () => {
+ let failed = false;
+ try {
+ execFileSync(O2B, ["brain", "note", " ", "--vault", vault, "--agent", "tester"], {
+ encoding: "utf8",
+ env: process.env,
+ });
+ } catch (exc: any) {
+ failed = true;
+ expect(exc.status).not.toBe(0);
+ }
+ expect(failed).toBe(true);
+ });
+});
+```
+
+- [ ] **Step 4.2: Run, confirm it fails.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test tests/cli/brain-note.test.ts
+```
+
+Expected: every test fails because `brain note` is an unknown verb.
+
+- [ ] **Step 4.3: Implement the verb handler.**
+
+Create `src/cli/brain/verbs/note.ts`:
+
+```ts
+/**
+ * `o2b brain note <text> [--agent <name>]` β€” CLI mirror of the MCP
+ * `brain_note` tool.
+ *
+ * Same on-disk contract as the agent path: writes one
+ * `Brain/log/<today>.md` entry under the `note` event kind plus the
+ * JSONL sidecar. Intended for cron jobs and shell scripts that
+ * cannot reach the MCP surface.
+ *
+ * Anchored in design doc Β§7.2 ("CLI surface").
+ */
+
+import { defaultConfigPath } from "../../../core/config.ts";
+import { appendBrainNote } from "../../../core/brain/note.ts";
+import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainNote(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ config: { type: "string" },
+ agent: { type: "string" },
+ json: { type: "boolean" },
+ });
+
+ if (positional.length === 0) {
+ return fail("brain note requires a text argument: o2b brain note \"<text>\"");
+ }
+ if (positional.length > 1) {
+ return fail(
+ "brain note takes exactly one positional argument β€” quote multi-word text",
+ );
+ }
+ const text = positional[0]!;
+
+ const config = (flags["config"] as string | undefined) ?? defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+
+ let res;
+ try {
+ res = appendBrainNote({
+ vault,
+ text,
+ ...(typeof flags["agent"] === "string" && flags["agent"].trim().length > 0
+ ? { agent: flags["agent"] as string }
+ : {}),
+ configPath: config,
+ });
+ } catch (exc) {
+ return fail((exc as Error).message ?? String(exc));
+ }
+
+ if (flags["json"]) {
+ return okJson({
+ logged_at: res.logged_at,
+ log_path: res.log_path,
+ absolute_log_path: res.absolute_log_path,
+ agent: res.agent,
+ });
+ }
+ return ok(`logged note at ${res.log_path}`);
+}
+```
+
+- [ ] **Step 4.4: Export from the verbs barrel.**
+
+Edit `src/cli/brain/verbs/index.ts`. Add:
+
+```ts
+export { cmdBrainNote } from "./note.ts";
+```
+
+- [ ] **Step 4.5: Wire the dispatcher.**
+
+Edit `src/cli/brain.ts`. Add `cmdBrainNote` to the import group at
+the top:
+
+```ts
+import {
+ // ... existing imports
+ cmdBrainNote,
+ // ...
+} from "./brain/verbs/index.ts";
+```
+
+In the dispatch `switch`, add the case alphabetically near the other
+plain verbs (between `cmdBrainMerge` and `cmdBrainPin` is fine):
+
+```ts
+ case "note": return await cmdBrainNote(rest);
+```
+
+- [ ] **Step 4.6: Document in BRAIN_HELP and VERB_HELP.**
+
+Edit `src/cli/brain/help-text.ts`. Add a `note` line to `BRAIN_HELP`
+near the related verbs (after `feedback`, `apply-evidence`):
+
+```
+ note <text> Append a one-line narrative milestone to Brain/log/today
+```
+
+Add a `VERB_HELP["note"]` entry:
+
+```ts
+ note: [
+ "o2b brain note <text> [--agent <name>] [--vault <path>] [--config <path>] [--json]",
+ "",
+ "Append one narrative-milestone line to Brain/log/<today>.md under the",
+ "`note` event kind. CLI mirror of the MCP `brain_note` tool β€” same on-disk",
+ "contract. Use from cron jobs and shell scripts.",
+ "",
+ "Multi-line input is collapsed to a single line (same contract as MCP).",
+ "",
+ ].join("\n"),
+```
+
+- [ ] **Step 4.7: Re-run the CLI test, confirm green.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test tests/cli/brain-note.test.ts
+```
+
+Expected: green.
+
+- [ ] **Step 4.8: Full suite + typecheck.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test
+bun run typecheck
+```
+
+Expected: green / zero errors.
+
+- [ ] **Step 4.9: Commit.**
+
+```bash
+git add src/cli/brain/verbs/note.ts src/cli/brain/verbs/index.ts src/cli/brain.ts src/cli/brain/help-text.ts tests/cli/brain-note.test.ts
+git commit -m "feat(cli): o2b brain note β€” Brain-native milestone log for cron/shell"
+```
+
+Pause: ask operator, wait for yes.
+
+---
+
+## Task 5: Hook detector accepts `o2b brain note`
+
+**Files:**
+- Modify: `hooks/lib/detect.ts`
+- Test: `tests/hooks/detect.test.ts` (extend; create if missing)
+
+Implements Β§7.3.
+
+- [ ] **Step 5.1: Locate the test file.**
+
+```bash
+ls -1 /srv/projects/open-second-brain/tests/hooks/ 2>&1
+```
+
+If `detect.test.ts` is absent: create it with the imports the other
+hook tests use. Otherwise extend it.
+
+- [ ] **Step 5.2: Add the failing assertions.**
+
+The public surface in `hooks/lib/detect.ts` is `summarizeTurn` β€”
+there is no public `isBrainEventBash`. Tests drive the bash-needle
+list through `summarizeTurn` with an empty `toolCalls` array and the
+candidate command in `bashCommandsThisTurn`. The existing needles
+(`"o2b brain feedback"`, `"o2b brain apply-evidence"`) are bare
+substrings matched via `String.prototype.includes`, so the new
+needle MUST follow the same convention (no trailing space).
+
+Append (or include in the new file):
+
+```ts
+import { describe, expect, test } from "bun:test";
+import { summarizeTurn } from "../../hooks/lib/detect.ts";
+
+describe("summarizeTurn β€” o2b brain note bash needle", () => {
+ test("o2b brain note '...' counts as a brain event", () => {
+ const s = summarizeTurn([], ["o2b brain note \"v0.10.10 released\""]);
+ expect(s.hadBrainEvent).toBe(true);
+ });
+ test("o2b brain note (no args) still trips the needle", () => {
+ // Mirrors the existing semantics for `o2b brain feedback` /
+ // `o2b brain apply-evidence`: bare-substring match. The CLI
+ // itself rejects empty text with exit 2; the hook side only
+ // cares about intent.
+ const s = summarizeTurn([], ["o2b brain note"]);
+ expect(s.hadBrainEvent).toBe(true);
+ });
+ test("an unrelated command does not trip the needle", () => {
+ const s = summarizeTurn([], ["echo hello"]);
+ expect(s.hadBrainEvent).toBe(false);
+ });
+});
+```
+
+> The existing needle list does NOT defend against lookalikes such
+> as `o2b brain notes` β€” the v0.10.6 needles (`o2b brain feedback`,
+> `o2b brain apply-evidence`) accept the same substring shape. We
+> deliberately do NOT introduce a stricter check for `note`; the
+> behaviour stays uniform across the three CLI verbs. If a real
+> CLI verb named `note-something` ever lands, revisit then.
+
+- [ ] **Step 5.3: Run, confirm failure on the positive cases.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test tests/hooks/detect.test.ts
+```
+
+Expected: at least the first two new tests fail.
+
+- [ ] **Step 5.4: Add the needle.**
+
+Edit `hooks/lib/detect.ts`. Find `BRAIN_EVENT_BASH_NEEDLES`. Add
+`"o2b brain note"` to the array (bare substring, matching the existing
+two entries' shape β€” `"o2b brain feedback"`, `"o2b brain apply-evidence"`).
+Alphabetise relative to those.
+
+Confirm `BRAIN_EVENT_NAME_SUFFIX` already includes `brain_note`
+(it does, as of v0.10.8). No edit needed there.
+
+- [ ] **Step 5.5: Re-run, confirm green.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test tests/hooks/detect.test.ts
+```
+
+Expected: green.
+
+- [ ] **Step 5.6: Full suite + typecheck.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test
+bun run typecheck
+```
+
+Expected: green / zero errors.
+
+- [ ] **Step 5.7: Commit.**
+
+```bash
+git add hooks/lib/detect.ts tests/hooks/detect.test.ts
+git commit -m "feat(hooks): detect o2b brain note as a brain event"
+```
+
+Pause: ask operator, wait for yes.
+
+---
+
+## Task 6: `brain_context` MCP tool
+
+**Files:**
+- Modify: `src/mcp/brain-tools.ts` (new `toolBrainContext`)
+- Modify: `src/mcp/tools.ts` (add to `WRITER_TOOL_NAMES` + tool table)
+- Modify: `src/mcp/instructions.ts` (document the new tool)
+- Test: `tests/mcp/brain-context.test.ts`
+
+Implements Β§5.
+
+- [ ] **Step 6.1: Write the failing test.**
+
+```ts
+// tests/mcp/brain-context.test.ts
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { buildToolTable } from "../../src/mcp/tools.ts";
+
+function findHandler(name: string) {
+ const tool = buildToolTable("full").find((t) => t.name === name);
+ if (!tool) throw new Error(`tool not in table: ${name}`);
+ return tool.handler;
+}
+
+function bootstrap(vault: string): void {
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ "dream:\n unconfirmed_window_days: 7\n",
+ "utf8",
+ );
+}
+
+describe("brain_context tool", () => {
+ let vault: string;
+ beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-mcp-brain-context-"));
+ });
+ afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ });
+
+ test("returns present:false when Brain/ does not exist", async () => {
+ const handler = findHandler("brain_context");
+ const out: any = await handler({ vault, configPath: null, repoRoot: null }, {});
+ expect(out.present).toBe(false);
+ expect(out.content).toBe("");
+ expect(out.counts.confirmed).toBe(0);
+ expect(out.generated_at).toBeNull();
+ });
+
+ test("self-heals active.md on first call when Brain/ exists", async () => {
+ bootstrap(vault);
+ const handler = findHandler("brain_context");
+ const out: any = await handler({ vault, configPath: null, repoRoot: null }, {});
+ expect(out.present).toBe(true);
+ expect(out.content).toContain("# Active Brain Preferences");
+ expect(out.generated_at).not.toBeNull();
+ // file exists on disk
+ const onDisk = readFileSync(join(vault, "Brain", "active.md"), "utf8");
+ expect(out.content).toBe(onDisk);
+ });
+
+ test("payload includes most_applied_30d count", async () => {
+ bootstrap(vault);
+ const handler = findHandler("brain_context");
+ const out: any = await handler({ vault, configPath: null, repoRoot: null }, {});
+ expect(typeof out.counts.most_applied_30d).toBe("number");
+ });
+
+ test("two calls return byte-equal content when nothing changed", async () => {
+ bootstrap(vault);
+ const handler = findHandler("brain_context");
+ const a: any = await handler({ vault, configPath: null, repoRoot: null }, {});
+ const b: any = await handler({ vault, configPath: null, repoRoot: null }, {});
+ expect(b.content).toBe(a.content);
+ expect(b.generated_at).toBe(a.generated_at);
+ });
+});
+```
+
+- [ ] **Step 6.2: Run, confirm failure.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test tests/mcp/brain-context.test.ts
+```
+
+Expected: `tool not in table: brain_context`.
+
+- [ ] **Step 6.3: Implement the handler.**
+
+Add to `src/mcp/brain-tools.ts` near the other reader handlers:
+
+```ts
+// ----- brain_context (v0.10.10) --------------------------------------------
+
+import { existsSync, readFileSync } from "node:fs";
+
+import { regenerateActive } from "../core/brain/active.ts";
+import { brainActivePath, brainDirs } from "../core/brain/paths.ts";
+import { computeBrainStatus } from "../core/brain/status.ts";
+import { parseFrontmatter } from "../core/vault.ts";
+
+interface BrainContextPayload {
+ vault_path: string;
+ present: boolean;
+ active_path: string;
+ content: string;
+ counts: {
+ confirmed: number;
+ quarantine: number;
+ retired_recent: number;
+ most_applied_30d: number;
+ };
+ generated_at: string | null;
+ error?: string;
+}
+
+async function toolBrainContext(
+ ctx: ServerContext,
+): Promise<Record<string, unknown>> {
+ const dirs = brainDirs(ctx.vault);
+ const activePath = brainActivePath(ctx.vault);
+ if (!existsSync(dirs.brain)) {
+ const empty: BrainContextPayload = {
+ vault_path: ctx.vault,
+ present: false,
+ active_path: activePath,
+ content: "",
+ counts: {
+ confirmed: 0,
+ quarantine: 0,
+ retired_recent: 0,
+ most_applied_30d: 0,
+ },
+ generated_at: null,
+ };
+ return empty;
+ }
+
+ // Idempotent regen β€” writes only if the body differs from disk.
+ // Counts come straight from the result so we never re-walk the
+ // preferences/log twice.
+ let counts;
+ let error: string | undefined;
+ try {
+ const r = regenerateActive(ctx.vault);
+ counts = r.counts;
+ } catch (err) {
+ error = (err as Error).message ?? String(err);
+ counts = {
+ confirmed: 0,
+ quarantine: 0,
+ retired_recent: 0,
+ most_applied_30d: 0,
+ };
+ }
+
+ let content = "";
+ let generatedAt: string | null = null;
+ if (!error && existsSync(activePath)) {
+ content = readFileSync(activePath, "utf8");
+ try {
+ const [meta] = parseFrontmatter(activePath);
+ const v = meta["generated_at"];
+ if (typeof v === "string" && v.trim().length > 0) {
+ generatedAt = v;
+ }
+ } catch {
+ // Frontmatter parse failure is non-fatal β€” leave generated_at null.
+ }
+ }
+
+ const payload: BrainContextPayload = {
+ vault_path: ctx.vault,
+ present: true,
+ active_path: activePath,
+ content,
+ counts,
+ generated_at: generatedAt,
+ ...(error ? { error } : {}),
+ };
+ return payload;
+}
+```
+
+> **DRY note:** the empty-counts literal repeats. If the reviewer
+> flags it, hoist a `const EMPTY_COUNTS = Object.freeze({…})` at the
+> top of the function β€” but do NOT export it; this counts shape is
+> local to the tool.
+
+- [ ] **Step 6.4: Register the tool.**
+
+Two files to edit. Tool definitions for Brain live in `BRAIN_TOOLS`
+(a const array exported from `src/mcp/brain-tools.ts`); the scope
+filter lives in `WRITER_TOOL_NAMES` (in `src/mcp/tools.ts`).
+
+**6.4a β€” add the entry to `BRAIN_TOOLS`.** In `src/mcp/brain-tools.ts`,
+near the other Brain tools (after the `brain_apply_evidence` and
+`brain_note` entries, before `brain_digest` β€” keep the writer trio
+contiguous):
+
+```ts
+ {
+ name: "brain_context",
+ description:
+ "Pull the current Brain/active.md body plus active-preference counts. Use at session start when SessionStart hook is unavailable (Cursor, Aider, raw Claude API). Read-only.",
+ inputSchema: {
+ type: "object",
+ properties: {},
+ additionalProperties: false,
+ },
+ handler: toolBrainContext,
+ },
+```
+
+**6.4b β€” extend the writer scope filter.** In `src/mcp/tools.ts`,
+update `WRITER_TOOL_NAMES`:
+
+```ts
+// The set is named after the original payload (mutating writers); as
+// of v0.10.10 it also hosts `brain_context`, a reader that has to be
+// always-loaded to be useful at session start. Renaming the server
+// to a neutral noun is deferred β€” see docs/plans/2026-05-20-v0.10.10-design.md
+// Β§12.
+const WRITER_TOOL_NAMES: ReadonlySet<string> = new Set([
+ "brain_apply_evidence",
+ "brain_context",
+ "brain_feedback",
+ "brain_note",
+]);
+```
+
+No new import is needed in `tools.ts` β€” `BRAIN_TOOLS` already
+flows in via `import { BRAIN_TOOLS } from "./brain-tools.ts";` and
+the new entry rides that wire.
+
+- [ ] **Step 6.5: Run the test, confirm green.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test tests/mcp/brain-context.test.ts
+```
+
+Expected: green.
+
+- [ ] **Step 6.6: Update writer-server instructions.**
+
+Edit `src/mcp/instructions.ts`. Find the writer-server description
+block. Add a line for `brain_context`:
+
+```
+ - brain_context β€” pull the current Brain/active.md body plus
+ counts. Use at session start when the host
+ runtime lacks a SessionStart hook (Cursor,
+ Aider, raw Claude API). Read-only.
+```
+
+Update any surrounding sentence that says "the writer-server hosts the
+three writer tools" to "hosts the writer tools plus the
+`brain_context` reader".
+
+- [ ] **Step 6.7: Verify the writer-scope tool table still loads four tools.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test tests/cli/mcp-scope-arg.test.ts tests/mcp/scope-filter.test.ts
+```
+
+Expected: green. If these tests asserted the writer scope had exactly
+three tools, update them to four and re-run.
+
+- [ ] **Step 6.8: Full suite + typecheck.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test
+bun run typecheck
+```
+
+Expected: green / zero errors.
+
+- [ ] **Step 6.9: Commit.**
+
+```bash
+git add src/mcp/brain-tools.ts src/mcp/tools.ts src/mcp/instructions.ts tests/mcp/brain-context.test.ts tests/cli/mcp-scope-arg.test.ts tests/mcp/scope-filter.test.ts
+git commit -m "feat(mcp): brain_context tool for runtimes without SessionStart"
+```
+
+Pause: ask operator, wait for yes.
+
+---
+
+## Task 7: `o2b status` semantic hint
+
+**Files:**
+- Modify: `src/cli/helpers.ts` (new `resolveSemanticConfigState`)
+- Modify: `src/cli/main.ts` (use the helper in both `cmdStatus` and `writeSearchInitBlock`)
+- Test: `tests/cli/status.test.ts`
+
+Implements Β§8.
+
+- [ ] **Step 7.1: Write the failing CLI test.**
+
+```ts
+// tests/cli/status.test.ts
+import { describe, expect, test, afterEach, beforeEach } from "bun:test";
+import { execFileSync } from "node:child_process";
+import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+const O2B = join(import.meta.dir, "..", "..", "scripts", "o2b");
+
+function runO2b(args: string[], env: Record<string, string> = {}) {
+ return execFileSync(O2B, args, {
+ encoding: "utf8",
+ env: { ...process.env, ...env },
+ });
+}
+
+function writeConfig(dir: string, body: string): string {
+ mkdirSync(dir, { recursive: true });
+ const p = join(dir, "config.yaml");
+ writeFileSync(p, body, "utf8");
+ return p;
+}
+
+describe("o2b status β€” semantic hint", () => {
+ let cfgDir: string;
+ beforeEach(() => {
+ cfgDir = mkdtempSync(join(tmpdir(), "osb-status-"));
+ });
+ afterEach(() => {
+ rmSync(cfgDir, { recursive: true, force: true });
+ });
+
+ test("hint absent when semantic_enabled is true and key is present", () => {
+ const cfg = writeConfig(
+ cfgDir,
+ [
+ "vault: /tmp/x",
+ "search_semantic_enabled: \"true\"",
+ "embedding_api_key: \"sk-test\"",
+ "embedding_base_url: \"https://example.test/v1\"",
+ "embedding_model: \"test-model\"",
+ ].join("\n") + "\n",
+ );
+ const out = runO2b(["status", "--config", cfg], {
+ // Defensive: nuke any operator env vars that could flip enabled.
+ OPEN_SECOND_BRAIN_SEARCH_SEMANTIC: "",
+ OPEN_SECOND_BRAIN_EMBEDDING_KEY: "",
+ });
+ expect(out).not.toContain("semantic:");
+ });
+
+ test("hint present when semantic_enabled is false", () => {
+ const cfg = writeConfig(cfgDir, "vault: /tmp/x\n");
+ const out = runO2b(["status", "--config", cfg], {
+ OPEN_SECOND_BRAIN_SEARCH_SEMANTIC: "",
+ OPEN_SECOND_BRAIN_EMBEDDING_KEY: "",
+ });
+ expect(out).toContain("semantic: off");
+ expect(out).toContain("o2b search check");
+ });
+
+ test("hint present when key is missing even with enabled flag set", () => {
+ const cfg = writeConfig(
+ cfgDir,
+ "vault: /tmp/x\nsearch_semantic_enabled: \"true\"\n",
+ );
+ const out = runO2b(["status", "--config", cfg], {
+ OPEN_SECOND_BRAIN_SEARCH_SEMANTIC: "",
+ OPEN_SECOND_BRAIN_EMBEDDING_KEY: "",
+ });
+ expect(out).toContain("semantic: off");
+ });
+
+ test("hint suppressed when search is disabled outright", () => {
+ const cfg = writeConfig(cfgDir, "vault: /tmp/x\nsearch_enabled: \"false\"\n");
+ const out = runO2b(["status", "--config", cfg]);
+ expect(out).not.toContain("semantic:");
+ });
+
+ test("--json carries semantic flags and hint", () => {
+ const cfg = writeConfig(cfgDir, "vault: /tmp/x\n");
+ const out = runO2b(["status", "--config", cfg, "--json"], {
+ OPEN_SECOND_BRAIN_SEARCH_SEMANTIC: "",
+ OPEN_SECOND_BRAIN_EMBEDDING_KEY: "",
+ });
+ const parsed = JSON.parse(out);
+ expect(parsed.semantic_enabled).toBe(false);
+ expect(parsed.embedding_key_present).toBe(false);
+ expect(typeof parsed.semantic_hint).toBe("string");
+ expect(parsed.semantic_hint).toContain("o2b search check");
+ });
+
+ test("--json semantic_hint is null when everything is configured", () => {
+ const cfg = writeConfig(
+ cfgDir,
+ [
+ "vault: /tmp/x",
+ "search_semantic_enabled: \"true\"",
+ "embedding_api_key: \"sk-test\"",
+ ].join("\n") + "\n",
+ );
+ const out = runO2b(["status", "--config", cfg, "--json"], {
+ OPEN_SECOND_BRAIN_SEARCH_SEMANTIC: "",
+ OPEN_SECOND_BRAIN_EMBEDDING_KEY: "",
+ });
+ const parsed = JSON.parse(out);
+ expect(parsed.semantic_enabled).toBe(true);
+ expect(parsed.embedding_key_present).toBe(true);
+ expect(parsed.semantic_hint).toBeNull();
+ });
+});
+```
+
+- [ ] **Step 7.2: Run, confirm failure.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test tests/cli/status.test.ts
+```
+
+Expected: every test fails (current `o2b status` never mentions
+semantic).
+
+- [ ] **Step 7.3: Add the helper.**
+
+Edit `src/cli/helpers.ts`. Append:
+
+```ts
+const SEMANTIC_HINT_MESSAGE =
+ "run 'o2b search check' for setup steps";
+
+export interface SemanticConfigState {
+ readonly semantic_enabled: boolean;
+ readonly embedding_key_present: boolean;
+ readonly search_disabled: boolean;
+ readonly off: boolean; // true when semantic is unusable AND search is enabled
+ readonly hint: string | null; // SEMANTIC_HINT_MESSAGE when off, else null
+}
+
+function truthyString(v: unknown): boolean {
+ if (typeof v !== "string") return false;
+ const s = v.trim().toLowerCase();
+ return s === "true" || s === "1";
+}
+
+/**
+ * Resolve whether semantic search is meaningfully usable, given a
+ * flat config map and the current environment. Mirrors the boolean
+ * logic already used by `writeSearchInitBlock` in `src/cli/main.ts`,
+ * lifted here so `o2b status` shares the same source of truth.
+ *
+ * Anchored in design doc Β§8.1.
+ */
+export function resolveSemanticConfigState(
+ configData: Readonly<Record<string, unknown>>,
+ env: NodeJS.ProcessEnv,
+): SemanticConfigState {
+ const searchDisabled = configData["search_enabled"] === "false";
+ const enabled =
+ truthyString(configData["search_semantic_enabled"]) ||
+ truthyString(env["OPEN_SECOND_BRAIN_SEARCH_SEMANTIC"]);
+ const cfgKey = configData["embedding_api_key"];
+ const keyPresent =
+ (typeof cfgKey === "string" && cfgKey.length > 0) ||
+ !!env["OPEN_SECOND_BRAIN_EMBEDDING_KEY"];
+
+ const off = !searchDisabled && (!enabled || !keyPresent);
+ return Object.freeze({
+ semantic_enabled: enabled,
+ embedding_key_present: keyPresent,
+ search_disabled: searchDisabled,
+ off,
+ hint: off ? SEMANTIC_HINT_MESSAGE : null,
+ });
+}
+```
+
+- [ ] **Step 7.4: Wire `cmdStatus`.**
+
+Edit `src/cli/main.ts`. Add the import:
+
+```ts
+import { resolveSemanticConfigState, /* existing */ } from "./helpers.ts";
+```
+
+In `cmdStatus`, after computing `result` from `discoverConfig`:
+
+```ts
+ const semantic = resolveSemanticConfigState(result.data, process.env);
+```
+
+In the `--json` branch, add the three keys to the output object (use
+unconditional assignment so consumers see a stable shape):
+
+```ts
+ output["semantic_enabled"] = semantic.semantic_enabled;
+ output["embedding_key_present"] = semantic.embedding_key_present;
+ output["semantic_hint"] = semantic.hint;
+```
+
+In the human branch, after the `config_keys` block:
+
+```ts
+ if (semantic.off) {
+ process.stdout.write(`semantic: off (${semantic.hint})\n`);
+ }
+```
+
+- [ ] **Step 7.5: DRY: route `writeSearchInitBlock` through the helper.**
+
+Still in `src/cli/main.ts`. Replace the inline truthy/key logic in
+`writeSearchInitBlock` with a call to the new helper:
+
+```ts
+function writeSearchInitBlock(configPath: string): void {
+ process.stdout.write("\nSearch:\n");
+ process.stdout.write(" next: o2b search index # build the vault search index\n");
+
+ const data = discoverConfig(configPath).data;
+ const semantic = resolveSemanticConfigState(data, process.env);
+ if (!semantic.semantic_enabled || semantic.embedding_key_present) return;
+ // … rest of the existing template unchanged …
+}
+```
+
+This keeps the existing onboarding banner verbatim but removes the
+duplicated logic.
+
+- [ ] **Step 7.6: Re-run the CLI tests, confirm green.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test tests/cli/status.test.ts
+```
+
+Expected: green.
+
+- [ ] **Step 7.7: Run the existing init-related tests to make sure the DRY refactor did not regress.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test tests/cli/cli.test.ts tests/cli/install-cli.test.ts
+```
+
+Expected: green.
+
+- [ ] **Step 7.8: Full suite + typecheck.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test
+bun run typecheck
+```
+
+Expected: green / zero errors.
+
+- [ ] **Step 7.9: Commit.**
+
+```bash
+git add src/cli/helpers.ts src/cli/main.ts tests/cli/status.test.ts
+git commit -m "feat(cli): o2b status β€” semantic-search hint line"
+```
+
+Pause: ask operator, wait for yes.
+
+---
+
+## Task 8: E2E happy path
+
+**Files:**
+- Test: `tests/e2e/v0.10.10-pull-channels.test.ts`
+
+End-to-end coverage for the most-load-bearing path: `o2b brain note`
+lands in `Brain/log/<today>.md` AND the JSONL sidecar under
+`note` kind with the correct agent identity, then `brain_context`
+sees the same vault state in its payload.
+
+- [ ] **Step 8.1: Write the e2e test.**
+
+```ts
+// tests/e2e/v0.10.10-pull-channels.test.ts
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { execFileSync } from "node:child_process";
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { buildToolTable } from "../../src/mcp/tools.ts";
+
+const O2B = join(import.meta.dir, "..", "..", "scripts", "o2b");
+
+describe("v0.10.10 pull-channels e2e", () => {
+ let vault: string;
+ beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-e2e-v0-10-10-"));
+ });
+ afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ });
+
+ test("init β†’ note β†’ brain_context sees the milestone", async () => {
+ execFileSync(O2B, ["brain", "init", "--vault", vault, "--agent-name", "tester"], {
+ encoding: "utf8",
+ env: process.env,
+ });
+
+ execFileSync(
+ O2B,
+ ["brain", "note", "v0.10.10 released", "--vault", vault, "--agent", "tester"],
+ { encoding: "utf8", env: process.env },
+ );
+
+ const today = new Date().toISOString().slice(0, 10);
+ const md = readFileSync(join(vault, "Brain", "log", `${today}.md`), "utf8");
+ expect(md).toContain("- note");
+ expect(md).toContain("- text: v0.10.10 released");
+ expect(md).toContain("- agent: tester");
+
+ const jsonl = readFileSync(join(vault, "Brain", "log", `${today}.jsonl`), "utf8");
+ expect(jsonl).toContain("\"eventType\":\"note\"");
+ expect(jsonl).toContain("\"text\":\"v0.10.10 released\"");
+
+ const handler = buildToolTable("full").find((t) => t.name === "brain_context")!.handler;
+ const ctx: any = await handler({ vault, configPath: null, repoRoot: null }, {});
+ expect(ctx.present).toBe(true);
+ expect(ctx.content).toContain("# Active Brain Preferences");
+ expect(typeof ctx.counts.most_applied_30d).toBe("number");
+ });
+});
+```
+
+> If `o2b brain init` is not the right verb for bootstrapping a
+> Brain/ layer in tests (look at how `tests/cli/brain.test.ts` does
+> it): use the same pattern that other e2e tests use. Do not write a
+> bespoke bootstrap helper.
+
+- [ ] **Step 8.2: Run, confirm green.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test tests/e2e/v0.10.10-pull-channels.test.ts
+```
+
+Expected: green.
+
+- [ ] **Step 8.3: Commit.**
+
+```bash
+git add tests/e2e/v0.10.10-pull-channels.test.ts
+git commit -m "test(e2e): v0.10.10 pull-channels happy path"
+```
+
+Pause: ask operator, wait for yes.
+
+---
+
+## Task 9: Documentation and CHANGELOG
+
+**Files:**
+- Modify: `CHANGELOG.md`
+- Modify: `hooks/README.md`
+- Modify: `docs/architecture.md`
+
+- [ ] **Step 9.1: Add the v0.10.10 changelog entry.**
+
+Edit `CHANGELOG.md`. Insert a new entry above `## [0.10.9]`:
+
+```markdown
+## [0.10.10] - <YYYY-MM-DD set on the day the release ships>
+
+Pull channels for runtimes without SessionStart. Adds an MCP
+`brain_context` tool, surfaces a `Most-applied (30d)` section in
+`Brain/active.md`, ships the `o2b brain note` CLI verb, and prints
+a semantic-search hint in `o2b status`. The always-loaded writer
+MCP server now also hosts one read tool; renaming the server is
+deferred (see `docs/plans/2026-05-20-v0.10.10-design.md` Β§12).
+
+### Added
+
+- `brain_context` MCP tool β€” returns the current `Brain/active.md`
+ body plus active-preference counts. Always-loaded in the
+ `open-second-brain-writer` MCP server. Intended for runtimes
+ without a `SessionStart` hook (Cursor, Aider, raw Claude API).
+- `Most-applied (30d)` section in `Brain/active.md` β€” top-ten
+ `confirmed` / `quarantine` preferences ranked by
+ `apply-evidence (result: applied)` events whose timestamp lies
+ inside the trailing 30-day window. Section is omitted when the
+ count is zero.
+- `o2b brain note <text>` CLI verb β€” Brain-native milestone log
+ for cron jobs and shell scripts. Same on-disk contract as the
+ MCP `brain_note` tool.
+- `o2b status` semantic-search hint β€” prints
+ `semantic: off (run 'o2b search check' for setup steps)` when
+ semantic search is enabled but unusable. Hint suppressed when
+ `search_enabled` is `false`. `--json` payload gains
+ `semantic_enabled`, `embedding_key_present`, and `semantic_hint`
+ keys (always present).
+
+### Changed
+
+- `RegenerateActiveResult.counts` gains a `most_applied_30d`
+ field. Internal consumers only β€” additive.
+- `vaultRelativeSafe` moved from `src/mcp/brain-tools.ts` to
+ `src/core/brain/paths.ts`. The MCP module re-exports the symbol
+ to preserve external imports.
+
+### Not changed
+
+- The always-loaded MCP server is still named
+ `open-second-brain-writer` even though it now hosts a read tool.
+ A rename to a neutral noun is deferred to the next release that
+ adds another reader.
+```
+
+- [ ] **Step 9.2: Update `hooks/README.md`.**
+
+In the section describing brain-event detection (the same place that
+lists `event_log_append` history and the v0.10.8 retirement), add a
+sentence noting that `o2b brain note` joins
+`o2b brain feedback` / `o2b brain apply-evidence` as bash-needle
+brain events. Match the existing prose tone (no marketing voice).
+
+- [ ] **Step 9.3: Update `docs/architecture.md`.**
+
+In the MCP / writer-server subsection, add one paragraph:
+
+> As of v0.10.10 the always-loaded `open-second-brain-writer` MCP
+> server hosts one read tool (`brain_context`) alongside the
+> three writers. The server name is preserved for backward
+> compatibility with existing client `.mcp.json` entries; renaming
+> is deferred until a second read tool joins the always-load
+> scope.
+
+- [ ] **Step 9.4: Run sync-version check (does NOT bump the version yet).**
+
+```bash
+cd /srv/projects/open-second-brain
+bun run sync-version:check
+```
+
+This is informational β€” it confirms that `package.json` /
+`pyproject.toml` / `openclaw.plugin.json` are in sync at whatever
+version is currently checked in. We do NOT bump to `0.10.10` in this
+plan; the operator owns the release-day version bump because it ties
+to the actual release date.
+
+- [ ] **Step 9.5: Full suite + typecheck.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test
+bun run typecheck
+```
+
+Expected: green / zero errors.
+
+- [ ] **Step 9.6: Commit.**
+
+```bash
+git add CHANGELOG.md hooks/README.md docs/architecture.md
+git commit -m "docs: v0.10.10 changelog, architecture, hooks README"
+```
+
+Pause: ask operator, wait for yes.
+
+---
+
+## Task 10: Vault summary update (operator-coordinated)
+
+The vault edit is intentionally split from the code PR because
+`/root/vault` is a Syncthing-replicated knowledge store, not part
+of the project repo. It is also the only edit in this plan that
+touches an operator-owned artifact rather than the project's
+source tree.
+
+- [ ] **Step 10.1: Confirm with the operator before writing.**
+
+State to the operator: "About to edit
+`/root/vault/Projects/OpenSecondBrain/Features/_summary.md` to mark
+v0.10.10 shipped. Ask the operator: should I make the edit now, or
+do you want to do it by hand?"
+
+Wait for a yes.
+
+- [ ] **Step 10.2: Apply the Β§11 spec edits.**
+
+If yes:
+
+1. In the `## Tier S` section, find the `### βœ… 1.` entry. Append to
+ its `*(Ρ€Π΅Π°Π»ΠΈΠ·ΠΎΠ²Π°Π½ΠΎ Π² v0.9.1)*` parenthetical:
+ `; + v0.10.10 Most-applied (30d) section`.
+2. In the `## Π‘ΠΏΠΎΡ€Π½Ρ‹Π΅ / ΠΎΡ‚Π»ΠΎΠΆΠ΅Π½Π½Ρ‹Π΅` section, remove the bullet
+ starting with **Pull-bootstrap MCP-tool `brain_context`/`brain_principles`**.
+3. In the `## Deferred work` section, find the
+ `**Β§32B CLI verb `o2b brain note`.**` bullet. Replace it with a
+ shipped reference pointing at the v0.10.10 release (mirroring the
+ tone of the other already-shipped deferred items).
+
+- [ ] **Step 10.3: Tell the operator.**
+
+Report the three edits made. Do NOT commit anything β€” the vault is
+not a git repo on this host; Syncthing replicates the markdown
+verbatim.
+
+---
+
+## Final pass
+
+- [ ] **Final.1: Full suite + typecheck one more time.**
+
+```bash
+cd /srv/projects/open-second-brain
+bun test
+bun run typecheck
+```
+
+Expected: green / zero errors.
+
+- [ ] **Final.2: Show the operator the commit list.**
+
+```bash
+git log --oneline master..HEAD
+```
+
+Expected: roughly seven commits β€” one per task that produced code,
+plus the docs commit and the e2e commit. Verify each commit is small
+and reviewable on its own.
+
+- [ ] **Final.3: Stop. Ask the operator how they want to proceed.**
+
+Possible next steps the operator may choose (do NOT pick one
+unilaterally):
+
+- Open a PR via `gh pr create`
+- Run a code review via CodeRabbit (operator-triggered only)
+- Bump version manifests and push the release commit
+- Continue iterating
+
+Wait for the operator's choice.
+
+---
+
+## Implementation order recap
+
+Sequencing follows the dependency graph:
+
+1. **Task 1** (computeMostApplied) β€” pure module, zero dependencies.
+2. **Task 2** (active.md render) β€” depends on Task 1.
+3. **Task 3** (appendBrainNote core) β€” independent; touches MCP only via the refactor.
+4. **Task 4** (CLI verb) β€” depends on Task 3.
+5. **Task 5** (hook detector) β€” depends on Task 4 (the needle).
+6. **Task 6** (brain_context tool) β€” depends on Task 2 (counts include `most_applied_30d`).
+7. **Task 7** (o2b status hint) β€” independent of Brain work.
+8. **Task 8** (e2e) β€” depends on Tasks 3, 4, 6.
+9. **Task 9** (docs) β€” depends on Tasks 1-7.
+10. **Task 10** (vault summary) β€” operator-side, depends on Task 9.
+
+Tasks 3 and 7 are technically independent of Tasks 1-2 and could
+ship in parallel branches. The single-branch order above is the
+recommended one because Tasks 1-2 land the user-facing payload
+(Most-applied) early, which lets the e2e test in Task 8 assert on
+the same shape `brain_context` exposes.
diff --git a/hooks/README.md b/hooks/README.md
index f32e03be..a54a5482 100644
--- a/hooks/README.md
+++ b/hooks/README.md
@@ -44,6 +44,13 @@ runtime as of Β§32 (v0.10.8). The bash CLI `o2b append-event` still
works for cron-jobs / shell scripts that target `Daily/`, but it no
longer counts as a brain event for the Stop guardrail.
+As of v0.10.10 a third bash needle joins the guardrail-clearing
+set: `o2b brain note` β€” the CLI mirror of the MCP `brain_note`
+tool. Cron jobs and shell scripts can land a Brain-native
+narrative-milestone event without going through the MCP surface;
+the matching turn clears the Stop guardrail the same way an MCP
+call would.
+
## Files
- `hooks.json` β€” lifecycle config picked up by both runtimes. Claude
diff --git a/hooks/lib/detect.ts b/hooks/lib/detect.ts
index f8202c9e..e0eb1250 100644
--- a/hooks/lib/detect.ts
+++ b/hooks/lib/detect.ts
@@ -48,19 +48,58 @@ const NATIVE_ARTIFACT_NAMES = new Set<string>([
const BRAIN_EVENT_NAME_SUFFIX =
/(?:^|__)(brain_feedback|brain_apply_evidence|brain_note)$/;
-// Bash command substrings that count as a brain-event call from the
-// CLI. We deliberately keep this list narrow: anything matched here
-// suppresses the guardrail. Spawning the MCP server (`o2b mcp …`)
-// does NOT log on its own, so it stays out of the list β€” only the
-// explicit event-emitting commands are in.
+// Bash command shape that counts as a brain-event call from the CLI.
+// Keep this anchored to command boundaries rather than raw substrings:
+// generated text like `echo "o2b brain note ..."` must not suppress the
+// guardrail. Spawning the MCP server (`o2b mcp …`) does NOT log on its
+// own, so it stays out of the matcher β€” only the explicit event-emitting
+// commands are in.
//
// Β§32 (v0.10.8) drops `o2b append-event` and `vault-log` β€” those
// still work for human / cron use, but they target the deprecated
// `Daily/` surface and no longer count as a Brain-side event.
-const BRAIN_EVENT_BASH_NEEDLES = [
- "o2b brain feedback",
- "o2b brain apply-evidence",
-];
+const SHELL_ASSIGNMENT = String.raw`[A-Za-z_][A-Za-z0-9_]*=(?:"[^"]*"|'[^']*'|\S+)`;
+const BRAIN_EVENT_BASH_COMMAND_RE = new RegExp(
+ String.raw`^(?:env\s+(?:${SHELL_ASSIGNMENT}\s+)*)?(?:${SHELL_ASSIGNMENT}\s+)*o2b\s+brain\s+(?:apply-evidence|feedback|note)(?:\s|$)`,
+);
+
+function splitShellCommandSegments(command: string): string[] {
+ const segments: string[] = [];
+ let current = "";
+ let quote: "'" | '"' | null = null;
+
+ for (let i = 0; i < command.length; i += 1) {
+ const ch = command[i]!;
+ if (quote) {
+ current += ch;
+ if (ch === "\\") {
+ const next = command[i + 1];
+ if (next !== undefined) {
+ current += next;
+ i += 1;
+ }
+ continue;
+ }
+ if (ch === quote) quote = null;
+ continue;
+ }
+
+ if (ch === "'" || ch === '"') {
+ quote = ch;
+ current += ch;
+ continue;
+ }
+ if (ch === ";" || ch === "&" || ch === "|") {
+ segments.push(current);
+ current = "";
+ if (command[i + 1] === ch) i += 1;
+ continue;
+ }
+ current += ch;
+ }
+ segments.push(current);
+ return segments;
+}
export function isArtifactToolName(name: string): boolean {
return NATIVE_ARTIFACT_NAMES.has(name);
@@ -97,7 +136,11 @@ export function summarizeTurn(
}
if (!hadBrainEvent) {
for (const cmd of bashCommandsThisTurn) {
- if (BRAIN_EVENT_BASH_NEEDLES.some((n) => cmd.includes(n))) {
+ if (
+ splitShellCommandSegments(cmd).some((segment) =>
+ BRAIN_EVENT_BASH_COMMAND_RE.test(segment.trim()),
+ )
+ ) {
hadBrainEvent = true;
break;
}
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 55943450..d2949dcb 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.10.9",
+ "version": "0.10.10",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 5e6b5f68..8e3c8b87 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.9",
+ "version": "0.10.10",
"type": "module",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
diff --git a/plugin.yaml b/plugin.yaml
index 656b4254..f88e7660 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.10.9"
+version: "0.10.10"
description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index ac299277..c661d803 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.10.9",
+ "version": "0.10.10",
"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 5e3544a8..33fff83b 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.10.9"
+version: "0.10.10"
description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/pyproject.toml b/pyproject.toml
index 60ef484b..ff43176c 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.10.9"
+version = "0.10.10"
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 1fe77150..61e8783d 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -11,6 +11,7 @@ import { BRAIN_HELP, VERB_HELP } from "./brain/helpers.ts";
import {
cmdBrainInit,
cmdBrainFeedback,
+ cmdBrainNote,
cmdBrainDream,
cmdBrainApplyEvidence,
cmdBrainDigest,
@@ -54,6 +55,7 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promis
switch (verb) {
case "init": return await cmdBrainInit(rest);
case "feedback": return await cmdBrainFeedback(rest);
+ case "note": return await cmdBrainNote(rest);
case "dream": return await cmdBrainDream(rest);
case "apply-evidence": return await cmdBrainApplyEvidence(rest);
case "digest": return await cmdBrainDigest(rest);
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
index b6dcb86d..626d9bca 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -14,6 +14,7 @@ Brain verbs (observing memory):
feedback Record a taste signal (--topic, --signal, --principle)
dream Run the deterministic dreaming pass (idempotent)
apply-evidence Log a real-work application of a preference
+ note Append a one-line narrative milestone to Brain/log/today
digest Render the recent-changes digest (markdown or --json)
query Read by --preference, --topic, or --since
reject Move a preference to retired (user-rejected); --yes if pinned
@@ -60,6 +61,11 @@ export const VERB_HELP: Record<string, string> = {
"usage: o2b brain apply-evidence --pref <id> --artifact <wikilink> --result applied|violated|outdated\n" +
" [--agent <name>] [--note <text>] [--vault <path>] [--json]\n" +
"Appends a single event to today's log. Missing preference exits 2.\n",
+ note:
+ "usage: o2b brain note <text> [--agent <name>] [--vault <path>] [--config <path>] [--json]\n" +
+ "Append one narrative-milestone line to Brain/log/<today>.md under the `note`\n" +
+ "event kind. CLI mirror of the MCP `brain_note` tool β€” same on-disk contract.\n" +
+ "Use from cron jobs and shell scripts. Multi-line text collapses to one line.\n",
digest:
"usage: o2b brain digest [--vault <path>] [--since <ISO>] [--until <ISO>] [--json] [--silent-if-empty]\n" +
"Renders the 24-hour change digest. Empty + --silent-if-empty exits 2.\n",
diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.ts
index e199ff97..d92832ba 100644
--- a/src/cli/brain/verbs/index.ts
+++ b/src/cli/brain/verbs/index.ts
@@ -1,5 +1,6 @@
export { cmdBrainInit } from "./init.ts";
export { cmdBrainFeedback } from "./feedback.ts";
+export { cmdBrainNote } from "./note.ts";
export { cmdBrainDream } from "./dream.ts";
export { cmdBrainApplyEvidence } from "./apply-evidence.ts";
export { cmdBrainDigest } from "./digest.ts";
diff --git a/src/cli/brain/verbs/note.ts b/src/cli/brain/verbs/note.ts
new file mode 100644
index 00000000..8f153c28
--- /dev/null
+++ b/src/cli/brain/verbs/note.ts
@@ -0,0 +1,83 @@
+/**
+ * `o2b brain note <text> [--agent <name>]` β€” CLI mirror of the MCP
+ * `brain_note` tool. Writes one `Brain/log/<today>.md` entry under
+ * the `note` event kind plus the JSONL sidecar. Intended for cron
+ * jobs and shell scripts that cannot reach the MCP surface.
+ */
+
+import { defaultConfigPath } from "../../../core/config.ts";
+import { appendBrainNote } from "../../../core/brain/note.ts";
+import {
+ normalizeFlagString,
+ ok,
+ okJson,
+ parse,
+ resolveBrainVault,
+} from "../helpers.ts";
+
+const USAGE_ERROR_EXIT = 2;
+
+function usageError(message: string): number {
+ process.stderr.write(`error: ${message}\n`);
+ return USAGE_ERROR_EXIT;
+}
+
+export async function cmdBrainNote(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ config: { type: "string" },
+ agent: { type: "string" },
+ json: { type: "boolean" },
+ });
+
+ if (positional.length === 0) {
+ return usageError(
+ 'brain note requires a text argument: o2b brain note "<text>"',
+ );
+ }
+ if (positional.length > 1) {
+ return usageError(
+ "brain note takes exactly one positional argument β€” quote multi-word text",
+ );
+ }
+ const text = positional[0]!;
+ // Pre-validate empty / whitespace-only text at the CLI surface so a
+ // cron caller that forgot to interpolate `$VAR` gets the same exit-2
+ // shape as a missing positional. The core would otherwise throw, and
+ // the catch arm below maps to exit 1 β€” that drift is on the spec
+ // (design Β§7.2: "Empty / whitespace only β†’ exit 2").
+ if (text.trim().length === 0) {
+ return usageError(
+ 'brain note requires non-empty text: o2b brain note "<text>"',
+ );
+ }
+
+ const config = (flags["config"] as string | undefined) ?? defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const explicitAgent = normalizeFlagString(flags["agent"]);
+
+ let res;
+ try {
+ res = appendBrainNote({
+ vault,
+ text,
+ ...(explicitAgent ? { agent: explicitAgent } : {}),
+ configPath: config,
+ });
+ } catch (exc) {
+ process.stderr.write(`error: ${(exc as Error).message ?? String(exc)}\n`);
+ return 1;
+ }
+
+ if (flags["json"]) {
+ okJson({
+ logged_at: res.logged_at,
+ log_path: res.log_path,
+ absolute_log_path: res.absolute_log_path,
+ agent: res.agent,
+ });
+ return 0;
+ }
+ ok(`logged note at ${res.log_path}`);
+ return 0;
+}
diff --git a/src/cli/helpers.ts b/src/cli/helpers.ts
index b6baf2b6..67f51cbf 100644
--- a/src/cli/helpers.ts
+++ b/src/cli/helpers.ts
@@ -60,3 +60,59 @@ export function sortedReplacer(_key: string, value: unknown): unknown {
}
return value;
}
+
+// ── Semantic-search state (v0.10.10) ────────────────────────────────────────
+
+const SEMANTIC_HINT_MESSAGE = "run 'o2b search check' for setup steps";
+
+export interface SemanticConfigState {
+ readonly semantic_enabled: boolean;
+ readonly embedding_key_present: boolean;
+ /** True when the operator deliberately turned the search layer off. */
+ readonly search_disabled: boolean;
+ /**
+ * True when semantic search is meaningfully unusable AND search has
+ * not been explicitly disabled. Drives the `o2b status` hint line:
+ * we do not nag operators who have search switched off outright.
+ */
+ readonly off: boolean;
+ /** Human-friendly one-liner; `null` when `off === false`. */
+ readonly hint: string | null;
+}
+
+function truthyConfigString(value: unknown): boolean {
+ if (typeof value !== "string") return false;
+ const s = value.trim().toLowerCase();
+ return s === "true" || s === "1";
+}
+
+/**
+ * Resolve whether semantic search is meaningfully usable for a given
+ * flat config map and process environment. Shared by `o2b status`
+ * (hint-line render) and `writeSearchInitBlock` (post-init banner).
+ */
+export function resolveSemanticConfigState(
+ configData: Readonly<Record<string, unknown>>,
+ env: NodeJS.ProcessEnv,
+): SemanticConfigState {
+ const searchDisabled = configData["search_enabled"] === "false";
+ const enabled =
+ truthyConfigString(configData["search_semantic_enabled"]) ||
+ truthyConfigString(env["OPEN_SECOND_BRAIN_SEARCH_SEMANTIC"]);
+ // `discoverConfig().data` is typed `Record<string, string>`, but
+ // this helper accepts the wider `unknown`-keyed map for forward
+ // compat with future callers; coerce defensively without throwing.
+ const cfgKey = configData["embedding_api_key"];
+ const envKey = env["OPEN_SECOND_BRAIN_EMBEDDING_KEY"];
+ const keyPresent =
+ (typeof cfgKey === "string" && cfgKey.trim().length > 0) ||
+ (typeof envKey === "string" && envKey.trim().length > 0);
+ const off = !searchDisabled && (!enabled || !keyPresent);
+ return Object.freeze({
+ semantic_enabled: enabled,
+ embedding_key_present: keyPresent,
+ search_disabled: searchDisabled,
+ off,
+ hint: off ? SEMANTIC_HINT_MESSAGE : null,
+ });
+}
diff --git a/src/cli/main.ts b/src/cli/main.ts
index c03baef6..c515eff8 100644
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -32,6 +32,7 @@ import {
NoVaultConfiguredError,
normalizeFlagString,
requireVault,
+ resolveSemanticConfigState,
sortedReplacer,
} from "./helpers.ts";
import {
@@ -67,10 +68,17 @@ async function cmdStatus(argv: string[]): Promise<number> {
json: { type: "boolean" },
});
const result = discoverConfig(flags["config"] as string | undefined);
+ // v0.10.10 β€” semantic-search hint. Same truthy / key-present logic as
+ // `writeSearchInitBlock`; lifted into `resolveSemanticConfigState`
+ // so both call sites share a single source of truth.
+ const semantic = resolveSemanticConfigState(result.data, process.env);
if (flags["json"]) {
const output: Record<string, unknown> = {
config_path: String(result.path),
config_exists: result.exists,
+ semantic_enabled: semantic.semantic_enabled,
+ embedding_key_present: semantic.embedding_key_present,
+ semantic_hint: semantic.hint,
};
if (Object.keys(result.data).length > 0) {
output["config_keys"] = Object.keys(result.data).sort();
@@ -86,6 +94,9 @@ async function cmdStatus(argv: string[]): Promise<number> {
process.stdout.write(`- ${key}\n`);
}
}
+ if (semantic.off && semantic.hint) {
+ process.stdout.write(`semantic: off (${semantic.hint})\n`);
+ }
}
return 0;
}
@@ -175,22 +186,12 @@ function writeSearchInitBlock(configPath: string): void {
process.stdout.write(" next: o2b search index # build the vault search index\n");
const data = discoverConfig(configPath).data;
- // Accept "true" / "True" / "TRUE" / "1" from both the config file
- // and the env override β€” matches the parseBool helper inside
- // resolveSearchConfig so the init banner does not lie about state.
- const truthy = (v: unknown): boolean => {
- if (typeof v !== "string") return false;
- const s = v.trim().toLowerCase();
- return s === "true" || s === "1";
- };
- const enabled =
- truthy(data["search_semantic_enabled"]) ||
- truthy(process.env["OPEN_SECOND_BRAIN_SEARCH_SEMANTIC"]);
- const keyPresent = !!(
- (data["embedding_api_key"] && data["embedding_api_key"] !== "") ||
- process.env["OPEN_SECOND_BRAIN_EMBEDDING_KEY"]
- );
- if (!enabled || keyPresent) return;
+ // v0.10.10 β€” share the truthy / key-present logic with `o2b status`
+ // through `resolveSemanticConfigState`. We only emit the detailed
+ // template when the operator explicitly turned semantic search on
+ // but did not configure the key.
+ const semantic = resolveSemanticConfigState(data, process.env);
+ if (!semantic.semantic_enabled || semantic.embedding_key_present) return;
process.stdout.write(
[
@@ -473,6 +474,7 @@ Brain (observing memory):
brain feedback Record a taste signal into Brain/inbox/
brain dream Run the deterministic dreaming pass (idempotent)
brain apply-evidence Log a real-work application of a preference
+ brain note Append a one-line narrative milestone to Brain/log/today
brain digest Render the recent-changes digest (markdown or --json)
brain query Read by --preference, --topic, or --since
brain reject Move a preference to retired/ (user-rejected)
diff --git a/src/core/brain/active.ts b/src/core/brain/active.ts
index 80731031..2ea94fa2 100644
--- a/src/core/brain/active.ts
+++ b/src/core/brain/active.ts
@@ -36,6 +36,7 @@ import { join } from "node:path";
import { atomicWriteFileSync } from "../fs-atomic.ts";
import { parseFrontmatter } from "../vault.ts";
+import { computeMostApplied, type MostAppliedEntry } from "./most-applied.ts";
import { parsePreference, parseRetired } from "./preference.ts";
import { brainActivePath, brainDirs } from "./paths.ts";
import { isoSecond } from "./time.ts";
@@ -63,6 +64,15 @@ export interface RegenerateActiveResult {
readonly confirmed: number;
readonly quarantine: number;
readonly retired_recent: number;
+ /**
+ * Length of the `Most-applied (30d)` section in this render
+ * pass. Zero when no `apply-evidence (result: applied)` events
+ * lie inside the trailing 30-day window or no preference still
+ * maps to one. `brain_context` echoes this through to MCP
+ * clients so they can render a counts ribbon without parsing
+ * the markdown body.
+ */
+ readonly most_applied_30d: number;
};
}
@@ -95,10 +105,16 @@ export function regenerateActive(
.filter((p) => p.status === BRAIN_PREFERENCE_STATUS.quarantine)
.sort(sortByIdAscending);
+ // Most-applied draws from the active candidates (confirmed +
+ // quarantine) only β€” retired preferences are reported in their own
+ // section below and never resurrected through the hot list.
+ const mostApplied = computeMostApplied(vault, [...confirmed, ...quarantine], { now });
+
const body = renderBody({
confirmed,
quarantine,
retiredRecent,
+ mostApplied,
});
// `readExistingBody` returns the trimmed body (parseFrontmatter
@@ -118,6 +134,7 @@ export function regenerateActive(
confirmed: confirmed.length,
quarantine: quarantine.length,
retired_recent: retiredRecent.length,
+ most_applied_30d: mostApplied.length,
},
};
}
@@ -194,6 +211,7 @@ interface RenderInput {
readonly confirmed: ReadonlyArray<BrainPreference>;
readonly quarantine: ReadonlyArray<BrainPreference>;
readonly retiredRecent: ReadonlyArray<BrainRetired>;
+ readonly mostApplied: ReadonlyArray<MostAppliedEntry>;
}
function renderBody(input: RenderInput): string {
@@ -212,6 +230,13 @@ function renderBody(input: RenderInput): string {
}
out.push("");
+ if (input.mostApplied.length > 0) {
+ out.push(`## Most-applied (30d) (${input.mostApplied.length})`);
+ out.push("");
+ for (const m of input.mostApplied) out.push(renderMostAppliedLine(m));
+ out.push("");
+ }
+
if (input.quarantine.length > 0) {
out.push(`## Quarantine (${input.quarantine.length})`);
out.push("");
@@ -243,6 +268,14 @@ function renderConfirmedLine(p: BrainPreference): string {
return `- \`${p.id}\` (${tags.join(", ")}) β€” ${p.principle}`;
}
+function renderMostAppliedLine(m: MostAppliedEntry): string {
+ const p = m.preference;
+ const tags: string[] = [];
+ if (p.scope) tags.push(`scope: ${p.scope}`);
+ tags.push(`applied_30d: ${m.applied_30d}`);
+ return `- \`${p.id}\` (${tags.join(", ")}) β€” ${p.principle}`;
+}
+
function renderQuarantineLine(p: BrainPreference): string {
const tags: string[] = [];
if (p.scope) tags.push(`scope: ${p.scope}`);
diff --git a/src/core/brain/most-applied.ts b/src/core/brain/most-applied.ts
new file mode 100644
index 00000000..ffbe8916
--- /dev/null
+++ b/src/core/brain/most-applied.ts
@@ -0,0 +1,121 @@
+/**
+ * Sliding 30-day applied-evidence ranker that backs the
+ * `## Most-applied (30d)` section of `Brain/active.md`.
+ *
+ * Pure read. Caller passes the candidate preferences (already
+ * filtered to `confirmed | quarantine` in `regenerateActive`); this
+ * module never re-walks the preferences directory.
+ */
+
+import { existsSync, readdirSync } from "node:fs";
+
+import { brainDirs } from "./paths.ts";
+import { readLogDay } from "./log-jsonl.ts";
+import { isoDate } from "./time.ts";
+import { normaliseWikilinkTarget } from "./wikilink.ts";
+import {
+ BRAIN_APPLY_RESULT,
+ BRAIN_LOG_EVENT_KIND,
+ BRAIN_PREFERENCE_STATUS,
+ type BrainPreference,
+} from "./types.ts";
+
+const WINDOW_MS = 30 * 24 * 3600 * 1000;
+const DAY_MS = 24 * 3600 * 1000;
+const DEFAULT_LIMIT = 10;
+const LOG_FILENAME_RE = /^(\d{4}-\d{2}-\d{2})\.md$/;
+
+export interface MostAppliedEntry {
+ readonly preference: BrainPreference;
+ readonly applied_30d: number;
+}
+
+export interface ComputeMostAppliedOptions {
+ /** Window anchor. Defaults to `new Date()`. */
+ readonly now?: Date;
+ /** Max entries returned. Defaults to 10. */
+ readonly limit?: number;
+}
+
+/**
+ * Compute the Most-applied list for the `active.md` section.
+ *
+ * @param vault Vault root.
+ * @param preferences Candidate preferences (confirmed | quarantine).
+ * Events referencing preferences outside this list
+ * are silently ignored by design β€” retired rules
+ * do not appear in `active.md`.
+ */
+export function computeMostApplied(
+ vault: string,
+ preferences: ReadonlyArray<BrainPreference>,
+ opts: ComputeMostAppliedOptions = {},
+): ReadonlyArray<MostAppliedEntry> {
+ const now = opts.now ?? new Date();
+ const limit = opts.limit ?? DEFAULT_LIMIT;
+ const dirs = brainDirs(vault);
+ if (!existsSync(dirs.log)) return [];
+
+ // The caller is supposed to filter to confirmed | quarantine upstream,
+ // but the status guard here keeps the contract honest if a future
+ // caller passes a wider list β€” retired rules must never surface in
+ // the active digest.
+ const prefByKey = new Map<string, BrainPreference>();
+ for (const p of preferences) {
+ if (
+ p.status !== BRAIN_PREFERENCE_STATUS.confirmed &&
+ p.status !== BRAIN_PREFERENCE_STATUS.quarantine
+ ) {
+ continue;
+ }
+ prefByKey.set(normaliseWikilinkTarget(p.id), p);
+ }
+ if (prefByKey.size === 0) return [];
+
+ const windowEndMs = now.getTime();
+ const windowStartMs = windowEndMs - WINDOW_MS;
+ // Day-level fence: include the day before window start to absorb
+ // UTC drift between the event timestamp and the file's date prefix.
+ const earliestDayPrefix = isoDate(new Date(windowStartMs - DAY_MS));
+
+ const counts = new Map<string, number>();
+ for (const name of readdirSync(dirs.log)) {
+ const m = LOG_FILENAME_RE.exec(name);
+ if (!m) continue;
+ const datePrefix = m[1]!;
+ if (datePrefix < earliestDayPrefix) continue;
+
+ let parsed;
+ try {
+ parsed = readLogDay(vault, datePrefix);
+ } catch (err) {
+ process.stderr.write(
+ `warning: most-applied: failed to read ${datePrefix}: ${(err as Error).message}\n`,
+ );
+ continue;
+ }
+ for (const e of parsed.entries) {
+ if (e.eventType !== BRAIN_LOG_EVENT_KIND.applyEvidence) continue;
+ if (e.body["result"] !== BRAIN_APPLY_RESULT.applied) continue;
+ const eventMs = Date.parse(e.timestamp);
+ if (Number.isNaN(eventMs)) continue;
+ if (eventMs < windowStartMs || eventMs > windowEndMs) continue;
+ const prefField = e.body["preference"];
+ if (typeof prefField !== "string") continue;
+ const key = normaliseWikilinkTarget(prefField);
+ if (!prefByKey.has(key)) continue;
+ counts.set(key, (counts.get(key) ?? 0) + 1);
+ }
+ }
+
+ const entries: MostAppliedEntry[] = [];
+ for (const [key, count] of counts) {
+ const pref = prefByKey.get(key)!;
+ entries.push({ preference: pref, applied_30d: count });
+ }
+ entries.sort((a, b) => {
+ if (b.applied_30d !== a.applied_30d) return b.applied_30d - a.applied_30d;
+ return a.preference.id.localeCompare(b.preference.id);
+ });
+ return entries.slice(0, limit);
+}
diff --git a/src/core/brain/note.ts b/src/core/brain/note.ts
new file mode 100644
index 00000000..80d6bfd3
--- /dev/null
+++ b/src/core/brain/note.ts
@@ -0,0 +1,74 @@
+/**
+ * Shared body for appending a `note` event to today's Brain log.
+ * Both the MCP `brain_note` tool and the `o2b brain note` CLI verb
+ * delegate here so the on-disk shape cannot drift between them.
+ * Wrappers translate the thrown `Error` into their protocol's
+ * idiom (MCP `INVALID_PARAMS` envelope, CLI exit code).
+ */
+
+import { resolve } from "node:path";
+
+import { normalizeAgentArgument } from "../agent-identity.ts";
+import { resolveAgentName } from "../config.ts";
+import { vaultRelative } from "../path-safety.ts";
+import { sanitiseTextField } from "../redactor.ts";
+
+import { appendLogEvent } from "./log.ts";
+import { isoSecond } from "./time.ts";
+import { BRAIN_LOG_EVENT_KIND } from "./types.ts";
+
+const NOTE_TEXT_MAX_LEN = 4096;
+
+export interface AppendBrainNoteInput {
+ readonly vault: string;
+ readonly text: string;
+ /** Identity override. Resolver default is used when omitted or blank. */
+ readonly agent?: string;
+ /** Wall clock for the event timestamp. Defaults to `new Date()`. */
+ readonly now?: Date;
+ /** Config path for `resolveAgentName`. Optional. */
+ readonly configPath?: string;
+}
+
+export interface AppendBrainNoteResult {
+ /** Canonical ISO-8601 UTC second of the appended event. */
+ readonly logged_at: string;
+ /** Vault-relative POSIX path (`Brain/log/<date>.md`). */
+ readonly log_path: string;
+ /** Absolute filesystem path of the markdown log file. */
+ readonly absolute_log_path: string;
+ /** Identity actually written into the log entry. */
+ readonly agent: string;
+}
+
+/**
+ * Append one `note` event to `Brain/log/<today>.md` (and the JSONL
+ * sidecar via `appendLogEvent`). Throws plain `Error` on empty text
+ * β€” wrappers translate the error to their protocol's idiom.
+ */
+export function appendBrainNote(
+ input: AppendBrainNoteInput,
+): AppendBrainNoteResult {
+ const sanitised = sanitiseTextField(input.text, {
+ maxLen: NOTE_TEXT_MAX_LEN,
+ singleLine: true,
+ }).trim();
+ if (!sanitised) {
+ throw new Error("brain_note: text is required");
+ }
+ const explicitAgent = normalizeAgentArgument(input.agent ?? null);
+ const agent = explicitAgent ?? resolveAgentName(input.configPath);
+ const timestamp = isoSecond(input.now ?? new Date());
+ const entry = {
+ timestamp,
+ eventType: BRAIN_LOG_EVENT_KIND.note,
+ body: { text: sanitised, agent },
+ } as const;
+ const res = appendLogEvent(input.vault, entry);
+ return {
+ logged_at: timestamp,
+ log_path: vaultRelative(res.logPath, input.vault),
+ absolute_log_path: resolve(res.logPath),
+ agent,
+ };
+}
diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.ts
index 9df17de6..3075ba1b 100644
--- a/src/mcp/brain-tools.ts
+++ b/src/mcp/brain-tools.ts
@@ -1,8 +1,8 @@
/**
* MCP tool registrations for the Brain layer.
*
- * Exposes the six Brain operations that are safe to invoke from an
- * agent harness:
+ * Exposes the Brain operations that are safe to invoke from an agent
+ * harness:
*
* - `brain_feedback` β€” record a single taste signal (or a
* directly-confirmed preference when
@@ -16,6 +16,8 @@
* - `brain_query` β€” read-only aggregation by preference id,
* topic, or time window.
* - `brain_doctor` β€” invariant / schema health check.
+ * - `brain_backlinks` β€” read-only inbound reference lookup.
+ * - `brain_context` β€” pull-bootstrap of `Brain/active.md`.
*
* The five Brain commands that remain CLI-only on purpose
* (`init`, `reject`, `pin`, `unpin`, `rollback`) deliberately do *not*
@@ -33,7 +35,18 @@
import { isAbsolute, relative, resolve } from "node:path";
+import { existsSync, readFileSync } from "node:fs";
+
import { resolveAgentName } from "../core/config.ts";
+import {
+ brainActivePath,
+ brainDirs,
+} from "../core/brain/paths.ts";
+import {
+ regenerateActive,
+ type RegenerateActiveResult,
+} from "../core/brain/active.ts";
+import { parseFrontmatter } from "../core/vault.ts";
import {
appendApplyEvidence,
BrainPreferenceNotFoundError,
@@ -71,7 +84,7 @@ import {
} from "../core/brain/types.ts";
import { appendLogEvent } from "../core/brain/log.ts";
import type { BrainLogEntry } from "../core/brain/log.ts";
-import { sanitiseTextField } from "../core/redactor.ts";
+import { appendBrainNote } from "../core/brain/note.ts";
import { INVALID_PARAMS, MCPError } from "./protocol.ts";
import type { ServerContext, ToolDefinition } from "./tools.ts";
@@ -312,14 +325,17 @@ async function toolBrainApplyEvidence(
// ----- brain_note (Β§32B, v0.10.8) ------------------------------------------
-const NOTE_TEXT_MAX_LEN = 4096;
-
/**
* Append one narrative-milestone line to today's Brain log. This is the
* Brain-native replacement for the deprecated `event_log_append` tool:
* agents now record release / merged-PR / discovered-fact lines under
* the `note` event kind in `Brain/log/<today>.md` (and the JSONL
* sidecar) instead of falling back to `Daily/`.
+ *
+ * The body lives in `appendBrainNote` so the CLI verb (`o2b brain
+ * note`) and this MCP handler share one code path. Validation errors
+ * land in MCP's `INVALID_PARAMS` envelope here; the CLI wrapper
+ * pre-validates usage shape and surfaces the same condition as exit 2.
*/
async function toolBrainNote(
ctx: ServerContext,
@@ -328,32 +344,105 @@ async function toolBrainNote(
const rawText = coerceStr(args, "text", true)!;
const agentArg = coerceStr(args, "agent", false);
- // `singleLine` collapses newlines and trims to NOTE_TEXT_MAX_LEN. The
- // shared sanitiser also strips C0 controls and folds U+2028/U+2029.
- const sanitised = sanitiseTextField(rawText, {
- maxLen: NOTE_TEXT_MAX_LEN,
- singleLine: true,
- }).trim();
- if (!sanitised) {
- throw new MCPError(INVALID_PARAMS, "brain_note: text is required");
+ let res;
+ try {
+ res = appendBrainNote({
+ vault: ctx.vault,
+ text: rawText,
+ ...(agentArg ? { agent: agentArg } : {}),
+ ...(ctx.configPath ? { configPath: ctx.configPath } : {}),
+ });
+ } catch (err) {
+ throw new MCPError(INVALID_PARAMS, (err as Error).message);
}
+ return {
+ logged_at: res.logged_at,
+ log_path: res.log_path,
+ absolute_log_path: res.absolute_log_path,
+ agent: res.agent,
+ };
+}
- const agent =
- normalizeAgentArgument(agentArg) ??
- resolveAgentName(ctx.configPath ?? undefined);
- const timestamp = isoSecond(new Date());
+// ----- brain_context (v0.10.10) --------------------------------------------
+
+type BrainContextCounts = RegenerateActiveResult["counts"];
+
+const EMPTY_CONTEXT_COUNTS: BrainContextCounts = {
+ confirmed: 0,
+ quarantine: 0,
+ retired_recent: 0,
+ most_applied_30d: 0,
+};
+
+/**
+ * Read-only pull-bootstrap of `Brain/active.md` + the active-preference
+ * counts. Built for runtimes that have no `SessionStart` hook (Cursor,
+ * Aider, raw Claude API): one tool call gives the agent the same
+ * shortcut card the SessionStart-aware runtimes get injected
+ * automatically.
+ *
+ * Behaviour matrix:
+ * - Brain/ absent β†’ present:false, content:"", zero counts.
+ * - Brain/ present, active.md absent β†’ call regenerateActive (idempotent)
+ * and read the regenerated file.
+ * - Brain/ present, active.md fresh β†’ idempotent regenerate is a no-op
+ * rewrite; the on-disk body is
+ * returned verbatim.
+ */
+async function toolBrainContext(
+ ctx: ServerContext,
+): Promise<Record<string, unknown>> {
+ const dirs = brainDirs(ctx.vault);
+ const activePath = brainActivePath(ctx.vault);
+ if (!existsSync(dirs.brain)) {
+ return {
+ vault_path: ctx.vault,
+ present: false,
+ active_path: activePath,
+ content: "",
+ counts: EMPTY_CONTEXT_COUNTS,
+ generated_at: null,
+ };
+ }
+
+ let counts: BrainContextCounts = EMPTY_CONTEXT_COUNTS;
+ let error: string | undefined;
+ try {
+ counts = regenerateActive(ctx.vault).counts;
+ } catch (err) {
+ error = (err as Error)?.message ?? String(err);
+ }
+
+ // After a successful regenerateActive, active.md is guaranteed to
+ // exist (the function either wrote it or confirmed an equal body
+ // already on disk). A read failure here is an unrelated filesystem
+ // race, not a missing-file branch β€” handle it in the same `error`
+ // slot the regenerate failure uses.
+ let content = "";
+ let generatedAt: string | null = null;
+ if (!error) {
+ try {
+ content = readFileSync(activePath, "utf8");
+ const [meta] = parseFrontmatter(activePath);
+ const v = meta["generated_at"];
+ if (typeof v === "string" && v.trim().length > 0) {
+ generatedAt = v;
+ }
+ } catch (err) {
+ error = (err as Error)?.message ?? String(err);
+ content = "";
+ generatedAt = null;
+ }
+ }
- const entry: BrainLogEntry = {
- timestamp,
- eventType: BRAIN_LOG_EVENT_KIND.note,
- body: { text: sanitised, agent },
- };
- const res = appendLogEvent(ctx.vault, entry);
return {
- logged_at: timestamp,
- log_path: vaultRelativeSafe(ctx.vault, res.logPath),
- absolute_log_path: resolve(res.logPath),
- agent,
+ vault_path: ctx.vault,
+ present: true,
+ active_path: activePath,
+ content,
+ counts,
+ generated_at: generatedAt,
+ ...(error ? { error } : {}),
};
}
@@ -766,6 +855,17 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
handler: toolBrainNote,
},
+ {
+ name: "brain_context",
+ description:
+ "Pull the current Brain/active.md body plus active-preference counts. Use at session start when SessionStart hook is unavailable (Cursor, Aider, raw Claude API). Read-only.",
+ inputSchema: {
+ type: "object",
+ properties: {},
+ additionalProperties: false,
+ },
+ handler: toolBrainContext,
+ },
{
name: "brain_digest",
description:
diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.ts
index 0bd1e70f..f0b8bc10 100644
--- a/src/mcp/instructions.ts
+++ b/src/mcp/instructions.ts
@@ -19,15 +19,21 @@ export interface BuildInstructionsOpts {
readonly scope?: ToolScope;
}
-const WRITER_INSTRUCTIONS = `Open Second Brain β€” writer surface (always-loaded).
+const WRITER_INSTRUCTIONS = `Open Second Brain β€” always-loaded MCP surface.
-Three tools live here:
+Four tools live here (three writers + one reader; the server's name is
+preserved for backward compatibility with existing client configs):
- brain_feedback β€” record one new taste signal the user just expressed.
- brain_apply_evidence β€” record applied | violated | outdated against an
active preference for an artifact this turn produced.
- brain_note β€” record one narrative milestone (release shipped,
PR merged, fact discovered) that fits neither
category.
+ - brain_context β€” pull the current Brain/active.md body plus
+ active-preference counts. Read-only. Use at session
+ start when the host runtime lacks a SessionStart
+ hook (Cursor, Aider, raw Claude API). Runtimes that
+ already inject active.md via a hook can skip this.
The remaining Brain surface (digest, query, doctor, backlinks, search,
Pay Memory tools, vault_health, second_brain_status, second_brain_query,
diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts
index 9a27cd20..8dbd4e45 100644
--- a/src/mcp/tools.ts
+++ b/src/mcp/tools.ts
@@ -192,9 +192,15 @@ async function toolVaultHealth(
export type ToolScope = "full" | "writer";
+// The set is named after the original payload (mutating writers). As
+// of v0.10.10 it also hosts `brain_context`, a *reader* tool that has
+// to be always-loaded to be useful at session start. Renaming the
+// MCP server itself is deferred β€” see
+// `docs/plans/2026-05-20-v0.10.10-design.md` Β§12.
const WRITER_TOOL_NAMES: ReadonlySet<string> = new Set([
- "brain_feedback",
"brain_apply_evidence",
+ "brain_context",
+ "brain_feedback",
"brain_note",
]);
diff --git a/tests/cli/brain-note.test.ts b/tests/cli/brain-note.test.ts
new file mode 100644
index 00000000..6abf62eb
--- /dev/null
+++ b/tests/cli/brain-note.test.ts
@@ -0,0 +1,106 @@
+/**
+ * Tests for `o2b brain note <text>` CLI verb (v0.10.10).
+ *
+ * Drives Β§7.2 of `docs/plans/2026-05-20-v0.10.10-design.md` β€” the
+ * Brain-native milestone-log mirror of the MCP `brain_note` tool.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ 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 configDir: string;
+let vault: string;
+let configPath: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-brain-note-cli-"));
+ configDir = mkdtempSync(join(tmpdir(), "o2b-brain-note-cli-cfg-"));
+ vault = join(tmp, "vault");
+ configPath = join(configDir, "config.yaml");
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ rmSync(configDir, { recursive: true, force: true });
+});
+
+function today(): string {
+ return new Date().toISOString().slice(0, 10);
+}
+
+describe("o2b brain note", () => {
+ test("writes a note with the positional text", async () => {
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: tester\n`, "utf8");
+ const r = await runCli(["brain", "note", "released v0.10.10"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath, VAULT_AGENT_NAME: "" },
+ });
+ expect(r.returncode).toBe(0);
+ const body = readFileSync(join(vault, "Brain", "log", `${today()}.md`), "utf8");
+ expect(body).toContain("β€” note");
+ expect(body).toContain("- text: released v0.10.10");
+ expect(body).toContain("- agent: tester");
+ });
+
+ test("--json emits the structured result", async () => {
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: tester\n`, "utf8");
+ const r = await runCli(
+ ["brain", "note", "json output check", "--json"],
+ {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath, VAULT_AGENT_NAME: "" },
+ },
+ );
+ expect(r.returncode).toBe(0);
+ const parsed = JSON.parse(r.stdout);
+ expect(parsed.ok).toBe(true);
+ expect(parsed.agent).toBe("tester");
+ expect(parsed.log_path).toMatch(/^Brain\/log\/\d{4}-\d{2}-\d{2}\.md$/);
+ expect(parsed.logged_at).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/);
+ expect(typeof parsed.absolute_log_path).toBe("string");
+ });
+
+ test("--agent flag overrides the config-resolved identity", async () => {
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: tester\n`, "utf8");
+ const r = await runCli(
+ ["brain", "note", "agent override", "--agent", "explicit-name", "--json"],
+ {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath, VAULT_AGENT_NAME: "" },
+ },
+ );
+ expect(r.returncode).toBe(0);
+ const parsed = JSON.parse(r.stdout);
+ expect(parsed.agent).toBe("explicit-name");
+ });
+
+ test("missing text exits 2 with a clear stderr message", async () => {
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: tester\n`, "utf8");
+ const r = await runCli(["brain", "note"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath, VAULT_AGENT_NAME: "" },
+ });
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toContain("brain note");
+ });
+
+ test("whitespace-only text exits 2 (usage error)", async () => {
+ // Design Β§7.2: empty / whitespace-only text is a usage error, not a
+ // runtime failure. Cron callers can distinguish "operator forgot
+ // text" (exit 2) from a real append failure (exit 1) by the code.
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: tester\n`, "utf8");
+ const r = await runCli(["brain", "note", " "], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath, VAULT_AGENT_NAME: "" },
+ });
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toContain("non-empty text");
+ });
+});
diff --git a/tests/cli/cli.test.ts b/tests/cli/cli.test.ts
index 75f5999f..895fe806 100644
--- a/tests/cli/cli.test.ts
+++ b/tests/cli/cli.test.ts
@@ -16,6 +16,14 @@ afterEach(() => {
rmSync(tmp, { recursive: true, force: true });
});
+describe("help", () => {
+ test("top-level help includes the Brain note verb", async () => {
+ const r = await runCli(["--help"]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("brain note");
+ });
+});
+
describe("status", () => {
test("reports missing config", async () => {
const config = join(tmp, "missing.yaml");
diff --git a/tests/cli/mcp-scope-arg.test.ts b/tests/cli/mcp-scope-arg.test.ts
index 4a632424..0392e417 100644
--- a/tests/cli/mcp-scope-arg.test.ts
+++ b/tests/cli/mcp-scope-arg.test.ts
@@ -44,6 +44,7 @@ describe("o2b mcp --scope arg validation", () => {
.map((t) => t.name).sort();
expect(names).toEqual([
"brain_apply_evidence",
+ "brain_context",
"brain_feedback",
"brain_note",
]);
diff --git a/tests/cli/status.test.ts b/tests/cli/status.test.ts
new file mode 100644
index 00000000..373eac49
--- /dev/null
+++ b/tests/cli/status.test.ts
@@ -0,0 +1,155 @@
+/**
+ * Tests for `o2b status` semantic-search hint (v0.10.10).
+ *
+ * Drives Β§8 of `docs/plans/2026-05-20-v0.10.10-design.md` β€” the
+ * single-line hint that surfaces when semantic search is enabled in
+ * config but cannot run (key missing, etc.), plus the equivalent
+ * `--json` keys.
+ */
+
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ test,
+} from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { runCli } from "../helpers/run-cli.ts";
+
+let cfgDir: string;
+let cfgPath: string;
+
+beforeEach(() => {
+ cfgDir = mkdtempSync(join(tmpdir(), "o2b-status-semantic-"));
+ cfgPath = join(cfgDir, "config.yaml");
+});
+
+afterEach(() => {
+ rmSync(cfgDir, { recursive: true, force: true });
+});
+
+const ENV_CLEAN: Record<string, string> = {
+ OPEN_SECOND_BRAIN_SEARCH_SEMANTIC: "",
+ OPEN_SECOND_BRAIN_EMBEDDING_KEY: "",
+ OPEN_SECOND_BRAIN_CONFIG: "",
+ VAULT_AGENT_NAME: "",
+ VAULT_DIR: "",
+};
+
+function writeCfg(body: string): void {
+ mkdirSync(cfgDir, { recursive: true });
+ writeFileSync(cfgPath, body, "utf8");
+}
+
+describe("o2b status β€” semantic hint (human output)", () => {
+ test("hint absent when semantic_enabled is true and key is present", async () => {
+ writeCfg(
+ [
+ "vault: /tmp/x",
+ 'search_semantic_enabled: "true"',
+ 'embedding_api_key: "sk-test"',
+ 'embedding_base_url: "https://example.test/v1"',
+ 'embedding_model: "test-model"',
+ ].join("\n") + "\n",
+ );
+ const r = await runCli(["status", "--config", cfgPath], { env: ENV_CLEAN });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).not.toContain("semantic: off");
+ });
+
+ test("hint present when semantic_enabled is false", async () => {
+ writeCfg("vault: /tmp/x\n");
+ const r = await runCli(["status", "--config", cfgPath], { env: ENV_CLEAN });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("semantic: off");
+ expect(r.stdout).toContain("o2b search check");
+ });
+
+ test("hint present when key is missing even with enabled flag set", async () => {
+ writeCfg('vault: /tmp/x\nsearch_semantic_enabled: "true"\n');
+ const r = await runCli(["status", "--config", cfgPath], { env: ENV_CLEAN });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("semantic: off");
+ });
+
+ test("hint present when configured key is whitespace-only", async () => {
+ writeCfg(
+ [
+ "vault: /tmp/x",
+ 'search_semantic_enabled: "true"',
+ 'embedding_api_key: " "',
+ ].join("\n") + "\n",
+ );
+ const r = await runCli(["status", "--config", cfgPath], { env: ENV_CLEAN });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("semantic: off");
+ });
+
+ test("hint suppressed when search is disabled outright", async () => {
+ writeCfg('vault: /tmp/x\nsearch_enabled: "false"\n');
+ const r = await runCli(["status", "--config", cfgPath], { env: ENV_CLEAN });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).not.toContain("semantic:");
+ });
+});
+
+describe("o2b status β€” semantic fields (--json)", () => {
+ test("--json carries semantic flags and hint when semantic is off", async () => {
+ writeCfg("vault: /tmp/x\n");
+ const r = await runCli(["status", "--config", cfgPath, "--json"], {
+ env: ENV_CLEAN,
+ });
+ expect(r.returncode).toBe(0);
+ const parsed = JSON.parse(r.stdout);
+ expect(parsed.semantic_enabled).toBe(false);
+ expect(parsed.embedding_key_present).toBe(false);
+ expect(typeof parsed.semantic_hint).toBe("string");
+ expect(parsed.semantic_hint).toContain("o2b search check");
+ });
+
+ test("--json semantic_hint is null when fully configured", async () => {
+ writeCfg(
+ [
+ "vault: /tmp/x",
+ 'search_semantic_enabled: "true"',
+ 'embedding_api_key: "sk-test"',
+ ].join("\n") + "\n",
+ );
+ const r = await runCli(["status", "--config", cfgPath, "--json"], {
+ env: ENV_CLEAN,
+ });
+ expect(r.returncode).toBe(0);
+ const parsed = JSON.parse(r.stdout);
+ expect(parsed.semantic_enabled).toBe(true);
+ expect(parsed.embedding_key_present).toBe(true);
+ expect(parsed.semantic_hint).toBeNull();
+ });
+
+ test("--json treats whitespace-only env key as missing", async () => {
+ writeCfg('vault: /tmp/x\nsearch_semantic_enabled: "true"\n');
+ const r = await runCli(["status", "--config", cfgPath, "--json"], {
+ env: {
+ ...ENV_CLEAN,
+ OPEN_SECOND_BRAIN_EMBEDDING_KEY: " ",
+ },
+ });
+ expect(r.returncode).toBe(0);
+ const parsed = JSON.parse(r.stdout);
+ expect(parsed.embedding_key_present).toBe(false);
+ expect(typeof parsed.semantic_hint).toBe("string");
+ });
+
+ test("--json semantic_hint is null when search is disabled outright", async () => {
+ writeCfg('vault: /tmp/x\nsearch_enabled: "false"\n');
+ const r = await runCli(["status", "--config", cfgPath, "--json"], {
+ env: ENV_CLEAN,
+ });
+ expect(r.returncode).toBe(0);
+ const parsed = JSON.parse(r.stdout);
+ expect(parsed.semantic_hint).toBeNull();
+ });
+});
diff --git a/tests/core/brain.active.test.ts b/tests/core/brain.active.test.ts
index f008ad41..f1f2249a 100644
--- a/tests/core/brain.active.test.ts
+++ b/tests/core/brain.active.test.ts
@@ -80,7 +80,12 @@ describe("regenerateActive β€” empty Brain", () => {
const result = regenerateActive(vault, { now: new Date("2026-05-15T10:00:00Z") });
expect(existsSync(result.path)).toBe(true);
- expect(result.counts).toEqual({ confirmed: 0, quarantine: 0, retired_recent: 0 });
+ expect(result.counts).toEqual({
+ confirmed: 0,
+ quarantine: 0,
+ retired_recent: 0,
+ most_applied_30d: 0,
+ });
const body = readActive();
expect(body).toContain("kind: brain-active");
@@ -207,3 +212,74 @@ describe("regenerateActive β€” corruption tolerance", () => {
expect(body).not.toContain("pref-corrupted");
});
});
+
+// ── Most-applied (30d) section β€” v0.10.10 ──────────────────────────────────
+
+import { appendLogEvent } from "../../src/core/brain/log.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../../src/core/brain/types.ts";
+
+function seedAppliedEvidence(
+ prefId: string,
+ timestamp: string,
+ artifact: string = "[[src/test.ts]]",
+): void {
+ appendLogEvent(vault, {
+ timestamp,
+ eventType: BRAIN_LOG_EVENT_KIND.applyEvidence,
+ body: {
+ preference: `[[${prefId}]]`,
+ artifact,
+ agent: "tester",
+ result: "applied",
+ },
+ });
+}
+
+describe("regenerateActive β€” Most-applied (30d) section", () => {
+ test("section absent when no apply-evidence events lie inside the window", () => {
+ seedConfirmed("a", "Rule A", "medium");
+ const result = regenerateActive(vault, { now: new Date("2026-05-20T00:00:00Z") });
+ const body = readActive();
+ expect(body).not.toContain("## Most-applied");
+ expect(result.counts.most_applied_30d).toBe(0);
+ });
+
+ test("renders the section and includes scope + applied_30d count", () => {
+ seedConfirmed("a", "Rule A", "medium");
+ seedAppliedEvidence("pref-a", "2026-05-15T10:00:00Z");
+ seedAppliedEvidence("pref-a", "2026-05-16T10:00:00Z");
+ const result = regenerateActive(vault, { now: new Date("2026-05-20T00:00:00Z") });
+ const body = readActive();
+ expect(body).toContain("## Most-applied (30d) (1)");
+ expect(body).toContain("`pref-a` (scope: writing, applied_30d: 2)");
+ expect(body).toContain("Rule A");
+ expect(result.counts.most_applied_30d).toBe(1);
+ });
+
+ test("section appears between Confirmed and Quarantine", () => {
+ seedConfirmed("a", "Confirmed rule", "high");
+ seedQuarantine("q", "Quarantined rule");
+ seedAppliedEvidence("pref-a", "2026-05-15T10:00:00Z");
+ regenerateActive(vault, { now: new Date("2026-05-20T00:00:00Z") });
+ const body = readActive();
+ const confirmedIdx = body.indexOf("## Confirmed");
+ const mostAppliedIdx = body.indexOf("## Most-applied");
+ const quarantineIdx = body.indexOf("## Quarantine");
+ expect(confirmedIdx).toBeGreaterThan(-1);
+ expect(mostAppliedIdx).toBeGreaterThan(confirmedIdx);
+ expect(quarantineIdx).toBeGreaterThan(mostAppliedIdx);
+ });
+
+ test("idempotent rerender with no log change leaves the file untouched", () => {
+ seedConfirmed("a", "Rule A", "medium");
+ seedAppliedEvidence("pref-a", "2026-05-15T10:00:00Z");
+ const first = regenerateActive(vault, { now: new Date("2026-05-20T00:00:00Z") });
+ const mtimeBefore = statSync(first.path).mtimeMs;
+ // Bump `now` so the frontmatter timestamp would differ if a write
+ // happened. The body must be identical, so `changed: false`.
+ const second = regenerateActive(vault, { now: new Date("2026-05-20T00:30:00Z") });
+ expect(second.changed).toBe(false);
+ const mtimeAfter = statSync(second.path).mtimeMs;
+ expect(mtimeAfter).toBe(mtimeBefore);
+ });
+});
diff --git a/tests/core/brain/most-applied.test.ts b/tests/core/brain/most-applied.test.ts
new file mode 100644
index 00000000..96d2cbaf
--- /dev/null
+++ b/tests/core/brain/most-applied.test.ts
@@ -0,0 +1,215 @@
+/**
+ * Tests for `src/core/brain/most-applied.ts` (v0.10.10).
+ *
+ * Drives Β§6.1 of `docs/plans/2026-05-20-v0.10.10-design.md` β€” the
+ * sliding 30-day applied-evidence ranker that backs the
+ * `Most-applied (30d)` section of `Brain/active.md`.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { computeMostApplied } from "../../../src/core/brain/most-applied.ts";
+import { appendLogEvent } from "../../../src/core/brain/log.ts";
+import type { BrainPreference } from "../../../src/core/brain/types.ts";
+import {
+ BRAIN_APPLY_RESULT,
+ BRAIN_LOG_EVENT_KIND,
+ BRAIN_PREFERENCE_STATUS,
+} from "../../../src/core/brain/types.ts";
+
+/**
+ * Build a minimal `BrainPreference` with the fields the ranker actually
+ * reads (`id`, `status`). The remaining fields are filled with type-safe
+ * placeholders so the value satisfies the interface without dragging
+ * unrelated test-shape concerns into this file.
+ */
+function buildPref(
+ id: string,
+ overrides: Partial<BrainPreference> = {},
+): BrainPreference {
+ const base: BrainPreference = {
+ kind: "brain-preference",
+ id,
+ created_at: "2026-04-01T00:00:00Z",
+ confirmed_at: null,
+ unconfirmed_until: "2026-04-08T00:00:00Z",
+ tags: [],
+ topic: id.replace(/^pref-/, ""),
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ principle: `principle for ${id}`,
+ evidenced_by: [],
+ applied_count: 0,
+ violated_count: 0,
+ last_evidence_at: null,
+ confidence: "medium",
+ confidence_value: 0.5,
+ pinned: false,
+ };
+ return { ...base, ...overrides };
+}
+
+function seedApplied(
+ vault: string,
+ timestamp: string,
+ prefWikilink: string,
+ result: string = BRAIN_APPLY_RESULT.applied,
+): void {
+ appendLogEvent(vault, {
+ timestamp,
+ eventType: BRAIN_LOG_EVENT_KIND.applyEvidence,
+ body: {
+ preference: prefWikilink,
+ artifact: "[[src/foo.ts]]",
+ agent: "tester",
+ result,
+ },
+ });
+}
+
+function writeMalformedLogDay(vault: string, date: string, body: string): void {
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+ writeFileSync(join(vault, "Brain", "log", `${date}.md`), body, "utf8");
+}
+
+describe("computeMostApplied", () => {
+ let vault: string;
+ beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-most-applied-"));
+ // `_brain.yaml` is required by some downstream readers; create
+ // the directory shell so `brainDirs(vault)` resolves cleanly.
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ });
+ afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ });
+
+ test("returns empty when log directory is missing", () => {
+ const result = computeMostApplied(vault, [buildPref("pref-a")], {
+ now: new Date("2026-05-20T00:00:00Z"),
+ });
+ expect(result).toEqual([]);
+ });
+
+ test("counts only result=applied events inside the 30d window", () => {
+ const now = new Date("2026-05-20T00:00:00Z");
+ seedApplied(vault, "2026-05-15T10:00:00Z", "[[pref-a]]");
+ seedApplied(vault, "2026-05-15T10:05:00Z", "[[pref-a]]");
+ // 31 days ago β€” outside the window.
+ seedApplied(vault, "2026-04-19T10:00:00Z", "[[pref-a]]");
+ const result = computeMostApplied(vault, [buildPref("pref-a")], { now });
+ expect(result.length).toBe(1);
+ expect(result[0]!.applied_30d).toBe(2);
+ });
+
+ test("ignores violated and outdated results", () => {
+ const now = new Date("2026-05-20T00:00:00Z");
+ seedApplied(vault, "2026-05-15T10:00:00Z", "[[pref-a]]", BRAIN_APPLY_RESULT.violated);
+ seedApplied(vault, "2026-05-15T10:05:00Z", "[[pref-a]]", BRAIN_APPLY_RESULT.outdated);
+ const result = computeMostApplied(vault, [buildPref("pref-a")], { now });
+ expect(result).toEqual([]);
+ });
+
+ test("excludes events whose preference is not in the caller's list", () => {
+ const now = new Date("2026-05-20T00:00:00Z");
+ seedApplied(vault, "2026-05-15T10:00:00Z", "[[pref-a]]");
+ // Caller passes ONLY confirmed/quarantine preferences. Retired
+ // preferences are dropped by the caller before reaching this
+ // function, so an event referencing pref-a with no matching
+ // entry in the candidate list is silently ignored.
+ const result = computeMostApplied(vault, [], { now });
+ expect(result).toEqual([]);
+ });
+
+ test("includes quarantine preferences", () => {
+ const now = new Date("2026-05-20T00:00:00Z");
+ seedApplied(vault, "2026-05-15T10:00:00Z", "[[pref-q]]");
+ const result = computeMostApplied(
+ vault,
+ [buildPref("pref-q", { status: BRAIN_PREFERENCE_STATUS.quarantine })],
+ { now },
+ );
+ expect(result.length).toBe(1);
+ expect(result[0]!.preference.id).toBe("pref-q");
+ expect(result[0]!.applied_30d).toBe(1);
+ });
+
+ test("sorts by count desc, then by id asc", () => {
+ const now = new Date("2026-05-20T00:00:00Z");
+ seedApplied(vault, "2026-05-15T10:00:00Z", "[[pref-a]]");
+ seedApplied(vault, "2026-05-15T10:01:00Z", "[[pref-a]]");
+ seedApplied(vault, "2026-05-15T10:02:00Z", "[[pref-b]]");
+ seedApplied(vault, "2026-05-15T10:03:00Z", "[[pref-c]]");
+ const result = computeMostApplied(
+ vault,
+ [buildPref("pref-a"), buildPref("pref-b"), buildPref("pref-c")],
+ { now },
+ );
+ expect(result.map((r) => r.preference.id)).toEqual([
+ "pref-a",
+ "pref-b",
+ "pref-c",
+ ]);
+ expect(result[0]!.applied_30d).toBe(2);
+ });
+
+ test("honours limit", () => {
+ const now = new Date("2026-05-20T00:00:00Z");
+ seedApplied(vault, "2026-05-15T10:00:00Z", "[[pref-a]]");
+ seedApplied(vault, "2026-05-15T10:00:01Z", "[[pref-b]]");
+ seedApplied(vault, "2026-05-15T10:00:02Z", "[[pref-c]]");
+ const result = computeMostApplied(
+ vault,
+ [buildPref("pref-a"), buildPref("pref-b"), buildPref("pref-c")],
+ { now, limit: 2 },
+ );
+ expect(result.length).toBe(2);
+ });
+
+ test("normalises wikilinks with alias decoration", () => {
+ // `renderPrefLink` (used by apply-evidence writers) emits
+ // `[[pref-id|principle title]]` β€” the alias must collapse to the
+ // bare id before the count lookup. Same shape `normaliseWikilinkTarget`
+ // already strips on the read side.
+ const now = new Date("2026-05-20T00:00:00Z");
+ seedApplied(
+ vault,
+ "2026-05-15T10:00:00Z",
+ "[[pref-a|principle title with spaces]]",
+ );
+ const result = computeMostApplied(vault, [buildPref("pref-a")], { now });
+ expect(result.length).toBe(1);
+ expect(result[0]!.applied_30d).toBe(1);
+ });
+
+ test("survives a malformed log day", () => {
+ const now = new Date("2026-05-20T00:00:00Z");
+ // Raw write bypasses `appendLogEvent` validation β€” required to
+ // simulate a hand-edited corrupted day file. Pair with a real
+ // event from the day next to it so the function still makes
+ // progress.
+ writeMalformedLogDay(vault, "2026-05-14", "this is not a valid log file");
+ seedApplied(vault, "2026-05-15T10:00:00Z", "[[pref-a]]");
+ const result = computeMostApplied(vault, [buildPref("pref-a")], { now });
+ expect(result.length).toBe(1);
+ expect(result[0]!.applied_30d).toBe(1);
+ });
+
+ test("event exactly on the window edge is included", () => {
+ const now = new Date("2026-05-20T00:00:00Z");
+ const windowStart = new Date(now.getTime() - 30 * 24 * 3600 * 1000);
+ const stamp = windowStart.toISOString().replace(/\.\d{3}Z$/, "Z");
+ seedApplied(vault, stamp, "[[pref-a]]");
+ const result = computeMostApplied(vault, [buildPref("pref-a")], { now });
+ expect(result.length).toBe(1);
+ });
+
+ test("event exactly at now is included", () => {
+ const now = new Date("2026-05-20T00:00:00Z");
+ seedApplied(vault, "2026-05-20T00:00:00Z", "[[pref-a]]");
+ const result = computeMostApplied(vault, [buildPref("pref-a")], { now });
+ expect(result.length).toBe(1);
+ });
+});
diff --git a/tests/core/brain/note.test.ts b/tests/core/brain/note.test.ts
new file mode 100644
index 00000000..a8901caa
--- /dev/null
+++ b/tests/core/brain/note.test.ts
@@ -0,0 +1,93 @@
+/**
+ * Tests for `src/core/brain/note.ts` (v0.10.10).
+ *
+ * Drives Β§7.1 of `docs/plans/2026-05-20-v0.10.10-design.md` β€” the
+ * shared `appendBrainNote` core that both the MCP `brain_note` tool
+ * and the new `o2b brain note` CLI verb delegate to.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, mkdirSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+
+import { appendBrainNote } from "../../../src/core/brain/note.ts";
+
+function bootstrap(vault: string): void {
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+}
+
+describe("appendBrainNote", () => {
+ let vault: string;
+ beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-brain-note-core-"));
+ bootstrap(vault);
+ });
+ afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ });
+
+ test("writes a one-line note to today's log under kind=note", () => {
+ const now = new Date("2026-05-20T12:34:56Z");
+ const res = appendBrainNote({
+ vault,
+ text: "released v0.10.10",
+ agent: "tester",
+ now,
+ });
+ expect(res.agent).toBe("tester");
+ expect(res.logged_at).toBe("2026-05-20T12:34:56Z");
+ expect(res.log_path).toBe("Brain/log/2026-05-20.md");
+ expect(res.absolute_log_path).toBe(resolve(vault, "Brain/log/2026-05-20.md"));
+ const body = readFileSync(res.absolute_log_path, "utf8");
+ expect(body).toContain("## 12:34:56Z β€” note");
+ expect(body).toContain("- text: released v0.10.10");
+ expect(body).toContain("- agent: tester");
+ });
+
+ test("collapses multi-line text to one space-joined line", () => {
+ const res = appendBrainNote({
+ vault,
+ text: "line one\nline two\r\nline three",
+ agent: "tester",
+ now: new Date("2026-05-20T00:00:00Z"),
+ });
+ const body = readFileSync(res.absolute_log_path, "utf8");
+ expect(body).toContain("- text: line one line two line three");
+ });
+
+ test("writes a sidecar JSONL line alongside the markdown", () => {
+ const res = appendBrainNote({
+ vault,
+ text: "release shipped",
+ agent: "tester",
+ now: new Date("2026-05-20T01:00:00Z"),
+ });
+ const jsonlPath = res.absolute_log_path.replace(/\.md$/, ".jsonl");
+ const jsonl = readFileSync(jsonlPath, "utf8");
+ expect(jsonl).toContain('"kind":"note"');
+ expect(jsonl).toContain('"text":"release shipped"');
+ });
+
+ test("rejects whitespace-only text", () => {
+ expect(() =>
+ appendBrainNote({ vault, text: " ", agent: "tester", now: new Date() }),
+ ).toThrow(/text is required/);
+ });
+
+ test("rejects text that becomes empty after sanitising", () => {
+ expect(() =>
+ appendBrainNote({ vault, text: "\n\t \n", agent: "tester", now: new Date() }),
+ ).toThrow(/text is required/);
+ });
+
+ test("explicit agent overrides the resolver default", () => {
+ const res = appendBrainNote({
+ vault,
+ text: "explicit agent path",
+ agent: "explicit-name",
+ now: new Date("2026-05-20T02:00:00Z"),
+ });
+ expect(res.agent).toBe("explicit-name");
+ });
+});
diff --git a/tests/e2e/v0.10.10-pull-channels.test.ts b/tests/e2e/v0.10.10-pull-channels.test.ts
new file mode 100644
index 00000000..65ad6f1e
--- /dev/null
+++ b/tests/e2e/v0.10.10-pull-channels.test.ts
@@ -0,0 +1,133 @@
+/**
+ * End-to-end happy path for the v0.10.10 pull-channels release.
+ *
+ * Exercises the CLI surface across multiple invocations:
+ * 1. `o2b init` + `o2b brain init` bootstrap a fresh vault.
+ * 2. `o2b brain note <text>` writes one note event to today's
+ * Brain log + JSONL sidecar with the resolved agent identity.
+ * 3. `o2b status` reports semantic search as `off` for a fresh
+ * vault that has no embedding key, with the expected hint
+ * pointing the operator at `o2b search check`.
+ * 4. The MCP `brain_context` tool, invoked through the full
+ * MCPServer path, returns the regenerated `Brain/active.md`
+ * with the new `most_applied_30d` count and the resulting
+ * `content` string.
+ *
+ * If any seam between CLI / core / MCP breaks, the chain surfaces it.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { runCli } from "../helpers/run-cli.ts";
+import {
+ JSONRPC_VERSION,
+ MCPServer,
+ PROTOCOL_VERSION,
+} from "../../src/mcp/index.ts";
+
+let tmp: string;
+let vault: string;
+let config: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-v0-10-10-e2e-"));
+ vault = join(tmp, "vault");
+ config = join(tmp, "config.yaml");
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function today(): string {
+ return new Date().toISOString().slice(0, 10);
+}
+
+describe("v0.10.10 pull-channels e2e", () => {
+ test("init β†’ brain note β†’ status β†’ brain_context MCP call", async () => {
+ // 1. Bootstrap the vault and the Brain layer through the CLI.
+ let r = await runCli(
+ ["init", "--vault", vault, "--name", "Pull Channels Test", "--agent-name", "tester"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config, VAULT_AGENT_NAME: "" } },
+ );
+ expect(r.returncode).toBe(0);
+
+ r = await runCli(["brain", "init", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config, VAULT_AGENT_NAME: "" },
+ });
+ expect(r.returncode).toBe(0);
+
+ // 2. CLI mirror of brain_note lands one event in Brain/log/<today>.md
+ // plus the JSONL sidecar, with the configured identity.
+ r = await runCli(
+ ["brain", "note", "v0.10.10 released", "--vault", vault, "--json"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config, VAULT_AGENT_NAME: "" } },
+ );
+ expect(r.returncode).toBe(0);
+ const noteResult = JSON.parse(r.stdout);
+ expect(noteResult.agent).toBe("tester");
+
+ const logMdPath = join(vault, "Brain", "log", `${today()}.md`);
+ const logJsonlPath = logMdPath.replace(/\.md$/, ".jsonl");
+ const md = readFileSync(logMdPath, "utf8");
+ expect(md).toContain("β€” note");
+ expect(md).toContain("- text: v0.10.10 released");
+ expect(md).toContain("- agent: tester");
+
+ const jsonl = readFileSync(logJsonlPath, "utf8");
+ expect(jsonl).toContain('"kind":"note"');
+ expect(jsonl).toContain('"text":"v0.10.10 released"');
+
+ // 3. `o2b status` (no semantic key configured) prints the hint and
+ // surfaces the matching keys in --json.
+ r = await runCli(["status", "--config", config, "--json"], {
+ env: {
+ OPEN_SECOND_BRAIN_CONFIG: config,
+ VAULT_AGENT_NAME: "",
+ OPEN_SECOND_BRAIN_SEARCH_SEMANTIC: "",
+ OPEN_SECOND_BRAIN_EMBEDDING_KEY: "",
+ },
+ });
+ expect(r.returncode).toBe(0);
+ const statusJson = JSON.parse(r.stdout);
+ expect(statusJson.semantic_enabled).toBe(false);
+ expect(statusJson.embedding_key_present).toBe(false);
+ expect(statusJson.semantic_hint).toContain("o2b search check");
+
+ // 4. MCP `brain_context` returns the regenerated active.md body
+ // plus counts (with the v0.10.10 `most_applied_30d` field).
+ const server = new MCPServer({ vault, configPath: config });
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "v0.10.10-e2e", version: "0" },
+ },
+ });
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ method: "notifications/initialized",
+ });
+ const call = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 2,
+ method: "tools/call",
+ params: { name: "brain_context", arguments: {} },
+ })) as { result: { content: ReadonlyArray<{ text: string }> } };
+ const ctx = JSON.parse(call.result.content[0]!.text);
+ expect(ctx.present).toBe(true);
+ expect(typeof ctx.content).toBe("string");
+ expect(ctx.content).toContain("# Active Brain Preferences");
+ expect(typeof ctx.counts.most_applied_30d).toBe("number");
+ });
+});
diff --git a/tests/hooks/detect.test.ts b/tests/hooks/detect.test.ts
index b57f91a2..af301df1 100644
--- a/tests/hooks/detect.test.ts
+++ b/tests/hooks/detect.test.ts
@@ -182,6 +182,66 @@ describe("summarizeTurn", () => {
expect(s).toEqual({ hadArtifact: true, hadBrainEvent: true });
});
+ // v0.10.10 β€” CLI mirror of `brain_note` MCP tool.
+ test("artifact + bash `o2b brain note <text>` clears guardrail", () => {
+ const s = summarizeTurn(
+ [{ name: "Write" }, { name: "Bash" }],
+ ['o2b brain note "v0.10.10 released"'],
+ );
+ expect(s).toEqual({ hadArtifact: true, hadBrainEvent: true });
+ });
+
+ test("artifact + env-prefixed bash `o2b brain note <text>` clears guardrail", () => {
+ const s = summarizeTurn(
+ [{ name: "Write" }, { name: "Bash" }],
+ ['VAULT_DIR=/tmp/vault o2b brain note "v0.10.10 released"'],
+ );
+ expect(s).toEqual({ hadArtifact: true, hadBrainEvent: true });
+ });
+
+ test("echoing `o2b brain note` text does NOT clear guardrail", () => {
+ const s = summarizeTurn(
+ [{ name: "Write" }, { name: "Bash" }],
+ ['echo \'o2b brain note "not executed"\''],
+ );
+ expect(s).toEqual({ hadArtifact: true, hadBrainEvent: false });
+ });
+
+ test("commented `o2b brain note` text does NOT clear guardrail", () => {
+ const s = summarizeTurn(
+ [{ name: "Write" }, { name: "Bash" }],
+ ['# o2b brain note "not executed"'],
+ );
+ expect(s).toEqual({ hadArtifact: true, hadBrainEvent: false });
+ });
+
+ test("quoted `o2b brain note` after a separator does NOT clear guardrail", () => {
+ const s = summarizeTurn(
+ [{ name: "Write" }, { name: "Bash" }],
+ ['echo "; o2b brain note not executed"'],
+ );
+ expect(s).toEqual({ hadArtifact: true, hadBrainEvent: false });
+ });
+
+ test("actual `o2b brain note` after a separator clears guardrail", () => {
+ const s = summarizeTurn(
+ [{ name: "Write" }, { name: "Bash" }],
+ ['cd /tmp && o2b brain note "executed"'],
+ );
+ expect(s).toEqual({ hadArtifact: true, hadBrainEvent: true });
+ });
+
+ test("`o2b brain notes` lookalike does NOT clear guardrail", () => {
+ // Trailing-space anchor in the needle list prevents a future
+ // `notes` / `note-...` verb from being silently treated as a
+ // brain event.
+ const s = summarizeTurn(
+ [{ name: "Write" }, { name: "Bash" }],
+ ["o2b brain notes --vault /tmp/x"],
+ );
+ expect(s).toEqual({ hadArtifact: true, hadBrainEvent: false });
+ });
+
test("artifact + `o2b brain query` does NOT clear guardrail (read-only)", () => {
const s = summarizeTurn(
[{ name: "Write" }, { name: "Bash" }],
diff --git a/tests/mcp/brain-context.test.ts b/tests/mcp/brain-context.test.ts
new file mode 100644
index 00000000..d64d3d2b
--- /dev/null
+++ b/tests/mcp/brain-context.test.ts
@@ -0,0 +1,210 @@
+/**
+ * MCP integration tests for the `brain_context` tool (v0.10.10).
+ *
+ * Drives Β§5 of `docs/plans/2026-05-20-v0.10.10-design.md` β€” the
+ * read-only pull-bootstrap tool that returns `Brain/active.md`
+ * verbatim plus counts for runtimes without a `SessionStart` hook
+ * (Cursor, Aider, raw Claude API).
+ *
+ * Exercises the full server path (`MCPServer.handleRequest β†’
+ * tools/call β†’ handler`) so registration drift is caught here too.
+ */
+
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ test,
+} from "bun:test";
+import {
+ existsSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ unlinkSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ JSONRPC_VERSION,
+ MCPServer,
+ PROTOCOL_VERSION,
+} from "../../src/mcp/index.ts";
+import { buildToolTable } from "../../src/mcp/tools.ts";
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { brainActivePath } from "../../src/core/brain/paths.ts";
+import { writePreference } from "../../src/core/brain/preference.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+
+let tmp: string;
+let vault: string;
+let configHome: string;
+let configPath: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-brain-context-"));
+ vault = join(tmp, "vault");
+ configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-brain-context-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ for (const k of [
+ "VAULT_AGENT_NAME",
+ "VAULT_TIMEZONE",
+ "VAULT_DIR",
+ "OPEN_SECOND_BRAIN_CONFIG",
+ ]) {
+ savedEnv[k] = process.env[k];
+ delete process.env[k];
+ }
+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;
+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+ for (const [k, v] of Object.entries(savedEnv)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+});
+
+async function initialize(server: MCPServer): Promise<void> {
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "brain-context-test", version: "0" },
+ },
+ });
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ method: "notifications/initialized",
+ });
+}
+
+async function callContext(server: MCPServer): Promise<Record<string, unknown>> {
+ const r = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 7,
+ method: "tools/call",
+ params: { name: "brain_context", arguments: {} },
+ })) as { result: { content: ReadonlyArray<{ type: string; text: string }> } };
+ // Tool returns are wrapped as `content: [{type:"text", text:"<json>"}]`.
+ const text = r.result.content[0]!.text;
+ return JSON.parse(text);
+}
+
+describe("brain_context tool registration", () => {
+ test("appears in the full tool table", () => {
+ const tools = buildToolTable("full");
+ expect(tools.find((t) => t.name === "brain_context")).toBeDefined();
+ });
+
+ test("appears in the writer scope (always-loaded)", () => {
+ const tools = buildToolTable("writer");
+ expect(tools.find((t) => t.name === "brain_context")).toBeDefined();
+ });
+
+ test("writer scope still hosts the three Brain writers", () => {
+ const names = buildToolTable("writer").map((t) => t.name).sort();
+ expect(names).toEqual(
+ ["brain_apply_evidence", "brain_context", "brain_feedback", "brain_note"].sort(),
+ );
+ });
+});
+
+describe("brain_context tool β€” Brain absent", () => {
+ test("returns present:false with empty content and zero counts", async () => {
+ // No bootstrapBrain β€” Brain/ does not exist.
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const out = await callContext(server);
+ expect(out["present"]).toBe(false);
+ expect(out["content"]).toBe("");
+ expect(out["generated_at"]).toBeNull();
+ const counts = out["counts"] as Record<string, number>;
+ expect(counts.confirmed).toBe(0);
+ expect(counts.quarantine).toBe(0);
+ expect(counts.retired_recent).toBe(0);
+ expect(counts.most_applied_30d).toBe(0);
+ });
+});
+
+describe("brain_context tool β€” Brain present", () => {
+ beforeEach(() => {
+ bootstrapBrain(vault, { configPath });
+ });
+
+ test("self-heals active.md when it is missing", async () => {
+ // bootstrapBrain may already create active.md; remove it so we
+ // exercise the regenerateActive self-heal path.
+ const active = brainActivePath(vault);
+ if (existsSync(active)) unlinkSync(active);
+
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const out = await callContext(server);
+ expect(out["present"]).toBe(true);
+ expect(typeof out["content"]).toBe("string");
+ expect(out["content"] as string).toContain("# Active Brain Preferences");
+ expect(existsSync(active)).toBe(true);
+ });
+
+ test("returns the active.md body verbatim once it exists", async () => {
+ writePreference(vault, {
+ slug: "demo",
+ topic: "demo",
+ principle: "Demo principle",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 0,
+ violated_count: 0,
+ last_evidence_at: null,
+ confidence: "medium",
+ scope: "writing",
+ });
+
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const out = await callContext(server);
+ const fromDisk = readFileSync(brainActivePath(vault), "utf8");
+ expect(out["content"]).toBe(fromDisk);
+ expect(typeof out["generated_at"]).toBe("string");
+ const counts = out["counts"] as Record<string, number>;
+ expect(counts.confirmed).toBe(1);
+ expect(typeof counts.most_applied_30d).toBe("number");
+ });
+
+ test("two consecutive calls return byte-equal content", async () => {
+ writePreference(vault, {
+ slug: "demo",
+ topic: "demo",
+ principle: "Demo principle",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 0,
+ violated_count: 0,
+ last_evidence_at: null,
+ confidence: "medium",
+ });
+
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const first = await callContext(server);
+ const second = await callContext(server);
+ expect(second["content"]).toBe(first["content"]);
+ expect(second["generated_at"]).toBe(first["generated_at"]);
+ });
+});
diff --git a/tests/mcp/brain.test.ts b/tests/mcp/brain.test.ts
index 47bc64ad..8d3e4174 100644
--- a/tests/mcp/brain.test.ts
+++ b/tests/mcp/brain.test.ts
@@ -807,9 +807,16 @@ describe("brain_note tool schema visibility", () => {
test("brain_note belongs to the writer tool scope", () => {
const writer = buildToolTable("writer").map((t) => t.name);
expect(writer).toEqual(
- expect.arrayContaining(["brain_feedback", "brain_apply_evidence", "brain_note"]),
+ expect.arrayContaining([
+ "brain_feedback",
+ "brain_apply_evidence",
+ "brain_note",
+ // v0.10.10 added the `brain_context` reader to the same scope
+ // so runtimes without a SessionStart hook can fetch active.md
+ // without going through ToolSearch.
+ "brain_context",
+ ]),
);
- // Writer scope is exactly these three β€” nothing else.
- expect(writer).toHaveLength(3);
+ expect(writer).toHaveLength(4);
});
});
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index b0aa6ab8..9e49a599 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -155,11 +155,13 @@ describe("tool listing", () => {
"second_brain_status",
"second_brain_query",
"vault_health",
- // Brain (brain_note added in v0.10.8 Β§32B).
+ // Brain (brain_note added in v0.10.8 Β§32B,
+ // brain_context added in v0.10.10).
"brain_feedback",
"brain_dream",
"brain_apply_evidence",
"brain_note",
+ "brain_context",
"brain_digest",
"brain_query",
"brain_doctor",
@@ -363,9 +365,9 @@ describe("stdio loop", () => {
const list = JSON.parse(lines[1]!);
expect(init.id).toBe(1);
expect(list.id).toBe(2);
- // v0.10.8: 3 core (status/query/health) + 8 Brain (brain_note added Β§32B)
- // + 8 Pay Memory + 1 Search = 20.
- expect(list.result.tools.length).toBe(20);
+ // v0.10.10: 3 core (status/query/health) + 9 Brain (brain_note Β§32B
+ // and brain_context v0.10.10) + 8 Pay Memory + 1 Search = 21.
+ expect(list.result.tools.length).toBe(21);
});
test("returns parse error for invalid JSON", async () => {
@@ -424,6 +426,7 @@ describe("serveStdioFromString respects scope+name", () => {
.map((t) => t.name).sort();
expect(toolNames).toEqual([
"brain_apply_evidence",
+ "brain_context",
"brain_feedback",
"brain_note",
]);
diff --git a/tests/mcp/scope-filter.test.ts b/tests/mcp/scope-filter.test.ts
index d0b9a10a..2c6a21d4 100644
--- a/tests/mcp/scope-filter.test.ts
+++ b/tests/mcp/scope-filter.test.ts
@@ -13,11 +13,12 @@ describe("buildToolTable scope filter", () => {
expect(full.length).toBeGreaterThanOrEqual(15);
});
- test("writer scope returns exactly the three writer tools (Β§32B v0.10.8)", () => {
+ test("writer scope returns the three writers plus brain_context (v0.10.10)", () => {
const writer = buildToolTable("writer");
const names = writer.map((t) => t.name).sort();
expect(names).toEqual([
"brain_apply_evidence",
+ "brain_context",
"brain_feedback",
"brain_note",
]);