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
56.6 KB
Raw Blame

Open Second Brain β€” runtime hooks

Plugin-bundled lifecycle hooks for Claude Code and Codex. The hooks make sure every turn that produces a durable artifact records the corresponding event in Brain/log/<date>.md (and its JSONL sidecar). Brain/log/ is the single agent-facing log surface; Daily/ remains as the human-CLI surface β€” populated by o2b append-event from cron-jobs and shell scripts, not by agents.

Hermes and OpenClaw deliberately do not load these hooks. Hermes already injects an identity / writer-tool reminder via its pre_llm_call plugin shim, so the same nudge arrives through a different channel without duplicating subsystems. OpenClaw's native JS plugin format predates these hooks. If either runtime grows a Claude-style hook schema later, point its config at hooks/hooks.json and the same scripts will work β€” they only depend on the documented hook payload shape, not on the runtime.

What the hooks do

Event Matcher Behaviour
SessionStart startup|resume|clear|compact Injects the budgeted Brain/active.md body (default 8,000 chars, active.inject_budget_chars in _brain.yaml) and records a non-blocking session-lifecycle observation. The compact matcher is the post-compaction re-injection path. Since v1.95.0 the session_inject context receipt this lane emits carries the payload's real session id as its session_id member (absent when the host sent none), the join key the receipt's reply_presence read joins on.
SessionStart startup|resume|clear|compact Opt-in (log_catchup_enabled in the machine-local config.yaml - NOT _brain.yaml; the gate reads the main config, like every default-OFF boolean - or OPEN_SECOND_BRAIN_LOG_CATCHUP_ENABLED, default off): log-catchup hands the agent the Brain/log lines OTHER agents appended since its identity's last look on this device - newest 50 as one fenced additionalContext block, a count of older ones, every line attributed to the agent that wrote it. "Me" resolves the config-resolved agent name, else the device id; self-authored lines are filtered. A first run has no cursor to read since: its scan is bounded to five dates behind the newest real date in the log (LOG_CATCHUP_FIRST_RUN_WINDOW_DATES) β€” older days are counted, never parsed (on a store-only machine the store's records are read once and the older days skipped), and reported once as N older day(s) not scanned (as a header-only block when nothing foreign surfaced), emitted only when that run's cursor write parks below, so the report never repeats against an unreadable window. The cursor is one un-synced (date, shardId, line) watermark with per-shard high-water marks per reading identity, under .open-second-brain/log-catchup.<identity>-<digest>.cursor.json in the machine state (the vault on an unswitched machine, the device-local state once store-only or with no vault) (the identity sanitized into the file name, <digest> 8 hex of the raw name so colliding identities never share a file; overwrite-only, symlink-guarded, fail-soft). It is rewritten on every run that actually scanned the log - silent runs included, so an idle vault does not rescan history at each start - keeping a three-date window of marks. The lane is a pure read - Brain/log is byte-identical after every run and stays distinct from the session-capture lifecycle event - and exits 0 on every path.
SessionStart startup|resume|clear|compact On the view writer device, renders the brain store's human view at most once an hour inside half the hook ceiling (view-render.ts); every other machine, and one without a store or a device id, does nothing. Prints nothing; a failed, refused, busy or deferred page is one line in the device-local hook audit.
UserPromptSubmit * Captures explicit @osb feedback ... markers from the submitted prompt immediately through the signal/dedup boundary.
UserPromptSubmit * Opt-in (reground_parts_enabled, default off): reground-deliver hands out the next queued part of an oversized SessionStart payload as additionalContext. A prompt carries a part rather than cancelling the queue, because after a manual /compact the next event is usually a prompt.
UserPromptSubmit * Opt-in (counterparty_brief_enabled in the machine-local config.yaml, or OPEN_SECOND_BRAIN_COUNTERPARTY_BRIEF_ENABLED, default off): counterparty-brief injects a dated brief of shareable facts about the counterparty the prompt names - at most three items, drawn from open pledges (Brain/pledges/) first (due-sorted) and then preference pages (most recent first among the pages the read cap covered; an item without a date renders undated), each with its source page. HARD REQUIREMENT: the flag alone does nothing without a non-empty counterparty_brief_triggers list in the same machine-local config (comma-separated tokens in the operator's language; an empty or malformed list stays inert, and nothing ships a built-in word list). The brief fires only when the prompt carries at least one trigger token AND names exactly one canonical-scope entity (zero or several matches abstain). Shareable-only: a page whose visibility: carries the reserved private token never surfaces, even though the hook runs locally, because a hook-injected block leaves the machine; an item drawn from a pledge and its cited source inherits the strictest visibility of the two. At most once per session via the injection ledger (a failed record costs one repeat, never a lost brief); a payload without a real session id neither emits nor records. Every path exits 0 under the shared process ceiling; one audit line per decision (the decision, its reason, the matched entity id and bounded counts - never the prompt text or the brief content) lands in the local hook-audit trail.
PreToolUse Write|Edit|MultiEdit|apply_patch Opt-in (host_settings_backup, default off): pretool-host-backup snapshots the current content of any .claude/settings.json or .claude/settings.local.json the call is about to write - into the sibling <dir>/.o2b-backups/<name>/ folder beside the target, each backup a FILE named with the UTC stamp (a same-second collision ladders the name) - and appends one audit receipt before the call is allowed to proceed. A backup that cannot be taken denies the call. Success emits nothing: an explicit allow would pre-approve the very write this hook exists to guard. .codex/config.toml is deliberately unmatched - o2b brain protect's own fence manages it. An apply_patch call carries its targets inside the patch body, so every *** Update File: / *** Add File: / *** Delete File: header is parsed and each protected path is backed up. A settings file that is itself a symlink (stow-style dotfiles) is protected through its lexical path, and the backup reads through the link. On first use the .o2b-backups/ root receives a .gitignore holding * (plus !.gitignore), so a project-level backup - a copy of a settings.local.json that can carry tokens - is never left unignored for the next git add -A to commit.
PostToolUse brain_feedback Replays successful brain_feedback tool input immediately through the same signal/dedup boundary.
PostToolUse Write|Edit|MultiEdit|apply_patch Emits additionalContext pointing at the three Brain writer tools. The full reminder is shown once per Claude Code session; later writes get a one-line nudge (Codex one-shot runs always get the full text).
PostToolUse Write|Edit|MultiEdit|apply_patch Fallback carrier for runtimes without a SubagentStart event: delivers the operator's context payload into a delegated sub-agent's turn at its first write-shaped call. A non-empty agent_id marks a tool call made inside a sub-agent; the main thread gets nothing. Fires once per sub-agent per session - the same delivery ledger the SubagentStart row below feeds, so on a host with both events the writes of a sub-agent already served at its start stay silent - and stays silent for read-only subagents and an entirely empty payload; a failed rules read delivers the explicit failure block instead. The ledger keeps the most recent 200 agent ids, so a session that spawns more than that re-delivers to an evicted id. Every runtime gets the PostToolUse hookSpecificOutput.additionalContext envelope (the additive-context channel the reminder row above uses); decision: "block" stays Stop-only, where it means continue-the-turn rather than reject-the-write.
PostToolUse * Opt-in (reground_parts_enabled, default off): reground-deliver hands out exactly one queued part per event (try-once lock, cursor advanced before printing, so a part is never duplicated) until the queue is empty or the next SessionStart replaces it. A tool call inside a sub-agent (the payload carries agent_id) takes nothing, so the part stays queued for the main agent. Claude Code and Codex only. Checks the flag before resolving the vault, so it is cheap when off.
SubagentStart * Primary carrier: delivers the operator's context payload into a delegated sub-agent's context at its conversation start, before its first prompt, and again if the subagent compacts - the host re-fires the event then, and the re-injection lands only if this hook answers that later event. The payload is what the session-start lane composes, through the same assembly: the standing rules, the scoped operator rules for this project and device, and the budgeted Brain/active.md + Brain/lessons.md digest under the same active.inject_budget_chars ceiling (runtime notices ride along when that channel is on). No tool gating - the event itself marks the sub-agent - and no ledger suppression: every SubagentStart for the id re-delivers, while the ledger it feeds after each delivery keeps the PostToolUse fallback row above to once per sub-agent per session. Runtimes without a SubagentStart event never fire this row; the fallback covers them.
PostCompact manual|auto Records a post-compact lifecycle observation only. Current Claude Code has no PostCompact hook event and rejects additionalContext under that name - re-injection moved to the SessionStart compact matcher; the registration stays as a silent no-op for older runtimes.
Stop (every Stop) If the turn produced a durable artifact and none of brain_feedback / brain_apply_evidence / brain_note landed, continues the turn once with a one-line reminder, then lets the second Stop pass. Claude Code gets hookSpecificOutput.additionalContext (shown as "Stop hook feedback", not a hook error); Codex, Grok Build and unrecognised runtimes get decision: "block" with the same line as reason.
Stop (every Stop) answer-quote-check verifies the quoted spans in the assistant's answer against the evidence the turn actually had: the note a span's context names (wikilink or vault-relative path), else membership in the injection ledger's delivered notes for the phases running. Five verdicts - verified, not-in-note, source-truncated, note-unavailable, not-text - and degradation never upgrades one: a note whose body reached context truncated arms source-truncated on a miss, an unreadable note arms note-unavailable, never an all-clear. Per-phase config in _brain.yaml (quote_check.recall, quote_check.active, quote_check.subagent, each off|shadow|enforce, default shadow); enforce also appends exactly one Brain-log note event per turn so findings survive the session. One non-blocking hookSpecificOutput.additionalContext annotation per turn lists the unverified spans as flattened, capped previews; Claude Code renders it, other runtimes stay silent. Never blocks, never edits a transcript: bounded message-window and character reads, fail-open exit 0. Since v1.95.0 every checked turn also folds ONE session-keyed reply_presence continuity record - a verdict per injected note (verified when a reply span checked out against it, the strongest miss verdict otherwise, absent when no span was ever measured against it, note-unavailable when the hook's time budget ran out before any span reached it or the turn's reply text never arrived), written even when every span verified and only when the turn had injected candidates at all. The record carries identifiers and verdicts only - never answer text (the answer is bound by hash) - and the session's records are what the receipt read surfaces join on: a receipt join matches the session by exact session id and folds every record written at or after the receipt's own creation, chronologically, with verified winning across turns, so one turn's record never answers for another's. A host that sends no real session id has no injection ledger to read, so the turn writes no presence record at all, and a receipt join then reads unjoined, which is the honest report rather than a fault.
Stop (every Stop) Opt-in (hygiene_digest_enabled, default off): hygiene-digest surfaces pending Brain hygiene findings as one line, once per change. Artifact-writing turns run the default sweep plus the dangling-link count; findings of warning and action severity fold into counts per detector, and a hash ledger keeps an unchanged set silent. Claude Code only: the line rides its non-blocking hookSpecificOutput.additionalContext Stop feedback, and on runtimes where a Stop block would force a continuation turn (Codex, Grok Build, unrecognised) the hook stays silent - an opt-in digest never buys a continuation. Checked before the vault, so it is cheap when off.
SubagentStop * Records a non-blocking lifecycle observation for a delegated sub-agent's close, attributed to <delegator>-sub-<agent-id> from the agent_id the event carries. The sibling agent_transcript_path is deliberately not persisted - it is a machine-local host path, and the sub-agent's turns reach memory through o2b brain import-session, which reads isSidechain and agentId off the transcript itself.
SessionEnd * Records a non-blocking lifecycle observation for session close.

Both PreToolUse gates are opt-in and checked before anything else, so the off path is a byte-identical no-op. Their deny channel is stdout hookSpecificOutput.permissionDecision: "deny", because scripts/o2b-hook is deliberately fail-soft and always exits 0. The guarantee has an honest hard floor: a missing bun, a missing hook script, or the dispatcher swallowing a non-zero exit means no deny at all and the write proceeds unprotected. The backup gate's matcher is the file-tool family on purpose: classifying Bash commands (redirections, cp, tee) is textual matching the repo avoids, so shell-class writes to a settings file are not covered, and a temp-then-rename or symlink-swap write can land on a different path than the one that was canonicalized and backed up.

Per-session hook state (nav-tier and orientation stamps, the recall dedupe set and the re-grounding queue) lives in one JSON file per session under .open-second-brain/hook-state/. The files are written with mode 0600, because the queue holds parts of the SessionStart payload. When .open-second-brain or hook-state is a symbolic link, the hooks neither read nor write nor prune that tree: reads answer empty and writes fail open. The SessionStart prune removes scope files, leftover temp files and abandoned locks older than seven days.

The Stop guardrail respects the runtime-provided stop_hook_active flag: it fires at most once per turn, so the agent can deliberately decide that an edit was trivial and skip logging by just finishing again. No deadlocks.

The reminder is one line on purpose (STOP_GUARDRAIL_TEXT in lib/messages.ts): Claude Code prints Stop hook output in the user's transcript, and until v1.58.2 a decision: "block" reason of about 25 lines showed up there as a red "Stop hook error" on every guarded turn. What to do when it fires is documented for the model in the brain-memory skill ("End-of-turn check"). Stop hooks cannot use a channel that is hidden from the user entirely; the model-only channel is the PostToolUse additionalContext reminder that already follows each write.

JSONL sidecar

Every event the writer lands in Brain/log/<date>.md is mirrored to Brain/log/<date>.jsonl in the same atomic step (one proper-lockfile lock for the pair). Machine consumers (o2b discipline report today, future tooling tomorrow) read JSONL through src/core/brain/log-jsonl.ts:readLogDay, which falls back to parsing markdown on days that pre-date v0.10.8. Hand-editing the markdown does not break the reader; deleting the JSONL forces the fallback path until the next write rebuilds it.

The retired event_log_append MCP tool no longer exists in any 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 Code looks for hooks/hooks.json at the plugin root by convention; Codex auto-loads the same file when the plugin manifest's "hooks" field points at it (set in both .codex-plugin/plugin.json and plugins/codex/.codex-plugin/plugin.json).

    Layout: Codex's marketplace source is ./plugins/codex/, and codex plugin add copies only that subtree into its plugin cache, dropping symlinks on the way. So plugins/codex/hooks/hooks.json is a real file generated from this one by bun run sync-plugin-mirrors, and CI gates it with bun run sync-plugin-mirrors:check (the same goes for plugins/codex/skills/, which is a byte copy of skills/). The one difference: SessionEnd timeouts are capped at Codex's 3 s limit, which Codex enforces anyway and warns about on every run otherwise. Only hooks.json is mirrored, never the *.ts scripts: Codex exports CLAUDE_PLUGIN_ROOT as the cache dir, and o2b-hook would pick a cached script there whose ../src imports do not exist. Edit hooks/hooks.json, then run the sync.

  • view-render.ts - Bun entry script that keeps the human view current. On the view writer device it runs one render pass of the brain store's human view, at most once an hour and inside half the hook ceiling; any other machine reads only the view writer records and stops, and a machine without a store or a device id does nothing. Prints nothing; a failure, a page deferred by the budget, or a page it could not write is one line in the device-local hook audit. Fail-open exit 0.

  • log-catchup.ts β€” Bun entry script for the opt-in cross-agent catch-up. Reads Brain/log through listLogDates/readLogDay only on an unswitched machine; on a store-only or no-vault one it reads the store's log-event records from the oldest date its cursor vouches about, the writing device standing in for the shard id and each event's index among that device's events of the day, in append order, for the line; filters self lines by a trimmed entry.agent comparison (in device-fallback mode, with no configured agent name, this device's shards count as self too - the consequence is that several unconfigured runtimes on one device do not see each other, because no per-agent identity exists to key on), renders the newest lines under the shared untrusted fence, and advances the per-identity derived-store cursor whenever the scan actually moved - also on a silent run, so an idle vault does not rescan history at each start; the cursor holds back only when none of the collected lines fit the block, while the lines the line or character cap cut are counted as older and then skipped. Never writes to Brain/log; fail-open exit 0.

  • session-capture.ts β€” Bun entry script that handles lifecycle observations and immediate marker/tool-feedback capture. It emits no stdout to the runtime; writes go to Brain signals plus session-lifecycle audit/log rows.

  • post-write-reminder.ts / stop-log-guardrail.ts β€” Bun entry scripts. They are tiny by design: they parse stdin, query lib/transcript.ts and lib/detect.ts, and emit the hook's JSON response on stdout. Never block on errors.

  • answer-quote-check.ts β€” Bun entry script for the Stop hook's answer-time quote verification (since v1.81.0). It reads the transcript's bounded tail window, resolves each quoted span's cited note or injection-ledger evidence, checks it through src/core/brain/answer-quotes/check.ts, and answers with one additionalContext annotation listing the unverified spans; in enforce it also appends one Brain-log event. Since v1.95.0 it folds one session-keyed reply_presence continuity record per checked turn (a verified / strongest-miss / absent verdict per injected note, or note-unavailable for a note the time budget left unmeasured or a turn whose reply text never arrived, from the same measured outcomes the annotation comes from; the receipt read surfaces join the session's records by exact session id, folding every record written at or after the receipt's own creation with verified winning across turns). Never blocks, never edits a transcript, fail-open.

  • counterparty-brief.ts β€” Bun entry script for the opt-in UserPromptSubmit counterparty brief (dated-commitments wave). Thin by design: the flag and the trigger vocabulary are checked first, the decision core is src/core/brain/counterparty-brief.ts (exactly-one entity, shareable-only items, named caps), the delivered entity id is recorded in the injection ledger after the stdout write, and every path exits 0.

  • lib/stdin.ts β€” read the single JSON object both runtimes send on stdin.

  • lib/transcript.ts β€” JSONL parser that recognises both the Claude Code shape (top-level {type:"user"|"assistant", message: {content:[...]}}) and the Codex shape ({type:"response_item", payload:{type:"function_call"|"custom_tool_call", name}}).

  • lib/detect.ts β€” canonical lists of artifact / log tool names.

  • lib/messages.ts β€” reminder + block text. Kept here so it can be unit-tested without a hook subprocess.

