Skip to content
Agent Memory
Hook

Hooks

What open-second-brain runs automatically, and when. A hook is a command Claude Code fires at a fixed moment, without you asking for it.

From plugin
open-second-brain
6046 skills9 hooks

Claude Code

> /plugin marketplace add itechmeat/open-second-brain
> /plugin install open-second-brain@open-second-brain

What fires, and when

PostToolUse

  • Matchesbrain_feedbackr="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" session-capture; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook session-capture; exit 0
  • MatchesWrite|Edit|MultiEdit|apply_patchr="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" post-write-reminder; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook post-write-reminder; exit 0r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" subagent-inject; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook subagent-inject; exit 0
  • Matches*r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" reground-deliver; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook reground-deliver; exit 0

SessionStart

Fires once when a session begins, and again after a context compaction. It is where a plugin sets up its environment, or restores state the compaction dropped.

  • Matchesstartup|resume|clear|compactr="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" active-inject; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook active-inject; exit 0r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" gap-agenda; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook gap-agenda; exit 0r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" backlog-nudge; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook backlog-nudge; exit 0r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" log-catchup; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook log-catchup; exit 0r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" view-render; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook view-render; exit 0r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" session-capture; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook session-capture; exit 0

UserPromptSubmit

Fires before Claude sees each prompt you send. A plugin can use it to inject context, so the same instruction reaches the model every turn instead of only at session start.

  • Matches*r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" session-capture; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook session-capture; exit 0r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" recall-inject; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook recall-inject; exit 0r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" nav-inject; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook nav-inject; exit 0r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" neighbour-updates; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook neighbour-updates; exit 0r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" counterparty-brief; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook counterparty-brief; exit 0r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" reground-deliver; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook reground-deliver; exit 0

PreToolUse

  • Matches*r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" pretool-orient; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook pretool-orient; exit 0
  • MatchesWrite|Edit|MultiEdit|apply_patchr="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" pretool-host-backup; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook pretool-host-backup; exit 0

Stop

  • Matches*r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" session-capture; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook session-capture; exit 0r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" stop-log-guardrail; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook stop-log-guardrail; exit 0r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" answer-quote-check; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook answer-quote-check; exit 0r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" hygiene-digest; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook hygiene-digest; exit 0

SubagentStart

  • Matches*r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" subagent-inject; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook subagent-inject; exit 0

SubagentStop

  • Matches*r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" session-capture; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook session-capture; exit 0

SessionEnd

  • Matches*r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" session-capture; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook session-capture; exit 0r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" gap-promote; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook gap-promote; exit 0

PostCompact

  • Matchesmanual|autor="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" active-inject; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook active-inject; exit 0r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" session-capture; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook session-capture; exit 0
Read hooks/hooks.json

