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.
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:
- 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.
brain_notehas no non-MCP entrypoint. Cron jobs and shell scripts cannot reach theBrain/log/<date>.mdnoteevent kind thatbrain_notewrites. They have to fall back tovault-log/o2b append-event(which write toDaily/), recreating the pre-v0.10.8 split the Β§32 deprecation was supposed to close.o2b statusis 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 tryo2b search statusoro2b 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_contextin the always-loaded writer-server scope that returns the currentBrain/active.mdbody plus structured counts. Discoverable withoutToolSearch, callable without arguments, idempotent. - Extend
Brain/active.mdwith a new## Most-applied (30d)section listing up to tenconfirmed/quarantinepreferences with the highest count ofapply-evidence (result: applied)events whosetimestampfalls 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 MCPbrain_notetool one-to-one for cron jobs and shell scripts. The CLI and the MCP handler share a singleappendBrainNotecore function. - Extend
o2b statuswith a single-line semantic-search hint. Printsemantic: off (run 'o2b search check' for setup steps)in human-output andsemantic_enabled/embedding_key_present/semantic_hintkeys in--jsonwheneversemantic_enabledisfalseor 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 fullactive.mdbody; callers that want a slice already havebrain_query. - Configurable
Most-appliedwindow 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.yamlknob in a later release. - Multi-line
o2b brain note(--stdinetc.). 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/activealready 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-writereven 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
- If
Brain/is not present in the vault: returnpresent: false,content: "",countsall zero,generated_at: null. No error. New vaults are a valid state for this tool to describe. - Otherwise: call
regenerateActive(vault). That function is idempotent β it writes only when the body differs from disk, so calling it on everybrain_contextinvocation costs at most the preference + retired + log walk it would do during dream. Use the returnedcountsdirectly. If the call throws (disk full, permission error), returnpresent: true,content: "", zero counts,generated_at: null, and the error message inerror: string. - Read
Brain/active.mdfrom disk and parse its frontmatter to pullgenerated_at. The file is guaranteed to exist after step- Return the full body in
content.
- Return the full body in
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:
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:
now = opts.now ?? new Date().limit = opts.limit ?? 10.- Window
[now - 30 * 24 * 3600 * 1000, now]in milliseconds. - Build a
Map<string, BrainPreference>keyed bynormaliseWikilinkTarget(pref.id)from thepreferencesargument (already filtered toconfirmed | quarantineupstream). - Walk
Brain/log/. Use the same allow-list regex asstatus.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). - For each remaining day: call
readLogDay(vault, date)(existing JSONL-preferred reader). Iterateentries:e.eventTypemust equalBRAIN_LOG_EVENT_KIND.applyEvidence.e.resultmust 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).
- Tally
Map<string, number>keyed by the normalised preference id. - Sort descending by count, tiebreaker
idascending. Takelimit. - 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:
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:
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 witherror: brain note requires text.--agentβ override identity. Defaults toresolveAgentName(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 islogged 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:
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.
tests/core/brain/most-applied.test.tsβ drives Β§6.1.tests/core/brain/active.test.tsextensions β drives Β§6.2, Β§6.3.tests/mcp/brain-context.test.tsβ drives Β§5.tests/core/brain/note.test.tsβ drives Β§7.1.tests/cli/brain-note.test.ts(execFile-based) β drives Β§7.2.tests/hooks/detect.test.tsextensions β drives Β§7.3.tests/cli/status.test.tsβ drives Β§8.tests/e2e/v0.10.10-pull-channels.test.tsβ one happy-path coveringo2b brain notewriting toBrain/log/today.mdwith correct identity and thenoteevent 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_30dcount reflected.o2b status: human-output presence/absence under each of the four state matrices (enabled Γ key-present), JSON shape under same, suppression whensearch_enabledisfalse.hooks/detect: positive match foro2b brain note "β¦", negative match foro2b brain notes,o2b brain not-quite.
10. Implementation order
- Tests in Β§9.1 (most-applied), implementation in
src/core/brain/most-applied.ts. - Tests in Β§9.2 (active.md), wiring in
src/core/brain/active.ts. - Tests in Β§9.3 (brain_context), handler in
src/mcp/brain-tools.ts, registration insrc/mcp/tools.ts, instructions update insrc/mcp/instructions.ts. - Tests in Β§9.4 (appendBrainNote core), extraction from
src/mcp/brain-tools.tsintosrc/core/brain/note.ts. MCP handler refactored to thin wrapper; existing MCP tests stay green. - Tests in Β§9.5 (CLI verb), implementation in
src/cli/brain/verbs/note.ts, dispatcher insrc/cli/brain.ts, help text. - Tests in Β§9.6 (hook detector), needle list update.
- Tests in Β§9.7 (
o2b status), helper extraction insrc/cli/helpers.ts, render update insrc/cli/main.ts. - E2E in Β§9.8.
- 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".
- "Disputed / deferred" β the
brain_contextbullet 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
- via
_brain.yaml. Trigger: first operator request after shipping.
- via
- Rename the always-loaded MCP server from
open-second-brain-writerto something neutral (open-second-brain-coreor similar). Trigger: a second reader tool joins the writer scope. brain_contextfilters (scope,topic). Trigger: a real agent use case where the full active.md is too large.o2b brain note --stdinfor multi-line piping. Trigger: a real cron / script that wants multi-line. (MCPbrain_notedoes not support multi-line either; the limitation is intentional.)- Surfacing the Most-applied section through
brain_digestas a second hot block alongside the existingtop_applied(lifetime). Trigger: a digest reader who specifically wants both lifetime and windowed views in one render.
13. Risks
nowinjection in tests.computeMostAppliedacceptsnowviaopts.nowbecause the window calculation otherwise reads the system clock. Every caller in production passes the default (new Date()). Tests inject a fixednowfor deterministic windowing. This is the same patternactive.tsalready follows.- Reading 30 log days on every
regenerateActive. Worst case is 30 JSONL files Γ ~50 entries each.readLogDayis 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_NAMESdeclaration explaining the always-load rationale. Rename is deferred β see Β§12. o2b statusJSON shape grows three keys. Existing consumers do not depend on the JSON shape today (verified via the absence of astatus --jsontest outsidecli). The three new keys are always-present booleans / nullable string, additive only.