Skip to content

A self-organizing Obsidian vault that gives AI coding agents persistent memory.

fix: route vault hygiene through actionable lifecycle hooks (#253)

Rafael Raposo69e75c76b780
diff --git a/.claude/commands/om-tidy.md b/.claude/commands/om-tidy.md
index 655e7cb..335221e 100644
--- a/.claude/commands/om-tidy.md
+++ b/.claude/commands/om-tidy.md
@@ -4,7 +4,7 @@ description: "Self-maintenance pass — acts on every hygiene flag: archives com
# /om-tidy
-The acting half of the hygiene system. The SessionStart/Stop hooks and the PostToolUse write-time flags DETECT drift; this command ACTS on it. Run on demand, at wrap-up when flags are present, or when the flag list has visibly piled up.
+The acting half of the hygiene system. The SessionStart and Stop hooks (SessionEnd on Gemini) and the PostToolUse write-time flags DETECT drift; this command ACTS on it. Run on demand, during wrap-up when flags are present, or when the flag list has visibly piled up. Stop fires after every response, so it shows its findings once per session and again only when they change, rather than repeating them every turn.
## Hard rails (safe by construction)
diff --git a/.claude/commands/om-wrap-up.md b/.claude/commands/om-wrap-up.md
index 35321e6..4d1202d 100644
--- a/.claude/commands/om-wrap-up.md
+++ b/.claude/commands/om-wrap-up.md
@@ -49,12 +49,15 @@ For each note created or modified this session:
- Any new people not added to People & Context?
- Any thinking notes that should be promoted or deleted?
-### 5. Archive Check
+### 5. Status Check
-- Are there notes in `work/active/` that should be moved to `work/archive/YYYY/`?
-- Any status fields still `active` that should be `completed`?
+- Any status fields still `active` that should be `completed`? Mark them; step 6's `/om-tidy` moves completed notes out of `work/active/` to `work/archive/YYYY/`, so do not move them by hand here.
-### 6. Ways of Working Review
+### 6. Act on Vault Hygiene
+
+Invoke `/om-tidy` while the conversation and tools are still live. It runs the same vault-hygiene scan the hooks use; if that reports drift, complete its safe mechanical tier now and bring its judgment-tier findings to the user instead of leaving them to a reminder that cannot act on them. Fold the tidy receipt into this wrap-up report; do not create a second report unless the findings need to survive the session.
+
+### 7. Ways of Working Review
**Index-first**: read each brain note's headline/one-liner structure, then open ONLY the topics this session actually touched — same knowledge transfer, a fraction of the tokens. Check if this session revealed:
- A new pattern that should be in `brain/Patterns.md`?
@@ -64,7 +67,7 @@ For each note created or modified this session:
- A new or improved slash command?
- A hook that should be added or modified?
-### 7. Suggest Improvements
+### 8. Suggest Improvements
Based on how the session went:
- Were there friction points in the workflow?
@@ -73,7 +76,7 @@ Based on how the session went:
- Are there Bases that should be created or updated?
- Any frontmatter properties that would help future queries?
-### 8. Report
+### 9. Report
Present a concise summary:
- **Done**: what was captured this session
diff --git a/.claude/scripts/classify-message.ts b/.claude/scripts/classify-message.ts
index 18e0cc1..aeb3414 100644
--- a/.claude/scripts/classify-message.ts
+++ b/.claude/scripts/classify-message.ts
@@ -8,12 +8,11 @@
* malformed input, missing prompt, or zero matches.
*/
-import { readFileSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { debug, readStdinJson, writeHookOutput } from "./lib/hook-io.ts";
import { classify } from "./lib/matcher.ts";
-import { parseHintState, prune, record, unseen } from "./lib/hint-state.ts";
+import { claimUnseen } from "./lib/hint-state.ts";
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
// CLASSIFY_HINT_STATE routes the state file into a tmp path for tests
@@ -48,29 +47,10 @@ debug(`classify: matched ${signals.length} signal(s)`);
let toEmit = signals;
const sessionId = input.session_id;
if (typeof sessionId === "string" && sessionId && signals.length > 0) {
- let state = parseHintState(null);
- try {
- state = parseHintState(readFileSync(STATE_PATH, { encoding: "utf-8" }));
- } catch {
- /* missing/unreadable state → empty (fail open) */
- }
- const unseenHints = new Set(unseen(state, sessionId, signals));
- toEmit = signals.filter((s) => unseenHints.has(s));
+ toEmit = claimUnseen(STATE_PATH, sessionId, signals);
debug(
`classify: ${signals.length - toEmit.length} signal(s) already fired this session`,
);
- if (toEmit.length > 0) {
- try {
- const now = new Date();
- const next = prune(
- record(state, sessionId, toEmit, now.toISOString()),
- now.getTime(),
- );
- writeFileSync(STATE_PATH, JSON.stringify(next));
- } catch {
- /* best-effort — a failed state write must never block the hint */
- }
- }
}
if (toEmit.length > 0) {
diff --git a/.claude/scripts/generate-memory-index.ts b/.claude/scripts/generate-memory-index.ts
index 17ac5d7..d4adfe0 100644
--- a/.claude/scripts/generate-memory-index.ts
+++ b/.claude/scripts/generate-memory-index.ts
@@ -19,6 +19,7 @@ import {
isMarkdownFilename,
} from "./lib/session-start.ts";
import { generateMemoryIndex, type BrainNote } from "./lib/automemory-index.ts";
+import { resolveProjectDir } from "./lib/project-dir.ts";
/**
* Collect brain/ notes (name + description) for index generation. Exported
@@ -49,7 +50,7 @@ export function collectBrainNotes(root: string): BrainNote[] | null {
}
function main(): void {
- const root = process.env["CLAUDE_PROJECT_DIR"] || process.cwd();
+ const root = resolveProjectDir(process.cwd());
const notes = collectBrainNotes(root);
if (notes === null) {
process.stderr.write("brain/ not found — run from the vault root.\n");
diff --git a/.claude/scripts/lib/active-hygiene.ts b/.claude/scripts/lib/active-hygiene.ts
index 0ca7c8d..eaf9771 100644
--- a/.claude/scripts/lib/active-hygiene.ts
+++ b/.claude/scripts/lib/active-hygiene.ts
@@ -1,6 +1,7 @@
/**
- * Active-folder hygiene scan — shared by the SessionStart and Stop hooks
- * (#98/#103), plus the write-time detectors validate-write.ts consumes.
+ * Active-folder hygiene scan — shared by the SessionStart hook and the
+ * conversation-boundary hook (Stop on Claude Code and Codex, SessionEnd on
+ * Gemini; #98/#103), plus the write-time detectors validate-write.ts consumes.
*
* Drift modes surfaced:
*
@@ -670,7 +671,7 @@ export function formatActiveHygiene(report: ActiveHygieneReport): string[] {
if (completedInActive.length > 0) {
lines.push(
- `⚠️ ${completedInActive.length} note(s) marked done but still in active/ — archive to archive/YYYY/ (try /om-project-archive):`,
+ `⚠️ ${completedInActive.length} note(s) marked done but still in active/ — archive to archive/YYYY/ (ask the agent to run om-project-archive):`,
);
for (const p of completedInActive) lines.push(` - ${p}`);
}
@@ -708,7 +709,7 @@ export function formatActiveHygiene(report: ActiveHygieneReport): string[] {
if (inboxPressure !== null) {
if (lines.length > 0) lines.push("");
lines.push(
- `⚠️ ${inboxPressure.count} raw export(s) sitting in work/meetings/ for ${INBOX_PRESSURE_DAYS}+ days (oldest ${inboxPressure.oldestDays}d) — run /om-intake to drain the inbox.`,
+ `⚠️ ${inboxPressure.count} raw export(s) sitting in work/meetings/ for ${INBOX_PRESSURE_DAYS}+ days (oldest ${inboxPressure.oldestDays}d) — ask the agent to run om-intake to drain the inbox.`,
);
}
diff --git a/.claude/scripts/lib/hint-state.ts b/.claude/scripts/lib/hint-state.ts
index f2f6a55..0df4644 100644
--- a/.claude/scripts/lib/hint-state.ts
+++ b/.claude/scripts/lib/hint-state.ts
@@ -1,16 +1,22 @@
/**
- * Once-per-session hint state — pure helpers for the classify-message
- * dedupe (Vault Improvement Backlog, 2026-07-14).
+ * Per-session hook state — what a session has already been shown, so a hook
+ * that fires every turn does not repeat itself (Vault Improvement Backlog,
+ * 2026-07-14; #252).
*
- * The classifier fires the same routing hint every time a keyword recurs;
- * a long shipping session pays the WIN hint dozens of times. This module
- * keys "already fired" signal names by Claude Code's session_id in a
- * single JSON state file (`.claude/scripts/.hint-state.json`, gitignored;
- * tests route it elsewhere via the CLASSIFY_HINT_STATE env var).
+ * Two hooks use it, each with its own gitignored JSON state file:
+ * - classify-message fires the same routing hint every time a keyword
+ * recurs; a long shipping session paid the WIN hint dozens of times.
+ * `claimUnseen` keeps a set per session: each hint fires once.
+ * (`.claude/scripts/.hint-state.json`; tests set CLASSIFY_HINT_STATE.)
+ * - stop-checklist runs after every response. `claimChanged` keeps the
+ * last report per session: it shows again only when the report differs
+ * from the last one shown, so drift that is fixed and then comes back is
+ * reported again. (`.claude/scripts/.checklist-state.json`; tests set
+ * STOP_CHECKLIST_STATE.)
*
* Design constraints, in order:
* - Fail open. A missing session_id, unreadable file, or malformed JSON
- * must degrade to today's behavior (all hints fire), never to silence.
+ * must degrade to showing everything, never to silence.
* - Single file, self-pruning. Per-session files would accumulate without
* bound and would put session_id into filesystem paths; a JSON key has
* no traversal surface. Sessions older than PRUNE_MAX_AGE_MS or beyond
@@ -19,6 +25,9 @@
* worst case is one duplicate hint, which is acceptable.
*/
+import { readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
+import { debug } from "./hook-io.ts";
+
export type HintSessionEntry = {
readonly seen: readonly string[];
readonly updated: string; // ISO timestamp of last write
@@ -105,3 +114,78 @@ export function prune(
);
return Object.fromEntries(fresh.slice(0, maxSessions));
}
+
+/** The state file's contents, or empty when missing or unreadable (fail open). */
+function loadHintState(path: string): HintState {
+ try {
+ return parseHintState(readFileSync(path, { encoding: "utf-8" }));
+ } catch {
+ return {};
+ }
+}
+
+/**
+ * Prune and write the state, through a temp file and a rename, so a hook
+ * killed mid-write leaves the previous state rather than truncated JSON that
+ * would read back as empty for every session. Best-effort: a failed write
+ * must never block a hook, and the caller then fails open (shows again).
+ */
+function saveHintState(path: string, state: HintState, now: Date): void {
+ const tmp = `${path}.${process.pid}.tmp`;
+ try {
+ writeFileSync(tmp, JSON.stringify(prune(state, now.getTime())));
+ renameSync(tmp, path);
+ } catch (err) {
+ debug(`hint-state: could not write ${path} (${(err as Error).message}); the next run fails open`);
+ try {
+ unlinkSync(tmp);
+ } catch {
+ /* nothing was written */
+ }
+ }
+}
+
+/**
+ * The names this session has not seen yet, now recorded as seen. Each name
+ * is returned once per session; a missing or unreadable state file returns
+ * them all.
+ */
+export function claimUnseen(
+ path: string,
+ sessionId: string,
+ names: readonly string[],
+ now: Date = new Date(),
+): string[] {
+ const state = loadHintState(path);
+ const fresh = unseen(state, sessionId, names);
+ if (fresh.length > 0) {
+ saveHintState(path, record(state, sessionId, fresh, now.toISOString()), now);
+ }
+ return fresh;
+}
+
+/**
+ * Whether `value` differs from the last value recorded for this session,
+ * recording it when it does. Unlike `claimUnseen`, only the latest value is
+ * kept, so a value that returns after a different one counts as changed
+ * (A → B → A shows A again). A missing or unreadable state file counts as
+ * changed.
+ */
+export function claimChanged(
+ path: string,
+ sessionId: string,
+ value: string,
+ now: Date = new Date(),
+): boolean {
+ // Same entry shape as claimUnseen, used as a one-slot record: `seen` holds
+ // only the latest value, so the shared parse and prune apply unchanged.
+ // A repeat is recorded too, refreshing `updated`: pruning goes by that
+ // stamp, and a long session whose report never changed must not age out
+ // and be shown again as if new.
+ const state = loadHintState(path);
+ const last = state[sessionId]?.seen;
+ const changed = !(last?.length === 1 && last[0] === value);
+ const entry = { seen: [value], updated: now.toISOString() };
+ saveHintState(path, { ...state, [sessionId]: entry }, now);
+ return changed;
+}
diff --git a/.claude/scripts/lib/project-dir.ts b/.claude/scripts/lib/project-dir.ts
new file mode 100644
index 0000000..1469698
--- /dev/null
+++ b/.claude/scripts/lib/project-dir.ts
@@ -0,0 +1,34 @@
+/**
+ * The project directory the calling agent gave a hook or script.
+ *
+ * Each agent names the project directory in its own variable: Claude Code
+ * sets CLAUDE_PROJECT_DIR; the Codex and Gemini configs pass
+ * CODEX_PROJECT_DIR and GEMINI_PROJECT_DIR. The first non-empty one wins.
+ * An empty value counts as unset (`||`, not `??`): an empty string is never
+ * a usable root, and treating it as one resolved paths against "".
+ *
+ * The fallback is the caller's. Every hook passes the working directory:
+ * the hook commands themselves resolve their script through
+ * `${*_PROJECT_DIR:-.}`, so when the variable is unset the hook only runs at
+ * all if cwd is the vault. Not to be confused with qmd-refresh.ts's
+ * resolveVaultRoot, which ignores these variables on purpose (a detached
+ * worker anchors to its own location), or with mcp-context.ts's, which
+ * reads OM_VAULT_PATH for the MCP server.
+ */
+
+const PROJECT_DIR_VARS = [
+ "CLAUDE_PROJECT_DIR",
+ "CODEX_PROJECT_DIR",
+ "GEMINI_PROJECT_DIR",
+] as const;
+
+export function resolveProjectDir(
+ fallback: string,
+ env: NodeJS.ProcessEnv = process.env,
+): string {
+ for (const name of PROJECT_DIR_VARS) {
+ const value = env[name];
+ if (value) return value;
+ }
+ return fallback;
+}
diff --git a/.claude/scripts/pre-compact.ts b/.claude/scripts/pre-compact.ts
index bc2daa4..d69dffc 100644
--- a/.claude/scripts/pre-compact.ts
+++ b/.claude/scripts/pre-compact.ts
@@ -20,6 +20,7 @@ import { fileURLToPath } from "node:url";
import { debug, readStdinJson } from "./lib/hook-io.ts";
import { isMainModule } from "./lib/main-guard.ts";
import { triggerDebouncedRefresh } from "./lib/qmd-refresh.ts";
+import { resolveProjectDir } from "./lib/project-dir.ts";
type HookInput = {
readonly transcript_path?: unknown;
@@ -90,7 +91,7 @@ if (isMainModule(import.meta.url)) {
process.exit(0);
}
- const projectDir = process.env["CLAUDE_PROJECT_DIR"] ?? process.cwd();
+ const projectDir = resolveProjectDir(process.cwd());
const backupDir = join(projectDir, "thinking/session-logs");
mkdirSync(backupDir, { recursive: true });
diff --git a/.claude/scripts/session-start.ts b/.claude/scripts/session-start.ts
index a290b66..ac0ed51 100644
--- a/.claude/scripts/session-start.ts
+++ b/.claude/scripts/session-start.ts
@@ -65,6 +65,7 @@ import {
} from "./lib/active-hygiene.ts";
import { readStdinJson } from "./lib/hook-io.ts";
+import { resolveProjectDir } from "./lib/project-dir.ts";
type HookInput = { readonly source?: unknown };
@@ -103,11 +104,7 @@ function readManifestRaw(): string | null {
}
}
-const cwd =
- process.env["CLAUDE_PROJECT_DIR"] ??
- process.env["CODEX_PROJECT_DIR"] ??
- process.env["GEMINI_PROJECT_DIR"] ??
- process.cwd();
+const cwd = resolveProjectDir(process.cwd());
process.chdir(cwd);
// Persist vault path for any downstream shell consumers (Claude Code feature).
diff --git a/.claude/scripts/stop-checklist.ts b/.claude/scripts/stop-checklist.ts
index cb3e116..a2edfef 100644
--- a/.claude/scripts/stop-checklist.ts
+++ b/.claude/scripts/stop-checklist.ts
@@ -1,27 +1,34 @@
#!/usr/bin/env node
/**
- * Stop hook — remind the user of session-wrap-up tasks and kick a
- * debounced QMD refresh so the next session opens against a current
- * index.
+ * Conversation-boundary hook — the wrap-up checklist plus concrete
+ * vault-hygiene findings, and a debounced QMD refresh so the next session
+ * opens against a current index.
*
- * Silently exits when the hook is being re-entered by a secondary
- * agent (stop_hook_active=true) to avoid recursive reminder output and
- * duplicated refresh spawns. Otherwise prints the vault-hygiene
- * checklist and routes through the same `triggerDebouncedRefresh`
- * entry the PostToolUse hook uses — one debounce contract, one spawn
- * shape, zero drift between the two paths.
+ * Where it runs is decided by where its message can be seen (#252):
*
- * 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.
+ * - Claude Code and Codex call it on Stop, which fires after EVERY
+ * response, not at the end of the session. An unconditional report there
+ * repeats unchanged drift on every turn, and a warning that never changes
+ * is one users learn to ignore (#155). So on Stop the report is shown
+ * once per session and again only when its text changes; otherwise the
+ * hook emits the empty envelope and only refreshes QMD.
+ * - Gemini calls it on SessionEnd, whose systemMessage it displays during
+ * shutdown. That is a last chance rather than a turn, so it always reports.
+ *
+ * Claude Code and Codex are deliberately NOT wired to SessionEnd: Claude Code
+ * discards a SessionEnd hook's systemMessage, and Codex documents SessionEnd
+ * as advisory and does not surface its systemMessage. Moving the report
+ * there would turn "every turn" into "never".
+ *
+ * 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 report
+ * uses the one user-facing field all three agents share, `systemMessage`.
+ * The documented event name is the only branch — no agent sniffing and no
+ * agent-specific argument.
*/
+import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import { dirname, join, resolve as resolvePath } from "node:path";
import { fileURLToPath } from "node:url";
@@ -38,6 +45,8 @@ import {
scanActiveHygiene,
} from "./lib/active-hygiene.ts";
import { parseInfraRootFilenames } from "./lib/session-start.ts";
+import { claimChanged } from "./lib/hint-state.ts";
+import { resolveProjectDir } from "./lib/project-dir.ts";
const DEBOUNCE_MS = 30_000;
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
@@ -47,8 +56,16 @@ const SENTINEL_PATH =
process.env["QMD_REFRESH_SENTINEL"] ??
join(SCRIPT_DIR, ".qmd-refresh-sentinel");
const WORKER_PATH = resolvePath(SCRIPT_DIR, "qmd-refresh-run.ts");
+// The last report each session was shown (lib/hint-state.ts, the same
+// self-pruning, fail-open store as the classifier's hint dedupe, #107).
+// STOP_CHECKLIST_STATE routes it to a tmp path for tests.
+const STATE_PATH =
+ process.env["STOP_CHECKLIST_STATE"] ??
+ join(SCRIPT_DIR, ".checklist-state.json");
type HookInput = {
+ readonly hook_event_name?: unknown;
+ readonly session_id?: unknown;
readonly stop_hook_active?: unknown;
};
@@ -63,17 +80,18 @@ if (input?.stop_hook_active === true) {
}
const checklist = [
- "Session end checklist:",
+ "Wrap-up checklist:",
"- Archive completed projects? (work/active/ -> work/archive/YYYY/)",
"- Update indexes? (Index.md, Memories.md, People & Context, Brag Doc)",
"- New notes linked? (orphans are bugs)",
- "- Run /om-vault-audit if many notes were created/modified",
+ "- Ask the agent to run om-vault-audit if many notes were created/modified",
+ "- To act on any drift, ask the agent to run om-tidy",
].join("\n");
// Concrete drift findings beat a generic checklist (#98/#103/#106): the
// same scan SessionStart runs, so the session closes against the same
// facts it opened with. Silent when clean.
-const vaultRoot = process.env["CLAUDE_PROJECT_DIR"] || process.cwd();
+const vaultRoot = resolveProjectDir(process.cwd());
let manifestJson: string | null = null;
try {
manifestJson = readFileSync(join(vaultRoot, "vault-manifest.json"), {
@@ -82,15 +100,14 @@ try {
} catch {
/* missing manifest → default open-loop config */
}
-const hygieneLines = formatActiveHygiene(
- scanActiveHygiene(
- vaultRoot,
- Date.now(),
- parseOpenLoopConfig(manifestJson),
- parseInfraRootFilenames(manifestJson),
- parseMemoryRoot(manifestJson),
- ),
+const report = scanActiveHygiene(
+ vaultRoot,
+ Date.now(),
+ parseOpenLoopConfig(manifestJson),
+ parseInfraRootFilenames(manifestJson),
+ parseMemoryRoot(manifestJson),
);
+const hygieneLines = formatActiveHygiene(report);
// No trailing newline: this is a message rendered by the agent's UI, not a
// line written to a stream.
@@ -100,7 +117,32 @@ const message =
? "\n\nVault Hygiene (drift detected):\n" + hygieneLines.join("\n")
: "");
-writeSystemMessage(message);
+// Numbers that move with no new drift to act on: a note growing past the
+// threshold, an item a day older. They stay in the message but not in the
+// comparison, or a note the agent keeps appending to would re-show the report
+// every turn — the #252 repeat by another route.
+const VOLATILE_FIELDS = new Set(["sizeKb", "ageDays", "oldestDays"]);
+
+/** What identifies a report: the checklist and which findings exist, not their ages or sizes. */
+function reportKey(): string {
+ const findings = JSON.stringify(report, (k, v) => (VOLATILE_FIELDS.has(k) ? undefined : v));
+ return createHash("sha256").update(checklist + "\n" + findings).digest("hex").slice(0, 16);
+}
+
+// SessionEnd (and any input without a recognisable event, the safe default)
+// always reports. Stop reports when the findings differ from the last report
+// this session was shown: the first Stop, and any change since, including
+// drift that was fixed and then came back. A missing session_id fails open
+// to reporting.
+const sessionId = input?.session_id;
+const show =
+ input?.hook_event_name !== "Stop" ||
+ typeof sessionId !== "string" ||
+ !sessionId ||
+ claimChanged(STATE_PATH, sessionId, reportKey());
+
+if (show) writeSystemMessage(message);
+else writeSilentHookOutput();
triggerDebouncedRefresh({
sentinelPath: SENTINEL_PATH,
diff --git a/.claude/scripts/tests/hint-state.test.ts b/.claude/scripts/tests/hint-state.test.ts
index 2130d1e..58b1c88 100644
--- a/.claude/scripts/tests/hint-state.test.ts
+++ b/.claude/scripts/tests/hint-state.test.ts
@@ -4,15 +4,21 @@
* classify-message.test.ts via runScript + CLASSIFY_HINT_STATE.
*/
-import { test, describe } from "node:test";
+import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
+import { mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import {
parseHintState,
unseen,
record,
prune,
+ claimUnseen,
+ claimChanged,
PRUNE_MAX_AGE_MS,
} from "../lib/hint-state.ts";
+import { rmTemp } from "./_helpers.ts";
describe("parseHintState — fail open on anything malformed", () => {
test("null input → empty state", () => {
@@ -108,3 +114,66 @@ describe("prune", () => {
assert.deepEqual(Object.keys(pruned).sort(), ["s0", "s1", "s2"]);
});
});
+
+describe("claimUnseen / claimChanged (state file I/O)", () => {
+ let dir = "";
+ let n = 0;
+ before(() => {
+ dir = mkdtempSync(join(tmpdir(), "hint-state-"));
+ });
+ after(() => rmTemp(dir));
+ const path = () => join(dir, `state-${++n}.json`);
+
+ test("claimUnseen returns each name once per session", () => {
+ const p = path();
+ assert.deepEqual(claimUnseen(p, "s", ["WIN", "DECISION"]), ["WIN", "DECISION"]);
+ assert.deepEqual(claimUnseen(p, "s", ["WIN", "PERSON"]), ["PERSON"]);
+ assert.deepEqual(claimUnseen(p, "other", ["WIN"]), ["WIN"]);
+ });
+
+ test("claimChanged is true on first sight and on change, false on repeat", () => {
+ const p = path();
+ assert.equal(claimChanged(p, "s", "A"), true);
+ assert.equal(claimChanged(p, "s", "A"), false);
+ assert.equal(claimChanged(p, "s", "B"), true);
+ });
+
+ test("claimChanged keeps only the last value, so A → B → A is a change", () => {
+ const p = path();
+ claimChanged(p, "s", "A");
+ claimChanged(p, "s", "B");
+ assert.equal(claimChanged(p, "s", "A"), true);
+ const stored = parseHintState(readFileSync(p, "utf-8"));
+ assert.deepEqual(stored["s"]?.seen, ["A"]);
+ });
+
+ test("a repeat refreshes the session's updated stamp, so an active session is not pruned", () => {
+ const p = path();
+ claimChanged(p, "s", "A", new Date("2026-10-01T00:00:00Z"));
+ assert.equal(claimChanged(p, "s", "A", new Date("2026-10-05T00:00:00Z")), false);
+ const stored = parseHintState(readFileSync(p, "utf-8"));
+ assert.equal(stored["s"]?.updated, "2026-10-05T00:00:00.000Z");
+ });
+
+ test("writes go through a temp file and leave none behind", () => {
+ const p = path();
+ claimChanged(p, "s", "A");
+ claimUnseen(p + ".u", "s", ["WIN"]);
+ const leftovers = readdirSync(dir).filter((f) => f.endsWith(".tmp"));
+ assert.deepEqual(leftovers, []);
+ });
+
+ test("an unreadable state file fails open for both", () => {
+ const p = path();
+ writeFileSync(p, "not json{{");
+ assert.deepEqual(claimUnseen(p, "s", ["WIN"]), ["WIN"]);
+ writeFileSync(p, "not json{{");
+ assert.equal(claimChanged(p, "s", "A"), true);
+ });
+
+ test("an unwritable state path still answers (best-effort write)", () => {
+ const p = join(dir, "no-such-dir", "state.json");
+ assert.deepEqual(claimUnseen(p, "s", ["WIN"]), ["WIN"]);
+ assert.equal(claimChanged(p, "s", "A"), true);
+ });
+});
diff --git a/.claude/scripts/tests/hook-config.test.ts b/.claude/scripts/tests/hook-config.test.ts
index b7e9565..db4c6d6 100644
--- a/.claude/scripts/tests/hook-config.test.ts
+++ b/.claude/scripts/tests/hook-config.test.ts
@@ -125,30 +125,47 @@ 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.
+ * The checklist hook runs on the event that can actually show its message.
+ *
+ * Claude Code and Codex: Stop, deduped inside the script to once per session
+ * plus on change (#252). Not SessionEnd: Claude Code discards a SessionEnd
+ * hook's `systemMessage` ("Claude Code discards their JSON output fields,
+ * such as systemMessage" — hooks reference), and Codex documents SessionEnd
+ * as advisory and leaves it out of the events whose `systemMessage` it
+ * surfaces. Wiring the checklist there turns "every turn" into "never".
+ *
+ * Gemini CLI: SessionEnd, whose `systemMessage` is "Displayed to the user
+ * during shutdown" (best effort). Gemini's per-turn event is AfterAgent, and
+ * the checklist is not wired to it.
+ *
+ * Pin the routing so a config edit cannot move the message somewhere it
+ * silently disappears, or back to an undeduped per-turn surface.
*/
-describe("hook config — the checklist hook is invoked identically everywhere", () => {
+const CHECKLIST_EVENT: Readonly<Record<string, string>> = {
+ "Claude Code": "Stop",
+ "Codex CLI": "Stop",
+ "Gemini CLI": "SessionEnd",
+};
+
+describe("hook config — the checklist runs where its message is shown", () => {
for (const { label, path } of configs) {
- const checklistCommands = eachNodeHookCommand(loadConfig(path))
- .map(({ command }) => command)
- .filter((command) => command.includes("stop-checklist.ts"));
+ const checklistHooks = eachNodeHookCommand(loadConfig(path)).filter(
+ ({ command }) => command.includes("stop-checklist.ts"),
+ );
+ const expected = CHECKLIST_EVENT[label];
+ const events = checklistHooks.map(({ event }) => event);
- 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} wires the checklist exactly once, on ${expected}`, () => {
+ assert.deepEqual(
+ events,
+ [expected],
+ `expected ${path} to invoke stop-checklist.ts once, on ${expected} — got ${JSON.stringify(events)}`,
);
});
test(`${label} passes the checklist hook no arguments`, () => {
assert.match(
- checklistCommands[0] ?? "",
+ checklistHooks[0]?.command ?? "",
/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/project-dir.test.ts b/.claude/scripts/tests/project-dir.test.ts
new file mode 100644
index 0000000..e7d6223
--- /dev/null
+++ b/.claude/scripts/tests/project-dir.test.ts
@@ -0,0 +1,31 @@
+/**
+ * Unit tests for lib/project-dir.ts — which project directory a hook runs
+ * against, whichever of the three agents called it.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { resolveProjectDir } from "../lib/project-dir.ts";
+
+describe("resolveProjectDir", () => {
+ test("each agent's variable is honoured", () => {
+ assert.equal(resolveProjectDir("/fb", { CLAUDE_PROJECT_DIR: "/c" }), "/c");
+ assert.equal(resolveProjectDir("/fb", { CODEX_PROJECT_DIR: "/x" }), "/x");
+ assert.equal(resolveProjectDir("/fb", { GEMINI_PROJECT_DIR: "/g" }), "/g");
+ });
+
+ test("Claude, then Codex, then Gemini", () => {
+ const all = { CLAUDE_PROJECT_DIR: "/c", CODEX_PROJECT_DIR: "/x", GEMINI_PROJECT_DIR: "/g" };
+ assert.equal(resolveProjectDir("/fb", all), "/c");
+ assert.equal(resolveProjectDir("/fb", { CODEX_PROJECT_DIR: "/x", GEMINI_PROJECT_DIR: "/g" }), "/x");
+ });
+
+ test("an empty value counts as unset", () => {
+ assert.equal(resolveProjectDir("/fb", { CLAUDE_PROJECT_DIR: "", CODEX_PROJECT_DIR: "/x" }), "/x");
+ assert.equal(resolveProjectDir("/fb", { CLAUDE_PROJECT_DIR: "" }), "/fb");
+ });
+
+ test("no variable falls back to the caller's choice", () => {
+ assert.equal(resolveProjectDir("/fb", {}), "/fb");
+ });
+});
diff --git a/.claude/scripts/tests/stop-checklist.test.ts b/.claude/scripts/tests/stop-checklist.test.ts
index 4b94990..ac37054 100644
--- a/.claude/scripts/tests/stop-checklist.test.ts
+++ b/.claude/scripts/tests/stop-checklist.test.ts
@@ -1,9 +1,17 @@
/**
- * Integration tests for the Stop hook entry point.
- * Locks the stop_hook_active bool-check semantics, the default-print
- * behavior on malformed or missing input, and the JSON output envelope.
+ * Integration tests for the shared Stop/SessionEnd hook entry point.
+ * Locks the once-per-session Stop report, the always-on SessionEnd report,
+ * stop_hook_active semantics, and the JSON output envelope.
*
- * The envelope matters more than it looks. Session-end stdout is
+ * Why Stop dedupes instead of moving to SessionEnd (#252): Stop fires after
+ * every response on Claude Code and Codex, so an unconditional report repeats
+ * unchanged drift on every turn. SessionEnd cannot carry it there instead —
+ * Claude Code discards a SessionEnd hook's `systemMessage`, and Codex does
+ * not list SessionEnd among the events whose `systemMessage` it surfaces.
+ * So Stop reports once per session and again only when the report changes;
+ * SessionEnd (Gemini's wiring) reports every time.
+ *
+ * The envelope matters more than it looks. Session-boundary 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
@@ -14,7 +22,7 @@
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
-import { mkdtempSync, writeFileSync } from "node:fs";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { fileURLToPath } from "node:url";
import { dirname, join, resolve } from "node:path";
@@ -40,6 +48,7 @@ const SCRIPT = resolve(
// then correctly declines to spawn.
let TMP_DIR = "";
let SENTINEL = "";
+let stateCounter = 0;
before(() => {
TMP_DIR = mkdtempSync(join(tmpdir(), "stop-checklist-"));
@@ -51,20 +60,41 @@ after(() => {
rmTemp(TMP_DIR);
});
-const runScript = (stdin: string | object | null) =>
- spawnHook(SCRIPT, stdin, { QMD_REFRESH_SENTINEL: SENTINEL });
+/** A fresh, isolated dedupe-state path, so no test sees another's history. */
+function freshState(): string {
+ stateCounter += 1;
+ return join(TMP_DIR, `checklist-state-${stateCounter}.json`);
+}
+
+/**
+ * Run the hook with an isolated sentinel and dedupe state. Pass the same
+ * `state` path to several calls to simulate one machine across turns.
+ */
+function run(
+ stdin: string | object | null,
+ opts: { readonly state?: string; readonly vault?: string } = {},
+) {
+ return spawnHook(SCRIPT, stdin, {
+ QMD_REFRESH_SENTINEL: SENTINEL,
+ STOP_CHECKLIST_STATE: opts.state ?? freshState(),
+ ...(opts.vault ? { CLAUDE_PROJECT_DIR: opts.vault } : {}),
+ });
+}
/** Parse stdout as the hook envelope, failing loudly if it isn't JSON. */
-function systemMessageOf(stdout: string): string {
- let parsed: unknown;
+function envelopeOf(stdout: string): Record<string, unknown> {
try {
- parsed = JSON.parse(stdout);
+ return JSON.parse(stdout) as Record<string, unknown>;
} catch {
- assert.fail(
+ return assert.fail(
`stop-checklist must write a JSON envelope to stdout — got:\n ${stdout}`,
);
}
- const message = (parsed as { systemMessage?: unknown }).systemMessage;
+}
+
+/** The envelope's systemMessage, failing loudly if absent. */
+function systemMessageOf(stdout: string): string {
+ const message = envelopeOf(stdout)["systemMessage"];
assert.equal(
typeof message,
"string",
@@ -73,14 +103,30 @@ function systemMessageOf(stdout: string): string {
return message as string;
}
+/** A vault with these completed notes left in work/active/ (none = clean). */
+function vault(name: string, ...completedNotes: string[]): string {
+ const root = join(TMP_DIR, name);
+ mkdirSync(join(root, "work/active"), { recursive: true });
+ for (const note of completedNotes) completeNote(root, note);
+ return root;
+}
+
+/** Leave `note` in work/active/ marked completed — one hygiene finding. */
+function completeNote(root: string, note: string): void {
+ writeFileSync(join(root, "work/active", note), "---\nstatus: completed\n---\n# Done\n");
+}
+
+// JSON.stringify drops an undefined session_id, so stop() is a Stop with none.
+const stop = (session_id?: string) => ({ session_id, hook_event_name: "Stop", stop_hook_active: false });
+
describe("stop-checklist", () => {
test("re-entry on strict boolean true emits the empty envelope", () => {
- const { stdout, code } = runScript({ stop_hook_active: true });
+ const { stdout, code } = run({ stop_hook_active: true });
assert.equal(code, 0);
// `{}` 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), {});
+ assert.deepEqual(envelopeOf(stdout), {});
});
test("re-entry writes its envelope before exiting", () => {
@@ -88,50 +134,154 @@ describe("stop-checklist", () => {
// 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 });
+ const { stdout } = run({ 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);
- const message = systemMessageOf(stdout);
- assert.match(message, /Session end checklist:/);
- assert.match(message, /Archive completed projects/);
+ 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);
+ assert.match(message, /Wrap-up checklist:/);
+ assert.match(message, /work\/active\/Done\.md/);
+ });
+
+ test("a later Stop with an unchanged report is silent (#252)", () => {
+ const root = vault("unchanged", "Done.md");
+ const state = freshState();
+ 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.deepEqual(envelopeOf(second.stdout), {});
+ assert.deepEqual(envelopeOf(third.stdout), {});
+ });
+
+ test("a Stop whose findings changed reports again", () => {
+ const root = vault("changed", "Done.md");
+ 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);
+ assert.match(message, /work\/active\/Also Done\.md/);
+ });
+
+ test("a report that returns to an earlier one is shown again (A → B → A)", () => {
+ // Drift fixed, then reintroduced: the last report shown was the clean
+ // one, so the returning finding is a change and must reach the user.
+ const root = vault("revert", "Done.md");
+ const state = freshState();
+ const a1 = run(stop("s-revert"), { vault: root, state });
+ rmSync(join(root, "work/active/Done.md"));
+ 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/);
+ });
+
+ test("a note growing past the threshold does not re-show the report", () => {
+ // The message carries "(31KB)"-style sizes and day ages; those move
+ // with no new drift, so they are left out of the comparison. A note
+ // the agent keeps appending to must not bring back the per-turn repeat.
+ const root = vault("growing");
+ mkdirSync(join(root, "notes"), { recursive: true });
+ const log = join(root, "notes/Log.md");
+ writeFileSync(log, "x".repeat(26_000));
+ const state = freshState();
+ 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.deepEqual(envelopeOf(second.stdout), {});
+ });
+
+ test("a new session reports again even when nothing changed", () => {
+ const root = vault("new-session", "Done.md");
+ 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/);
+ });
+
+ test("a clean vault still gets the checklist once, then silence", () => {
+ const root = vault("clean-vault");
+ 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.deepEqual(envelopeOf(second.stdout), {});
+ });
+
+ test("a Stop without a session_id fails open and reports every time", () => {
+ // Same rule as the classifier's hint dedupe (#107): no key to
+ // remember by means today's behaviour, never silence.
+ 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:/);
+ });
+
+ 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:/);
+ });
+
+ 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:/);
+ });
+
+ test("SessionEnd reports every time — it is the last chance, not a turn", () => {
+ const root = vault("session-end", "Done.md");
+ const state = freshState();
+ 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/);
});
- test("emits the checklist when stop_hook_active is string 'true' (not strict)", () => {
- const { stdout } = runScript({ stop_hook_active: "true" });
- assert.match(systemMessageOf(stdout), /Session end checklist:/);
+ test("SessionEnd after a deduped Stop still reports", () => {
+ const root = vault("stop-then-end", "Done.md");
+ 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/);
});
- test("emits the checklist when the field is absent", () => {
- const { stdout } = runScript({});
- assert.match(systemMessageOf(stdout), /Session end checklist:/);
+ test("the checklist hands drift to om-tidy", () => {
+ const message = systemMessageOf(run(stop("s-handoff")).stdout);
+ assert.match(message, /ask the agent to run om-tidy/i);
});
- test("emits valid JSON on malformed input (safe default)", () => {
- const { stdout, code } = runScript("garbage{{");
+ test("malformed input emits a valid default", () => {
+ const { stdout, code } = run("garbage{{");
assert.equal(code, 0);
- assert.match(systemMessageOf(stdout), /Session end checklist:/);
+ assert.match(systemMessageOf(stdout), /Wrap-up checklist:/);
});
- test("emits valid JSON on empty stdin", () => {
- const { stdout, code } = runScript(null);
+ test("empty stdin emits a valid default", () => {
+ const { stdout, code } = run(null);
assert.equal(code, 0);
- assert.match(systemMessageOf(stdout), /Session end checklist:/);
+ assert.match(systemMessageOf(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(runScript({}).stdout);
+ const message = systemMessageOf(run({}).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.
+ // One script serves three agents whose payloads differ in shape: Claude
+ // Code and Codex call it on Stop, Gemini on SessionEnd. Payloads mirror
+ // each vendor's documented schema. Each runs against fresh state, so the
+ // first report of each is the one compared.
const AGENT_PAYLOADS: ReadonlyArray<{
readonly label: string;
readonly payload: Record<string, unknown>;
@@ -176,10 +326,10 @@ describe("stop-checklist", () => {
const rendered = new Set<string>();
for (const { label, payload } of AGENT_PAYLOADS) {
test(`${label} receives the same JSON envelope`, () => {
- const { stdout, code } = runScript(payload);
+ const { stdout, code } = run(payload);
assert.equal(code, 0);
const message = systemMessageOf(stdout);
- assert.match(message, /Session end checklist:/);
+ assert.match(message, /Wrap-up checklist:/);
rendered.add(message);
});
}
diff --git a/.claude/scripts/tidy-fix.ts b/.claude/scripts/tidy-fix.ts
index d1d7ebd..3e0f002 100644
--- a/.claude/scripts/tidy-fix.ts
+++ b/.claude/scripts/tidy-fix.ts
@@ -61,6 +61,7 @@ import {
} from "./lib/active-hygiene.ts";
import { generateMemoryIndex } from "./lib/automemory-index.ts";
import { collectBrainNotes } from "./generate-memory-index.ts";
+import { resolveProjectDir } from "./lib/project-dir.ts";
const ACTIVE_REL = "work/active";
@@ -262,7 +263,7 @@ function fixMisplacedMemory(
function main(): void {
const apply = process.argv.includes("--apply");
- const vaultRoot = (process.env["CLAUDE_PROJECT_DIR"] || process.cwd())
+ const vaultRoot = resolveProjectDir(process.cwd())
.replaceAll("\\", "/")
.replace(/\/+$/, "");
diff --git a/.claude/scripts/validate-write.ts b/.claude/scripts/validate-write.ts
index cf51996..bdc930e 100644
--- a/.claude/scripts/validate-write.ts
+++ b/.claude/scripts/validate-write.ts
@@ -34,6 +34,7 @@ import {
shouldRefreshForPath,
triggerDebouncedRefresh,
} from "./lib/qmd-refresh.ts";
+import { resolveProjectDir } from "./lib/project-dir.ts";
type HookInput = {
readonly tool_input?: unknown;
@@ -128,9 +129,9 @@ if (isBlockedMemoryPath(filePath) || isBlockedMemoryPath(resolvedPath)) {
// Vault-root skip AFTER the memory guard (which must inspect outside-vault
// paths): files outside the vault are not vault notes — no validation.
-// Boundary-safe: "/vault" must not match "/vaulting/…", and an empty env
-// value falls back to cwd (|| not ??).
-const vaultRoot = (process.env["CLAUDE_PROJECT_DIR"] || process.cwd())
+// Boundary-safe: "/vault" must not match "/vaulting/…"; an empty env value
+// falls back to cwd (lib/project-dir.ts).
+const vaultRoot = resolveProjectDir(process.cwd())
.replaceAll("\\", "/")
.replace(/\/+$/, "");
const filePathFwd = filePath.replaceAll("\\", "/");
diff --git a/.gitignore b/.gitignore
index 578e5d9..327e452 100644
--- a/.gitignore
+++ b/.gitignore
@@ -35,6 +35,7 @@ node_modules/
# Hook runtime state (local, self-pruning / debounce sentinel)
.claude/scripts/.hint-state.json
+.claude/scripts/.checklist-state.json
.claude/scripts/.qmd-refresh-sentinel
# MCP server audit log — every vault read, with the calling repo and the query
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 0b6d097..d35df48 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -11,7 +11,7 @@ It is not a folder tour. For the day-to-day layout, read `CLAUDE.md`. For the us
obsidian-mind is a plain Obsidian vault with four systems layered on top:
1. **The vault itself** — Markdown files, frontmatter, wikilinks. Portable, git-tracked, Obsidian-browsable.
-2. **A hook pipeline** — small TypeScript scripts invoked by the agent harness at lifecycle events (session start, every message, after writes, before compaction, at session end).
+2. **A hook pipeline** — small TypeScript scripts invoked by the agent harness at lifecycle events (session start, every message, after writes, before compaction, after each response; Gemini at session end).
3. **A semantic search layer (QMD)** — a separate CLI + SQLite index + MCP server, all scoped to a named index read from `vault-manifest.json`.
4. **The `om` MCP server** — the vault as a service, so a session running in a *different repository* can search it, read notes, follow the graph, and record back into it.
@@ -191,18 +191,21 @@ sequenceDiagram
Agent->>Hooks: PreCompact
Hooks->>Vault: back up transcript to thinking/session-logs/
- User->>Agent: end session
- Agent->>Hooks: Stop
- Hooks-->>Agent: wrap-up checklist reminder
+ loop each completed response
+ Agent->>Hooks: Stop
+ Hooks->>QMD: debounced refresh (detached)
+ Hooks-->>User: checklist + hygiene, first time this session or when changed
+ end
```
A few specific design choices are worth calling out:
- **`SessionStart` injects, it does not load.** It builds a briefing (filename listing, North Star excerpt, git summary, open tasks aggregated from `work/active/` and the vault root) and hands it to the agent. Full note contents never flow through this hook. Its size is bounded by `eager_layer_budget_bytes` and reported by the meter on the last line of every injection, so the cost is visible rather than assumed. The open-tasks scan is filesystem-only so the hook never spawns the Obsidian CLI — that subprocess flashes the Electron app on macOS when no instance is running (#83).
- **`UserPromptSubmit` classifies, it does not route.** It tags the prompt with hints like `ARCHITECTURE discussion` or `DECISION`; the agent decides where to file. Keeping the hook opinion-free means the routing logic lives in `CLAUDE.md`, which is editable per-user without touching scripts.
-- **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` (end of session) — 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.
+- **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` is deliberately lightweight.** Beyond triggering the shared refresh, it only prints a short checklist. For a thorough review, the user invokes `/om-wrap-up` explicitly. Putting heavy logic in a Stop hook would slow every session exit and surprise the user.
+- **`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.
+- **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.
---
@@ -214,7 +217,7 @@ QMD provides semantic search. It is the mechanism behind most of the agent's ret
|--------|-------------|------|
| Agent tool menu | `.mcp.json` → `qmd-mcp.mjs` | Every `mcp__qmd__*` tool call from a session inside the vault |
| Session startup | `session-start.ts` | Re-index on every new session |
-| Mid-session refresh | `validate-write.ts` / `stop-checklist.ts` / `pre-compact.ts` → `lib/qmd-refresh.ts` (shared sentinel + debounce) → detached `qmd-refresh-run.ts` | After `.md` writes, at session end, and before compaction |
+| Mid-session refresh | `validate-write.ts` / `stop-checklist.ts` / `pre-compact.ts` → `lib/qmd-refresh.ts` (shared sentinel + debounce) → detached `qmd-refresh-run.ts` | After `.md` writes, after responses, and before compaction |
| The `om` server | `lib/mcp-qmd-client.ts` (search) and `reindexSync` (after a write) | Every `search`, every queried `recall`, every `remember` / `record_work` |
Every `qmd update` invocation re-reads the per-index YAML (`~/.config/qmd/<index>.yml`), so changes to the collection config — including the ignore list synced from `.obsidian/app.json` — propagate to every surface without a session restart.
@@ -869,9 +872,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, and so are the arguments they are invoked with.
+The 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-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.
+Session-boundary output is JSON-or-nothing on all three agents. `stop-checklist.ts` emits `{"systemMessage": ...}` when it reports and `{}` when a Stop has nothing new to say. `systemMessage` is intentionally a user warning rather than model context: it tells the user what to ask for, but it cannot make the agent act. That is why `om-wrap-up` owns the acting path and the hook owns only the report.
```mermaid
flowchart TB
diff --git a/CLAUDE.md b/CLAUDE.md
index a211a7e..beb4cdf 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 | End of every session | Lightweight checklist reminder + concrete vault-hygiene drift findings (same scan as SessionStart). 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`. Also triggers the debounced QMD refresh. For thorough review, use `/om-wrap-up` instead. |
## Write-Correctness Laws
diff --git a/README.ja.md b/README.ja.md
index 32edfc8..288d9ce 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -198,7 +198,7 @@ QMDは**3つの小さなモデルをローカルで**実行します。設定す
| 💬 UserPromptSubmit | 全メッセージ | コンテンツを分類(意思決定、インシデント、実績、1on1、アーキテクチャ、人物、プロジェクト更新)してルーティングヒントを注入 |
| ✍️ PostToolUse | `.md`書き込み後 | フロントマター+ウィキリンクの検証、誤配置メモリファイルのブロック、肥大ノート(削るのではなく分割)と書き込み時トピッククラスタのフラグ |
| 💾 PreCompact | コンテキスト圧縮前 | セッション記録を`thinking/session-logs/`にバックアップ |
-| 🏁 Stop | セッション終了時 | チェックリスト+具体的なドリフト検出(SessionStartと同じ衛生スキャン) |
+| 🏁 Stop | 各応答の終了時 | チェックリスト+具体的なドリフト検出(SessionStartと同じ衛生スキャン)。セッションごとに1回、内容が変わった時のみ再表示。対応は`om-tidy`へ |
> [!TIP]
> ただ話すだけ。フックがルーティングを処理します。
diff --git a/README.ko.md b/README.ko.md
index 66d6264..a17db2b 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -198,7 +198,7 @@ QMD는 **세 개의 작은 모델을 로컬에서** 실행하므로, 설정할 A
| 💬 UserPromptSubmit | 매 메시지마다 | 콘텐츠 분류(의사결정, 인시던트, 성과, 1:1, 아키텍처, 인물, 프로젝트 업데이트) 및 라우팅 힌트 주입 |
| ✍️ PostToolUse | `.md` 작성 후 | 프론트매터+위키링크 검증, 잘못 배치된 메모리 파일 차단, 비대 노트(줄이지 말고 분할)와 작성 시점 토픽 클러스터 플래그 |
| 💾 PreCompact | 컨텍스트 압축 전 | 세션 트랜스크립트를 `thinking/session-logs/`에 백업 |
-| 🏁 Stop | 세션 종료 시 | 체크리스트+구체적인 드리프트 발견 (SessionStart와 동일한 위생 스캔) |
+| 🏁 Stop | 각 응답 종료 시 | 체크리스트+구체적인 드리프트 발견 (SessionStart와 동일한 위생 스캔). 세션당 한 번, 내용이 바뀔 때만 다시 표시. 조치는 `om-tidy`로 |
> [!TIP]
> 그냥 이야기하세요. 훅이 라우팅을 처리합니다.
diff --git a/README.md b/README.md
index bf287a3..6db70c5 100644
--- a/README.md
+++ b/README.md
@@ -205,7 +205,7 @@ Five lifecycle hooks handle routing automatically:
| 💬 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 oversized notes (split, don't trim) and write-time topic clusters |
| 💾 PreCompact | Before context compaction | Backs up session transcript to `thinking/session-logs/` |
-| 🏁 Stop | End of session | Checklist + concrete drift findings (same hygiene scan as SessionStart) |
+| 🏁 Stop | After every response | Checklist + concrete drift findings (same hygiene scan as SessionStart), shown once per session and again only when they change; hands drift to `om-tidy` |
> [!TIP]
> You just talk. The hooks handle the routing.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 3335d07..f507d70 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -198,7 +198,7 @@ QMD **在本地运行三个小模型**,因此不需要配置 API 密钥,没
| 💬 UserPromptSubmit | 每条消息 | 对内容分类(决策、事件、成就、1:1、架构、人员、项目更新)并注入路由提示 |
| ✍️ PostToolUse | 写入 `.md` 后 | 验证 frontmatter+wikilinks,拦截误放的记忆文件,标记过大笔记(拆分而非删减)与写入时的主题集群 |
| 💾 PreCompact | 上下文压缩前 | 将会话记录备份到 `thinking/session-logs/` |
-| 🏁 Stop | 会话结束时 | 检查清单+具体漂移发现(与 SessionStart 相同的卫生扫描) |
+| 🏁 Stop | 每次响应结束后 | 检查清单+具体漂移发现(与 SessionStart 相同的卫生扫描),每个会话显示一次,仅在内容变化时再次显示;处理交给 `om-tidy` |
> [!TIP]
> 你只需要正常对话。钩子会处理路由。
diff --git a/brain/Skills.md b/brain/Skills.md
index d7935f6..ca7dd41 100644
--- a/brain/Skills.md
+++ b/brain/Skills.md
@@ -106,7 +106,7 @@ Subagents run in isolated context windows via `.claude/agents/`. They don't poll
| UserPromptSubmit | Every message | Classify content (decision, incident, 1:1, win, architecture, person, project update) and inject routing hints |
| PostToolUse | After writing `.md` | Validates frontmatter, checks for wikilinks |
| PreCompact | Before context compaction | Back up session transcript to `thinking/session-logs/` |
-| Stop | End of session | Checklist: archive, update indexes, check orphans |
+| Stop | After every response | Checklist + hygiene findings, once per session and again when they change; ask the agent to run `om-tidy` to act |
## Semantic Search (QMD)