A self-organizing Obsidian vault that gives AI coding agents persistent memory.
TypeScript ai-agentsclaude-codecodex-cligemini-cliknowledge-managementobsidianobsidian-vaultpersistent-memorysecond-braintemplate
fix: emit the session-end checklist as JSON on every agent (#194)
Rafael Raposo137c36ff0cec
diff --git a/.claude/scripts/lib/hook-io.ts b/.claude/scripts/lib/hook-io.tsindex d00f4a0..72527df 100644--- a/.claude/scripts/lib/hook-io.ts+++ b/.claude/scripts/lib/hook-io.ts@@ -10,6 +10,8 @@* and you need to see which path it took.*/+import { writeSync } from "node:fs";+export function debug(msg: string): void {if (process.env["HOOK_DEBUG"] === "1") {process.stderr.write(`[hook-debug ${new Date().toISOString()}] ${msg}\n`);@@ -70,3 +72,50 @@ export function writeHookOutput(}),);}++/**+ * Emit a message addressed to the *user* rather than to the model.+ *+ * `systemMessage` is the one output field all three agents implement with+ * the same meaning — "show this to the human" — which makes it the only+ * portable channel for a hook that has something to say at session end.+ * The alternative, `hookSpecificOutput.additionalContext`, is Claude-Code-+ * only and is documented as feedback that *continues the conversation* —+ * wrong semantics for a wrap-up reminder, and a re-entry risk on Stop.+ *+ * Session-end stdout is JSON-or-nothing on every agent we ship configs for:+ * Codex rejects plain text outright, Gemini's SessionEnd contract is+ * "must not print any plain text to stdout other than the final JSON",+ * and Claude Code routes non-exempt plain stdout to the debug log where+ * nobody reads it. So there is no text path worth keeping.+ */+export function writeSystemMessage(message: string): void {+ process.stdout.write(JSON.stringify({ systemMessage: message }));+}++/**+ * The empty envelope — valid JSON carrying no fields — for a hook that has+ * nothing to say on a protocol that wants JSON.+ *+ * Zero bytes would probably be fine: there is nothing for a parser to+ * reject. But Codex documents Stop stdout as "JSON on stdout when it exits+ * 0, plain text is invalid" without saying which side of that line empty+ * falls on, and a hook that is *sometimes* silent and *sometimes* JSON is a+ * harder contract to state than one that always emits exactly one object.+ * `{}` is unambiguous everywhere and renders nothing on all three agents,+ * since every common output field defaults to the no-op value.+ *+ * writeSync rather than process.stdout.write: callers use this immediately+ * before exiting, and stdout here is a pipe — pipe writes are asynchronous+ * on Windows, so a write raced against process.exit() can be truncated or+ * dropped entirely. The throw guard keeps a closed stdout from turning a+ * silent no-op into a non-zero exit, which the agent would report as a hook+ * failure — the exact class of bug this envelope exists to avoid.+ */+export function writeSilentHookOutput(): void {+ try {+ writeSync(1, "{}");+ } catch {+ /* stdout gone — nothing to report it to */+ }+}diff --git a/.claude/scripts/stop-checklist.ts b/.claude/scripts/stop-checklist.tsindex 4462402..cb3e116 100644--- a/.claude/scripts/stop-checklist.ts+++ b/.claude/scripts/stop-checklist.ts@@ -10,12 +10,26 @@* checklist and routes through the same `triggerDebouncedRefresh`* entry the PostToolUse hook uses — one debounce contract, one spawn* shape, zero drift between the two paths.+ *+ * Output is JSON on every agent, never plain text. Codex surfaced this by+ * failing loudly — its Stop protocol rejects non-JSON stdout — but the text+ * path was never read anywhere: Gemini's SessionEnd contract forbids plain+ * stdout, and Claude Code sends non-exempt Stop stdout to the debug log+ * rather than to the user or the model. A checklist nobody receives is the+ * same bug in three places, so all three get the one field they agree on,+ * `systemMessage`. Emitting it unconditionally is also what keeps this+ * script agent-agnostic: no flag, and no sniffing the payload to guess who+ * is calling.*/import { readFileSync } from "node:fs";import { dirname, join, resolve as resolvePath } from "node:path";import { fileURLToPath } from "node:url";-import { readStdinJson } from "./lib/hook-io.ts";+import {+ readStdinJson,+ writeSilentHookOutput,+ writeSystemMessage,+} from "./lib/hook-io.ts";import { triggerDebouncedRefresh } from "./lib/qmd-refresh.ts";import {formatActiveHygiene,@@ -39,7 +53,14 @@ type HookInput = {};const input = await readStdinJson<HookInput>();-if (input?.stop_hook_active === true) process.exit(0);+// Re-entry by a secondary agent: say nothing and spawn no second refresh,+// but still emit the empty envelope rather than zero bytes — see+// writeSilentHookOutput for why "sometimes silent, sometimes JSON" is the+// weaker contract.+if (input?.stop_hook_active === true) {+ writeSilentHookOutput();+ process.exit(0);+}const checklist = ["Session end checklist:",@@ -71,13 +92,15 @@ const hygieneLines = formatActiveHygiene(),);-process.stdout.write(+// No trailing newline: this is a message rendered by the agent's UI, not a+// line written to a stream.+const message =checklist +- (hygieneLines.length > 0- ? "\n\nVault Hygiene (drift detected):\n" + hygieneLines.join("\n")- : "") +- "\n",-);+ (hygieneLines.length > 0+ ? "\n\nVault Hygiene (drift detected):\n" + hygieneLines.join("\n")+ : "");++writeSystemMessage(message);triggerDebouncedRefresh({sentinelPath: SENTINEL_PATH,diff --git a/.claude/scripts/tests/hook-config.test.ts b/.claude/scripts/tests/hook-config.test.tsindex 98aa531..b7e9565 100644--- a/.claude/scripts/tests/hook-config.test.ts+++ b/.claude/scripts/tests/hook-config.test.ts@@ -123,3 +123,35 @@ describe("hook config — CWD-independent script resolution (issue #45)", () =>});}});++/**+ * The session-end checklist is one script with one output contract. It used+ * to be tempting to give Codex a `--json` flag, because Codex is the only+ * agent that *fails* on plain-text stdout — but Gemini ignores it and Claude+ * Code buries it, so the flag would have encoded a per-agent difference that+ * does not exist. The script now always emits the JSON envelope, which means+ * no config may pass it agent-specific arguments.+ */+describe("hook config — the checklist hook is invoked identically everywhere", () => {+ for (const { label, path } of configs) {+ const checklistCommands = eachNodeHookCommand(loadConfig(path))+ .map(({ command }) => command)+ .filter((command) => command.includes("stop-checklist.ts"));++ test(`${label} wires the checklist hook exactly once`, () => {+ assert.equal(+ checklistCommands.length,+ 1,+ `expected ${path} to invoke stop-checklist.ts once — got ${checklistCommands.length}`,+ );+ });++ test(`${label} passes the checklist hook no arguments`, () => {+ assert.match(+ checklistCommands[0] ?? "",+ /stop-checklist\.ts"$/,+ `${path} must invoke stop-checklist.ts with no trailing arguments — its output contract is the same for every agent`,+ );+ });+ }+});diff --git a/.claude/scripts/tests/stop-checklist.test.ts b/.claude/scripts/tests/stop-checklist.test.tsindex 9446abb..0603f07 100644--- a/.claude/scripts/tests/stop-checklist.test.ts+++ b/.claude/scripts/tests/stop-checklist.test.ts@@ -1,54 +1,194 @@/*** Integration tests for the Stop hook entry point.- * Locks the stop_hook_active bool-check semantics and the default-print- * behavior on malformed or missing input.+ * Locks the stop_hook_active bool-check semantics, the default-print+ * behavior on malformed or missing input, and the JSON output envelope.+ *+ * The envelope matters more than it looks. Session-end stdout is+ * JSON-or-nothing on all three agents, and each one fails differently when+ * it isn't: Codex reports a hook failure, Gemini ignores the output, and+ * Claude Code files it in the debug log — silently, which is why plain text+ * survived here so long. These tests parse stdout rather than regex-matching+ * it, so a regression back to plain text fails instead of passing on a+ * substring that appears inside the JSON either way.*/-import { test, describe } from "node:test";+import { test, describe, before, after } from "node:test";import assert from "node:assert/strict";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";import { fileURLToPath } from "node:url";-import { dirname, resolve } from "node:path";+import { dirname, join, resolve } from "node:path";import { runScript as spawnHook } from "./_helpers.ts";const SCRIPT = resolve(dirname(fileURLToPath(import.meta.url)),"../stop-checklist.ts",);-const runScript = (stdin: string | object | null) => spawnHook(SCRIPT, stdin);++// Route the debounce sentinel through a per-file tmp path. Every run of this+// hook calls triggerDebouncedRefresh, and without an override that lands on+// the repo's own .claude/scripts/.qmd-refresh-sentinel — shared with+// qmd-refresh.integration.test.ts, which already isolates itself and names+// this file as the reason it has to.+//+// The sentinel is created *pre-dated to now* rather than left absent,+// because "null sentinel → not debounced" is the documented rule: an empty+// tmp dir would make every one of these spawns fire a real detached QMD+// refresh at the working tree, which is both a side effect these tests+// don't want and enough load to time out unrelated suites. A fresh mtime+// puts each run inside the debounce window, so the trigger is exercised and+// then correctly declines to spawn.+let TMP_DIR = "";+let SENTINEL = "";++before(() => {+ TMP_DIR = mkdtempSync(join(tmpdir(), "stop-checklist-"));+ SENTINEL = join(TMP_DIR, ".qmd-refresh-sentinel");+ writeFileSync(SENTINEL, "");+});++after(() => {+ if (TMP_DIR) rmSync(TMP_DIR, { recursive: true, force: true });+});++const runScript = (stdin: string | object | null) =>+ spawnHook(SCRIPT, stdin, { QMD_REFRESH_SENTINEL: SENTINEL });++/** Parse stdout as the hook envelope, failing loudly if it isn't JSON. */+function systemMessageOf(stdout: string): string {+ let parsed: unknown;+ try {+ parsed = JSON.parse(stdout);+ } catch {+ assert.fail(+ `stop-checklist must write a JSON envelope to stdout — got:\n ${stdout}`,+ );+ }+ const message = (parsed as { systemMessage?: unknown }).systemMessage;+ assert.equal(+ typeof message,+ "string",+ `expected a string systemMessage — got: ${stdout}`,+ );+ return message as string;+}describe("stop-checklist", () => {- test("silent when stop_hook_active is strict boolean true", () => {+ test("re-entry on strict boolean true emits the empty envelope", () => {const { stdout, code } = runScript({ stop_hook_active: true });assert.equal(code, 0);- assert.equal(stdout.trim(), "");+ // `{}` rather than zero bytes: stdout is JSON-or-nothing here and+ // "nothing" is only documented by omission. The object carries no+ // field, so nothing renders on any agent.+ assert.deepEqual(JSON.parse(stdout), {});});- test("prints checklist when stop_hook_active is false", () => {+ test("re-entry writes its envelope before exiting", () => {+ // Regression guard for a platform-specific truncation: stdout is a+ // pipe, pipe writes are async on Windows, and this path writes and+ // then immediately calls process.exit(). A non-sync write here+ // arrives empty on Windows and passes everywhere else.+ const { stdout } = runScript({ stop_hook_active: true });+ assert.equal(stdout, "{}");+ });++ test("emits the checklist when stop_hook_active is false", () => {const { stdout, code } = runScript({ stop_hook_active: false });assert.equal(code, 0);- assert.match(stdout, /Session end checklist:/);- assert.match(stdout, /Archive completed projects/);+ const message = systemMessageOf(stdout);+ assert.match(message, /Session end checklist:/);+ assert.match(message, /Archive completed projects/);});- test("prints checklist when stop_hook_active is string 'true' (not strict)", () => {+ test("emits the checklist when stop_hook_active is string 'true' (not strict)", () => {const { stdout } = runScript({ stop_hook_active: "true" });- assert.match(stdout, /Session end checklist:/);+ assert.match(systemMessageOf(stdout), /Session end checklist:/);});- test("prints checklist when field is absent", () => {+ test("emits the checklist when the field is absent", () => {const { stdout } = runScript({});- assert.match(stdout, /Session end checklist:/);+ assert.match(systemMessageOf(stdout), /Session end checklist:/);});- test("prints checklist on malformed JSON (safe default)", () => {+ test("emits valid JSON on malformed input (safe default)", () => {const { stdout, code } = runScript("garbage{{");assert.equal(code, 0);- assert.match(stdout, /Session end checklist:/);+ assert.match(systemMessageOf(stdout), /Session end checklist:/);});- test("prints checklist on empty stdin", () => {+ test("emits valid JSON on empty stdin", () => {const { stdout, code } = runScript(null);assert.equal(code, 0);- assert.match(stdout, /Session end checklist:/);+ assert.match(systemMessageOf(stdout), /Session end 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(runScript({}).stdout);+ assert.equal(message, message.trimEnd());+ });++ // One script serves three agents whose session-end payloads differ in+ // shape. None of those fields steer the output any more — that is the+ // property under test. Payloads mirror each vendor's documented schema.+ const AGENT_PAYLOADS: ReadonlyArray<{+ readonly label: string;+ readonly payload: Record<string, unknown>;+ }> = [+ {+ label: "Claude Code Stop",+ payload: {+ session_id: "s1",+ transcript_path: "/tmp/t.json",+ cwd: ".",+ permission_mode: "default",+ hook_event_name: "Stop",+ last_assistant_message: "done",+ stop_hook_active: false,+ },+ },+ {+ label: "Codex Stop",+ payload: {+ session_id: "s1",+ transcript_path: "/tmp/t.json",+ cwd: ".",+ hook_event_name: "Stop",+ model: "gpt-5.6-sol",+ permission_mode: "default",+ stop_hook_active: false,+ },+ },+ {+ label: "Gemini SessionEnd",+ payload: {+ session_id: "s1",+ transcript_path: "/tmp/t.json",+ cwd: ".",+ hook_event_name: "SessionEnd",+ timestamp: "2026-08-03T12:00:00Z",+ reason: "exit",+ },+ },+ ];++ const rendered = new Set<string>();+ for (const { label, payload } of AGENT_PAYLOADS) {+ test(`${label} receives the same JSON envelope`, () => {+ const { stdout, code } = runScript(payload);+ assert.equal(code, 0);+ const message = systemMessageOf(stdout);+ assert.match(message, /Session end checklist:/);+ rendered.add(message);+ });+ }++ test("output does not vary by calling agent", () => {+ assert.equal(+ rendered.size,+ 1,+ `every agent must get byte-identical output — got ${rendered.size} variants`,+ );});});diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex 7895ed7..3677f36 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -865,7 +865,9 @@ Step 2 is not documentation garnish. Measured: with the server wired and no repo## Multi-Agent Portability-The same scripts serve three agents. Each agent has its own config file mapping its own event names to the shared scripts. The event vocabularies differ — Claude Code calls it `Stop`, Gemini calls it `SessionEnd`, Codex has no compaction event — but the scripts are identical.+The same scripts serve three agents. Each agent has its own config file mapping its own event names to the shared scripts. The event vocabularies differ — Claude Code calls it `Stop`, Gemini calls it `SessionEnd`, Codex has no compaction event — but the scripts are identical, and so are the arguments they are invoked with.++Session-end output is the one place where that uniformity had to be earned rather than assumed. All three agents treat session-end stdout as JSON-or-nothing, but only Codex says so out loud: it reports a hook failure on plain text, while Gemini's `SessionEnd` contract silently drops anything that isn't the final JSON object, and Claude Code routes non-exempt `Stop` stdout to the debug log — read by nobody. A plain-text checklist therefore looked like it worked on two agents and broke on one, when in fact it reached none of them. `stop-checklist.ts` emits `{"systemMessage": ...}` unconditionally: `systemMessage` is the only output field all three implement with the same meaning, and emitting it unconditionally is what keeps the script from having to know which agent invoked it.```mermaidflowchart TB