A self-organizing Obsidian vault that gives AI coding agents persistent memory.
TypeScript ai-agentsclaude-codecodex-cligemini-cliknowledge-managementobsidianobsidian-vaultpersistent-memorysecond-braintemplate
fix: a Stop block carries the report once, as its reason (#258)
Brenno Ferrari7b73e0f64a67
diff --git a/.claude/scripts/lib/hook-io.ts b/.claude/scripts/lib/hook-io.tsindex 3928fc5..effd667 100644--- a/.claude/scripts/lib/hook-io.ts+++ b/.claude/scripts/lib/hook-io.ts@@ -127,8 +127,10 @@ export function fitEncoded(text: string, max: number): string {}/**- * A Stop that hands `reason` to the agent now and gives it another turn,- * while showing the user `message` (#256).+ * A Stop that hands `reason` to the agent now and gives it another turn+ * (#256). The user reads the same text: Claude Code prints a block's reason+ * in the transcript, so a systemMessage beside it only showed the report+ * twice, the second copy cut to a third of the cap.** `decision: "block"` is the only Stop output that reaches the model; every* other field is for the user. It also gives the agent a turn nobody typed,@@ -138,13 +140,9 @@ export function fitEncoded(text: string, max: number): string {* its UI even on success; Codex documents the same field. Gemini runs the* checklist on SessionEnd and never gets it.*/-export function writeStopBlock(reason: string, message: string): void {- // Both copies share one output cap: the user's gets at most a third, the- // agent's whatever is left.- const shown = fitEncoded(message, Math.floor(HOOK_OUTPUT_MAX_CHARS / 3));- const overhead = JSON.stringify({ decision: "block", reason: "", systemMessage: shown }).length - 2;- const handed = fitEncoded(reason, HOOK_OUTPUT_MAX_CHARS - overhead);- process.stdout.write(JSON.stringify({ decision: "block", reason: handed, systemMessage: shown }));+export function writeStopBlock(reason: string): void {+ const overhead = JSON.stringify({ decision: "block", reason: "" }).length - 2;+ process.stdout.write(JSON.stringify({ decision: "block", reason: fitEncoded(reason, HOOK_OUTPUT_MAX_CHARS - overhead) }));}/**diff --git a/.claude/scripts/stop-checklist.ts b/.claude/scripts/stop-checklist.tsindex 016d601..58f7e85 100644--- a/.claude/scripts/stop-checklist.ts+++ b/.claude/scripts/stop-checklist.ts@@ -32,10 +32,12 @@** Output is JSON on every agent, never plain text. Codex rejects plain Stop* stdout, Gemini's SessionEnd contract requires a final JSON object, and- * Claude Code otherwise files non-exempt stdout in the debug log. The user- * gets the report in `systemMessage`, the one user-facing field all three- * agents share; the agent gets it as a Stop block's `reason` (above). Both- * are held under Claude Code's hook output cap (lib/hook-io.ts).+ * Claude Code otherwise files non-exempt stdout in the debug log. Where no+ * block is sent, the user gets the report in `systemMessage`, the one+ * user-facing field all three agents share. A Stop block's `reason` (above)+ * is printed in the transcript, so there the user reads the agent's copy and+ * no systemMessage is sent beside it. Either is held under Claude Code's hook+ * output cap (lib/hook-io.ts).* The documented event name is the only branch — no agent sniffing and no* agent-specific argument.*/@@ -154,7 +156,7 @@ const AGENT_PREFACE ="Stop hook report: your response just ended, and these findings are new or changed since the last report this session; the user was shown the same report. Decide what it calls for: act on what bears on the current work, ask the user when something needs their call, or reply in one line that nothing needs doing now. Never move or delete notes without asking, and do not recite the report back.";if (!show) writeSilentHookOutput();-else if (isStop && hasSession) writeStopBlock(`${AGENT_PREFACE}\n\n${message}`, message);+else if (isStop && hasSession) writeStopBlock(`${AGENT_PREFACE}\n\n${message}`);else writeSystemMessage(message);triggerDebouncedRefresh({diff --git a/.claude/scripts/tests/hook-io.test.ts b/.claude/scripts/tests/hook-io.test.tsindex c891356..aac5dfa 100644--- a/.claude/scripts/tests/hook-io.test.ts+++ b/.claude/scripts/tests/hook-io.test.ts@@ -129,14 +129,13 @@ function captureStdout(write: () => void): string {// "x" encodes to one character, so the cut can land exactly on the cap:// these tests assert the exact length, which catches an off-by-one either way.describe("writeStopBlock — the whole output fits", () => {- test("a huge report and message fill the cap exactly, both marked as cut", () => {- const out = captureStdout(() => writeStopBlock("x".repeat(20_000), "x".repeat(20_000)));+ test("a huge report fills the cap exactly, marked as cut, and is the only field", () => {+ const out = captureStdout(() => writeStopBlock("x".repeat(20_000)));assert.equal(out.length, HOOK_OUTPUT_MAX_CHARS);- const parsed = JSON.parse(out) as { decision: string; reason: string; systemMessage: string };- assert.equal(parsed.decision, "block");- assert.match(parsed.reason, /truncated to fit the hook output cap\)$/);- assert.match(parsed.systemMessage, /truncated to fit the hook output cap\)$/);- assert.ok(parsed.reason.length > parsed.systemMessage.length, "the agent's copy gets the larger share");+ const parsed = JSON.parse(out) as Record<string, string>;+ assert.deepEqual(Object.keys(parsed), ["decision", "reason"]);+ assert.equal(parsed["decision"], "block");+ assert.match(parsed["reason"] ?? "", /truncated to fit the hook output cap\)$/);});});diff --git a/.claude/scripts/tests/stop-checklist.test.ts b/.claude/scripts/tests/stop-checklist.test.tsindex f3c14fd..bf8384f 100644--- a/.claude/scripts/tests/stop-checklist.test.ts+++ b/.claude/scripts/tests/stop-checklist.test.ts@@ -92,9 +92,18 @@ function envelopeOf(stdout: string): Record<string, unknown> {}}-/** The envelope's systemMessage, failing loudly if absent. */-function systemMessageOf(stdout: string): string {- const message = envelopeOf(stdout)["systemMessage"];+/**+ * The report the user is shown, failing loudly if absent: a Stop block's+ * reason after the agent preface (Claude Code prints the reason in the+ * transcript), otherwise the systemMessage.+ */+function shownOf(stdout: string): string {+ const envelope = envelopeOf(stdout);+ if (envelope["decision"] === "block") {+ const reason = String(envelope["reason"]);+ return reason.slice(reason.indexOf("\n\n") + 2);+ }+ const message = envelope["systemMessage"];assert.equal(typeof message,"string",@@ -140,7 +149,7 @@ describe("stop-checklist", () => {test("the first Stop of a session reports the checklist and findings", () => {const root = vault("first-stop", "Done.md");- const message = systemMessageOf(run(stop("s-first"), { vault: root }).stdout);+ const message = shownOf(run(stop("s-first"), { vault: root }).stdout);assert.match(message, /Wrap-up checklist:/);assert.match(message, /work\/active\/Done\.md/);});@@ -151,7 +160,7 @@ describe("stop-checklist", () => {const first = run(stop("s-same"), { vault: root, state });const second = run(stop("s-same"), { vault: root, state });const third = run(stop("s-same"), { vault: root, state });- assert.match(systemMessageOf(first.stdout), /work\/active\/Done\.md/);+ assert.match(shownOf(first.stdout), /work\/active\/Done\.md/);assert.deepEqual(envelopeOf(second.stdout), {});assert.deepEqual(envelopeOf(third.stdout), {});});@@ -161,7 +170,7 @@ describe("stop-checklist", () => {const state = freshState();run(stop("s-change"), { vault: root, state });completeNote(root, "Also Done.md");- const message = systemMessageOf(run(stop("s-change"), { vault: root, state }).stdout);+ const message = shownOf(run(stop("s-change"), { vault: root, state }).stdout);assert.match(message, /work\/active\/Also Done\.md/);});@@ -175,9 +184,9 @@ describe("stop-checklist", () => {const b = run(stop("s-revert"), { vault: root, state });completeNote(root, "Done.md");const a2 = run(stop("s-revert"), { vault: root, state });- assert.match(systemMessageOf(a1.stdout), /work\/active\/Done\.md/);- assert.doesNotMatch(systemMessageOf(b.stdout), /Vault Hygiene/);- assert.match(systemMessageOf(a2.stdout), /work\/active\/Done\.md/);+ assert.match(shownOf(a1.stdout), /work\/active\/Done\.md/);+ assert.doesNotMatch(shownOf(b.stdout), /Vault Hygiene/);+ assert.match(shownOf(a2.stdout), /work\/active\/Done\.md/);});test("a note growing past the threshold does not re-show the report", () => {@@ -192,7 +201,7 @@ describe("stop-checklist", () => {const first = run(stop("s-grow"), { vault: root, state });writeFileSync(log, "x".repeat(40_000));const second = run(stop("s-grow"), { vault: root, state });- assert.match(systemMessageOf(first.stdout), /notes\/Log\.md \(26KB\)/);+ assert.match(shownOf(first.stdout), /notes\/Log\.md \(26KB\)/);assert.deepEqual(envelopeOf(second.stdout), {});});@@ -207,20 +216,21 @@ describe("stop-checklist", () => {const first = run(stop("s-two-grow"), { vault: root, state });writeFileSync(join(root, "notes/B.md"), "x".repeat(34_000));const second = run(stop("s-two-grow"), { vault: root, state });- assert.match(systemMessageOf(first.stdout), /notes\/A\.md \(30KB\)[\s\S]*notes\/B\.md \(26KB\)/);+ assert.match(shownOf(first.stdout), /notes\/A\.md \(30KB\)[\s\S]*notes\/B\.md \(26KB\)/);assert.deepEqual(envelopeOf(second.stdout), {});});test("a changed Stop report reaches the agent: decision block with the report as the reason (#256)", () => {// A Stop systemMessage never reaches the model. decision "block" is the// one Stop output that does, with a turn to act, ask, or say nothing- // needs doing; the user still sees the report.+ // needs doing. Claude Code prints the reason in the transcript, so the+ // user reads it there; a systemMessage beside it showed the report twice.const root = vault("block", "Done.md");const envelope = envelopeOf(run(stop("s-block"), { vault: root }).stdout);+ assert.deepEqual(Object.keys(envelope), ["decision", "reason"]);assert.equal(envelope["decision"], "block");const reason = String(envelope["reason"]);assert.match(reason, /^Stop hook report: .*ask the user when something needs their call/);- assert.ok(reason.endsWith(`\n\n${String(envelope["systemMessage"])}`), "the reason carries the report the user sees");assert.match(reason, /work\/active\/Done\.md/);});@@ -267,7 +277,7 @@ describe("stop-checklist", () => {const state = freshState();run(stop("s-one"), { vault: root, state });const other = run(stop("s-two"), { vault: root, state });- assert.match(systemMessageOf(other.stdout), /work\/active\/Done\.md/);+ assert.match(shownOf(other.stdout), /work\/active\/Done\.md/);});test("a clean vault still gets the checklist once, then silence", () => {@@ -275,8 +285,8 @@ describe("stop-checklist", () => {const state = freshState();const first = run(stop("s-clean"), { vault: root, state });const second = run(stop("s-clean"), { vault: root, state });- assert.match(systemMessageOf(first.stdout), /Wrap-up checklist:/);- assert.doesNotMatch(systemMessageOf(first.stdout), /Vault Hygiene/);+ assert.match(shownOf(first.stdout), /Wrap-up checklist:/);+ assert.doesNotMatch(shownOf(first.stdout), /Vault Hygiene/);assert.deepEqual(envelopeOf(second.stdout), {});});@@ -286,20 +296,20 @@ describe("stop-checklist", () => {const state = freshState();const first = run(stop(), { state });const second = run(stop(), { state });- assert.match(systemMessageOf(first.stdout), /Wrap-up checklist:/);- assert.match(systemMessageOf(second.stdout), /Wrap-up checklist:/);+ assert.match(shownOf(first.stdout), /Wrap-up checklist:/);+ assert.match(shownOf(second.stdout), /Wrap-up checklist:/);});test("an unreadable dedupe state fails open", () => {const state = freshState();writeFileSync(state, "not json{{");const { stdout } = run(stop("s-corrupt"), { state });- assert.match(systemMessageOf(stdout), /Wrap-up checklist:/);+ assert.match(shownOf(stdout), /Wrap-up checklist:/);});test("string stop_hook_active is not re-entry", () => {const { stdout } = run({ ...stop("s-string"), stop_hook_active: "true" });- assert.match(systemMessageOf(stdout), /Wrap-up checklist:/);+ assert.match(shownOf(stdout), /Wrap-up checklist:/);});test("SessionEnd reports every time — it is the last chance, not a turn", () => {@@ -308,8 +318,8 @@ describe("stop-checklist", () => {const payload = { session_id: "s-end", hook_event_name: "SessionEnd" };const first = run(payload, { vault: root, state });const second = run(payload, { vault: root, state });- assert.match(systemMessageOf(first.stdout), /work\/active\/Done\.md/);- assert.match(systemMessageOf(second.stdout), /work\/active\/Done\.md/);+ assert.match(shownOf(first.stdout), /work\/active\/Done\.md/);+ assert.match(shownOf(second.stdout), /work\/active\/Done\.md/);});test("SessionEnd after a deduped Stop still reports", () => {@@ -317,30 +327,30 @@ describe("stop-checklist", () => {const state = freshState();run(stop("s-mixed"), { vault: root, state });const end = run({ session_id: "s-mixed", hook_event_name: "SessionEnd" }, { vault: root, state });- assert.match(systemMessageOf(end.stdout), /work\/active\/Done\.md/);+ assert.match(shownOf(end.stdout), /work\/active\/Done\.md/);});test("the checklist hands drift to om-tidy", () => {- const message = systemMessageOf(run(stop("s-handoff")).stdout);+ const message = shownOf(run(stop("s-handoff")).stdout);assert.match(message, /ask the agent to run om-tidy/i);});test("malformed input emits a valid default", () => {const { stdout, code } = run("garbage{{");assert.equal(code, 0);- assert.match(systemMessageOf(stdout), /Wrap-up checklist:/);+ assert.match(shownOf(stdout), /Wrap-up checklist:/);});test("empty stdin emits a valid default", () => {const { stdout, code } = run(null);assert.equal(code, 0);- assert.match(systemMessageOf(stdout), /Wrap-up checklist:/);+ assert.match(shownOf(stdout), /Wrap-up checklist:/);});test("does not terminate the message with a stray newline", () => {// systemMessage is rendered by the agent's UI, not written to a// stream — a trailing newline is padding in all three.- const message = systemMessageOf(run({}).stdout);+ const message = shownOf(run({}).stdout);assert.equal(message, message.trimEnd());});@@ -394,7 +404,7 @@ describe("stop-checklist", () => {test(`${label} receives the same JSON envelope`, () => {const { stdout, code } = run(payload);assert.equal(code, 0);- const message = systemMessageOf(stdout);+ const message = shownOf(stdout);assert.match(message, /Wrap-up checklist:/);rendered.add(message);});diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex b4df02e..009ea2f 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -206,7 +206,7 @@ A few specific design choices are worth calling out:- **QMD refresh is shared, debounced, and detached.** Three hook entries fire the same refresh helper — `PostToolUse` (after `.md` writes), `PreCompact` (before transcript backup; writes tend to cluster before compaction), and `Stop` (after a response) — sharing one sentinel file so a burst of events produces at most one worker per debounce window. The actual indexing runs in `.claude/scripts/qmd-refresh-run.ts` as a detached, stdio-silent worker (`qmd update` → `qmd embed` → tail-chase `qmd update`), so the parent hook returns in milliseconds and nothing flows to the agent's context.- **`PreCompact` also backs up the transcript.** In addition to kicking the QMD refresh, it copies the current session transcript out to `thinking/session-logs/` so long conversations remain recoverable after compaction.- **`Stop` reports once, not every turn.** Claude and Codex fire it whenever the agent finishes a response, not when the session ends (#252). It triggers the shared refresh every time, but shows the checklist and hygiene findings only the first time a session sees that exact report, and again when the findings change; otherwise it returns the empty JSON envelope. A warning that repeats unchanged is one users learn to ignore (#155). The dedupe reuses the classifier's per-session state shape (#107): one self-pruning file, failing open to "show" on a missing `session_id` or unreadable state.-- **A changed `Stop` report reaches the agent too (#256).** A `systemMessage` is shown to the user and never added to the model's context, so the drift the agent is best placed to fix never reached it. When the findings change, `Stop` also returns `decision: "block"` with the report as the reason, the one `Stop` output that reaches the model. The agent gets a turn to act on it, ask the user, or say in one line that nothing needs doing. The forced turn's own `Stop` arrives with `stop_hook_active` and exits early, so it cannot loop. `SessionEnd` has no turn to give, and a `Stop` without a `session_id` has nothing to stop a block repeating, so neither blocks.+- **A changed `Stop` report reaches the agent too (#256).** A `systemMessage` is shown to the user and never added to the model's context, so the drift the agent is best placed to fix never reached it. When the findings change, `Stop` returns `decision: "block"` instead, with the report as the reason, the one `Stop` output that reaches the model. Claude Code prints that reason in the transcript, so the user reads the same report and no `systemMessage` is sent beside it; one was, at first, and it only showed the report twice. The agent gets a turn to act on it, ask the user, or say in one line that nothing needs doing. The forced turn's own `Stop` arrives with `stop_hook_active` and exits early, so it cannot loop. `SessionEnd` has no turn to give, and a `Stop` without a `session_id` has nothing to stop a block repeating, so neither blocks.- **Why not `SessionEnd`.** It looks like the natural home for an end-of-session checklist, but Claude Code discards a SessionEnd hook's `systemMessage`, and Codex documents SessionEnd as advisory and does not surface its `systemMessage`. Wired there, the checklist would reach nobody on two of the three agents. Gemini does display it during shutdown, so Gemini keeps its SessionEnd wiring. The acting path is `/om-wrap-up`, which runs the hygiene pass while tools are still live.---@@ -876,7 +876,7 @@ Step 2 is not documentation garnish. Measured: with the server wired and no repoThe same scripts serve three agents. Each agent has its own config file mapping equivalent lifecycle events to the shared scripts. The checklist runs on `Stop` for Claude Code and Codex (per response, deduped) and on `SessionEnd` for Gemini (at shutdown). The script branches on the documented event name, never on an agent-specific payload field.-Session-boundary output is JSON-or-nothing on all three agents. `stop-checklist.ts` emits `{}` when a Stop has nothing new to say. When it reports, the user gets the report in `systemMessage`, the one user-facing field all three agents share. On a Stop whose findings changed, the agent also gets it as a block `reason`, the one Stop output that reaches the model, with a turn to act, ask, or say nothing needs doing. SessionEnd (Gemini) has no turn to give, so there the report is `systemMessage` only. `om-wrap-up` still owns the deliberate acting pass at the end of a session.+Session-boundary output is JSON-or-nothing on all three agents. `stop-checklist.ts` emits `{}` when a Stop has nothing new to say. When it reports without blocking, the user gets the report in `systemMessage`, the one user-facing field all three agents share. On a Stop whose findings changed, it goes out once, as a block `reason`: the one Stop output that reaches the model, with a turn to act, ask, or say nothing needs doing, and printed in the transcript for the user too. SessionEnd (Gemini) has no turn to give, so there the report is `systemMessage` only. `om-wrap-up` still owns the deliberate acting pass at the end of a session.```mermaidflowchart TBdiff --git a/CLAUDE.md b/CLAUDE.mdindex e5ee195..6a35a65 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -444,7 +444,7 @@ Five lifecycle hooks in `.claude/settings.json`:| UserPromptSubmit | Every message | Classifies content (decision, incident, win, 1:1, architecture, person, project update) and injects routing hints || PostToolUse | After writing `.md` | Validates frontmatter + wikilinks, blocks misplaced memory files, flags notes crossing the 25KB organization threshold (split, don't trim) and write-time topic clusters || PreCompact | Before context compaction | Backs up session transcript to `thinking/session-logs/` |-| Stop | After every response | Checklist + concrete vault-hygiene drift findings (same scan as SessionStart), shown once per session and again only when the findings change; hands drift to `om-tidy`. A Stop `systemMessage` reaches only the user, so a changed report also returns `decision: "block"` with the report as the reason: the agent receives it at once and decides whether to act, ask the user, or say in one line that nothing needs doing. The forced turn's own Stop exits early (`stop_hook_active`), and SessionEnd or a Stop without a session id never blocks. Claude Code labels a Stop block "Stop hook error occurred" even when the hook succeeded. Also triggers the debounced QMD refresh. For thorough review, use `/om-wrap-up` instead. |+| Stop | After every response | Checklist + concrete vault-hygiene drift findings (same scan as SessionStart), shown once per session and again only when the findings change; hands drift to `om-tidy`. A Stop `systemMessage` reaches only the user, so a changed report returns `decision: "block"` instead, with the report as the reason, which Claude Code also prints for the user: the agent receives it at once and decides whether to act, ask the user, or say in one line that nothing needs doing. The forced turn's own Stop exits early (`stop_hook_active`), and SessionEnd or a Stop without a session id never blocks. Claude Code labels a Stop block "Stop hook error occurred" even when the hook succeeded. Also triggers the debounced QMD refresh. For thorough review, use `/om-wrap-up` instead. |## Write-Correctness Laws