How both runtimes find the hook commands

Each hooks.json command resolves the launcher version-currently, with a fallback, and can never block:

r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" <name>; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook <name>; exit 0
  • Claude Code sets CLAUDE_PLUGIN_ROOT to the active plugin version directory, so the command runs scripts/o2b-hook from the version Claude Code just loaded β€” never a stale copy.
  • Codex exports CLAUDE_PLUGIN_ROOT too, but as its plugin cache dir, which holds only the Codex plugin subtree (hooks.json and the skills) and no scripts/o2b-hook. So the command falls through to the PATH o2b-hook shim (o2b install-cli puts it on PATH; on a server it points at the stable checkout, which never rotates).
  • If neither resolves, the command exit 0s β€” a missing launcher is a no-op, never a blocked turn.
  • Codex on Windows runs a hook as %COMSPEC% /C "<command>", which cannot parse the POSIX form, so the Codex mirror (plugins/codex/hooks/hooks.json, generated by bun run sync-plugin-mirrors) gives every hook a commandWindows: set NoDefaultCurrentDirectoryInExePath=1& where /q $PATH:o2b-hook && o2b-hook <name> & exit /b 0. It runs the PATH o2b-hook.cmd that o2b install-cli writes, never one in the project Codex opened, and always exits 0.

scripts/o2b-hook itself resolves the checkout root in the same order ($CLAUDE_PLUGIN_ROOT β†’ its own realpath β†’ $OSB_PLUGIN_ROOT) and is fail-soft: any unresolved hook, missing Bun, or other internal error prints a warning to stderr and exits 0. It must never exit 2 β€” that is the only hook exit code Claude Code treats as blocking.