Where it lives

  • hooks/active-inject.tsGitHub
    Read the script
    #!/usr/bin/env -S bun
    /**
     * SessionStart / PostCompact hook: inject the current `Brain/active.md`
     * digest as `additionalContext` so the agent sees the live set of
     * confirmed and quarantined preferences without explicitly calling
     * `brain_query` first.
     *
     * Three lanes share the surface, and the order between them is the point.
     * `Brain/standing-rules.md` is operator-authored and goes FIRST, read
     * outside the fail-open memory load so it survives a memory-layer
     * failure and never enters the inject cache. The scoped operator rules
     * for this session's project and this device
     * (`Brain/standing-rules/{project,host}/<key>.md`) come next, also read
     * outside the boundary and never cached - the cache key is vault-wide, so
     * a cached block could replay one project's rules in another - but
     * charged against the injection budget. Everything after them - runtime
     * notices, `active.md`, `lessons.md` - is what the agent learned about
     * itself, assembled inside the fail-open boundary and charged against
     * what is left of the configured injection budget.
     *
     * One ceiling over all of it: the host takes at most 10,000 characters of
     * context from one hook and replaces a longer value with a file path and
     * a preview, so the whole payload of one run - every lane above, the
     * notices, the framing and the separators - is sized to
     * `HOST_CONTEXT_CEILING_CHARS` (`hooks/lib/host-context-ceiling.ts`).
     * The memory bodies share what the lanes ahead of them leave; a payload
     * the operator's caps still push past it is cut there with the usual
     * truncation notice. Only a payload the re-delivery lane splits is sized
     * per part instead.
     *
     * Contract (identical for Claude Code and Codex):
     *   stdin: hook payload JSON. The vault path is resolved from the
     *     persisted Open Second Brain config (env `VAULT_DIR` → config
     *     `vault:` field), not from the payload — both runtimes route the
     *     hook through the same `o2b-hook` PATH-shim, so this stays
     *     runtime-agnostic.
     *   stdout: JSON of the shape
     *     {
     *       "hookSpecificOutput": {
     *         "hookEventName": "SessionStart" | "PostCompact",
     *         "additionalContext": "<standing-rules block, the scoped rules
     *                               block, then the budgeted memory context:
     *                               runtime notices, the rendered
     *                               Brain/active.md body, lessons>"
     *       }
     *     }
     *
     * Quiet on the failure modes that leave it with nothing to say (no config,
     * no vault, malformed payload): the hook exits 0 with no output and the
     * runtime proceeds as if it never ran. A SessionStart that silently fails
     * is far less harmful than one that aborts the session with a stderr
     * trace. The agent simply does not get the per-session preferences nudge —
     * exactly the v0.9.0 behaviour.
     *
     * A missing `Brain/active.md` is NOT one of those modes any more, and
     * neither is a memory layer that threw. The standing-rules lane is read
     * outside the fail-open boundary, so a vault whose operator wrote rules
     * still emits them with an empty memory context behind them; a rules file
     * that exists and cannot be read emits the block that says so. The empty
     * exit is reached only when there are NEITHER standing rules NOR memory,
     * and `tests/hooks/active-inject.test.ts` asserts it.
     */
    
    import { resolveAnswerQuoteCheckModes } from "../src/core/brain/quote-check-modes.ts";
    import {
      resolveQuoteCheckEnabled,
      resolveRecallInjectEnabled,
      resolveRegroundPartChars,
      resolveRegroundPartsEnabled,
    } from "../src/core/config.ts";
    import { healCliSymlinks } from "../src/cli/install-cli.ts";
    import { ensureVaultCurrent } from "../src/core/maintenance/ensure-current.ts";
    import { hookAuditDir } from "../src/core/brain/paths.ts";
    import { loadInjectContextFailOpen } from "../src/core/brain/inject-failopen.ts";
    import { armProcessCeiling, decisionWaitMs, resolveHookCeilingMs } from "./lib/process-ceiling.ts";
    import { appendAuditRecord } from "../src/core/reliability/audit.ts";
    import { asHookPayload, readHookInput, type HookPayloadBase } from "./lib/stdin.ts";
    import {
      beginInjectionEpoch,
      digestDeliveredText,
      digestNotePaths,
      isRealSessionId,
    } from "./lib/injection-ledger.ts";
    import {
      LANE_BUDGETED,
      LANE_UNBUDGETED,
      renderStandingBlock,
      type InjectionMeter,
    } from "./lib/standing-block.ts";
    import { buildAgentContextBlocks } from "./lib/agent-context-blocks.ts";
    import {
      assembleActiveContext,
      BLOCK_SEPARATOR,
      createInjectionMeter,
      joinBlocks,
      MEMORY_SOURCES,
      renderScopedBlock,
      resolveInjectionLimits,
      scopedSectionCap,
      SOURCE_ACTIVE_BODY,
      SOURCE_DIGEST_CUT_NOTE,
      SOURCE_LESSONS_BODY,
      type InjectionLimits,
    } from "./lib/active-context.ts";
    import { pruneHookStateFiles } from "./lib/session-state.ts";
    import { detectHookRuntime } from "./lib/detect.ts";
    import { splitRegroundParts } from "../src/core/brain/reground-parts.ts";
    import { isContextEventName } from "./lib/context-events.ts";
    import { emitContextReceipt } from "../src/core/brain/context-receipts.ts";
    import { estimateTokens } from "../src/core/brain/text/tokenizer.ts";
    import type { InjectContextSource } from "../src/core/brain/inject-failopen.ts";
    import { resolveHookTarget } from "./lib/hook-vault.ts";
    import {
      fitHostContext,
      HOST_CONTEXT_CEILING_CHARS,
      hostMeasureFor,
      type HostMeasure,
    } from "./lib/host-context-ceiling.ts";
    import {
      DIGEST_CUT_NOTE_RESERVE,
      type DigestCut,
      parseDigestCuts,
      renderDigestCutNote,
    } from "../src/core/agent-context/digest-cut-note.ts";
    
    /**
     * Best-effort hook audit line. Never throws: a failure to record must never
     * disturb the fail-soft hook contract, and a hung filesystem is exactly when
     * this runs, so it is wrapped defensively.
     */
    function auditHook(vault: string | null, action: string, details: Record<string, unknown>): void {
      if (vault === null) return;
      try {
        appendAuditRecord(hookAuditDir(vault), {
          timestamp: new Dat
  • hooks/answer-quote-check.tsGitHub
    Read the script
    #!/usr/bin/env -S bun
    /**
     * Stop hook: answer-time quote verification (answer-trust wave, Lane A).
     *
     * At turn end this step reads the LAST assistant messages of the turn,
     * finds their quoted spans with the distill lane's own
     * `findQuoteSpans`, and checks each span against the evidence the turn
     * actually had:
     *
     *   - the note the span cites - a wikilink target or a vault-relative
     *     path in the message text, resolved against the vault; and
     *   - otherwise the notes the injection ledger says entered context this
     *     session, across the four phase keys (recall keys, the active
     *     digest's emitted paths plus its queued re-delivery parts, and the
     *     note paths the sub-agent carrier recorded with its deliveries).
     *
     * Each span gets one verdict from
     * `src/core/brain/answer-quotes/check.ts` - `verified`, `not-in-note`,
     * `source-truncated`, `note-unavailable` or `not-text` - and the
     * unverified ones are listed in exactly ONE
     * `hookSpecificOutput.additionalContext` annotation (the
     * `hooks/stop-log-guardrail.ts` precedent). The hook NEVER blocks and
     * NEVER edits the transcript: a verdict is reported, not enforced.
     *
     * Phases. A phase runs only when BOTH hold: the phase's injection is
     * enabled (recall requires `recall_inject_enabled`; active and subagent
     * require a live injection ledger for the session) and its
     * `quote_check.<phase>` resolver returns more than `off`.
     * `shadow` annotates only; `enforce` additionally appends exactly one
     * Brain-log event per turn with the unverified spans, so findings survive
     * the session - and never blocks.
     *
     * Channel. This hook is synchronous and does every read and every durable
     * write itself (the `reply_presence` record and the `enforce` Brain-log
     * event below). On Claude Code with the default
     * `stop_advisory_delivery: "async"` it prints nothing: the annotation -
     * worded as a finding about "the previous answer" - is handed over
     * (hooks/lib/stop-advisory-handover.ts) to the async `stop-advisory-deliver`
     * hook, whose `hookSpecificOutput.additionalContext` reaches the model with
     * the next user message, unprinted and without a model turn of its own. A
     * one-shot `claude -p` run kills that async hook at teardown and so loses
     * the annotation, never a record. With `"sync"` the annotation rides a
     * synchronous Stop `additionalContext`, which Claude Code prints as "Stop
     * hook says: ..." and answers with one more turn. Codex and grok accept the
     * registration but read no Stop annotation - and grok ships no
     * `transcript_path` at all - so the check is silently inert on them:
     * fail-open silence, kept deliberately, with the `enforce` Brain-log
     * trail as the one finding surface that survives the session.
     *
     * Switch. `quote_check_enabled: "false"` (machine config, env
     * `OPEN_SECOND_BRAIN_QUOTE_CHECK_ENABLED`) turns the whole hook off
     * before any read: no annotation, no Brain-log event, no presence record.
     *
     * Reply presence (t_f8510c55). Wherever a transcript exists - annotation
     * rendering or not - every checked turn also appends exactly one
     * `reply_presence` continuity record: per injected note, whether a
     * quoted span verified against it, its strongest miss verdict, `absent`
     * when no span was ever measured against it, or `note-unavailable` when
     * the budget cut the walk before the note could be measured. A span
     * that verified is measured against the note that carries it alone, so
     * the per-note verdicts hold whichever way the candidates sort. The
     * record is keyed by session id and joined to the session's context
     * receipts on read; identifiers and verdicts only, never answer text.
     * The presence record rides the same per-phase modes: every phase `off`
     * writes nothing.
     *
     * Bounded, fail-open. The step reads at most
     * {@link ANSWER_QUOTE_TAIL_BYTES} of the transcript, the last
     * {@link ANSWER_QUOTE_MAX_MESSAGES} assistant messages of the turn,
     * {@link ANSWER_QUOTE_MAX_CHARS} characters of each, and gives up by
     * checking nothing further once {@link ANSWER_QUOTE_BUDGET_MS} have
     * passed - unchecked spans are dropped rather than run long. Every error
     * path exits 0 with exactly one stderr audit line, producing nothing.
     * Fires at most once per turn: when the runtime reports
     * `stop_hook_active === true` (this turn was already continued by a Stop
     * hook) the hook exits 0 silently.
     */
    
    import {
      closeSync,
      existsSync,
      fstatSync,
      openSync,
      readFileSync,
      readSync,
      statSync,
    } from "node:fs";
    import { createHash } from "node:crypto";
    
    import {
      resolveAgentName,
      resolveQuoteCheckEnabled,
      resolveRecallInjectEnabled,
      type AnswerQuoteCheckMode,
      type AnswerQuoteCheckPhase,
      ANSWER_QUOTE_CHECK_PHASES,
    } from "../src/core/config.ts";
    import {
      ANSWER_QUOTE_VERDICT,
      checkAnswerQuotes,
      mergeAnswerQuoteVerdicts,
      previewAnswerQuoteSpan,
      type AnswerQuoteEvidence,
      type AnswerQuoteVerdict,
    } from "../src/core/brain/answer-quotes/check.ts";
    import { findQuoteSpans } from "../src/core/brain/distill/quote-spans.ts";
    import { resolveAnswerQuoteCheckModes } from "../src/core/brain/quote-check-modes.ts";
    import { compiledDigestPath } from "../src/core/brain/compiled-digest-path.ts";
    import { insideBrain, lanePagesInStore } from "../src/core/store/lane-entry-store.ts";
    import {
      neutralizeUntrustedText,
      untrustedFramingHeader,
    } from "../src/core/brain/untrusted-source.ts";
    import { appendLogEvent } from "../src/core/brain/log.ts";
    import { BRAIN_LOG_EVENT_KIND } from "../src/core/brain/types.ts";
    import { isoSecond } from "../src/core/brain/time.ts";
    import { appendContinuityRecord } from "../src/core/brain/continuity/store.ts";
    import { CONTINUITY_SESSION_ID_KEY } from "../src/core/brain/continuity/types.ts";
    import { ensureInsideVault } from "../src/core/path-safety.ts";
    import { asHookPayload, type HookPayloadBase, readHookInput } from "./lib/stdin.ts";
    import { stopAdvisoryHandsOver, writeStopAdvisoryHandover } from "./lib/stop-advisory-handove
  • hooks/backlog-nudge.tsGitHub
    Read the script
    #!/usr/bin/env -S bun
    /**
     * SessionStart hook: opt-in undistilled backlog nudge (session-mining-economy,
     * t_0358af42).
     *
     * When `backlog_nudge_enabled` is set (default OFF), reports how many
     * imported sessions have never been distilled, as ONE `additionalContext`
     * line, so the agent starts the session aware of the backlog still waiting.
     * The count comes from the vault-side mining census
     * (`src/core/brain/sessions/mining-census.ts`), which reads the import
     * ledger joined to the mining record and never hashes a source log - the
     * honest count is affordable inside this hook's budget.
     *
     * The nudge is change-keyed, not timed: the line is injected when the
     * undistilled count differs from the count injected last (state:
     * hooks/lib/backlog-nudge-state.ts, one overwrite-only file beside the
     * hygiene digest). An unchanged backlog is never re-nagged, and a drained
     * backlog is recorded without being announced - a line that says there is
     * nothing to do is the noise this hook exists to avoid.
     *
     * Under the deadline the hook degrades to silence, never to a fabricated
     * number: the census runs under the process ceiling's cooperative
     * safeguard, and a census that cannot verify its ledgers names the failure
     * on stderr and injects nothing.
     *
     * Flag off is an immediate no-op with zero output, keeping the session
     * preamble byte-identical. Fail-open: the hook arms the shared process
     * ceiling and exits 0 on every path.
     */
    
    import { resolveBacklogNudgeEnabled } from "../src/core/config.ts";
    import { isContextEventName } from "./lib/context-events.ts";
    import {
      armProcessCeiling,
      ceilingSafeguard,
      resolveHookCeilingMs,
    } from "./lib/process-ceiling.ts";
    import { backlogNudgeCountMatches, writeBacklogNudgeCount } from "./lib/backlog-nudge-state.ts";
    import { asHookPayload, readHookInput } from "./lib/stdin.ts";
    import { resolveHookTarget } from "./lib/hook-vault.ts";
    import { fitHostContextFor } from "./lib/host-context-ceiling.ts";
    
    async function main(): Promise<void> {
      // Fast opt-out FIRST: default OFF means an immediate no-op, no output.
      if (!resolveBacklogNudgeEnabled()) return;
    
      const ceilingMs = resolveHookCeilingMs();
      const disarm = armProcessCeiling({ ceilingMs });
      try {
        let payload;
        try {
          payload = asHookPayload(await readHookInput());
        } catch {
          return;
        }
    
        const hookEventName =
          typeof payload.hook_event_name === "string" && payload.hook_event_name.length > 0
            ? payload.hook_event_name
            : "SessionStart";
        // Default-closed: only an additionalContext-eligible event may emit.
        if (!isContextEventName(hookEventName)) return;
    
        // With no vault the hook does its store-side part (design D14, task 2.10).
        const target = resolveHookTarget();
        if (target === null) return;
        const vault = target.vault;
    
        // Loaded only here, after every gate: the census and its ledger chain
        // are the one heavy import, and a flag-off session start pays nothing
        // for them (the hygiene-digest hook's lazy-load precedent).
        const { buildMiningCensus } = await import("../src/core/brain/sessions/mining-census.ts");
        let count: number;
        try {
          count = buildMiningCensus(vault, { safeguard: ceilingSafeguard(ceilingMs) }).undistilled;
        } catch (err) {
          // Never block, never guess: a census that cannot verify its ledgers
          // says why and injects nothing.
          process.stderr.write(
            `backlog-nudge: the backlog census failed: ${(err as Error).message ?? String(err)}\n`,
          );
          return;
        }
    
        // Changed-count gate. A missing or corrupt state file compares unequal,
        // so the next eligible session emits again (lose-not-duplicate).
        if (backlogNudgeCountMatches(vault, count)) return;
    
        // A drained backlog is recorded, not announced.
        if (count <= 0) {
          writeBacklogNudgeCount(vault, count);
          return;
        }
    
        const sessions = count === 1 ? "session" : "sessions";
        const line =
          `Open Second Brain session backlog: ${count} imported ${sessions} not yet distilled. ` +
          "Run 'o2b brain import-session --status' for the per-runtime breakdown, or " +
          "'o2b brain import-session --propose-backlog --json' for the next sessions to mine.";
        process.stdout.write(
          JSON.stringify({
            hookSpecificOutput: { hookEventName, additionalContext: fitHostContextFor(payload, line) },
          }) + "\n",
        );
    
        // The state lands AFTER the emit: a crash in between loses the dedupe
        // and the next eligible session emits again, rather than never.
        writeBacklogNudgeCount(vault, count);
      } finally {
        disarm();
      }
    }
    
    main().catch(() => {
      // Never crash the runtime; the session start must proceed regardless.
    });
    
  • hooks/counterparty-brief.tsGitHub
    Read the script
    #!/usr/bin/env -S bun
    /**
     * UserPromptSubmit hook: the opt-in counterparty brief (dated commitments,
     * t_43b0a379).
     *
     * When `counterparty_brief_enabled` is set (default OFF) AND the operator
     * declared a `counterparty_brief_triggers` vocabulary (machine-local main
     * config), the first prompt of a session that names exactly one canonical
     * counterparty and carries a trigger token injects a small dated brief of
     * shareable facts about that person as `additionalContext`. The decision
     * core is src/core/brain/counterparty-brief.ts; this entry script only
     * wires the payload, the flag, the ledger and the envelope:
     *
     *   - OPT-IN and INERT-BY-DEFAULT: the flag is checked first (byte-identical
     *     no-op when off), and an empty trigger vocabulary stays inert - the
     *     requirement is documented in hooks/README.md, and nothing ships a
     *     natural-language word list.
     *   - ONCE PER SESSION: the injection ledger records the delivered entity
     *     id after the stdout write; a later prompt of the same session emits
     *     nothing. A payload without a real session id neither emits nor
     *     records: suppression is impossible without a session, and an
     *     unrecordable brief would repeat on every prompt.
     *   - SHAREABLE-ONLY: the core excludes pages whose visibility carries the
     *     reserved token regardless of reach, because a hook-injected block
     *     leaves the machine; withheld pages contribute nothing and are not
     *     counted.
     *   - FAIL-OPEN FOR THE SESSION: every path exits 0; the shared process
     *     ceiling arms against a hung vault, and any internal error is
     *     silence, never a blocked prompt.
     *   - AUDITED: one structured audit line per decision (counts and reasons
     *     only - never the prompt text or the brief content) lands in the
     *     LOCAL hook-audit trail; the line counts the pages the brief could
     *     not read, so a degraded walk is visible instead of silent.
     *
     * Contract mirrors recall-inject.ts: stdin is the hook payload JSON; the
     * vault is resolved from the environment/config, not the payload; stdout,
     * when present, is the standard `hookSpecificOutput.additionalContext`
     * envelope.
     */
    
    import {
      defaultConfigPath,
      resolveCounterpartyBriefEnabled,
      resolveCounterpartyBriefTriggers,
    } from "../src/core/config.ts";
    import { appendAuditRecord } from "../src/core/reliability/audit.ts";
    import {
      buildCounterpartyBrief,
      renderCounterpartyBrief,
    } from "../src/core/brain/counterparty-brief.ts";
    import { hookAuditDir } from "../src/core/brain/paths.ts";
    import {
      isRealSessionId,
      readBriefDelivered,
      recordBriefDelivered,
    } from "./lib/injection-ledger.ts";
    import { armProcessCeiling, resolveHookCeilingMs } from "./lib/process-ceiling.ts";
    import { asHookPayload, readHookInput } from "./lib/stdin.ts";
    import { isContextEventName } from "./lib/context-events.ts";
    import { resolveHookTarget } from "./lib/hook-vault.ts";
    import { fitHostContextFor } from "./lib/host-context-ceiling.ts";
    
    /** Runtime identity on the audit record. */
    const HOOK_ACTOR = "counterparty-brief";
    
    /**
     * One best-effort audit line per decision. Never throws and never records
     * the prompt text or the brief content - only the decision, its reason,
     * the matched entity id and bounded counts.
     */
    function audit(vault: string, ok: boolean, details: Record<string, unknown>): void {
      try {
        appendAuditRecord(hookAuditDir(vault), {
          timestamp: new Date().toISOString(),
          actor: HOOK_ACTOR,
          action: "counterparty_brief_decision",
          target: "UserPromptSubmit",
          ok,
          details,
        });
      } catch {
        // best-effort: auditing must never disturb the fail-open contract
      }
    }
    
    async function main(): Promise<void> {
      // Fast opt-out FIRST: default OFF is an immediate no-op, no process
      // ceiling armed, no payload read, no output - byte-identical to before.
      if (!resolveCounterpartyBriefEnabled()) return;
    
      let auditVault: string | null = null;
      const disarm = armProcessCeiling({
        ceilingMs: resolveHookCeilingMs(),
        onExpire: () => {
          if (auditVault !== null) {
            audit(auditVault, false, { decision: "error", reason: "hook_ceiling_exceeded" });
          }
        },
      });
      try {
        let payload;
        try {
          payload = asHookPayload(await readHookInput());
        } catch {
          return;
        }
    
        const hookEventName =
          typeof payload.hook_event_name === "string" && payload.hook_event_name.length > 0
            ? payload.hook_event_name
            : "UserPromptSubmit";
        // Default-closed: only an additionalContext-eligible event may emit.
        if (!isContextEventName(hookEventName)) return;
    
        const prompt = typeof payload.prompt === "string" ? payload.prompt : "";
    
        // With no vault the hook does its store-side part (design D14, task 2.10).
        const target = resolveHookTarget();
        if (target === null) return;
        const vault = target.vault;
        auditVault = vault;
    
        const triggers = resolveCounterpartyBriefTriggers(defaultConfigPath());
        // Inert without an operator-declared vocabulary - the safe direction,
        // disclosed in hooks/README.md rather than doctor-surfaced.
        if (triggers.length === 0) {
          audit(vault, false, { decision: "abstain", reason: "no_triggers" });
          return;
        }
    
        const sessionId = isRealSessionId(payload.session_id) ? payload.session_id : null;
        // A sessionless host gets neither a brief nor a ledger write: the
        // once-per-session promise cannot be kept without a session, and an
        // unrecordable brief would repeat on every prompt.
        if (sessionId === null) {
          audit(vault, false, { decision: "abstain", reason: "no_session" });
          return;
        }
    
        let delivered: string | null = null;
        try {
          delivered = readBriefDelivered(vault, sessionId);
        } catch {
          delivered = null;
        }
        if (delivered !== null) {
          audit(vault, false, { decision: "abstain", reason: "already_delivered", entity: delivered });
          return;
        }
    
        const b
  • hooks/gap-agenda.tsGitHub
    Read the script
    #!/usr/bin/env -S bun
    /**
     * SessionStart hook: opt-in knowledge-gap agenda (theme A, t_67d38036).
     *
     * When `gap_loop_enabled` is set (default OFF), renders the open recall-gap
     * task notes as a compact agenda and injects it as `additionalContext` so
     * the agent starts the session aware of the recurring gaps still unresolved.
     * The agenda is rendered through the shared session-start activity helper.
     *
     * Flag off is an immediate no-op with zero output, keeping the session
     * preamble byte-identical. Fail-open: the hook arms the shared process
     * ceiling and exits 0 on every path.
     */
    
    import { resolveGapLoopEnabled } from "../src/core/config.ts";
    import { renderGapAgenda } from "../src/core/brain/gaps/gap-loop.ts";
    import { armProcessCeiling, resolveHookCeilingMs } from "./lib/process-ceiling.ts";
    import { asHookPayload, readHookInput } from "./lib/stdin.ts";
    import { isContextEventName } from "./lib/context-events.ts";
    import { resolveHookTarget } from "./lib/hook-vault.ts";
    import { fitHostContextFor } from "./lib/host-context-ceiling.ts";
    
    async function main(): Promise<void> {
      // Fast opt-out FIRST: default OFF means an immediate no-op, no output.
      if (!resolveGapLoopEnabled()) return;
    
      const disarm = armProcessCeiling({ ceilingMs: resolveHookCeilingMs() });
      try {
        let payload;
        try {
          payload = asHookPayload(await readHookInput());
        } catch {
          return;
        }
    
        const hookEventName =
          typeof payload.hook_event_name === "string" && payload.hook_event_name.length > 0
            ? payload.hook_event_name
            : "SessionStart";
        // Default-closed: only an additionalContext-eligible event may emit.
        if (!isContextEventName(hookEventName)) return;
    
        // With no vault the hook does its store-side part (design D14, task 2.10).
        const target = resolveHookTarget();
        if (target === null) return;
        const vault = target.vault;
    
        const agenda = renderGapAgenda(vault, new Date());
        if (agenda.length === 0) return;
    
        const out = {
          hookSpecificOutput: {
            hookEventName,
            additionalContext: fitHostContextFor(payload, agenda),
          },
        };
        process.stdout.write(JSON.stringify(out) + "\n");
      } finally {
        disarm();
      }
    }
    
    main().catch(() => {
      // Never crash the runtime; the session start must proceed regardless.
    });
    
  • hooks/gap-promote.tsGitHub
    Read the script
    #!/usr/bin/env -S bun
    /**
     * SessionEnd hook: opt-in knowledge-gap promotion and auto-close (theme A,
     * t_67d38036).
     *
     * When `gap_loop_enabled` is set (default OFF), at session end:
     *   1. every recurring recall gap (from the recall-telemetry gap_counts
     *      aggregate, above a tunable threshold) promotes to ONE durable
     *      gap-task note under the Brain area, deduped on a stable gap key so
     *      re-promotion never collides;
     *   2. every open gap task whose topic now recalls with sufficient
     *      confidence auto-closes (a recorded status flip in frontmatter),
     *      mirroring the dream freshness auto-resolve precedent.
     *
     * Gap-task notes are plain durable files; they never touch the Hermes
     * kanban board. Flag off writes nothing (byte-identical no-op). Fail-open:
     * the hook arms the shared process ceiling and exits 0 on every path; a
     * best-effort audit line records the run's counts, and a run that threw
     * records a `gap_loop_failed` line plus a stderr notice instead of
     * vanishing. SessionEnd cannot carry additionalContext, so this hook never
     * writes stdout.
     */
    
    import {
      defaultConfigPath,
      resolveGapLoopEnabled,
      resolveGapLoopThreshold,
    } from "../src/core/config.ts";
    import { appendAuditRecord } from "../src/core/reliability/audit.ts";
    import { hookAuditDir } from "../src/core/brain/paths.ts";
    import { gapScopedRecallRetriever } from "../src/core/brain/gaps/gap-recall.ts";
    import { autoCloseRecalledGaps, promoteGapsToTasks } from "../src/core/brain/gaps/gap-loop.ts";
    import { armProcessCeiling, resolveHookCeilingMs } from "./lib/process-ceiling.ts";
    import { asHookPayload, readHookInput } from "./lib/stdin.ts";
    import { resolveHookTarget } from "./lib/hook-vault.ts";
    
    /**
     * The vault this run resolved, remembered for the failure path.
     *
     * A failure is only auditable once the vault is known, and the vault is
     * resolved inside the run - so the failure reporter reads it from here
     * rather than re-resolving (which could itself be the thing that threw).
     */
    let auditedVault: string | null = null;
    
    function auditRun(vault: string, details: Record<string, unknown>): void {
      try {
        appendAuditRecord(hookAuditDir(vault), {
          timestamp: new Date().toISOString(),
          actor: "gap-promote",
          action: "gap_loop_run",
          target: "SessionEnd",
          ok: true,
          details,
        });
      } catch {
        // best-effort: auditing must never disturb the fail-open contract
      }
    }
    
    /**
     * Report a run that threw, on both channels, and never rethrow.
     *
     * Fail-open is about the SESSION, not about the fault: swallowing the
     * throw silently is what let a retriever that ignored its membership rule
     * leave this hook doing nothing at all, run after run, with no trace
     * anywhere - a fallback that quietly does nothing, which this repository
     * does not allow. So the failure lands as its OWN audit action (`ok:
     * false`), never as a `gap_loop_run` row: a run that threw produced no
     * counts, and a counts row with zeros would read as a quiet, healthy
     * no-op - exactly the report this fault already got away with. Stderr
     * carries it too, for the operator who is not reading the audit log.
     *
     * Every step is individually guarded, because this is the last frame
     * before the process exits and there is nothing left to catch it.
     */
    function reportRunFailure(exc: unknown): void {
      const kind = exc instanceof Error ? exc.name : typeof exc;
      const message = exc instanceof Error ? exc.message : "";
      try {
        process.stderr.write(`gap-promote: gap loop failed [${kind}] ${message}\n`);
      } catch {
        // a closed stderr must not become the crash the fail-open forbids
      }
      if (auditedVault === null) return;
      try {
        appendAuditRecord(hookAuditDir(auditedVault), {
          timestamp: new Date().toISOString(),
          actor: "gap-promote",
          action: "gap_loop_failed",
          target: "SessionEnd",
          ok: false,
          details: { error: kind, message },
        });
      } catch {
        // best-effort: auditing must never disturb the fail-open contract
      }
    }
    
    async function main(): Promise<void> {
      // Fast opt-out FIRST: default OFF means an immediate no-op, no writes.
      if (!resolveGapLoopEnabled()) return;
    
      const disarm = armProcessCeiling({ ceilingMs: resolveHookCeilingMs() });
      try {
        try {
          asHookPayload(await readHookInput());
        } catch {
          return;
        }
    
        // With no vault the hook does its store-side part (design D14, task 2.10).
        const target = resolveHookTarget();
        if (target === null) return;
        const vault = target.vault;
        auditedVault = vault;
        const configPath = defaultConfigPath();
        const now = new Date();
        const threshold = resolveGapLoopThreshold(configPath);
    
        const promotion = promoteGapsToTasks(vault, {
          now,
          ...(threshold !== undefined ? { threshold } : {}),
        });
        const closure = await autoCloseRecalledGaps(
          vault,
          // NOT `defaultRecallRetriever`: that one takes only the query, and a
          // one-parameter function is structurally assignable here, so it
          // compiled while silently ignoring the membership rule - returning
          // the gap-task note itself and making the gate throw on every run.
          gapScopedRecallRetriever(configPath, vault),
          { now },
        );
        auditRun(vault, {
          promoted: promotion.created.length,
          skipped: promotion.skipped.length,
          // Both bounds the run enforces are reported, never dropped: a pruned
          // count explains a shrinking directory, and a non-zero cap refusal is
          // the operator's only signal that gap tasks are being turned away.
          pruned: promotion.pruned.length,
          capped: promotion.capped,
          closed: closure.closed.length,
          kept: closure.kept.length,
          // Why a recall narrowed (a gated query embed, a missing semantic
          // lane) rides this local line only, present only when non-empty.
          ...(closure.retrievalDegraded !== undefined
            ? { retrieval_degraded: closure.retrievalDegraded }
           
  • hooks/hygiene-digest.tsGitHub
  • hooks/log-catchup.tsGitHub
  • hooks/nav-inject.tsGitHub
  • hooks/neighbour-updates.tsGitHub
  • hooks/post-write-reminder.tsGitHub
  • hooks/pretool-host-backup.tsGitHub
  • hooks/pretool-orient.tsGitHub
  • hooks/recall-inject.tsGitHub
  • hooks/reground-deliver.tsGitHub
  • hooks/session-capture.tsGitHub
  • hooks/stop-log-guardrail.tsGitHub
  • hooks/subagent-inject.tsGitHub
  • hooks/view-render.tsGitHub

All 19 scripts are listed above. The source is inlined for 6 of them, starting with whatever hooks.json actually runs. See all of them in the repo.

Read the script before you install anything that runs on your machine. This is the one part of a plugin that acts without being asked.

@itechmeat
Ships withopen-second-brain

Open Second Brain is a memory layer for AI agents that lives in an Obsidian vault. Agents read and write it through MCP servers, lifecycle hooks and the o2b CLI.

Stars on GitHub

Momentum

stars in total
604
Star history of itechmeat/open-second-brain on GitHub, a chart by star-history.com

More plugins that ship hooks.

mempalace

mempalace

Gives Claude Code a private memory that stays on your machine. It stores past conversations word for word, so you can ask what was decided, what happened before, or who was involved and get the original context back. It can also hand tasks to other agents.

3 skills+361k
@milla-jovovich@milla-jovovich
Install Plugin
mempalace

mempalace

Local-first memory for Claude Code. It stores conversations verbatim in a private palace you can search before answering about past work, people, projects, or decisions, with optional shared-brain hub setup.

3 skills+361k
@mempalace@mempalace
Install Plugin
context-mode

context-mode

Keeps large command outputs, logs and data files out of your AI assistant's context by running processing in a sandbox and returning only the relevant parts. You also get a searchable index of local files and diagnostics for checking the setup.

4 skills4 hooks34k
@mksglu@mksglu
Install Plugin
context-mode

context-mode

Keeps large tool outputs, logs, and files out of Claude Code's context window by processing them in a sandbox and indexing them for focused search. Includes diagnostics and a knowledge base indexer.

4 skills4 hooks34k
@mksglu@mksglu
Install Plugin
ai-memory

ai-memory

Gives coding agents a git-backed wiki for long-term project memory, with skills for retrieval, durable notes, session handoffs between agents, cross-project messaging, and memory consolidation.

7 skills+216k
@akitaonrails@akitaonrails
Install Plugin
letta-code

letta-code

A coding agent harness whose agents keep memory and identity across sessions, so they learn and improve over time. You can run it in a terminal, in the browser, or through Telegram, Slack and Discord.

26 skills8 hooks3.9k
@letta-ai@letta-ai
Install Plugin
token-optimizer

token-optimizer

Audits a Claude Code or Codex setup for context-window waste, fixes it with the user's approval, and measures the savings. It also tracks costs, helps resume prior sessions, and offers a usage dashboard.

5 skills+23k
@alexgreensh@alexgreensh
Install Plugin
claude-subconscious

claude-subconscious

A background agent for Claude Code that watches your sessions and reads your files, builds up memory over time, and offers guidance back during your work.

4 hooks2.9k
@letta-ai@letta-ai
Install Plugin

Questions about the hooks in open-second-brain.

Which coding agents can use the hooks in open-second-brain?
The hooks in open-second-brain install in Claude Code and Cursor: each runs Claude Code hooks from .claude/settings.json, so copy the hooks there.