The global ~/.local/bin/{o2b,o2b-hook,vault-log} symlinks are self-healing: the SessionStart active-inject hook calls healCliSymlinks() from the current checkout, re-pointing a dangling or plugin-cache-stale OSB symlink with no user action (it leaves stable-directory installs, foreign symlinks, and real files untouched).

Invariant for anyone editing hooks, the launcher, or install-cli β€” updates must never break existing installs. A plugin update rotates the versioned cache directory under ~/.claude/plugins/cache/..., so any resolution that pins to a specific version path (a PATH symlink into a cache dir, a hard-coded version, a stored absolute path) WILL dangle on the next update. Always:

  1. resolve the launcher via $CLAUDE_PLUGIN_ROOT first (Claude Code re-reads hooks.json from the active version each session, so a correct command shape here repairs an already-broken install on the next update);
  2. keep hooks fail-soft β€” exit 0 on every internal error, never exit 2, never a hard command not found trace as the only path;
  3. keep symlink resolution self-healing and conservative (never hijack a stable-dir or foreign symlink).

These three properties are locked by tests/hooks/o2b-hook.test.ts, tests/hooks/hooks-json-shape.test.ts, and tests/cli/install-cli.test.ts. See docs/updating.md.

Local dev loop

The plugin lives at /srv/projects/open-second-brain/ and Claude Code / Codex are wired to that directory via local marketplaces (extraKnownMarketplaces in ~/.claude/settings.json, [marketplaces.open-second-brain] source_type = "local" in ~/.codex/config.toml). Both runtimes cache the installed plugin, so edits to hooks/*.ts don't auto-propagate.

After changing a hook script:

# Claude Code: refresh the local-marketplace cache and reinstall.
claude plugin marketplace update open-second-brain
claude plugin update open-second-brain@open-second-brain

# Codex: re-add the marketplace (there is no "upgrade" for local
# marketplaces; remove + add wipes the cache and re-stages the
# plugin tree from /srv/projects/open-second-brain/plugins/codex/).
codex plugin marketplace remove open-second-brain
codex plugin marketplace add /srv/projects/open-second-brain

Then exercise the hook end-to-end:

# Claude Code
claude -p 'create a tiny note.md in /tmp/x with content hello' \
    --output-format=stream-json --verbose --include-hook-events \
    --allowedTools 'Write Read' --add-dir /tmp/x

# Codex
codex exec --skip-git-repo-check 'create a tiny /tmp/x/note.md ...'

Expect the stream to show hook_started / hook_response events around each Write and around the Stop event; the agent's first reply gets the one-line reminder (Claude Code: Stop additionalContext; Codex: decision: "block") and it has to either log or send a second finishing message.

Unit tests

tests/hooks/*.test.ts exercises the library and spawns the hook entry scripts as subprocesses with synthetic stdin / JSONL transcripts. Run with:

bun test tests/hooks/

The subprocess tests inherit the test runner's cwd, not the plugin's, which matches production behaviour: Claude Code and Codex both spawn the hook in the user's session cwd, not in the plugin checkout. The scripts therefore must NEVER use process.cwd() to locate plugin files β€” resolve paths via import.meta.url or relative imports, as the current code does. If you ever need to read a vault path, take it from the hook payload or the persisted plugin config.