Skip to content

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

fix: the Stop report shows the user a summary and reaches the agent with the next prompt (#261)

Brenno Ferrari9c17cb3d7b2f
diff --git a/.claude/scripts/classify-message.ts b/.claude/scripts/classify-message.ts
index aeb3414..c218575 100644
--- a/.claude/scripts/classify-message.ts
+++ b/.claude/scripts/classify-message.ts
@@ -4,8 +4,10 @@
*
* Reads the hook JSON payload from stdin, inspects the `prompt` field for
* signal patterns (see lib/signals.ts), and emits a hookSpecificOutput
- * envelope on stdout with one hint per matched signal. Exits 0 silently on
- * malformed input, missing prompt, or zero matches.
+ * envelope on stdout with one hint per matched signal. Also hands the agent
+ * the previous turn's Stop report when one is waiting (lib/stop-handoff.ts).
+ * Exits 0 silently on malformed input, or when there is neither a hint nor a
+ * waiting report.
*/
import { dirname, join } from "node:path";
@@ -13,6 +15,7 @@ import { fileURLToPath } from "node:url";
import { debug, readStdinJson, writeHookOutput } from "./lib/hook-io.ts";
import { classify } from "./lib/matcher.ts";
import { claimUnseen } from "./lib/hint-state.ts";
+import { HANDOFF_DIR, takeHandoff } from "./lib/stop-handoff.ts";
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
// CLASSIFY_HINT_STATE routes the state file into a tmp path for tests
@@ -32,20 +35,22 @@ if (!input) {
process.exit(0);
}
-const prompt = input.prompt;
-if (typeof prompt !== "string" || !prompt) {
- debug(`classify: no usable prompt (type=${typeof prompt})`);
- process.exit(0);
-}
+// The previous turn's Stop report, if one is waiting (lib/stop-handoff.ts).
+// Taken before anything about the prompt is checked: it rides with this
+// prompt whatever the prompt holds.
+const sessionId = input.session_id;
+const stopReport = typeof sessionId === "string" && sessionId ? takeHandoff(HANDOFF_DIR, sessionId) : null;
-const signals = classify(prompt);
+const prompt = input.prompt;
+const usable = typeof prompt === "string" && prompt !== "";
+if (!usable) debug(`classify: no usable prompt (type=${typeof prompt})`);
+const signals = usable ? classify(prompt) : [];
debug(`classify: matched ${signals.length} signal(s)`);
// Once-per-session dedupe (#107): each hint fires once per session_id via
// a self-pruning state file (7-day age + 200-session cap). Missing/invalid
// session_id fails OPEN — every hint emits, matching today's behavior.
let toEmit = signals;
-const sessionId = input.session_id;
if (typeof sessionId === "string" && sessionId && signals.length > 0) {
toEmit = claimUnseen(STATE_PATH, sessionId, signals);
debug(
@@ -53,19 +58,24 @@ if (typeof sessionId === "string" && sessionId && signals.length > 0) {
);
}
+const parts: string[] = [];
if (toEmit.length > 0) {
const hints = toEmit.map((s) => `- ${s}`).join("\n");
- const additionalContext =
+ parts.push(
"Content classification hints (act on these if the user's message contains relevant info):\n" +
- hints +
- "\n\nRemember: use proper templates, add [[wikilinks]], follow CLAUDE.md conventions.";
+ hints +
+ "\n\nRemember: use proper templates, add [[wikilinks]], follow CLAUDE.md conventions.",
+ );
+}
+if (stopReport !== null) parts.push(stopReport);
+if (parts.length > 0) {
const eventName =
typeof input.hook_event_name === "string"
? input.hook_event_name
: "UserPromptSubmit";
- writeHookOutput(eventName, additionalContext);
+ writeHookOutput(eventName, parts.join("\n\n"));
}
process.exit(0);
diff --git a/.claude/scripts/lib/active-hygiene.ts b/.claude/scripts/lib/active-hygiene.ts
index 2aa6cf7..d3cb8da 100644
--- a/.claude/scripts/lib/active-hygiene.ts
+++ b/.claude/scripts/lib/active-hygiene.ts
@@ -671,6 +671,33 @@ export function namesCapped(names: readonly string[]): string {
return more === null ? shown.join(", ") : [...shown, more].join(", ");
}
+/**
+ * Each finding's claim: what it says, without its file list or instructions.
+ * The formatter's headline opens with it, and a Stop summary is made of them
+ * (lib/stop-report.ts), so the two cannot drift apart.
+ */
+const claims = {
+ completed: (n: number) => `${n} note(s) marked done but still in active/`,
+ clusters: () => "Loose active/ notes that look like one topic",
+ oversized: (n: number) => `${n} note(s) past the ${MONOLITH_BYTES / 1000}KB organization threshold`,
+ openLoops: (n: number) => `${n} note(s) with open follow-ups untouched ${OPEN_LOOP_DAYS}+ days`,
+ inbox: (n: number) => `${n} raw export(s) sitting in work/meetings/ for ${INBOX_PRESSURE_DAYS}+ days`,
+ memoryInbox: (n: number) => `${n} cross-repo memory capture(s) awaiting review`,
+};
+
+/** The claim of every finding in `report`, in the order the formatter lists them. */
+export function hygieneClaims(report: ActiveHygieneReport): string[] {
+ const { completedInActive, ungroupedClusters, oversizedNotes, openLoops, inboxPressure, memoryInbox } = report;
+ const out: string[] = [];
+ if (completedInActive.length > 0) out.push(claims.completed(completedInActive.length));
+ if (ungroupedClusters.length > 0) out.push(claims.clusters());
+ if (oversizedNotes.length > 0) out.push(claims.oversized(oversizedNotes.length));
+ if (openLoops.length > 0) out.push(claims.openLoops(openLoops.length));
+ if (inboxPressure !== null) out.push(claims.inbox(inboxPressure.count));
+ if (memoryInbox !== null) out.push(claims.memoryInbox(memoryInbox.count));
+ return out;
+}
+
/**
* Render the report as markdown lines for hook output. Returns [] when the
* vault is clean, so callers can skip emitting a section entirely.
@@ -698,7 +725,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/ (ask the agent to run om-project-archive):`,
+ `⚠️ ${claims.completed(completedInActive.length)} — archive to archive/YYYY/ (ask the agent to run om-project-archive):`,
);
lines.push(...listCapped(completedInActive, (p) => ` - ${p}`));
}
@@ -706,7 +733,7 @@ export function formatActiveHygiene(report: ActiveHygieneReport): string[] {
if (ungroupedClusters.length > 0) {
if (lines.length > 0) lines.push("");
lines.push(
- "⚠️ Loose active/ notes that look like one topic — consider a folder (active/<Topic>/):",
+ `⚠️ ${claims.clusters()} — consider a folder (active/<Topic>/):`,
);
lines.push(...listCapped(ungroupedClusters, ({ token, files }) => ` - "${token}": ${namesCapped(files)}`));
}
@@ -714,7 +741,7 @@ export function formatActiveHygiene(report: ActiveHygieneReport): string[] {
if (oversizedNotes.length > 0) {
if (lines.length > 0) lines.push("");
lines.push(
- `⚠️ ${oversizedNotes.length} note(s) past the ${MONOLITH_BYTES / 1000}KB organization threshold — do NOT trim content; SPLIT (domain notes / event-log satellites / a cluster folder, verbatim, one-liner index behind):`,
+ `⚠️ ${claims.oversized(oversizedNotes.length)} — do NOT trim content; SPLIT (domain notes / event-log satellites / a cluster folder, verbatim, one-liner index behind):`,
);
lines.push(...listCapped(oversizedNotes, ({ path, sizeKb }) => ` - ${path} (${sizeKb}KB)`));
}
@@ -722,7 +749,7 @@ export function formatActiveHygiene(report: ActiveHygieneReport): string[] {
if (openLoops.length > 0) {
if (lines.length > 0) lines.push("");
lines.push(
- `⚠️ ${openLoops.length} note(s) with open follow-ups untouched ${OPEN_LOOP_DAYS}+ days — close, chase, or consciously park (paths + counts only by design):`,
+ `⚠️ ${claims.openLoops(openLoops.length)} — close, chase, or consciously park (paths + counts only by design):`,
);
for (const { path, ageDays, openItems } of openLoops) {
lines.push(` - ${path} (${ageDays}d, ${openItems} open item(s))`);
@@ -732,7 +759,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) — ask the agent to run om-intake to drain the inbox.`,
+ `⚠️ ${claims.inbox(inboxPressure.count)} (oldest ${inboxPressure.oldestDays}d) — ask the agent to run om-intake to drain the inbox.`,
);
}
@@ -742,7 +769,7 @@ export function formatActiveHygiene(report: ActiveHygieneReport): string[] {
if (memoryInbox !== null) {
if (lines.length > 0) lines.push("");
lines.push(
- `⚠️ ${memoryInbox.count} cross-repo memory capture(s) awaiting review (oldest ${memoryInbox.oldestDays}d). Promote a durable one by COPYING it into the right brain/ note and adding \`promoted: "brain/Note#^om-a1b2c3"\` to the capture's frontmatter, pointing at the block you copied — the entry stays, because recall reaches brain/ only THROUGH a capture, so deleting it takes the lesson away from every repo that cannot read brain/ at all. The ANCHOR is what lets recall serve the corrected text; a bare \`promoted: <note>\` clears this count but serves nothing.`,
+ `⚠️ ${claims.memoryInbox(memoryInbox.count)} (oldest ${memoryInbox.oldestDays}d). Promote a durable one by COPYING it into the right brain/ note and adding \`promoted: "brain/Note#^om-a1b2c3"\` to the capture's frontmatter, pointing at the block you copied — the entry stays, because recall reaches brain/ only THROUGH a capture, so deleting it takes the lesson away from every repo that cannot read brain/ at all. The ANCHOR is what lets recall serve the corrected text; a bare \`promoted: <note>\` clears this count but serves nothing.`,
);
// Evidence for the sentence above, from this vault rather than in the
// abstract. Told once the flag is already firing — it never raises one of
diff --git a/.claude/scripts/lib/atomic-write.ts b/.claude/scripts/lib/atomic-write.ts
index f0642ad..fa4a04f 100644
--- a/.claude/scripts/lib/atomic-write.ts
+++ b/.claude/scripts/lib/atomic-write.ts
@@ -18,7 +18,7 @@
* half-written note for the indexer to pick up.
*/
-import { writeFileSync, copyFileSync, unlinkSync, constants } from "node:fs";
+import { writeFileSync, copyFileSync, renameSync, unlinkSync, constants } from "node:fs";
import { join } from "node:path";
/** Per-process counter, so two in-flight writes cannot share a temp name. */
@@ -79,3 +79,24 @@ export function claimFile(
}
}
}
+
+/**
+ * Replace `path` with `text` through a temp file and a rename, so a reader
+ * never sees half a file and a process killed mid-write leaves the previous
+ * one. Unlike `claimFile`, it overwrites. Throws if it cannot, after removing
+ * its temp file.
+ */
+export function writeFileAtomic(path: string, text: string): void {
+ const tmp = `${path}.${process.pid}-${++tmpSeq}.tmp`;
+ try {
+ writeFileSync(tmp, text, "utf8");
+ renameSync(tmp, path);
+ } catch (err) {
+ try {
+ unlinkSync(tmp);
+ } catch {
+ /* nothing was written */
+ }
+ throw err;
+ }
+}
diff --git a/.claude/scripts/lib/hint-state.ts b/.claude/scripts/lib/hint-state.ts
index 0df4644..012c77f 100644
--- a/.claude/scripts/lib/hint-state.ts
+++ b/.claude/scripts/lib/hint-state.ts
@@ -25,7 +25,8 @@
* worst case is one duplicate hint, which is acceptable.
*/
-import { readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
+import { readFileSync } from "node:fs";
+import { writeFileAtomic } from "./atomic-write.ts";
import { debug } from "./hook-io.ts";
export type HintSessionEntry = {
@@ -131,17 +132,10 @@ function loadHintState(path: string): HintState {
* 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);
+ writeFileAtomic(path, JSON.stringify(prune(state, now.getTime())));
} 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 */
- }
}
}
diff --git a/.claude/scripts/lib/hook-io.ts b/.claude/scripts/lib/hook-io.ts
index 0bf5f15..9ac5866 100644
--- a/.claude/scripts/lib/hook-io.ts
+++ b/.claude/scripts/lib/hook-io.ts
@@ -86,9 +86,10 @@ export function writeHookOutput(
* `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.
+ * On Stop, `hookSpecificOutput.additionalContext` is not an alternative: it is
+ * feedback for the model that *continues the conversation*, and Claude Code
+ * prints it in full for the user too, so it is used only as a fallback
+ * (`writeStopFeedback`).
*
* Session-end stdout is JSON-or-nothing on every agent we ship configs for:
* Codex rejects plain text outright, Gemini's SessionEnd contract is
@@ -96,7 +97,8 @@ export function writeHookOutput(
* and Claude Code routes non-exempt plain stdout to the debug log where
* nobody reads it. So there is no text path worth keeping.
*
- * To reach the model as well, a Stop hook uses `writeStopBlock` instead.
+ * A Stop hook's full report reaches the model with the next prompt instead
+ * (lib/stop-handoff.ts); `writeStopFeedback` is its fallback.
*/
export function writeSystemMessage(message: string): void {
const overhead = JSON.stringify({ systemMessage: "" }).length - 2;
@@ -171,22 +173,32 @@ export function fitHookOutput(
}
/**
- * 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.
+ * The fallback when a Stop report cannot be saved for the next prompt: the
+ * agent gets `report` now, and the user is shown `summary`.
*
- * `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,
- * so stop-checklist uses it only when its findings change, and relies on
- * `stop_hook_active` to keep the forced turn's own Stop from blocking again.
- * Claude Code honours it on Stop, and labels it "Stop hook error occurred" in
- * its UI even on success; Codex documents the same field. Gemini runs the
- * checklist on SessionEnd and never gets it.
+ * Stop's `hookSpecificOutput.additionalContext` is "non-error feedback for
+ * Claude: the conversation continues so Claude can act on it", under the same
+ * loop protections as a block (`stop_hook_active`, the continuation cap). It is
+ * not labelled an error, but Claude Code prints it in full in the transcript
+ * as "Stop hook feedback", so the user reads the whole report too. That is why
+ * it is the fallback and not the path: the next prompt's UserPromptSubmit is
+ * the one channel the user never sees (lib/stop-handoff.ts). A
+ * `decision: "block"` reason is printed in full as well, and labelled a hook
+ * error.
+ *
+ * Both fields share one output cap: the summary gets at most a third, the
+ * report whatever is left. Gemini runs the checklist on SessionEnd and never
+ * gets this. Codex documents Stop's `decision`, but whether it honours Stop
+ * `additionalContext` is unverified.
*/
-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) }));
+export function writeStopFeedback(report: string, summary: string): void {
+ const shown = fitEncoded(summary, Math.floor(HOOK_OUTPUT_MAX_CHARS / 3));
+ const envelope = (context: string) => ({
+ systemMessage: shown,
+ hookSpecificOutput: { hookEventName: "Stop", additionalContext: context },
+ });
+ const overhead = JSON.stringify(envelope("")).length - 2;
+ process.stdout.write(JSON.stringify(envelope(fitEncoded(report, HOOK_OUTPUT_MAX_CHARS - overhead))));
}
/**
diff --git a/.claude/scripts/lib/stop-handoff.ts b/.claude/scripts/lib/stop-handoff.ts
new file mode 100644
index 0000000..50d0f25
--- /dev/null
+++ b/.claude/scripts/lib/stop-handoff.ts
@@ -0,0 +1,93 @@
+/**
+ * Stop → UserPromptSubmit handoff for the Stop report.
+ *
+ * Every Stop output that reaches the model is also printed in the user's
+ * transcript: a `decision: "block"` reason in full under a "Stop hook error"
+ * label, and Stop `additionalContext` in full under "Stop hook feedback"
+ * (both seen in a real terminal session, Claude Code 2.1.287). UserPromptSubmit
+ * `additionalContext` is the one channel the model reads and the user never
+ * sees. So Stop shows the user a one-line-per-section summary and saves the
+ * full report here, and the next UserPromptSubmit in the same session hands it
+ * to the model once and removes it.
+ *
+ * One file per session, so two sessions never read each other's report (the
+ * shared mailbox an earlier design used lost reports under concurrency). A
+ * write lands through a temp file and a rename, so a reader never sees half a
+ * report. A read claims the file by renaming it first, so two racing hooks
+ * cannot both deliver it. The newest report replaces an unread older one,
+ * because it describes the current state. A report that cannot be written
+ * throws, so Stop can send it as feedback instead; one that cannot be read is
+ * null. Neither breaks a hook.
+ *
+ * A report saved just before /clear or the end of a session is never
+ * collected: the next prompt arrives under a new session id. Nothing is lost
+ * with it. The dedupe is per session, so the new session's first Stop reports
+ * the same findings again, and the prune removes the orphan after a week.
+ */
+
+import { mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { writeFileAtomic } from "./atomic-write.ts";
+
+/**
+ * Where a Stop report waits for the next prompt: one place for the writer
+ * (stop-checklist) and the reader (classify-message), so they cannot drift
+ * apart. STOP_HANDOFF_DIR routes it to a tmp path for tests.
+ */
+export const HANDOFF_DIR =
+ process.env["STOP_HANDOFF_DIR"] ?? join(dirname(fileURLToPath(import.meta.url)), "..", ".stop-handoff");
+
+/** Reports nobody picked up are removed after this long. */
+export const HANDOFF_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
+
+/** The session's handoff file. Session ids are reduced to a safe filename. */
+export function handoffPath(dir: string, sessionId: string): string {
+ return join(dir, `${sessionId.replace(/[^A-Za-z0-9_-]/g, "_")}.txt`);
+}
+
+/** Save `text` for the session's next prompt, replacing any unread report. Throws if it cannot. */
+export function writeHandoff(dir: string, sessionId: string, text: string): void {
+ mkdirSync(dir, { recursive: true });
+ writeFileAtomic(handoffPath(dir, sessionId), text);
+}
+
+/** Take the session's report, once. Null when there is none or it cannot be claimed. */
+export function takeHandoff(dir: string, sessionId: string): string | null {
+ const target = handoffPath(dir, sessionId);
+ const claimed = `${target}.${process.pid}.claimed`;
+ try {
+ renameSync(target, claimed);
+ } catch {
+ return null; // none waiting, or another hook claimed it first
+ }
+ try {
+ return readFileSync(claimed, "utf8");
+ } catch {
+ return null;
+ } finally {
+ try {
+ unlinkSync(claimed);
+ } catch {
+ /* best effort */
+ }
+ }
+}
+
+/** Remove reports and leftovers older than `maxAgeMs`. Best effort. */
+export function pruneHandoffs(dir: string, now: number, maxAgeMs: number = HANDOFF_MAX_AGE_MS): void {
+ let names: string[];
+ try {
+ names = readdirSync(dir);
+ } catch {
+ return;
+ }
+ for (const name of names) {
+ const full = join(dir, name);
+ try {
+ if (now - statSync(full).mtimeMs > maxAgeMs) unlinkSync(full);
+ } catch {
+ /* best effort */
+ }
+ }
+}
diff --git a/.claude/scripts/lib/stop-report.ts b/.claude/scripts/lib/stop-report.ts
new file mode 100644
index 0000000..70312e6
--- /dev/null
+++ b/.claude/scripts/lib/stop-report.ts
@@ -0,0 +1,33 @@
+/**
+ * The Stop report in two forms: a short summary for the user and the full
+ * report for the agent. Why two, and how the full one travels: lib/stop-handoff.ts.
+ */
+
+/** What both framings close with, so the two cannot drift apart on it. */
+const STANDING_RULES = "Never move or delete notes without asking, and do not recite the report back.";
+
+/** Framing for the agent, which reads the report alongside the user's next message. */
+export const AGENT_PREFACE = `Stop hook report, handed over with this message: when your previous response ended, these findings were new or changed since the last report this session. The user saw only a one-line summary of each section. Deal with the user's message first, then decide what the report calls for: act on what bears on the current work, ask the user when something needs their call, or leave it unmentioned if nothing needs doing. ${STANDING_RULES}`;
+
+/** The closing line of the summary: where the detail went. */
+export const SUMMARY_TRAILER = "The full report reaches the agent with your next message.";
+
+/**
+ * The same pair for the fallback, when the report could not be saved and goes
+ * out now as Stop feedback: the agent gets it at once, in a turn with no user
+ * message, and Claude Code prints it in full for the user too.
+ */
+export const FEEDBACK_PREFACE = `Stop hook report: your response just ended, and these findings are new or changed since the last report this session; the user is shown this report too. 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. ${STANDING_RULES}`;
+export const FEEDBACK_TRAILER = "The full report went to the agent now, as Stop hook feedback.";
+
+/**
+ * The user's copy: the checklist reduced to one line, one line naming each
+ * hygiene finding by its claim (`hygieneClaims` in lib/active-hygiene.ts: no
+ * file lists, no instructions), and where the full report went (`trailer`).
+ */
+export function stopSummary(checklistLine: string, claims: readonly string[], trailer: string = SUMMARY_TRAILER): string {
+ const lines = [checklistLine];
+ if (claims.length > 0) lines.push(`Hygiene: ${claims.join(" · ")}`);
+ lines.push(trailer);
+ return lines.join("\n");
+}
diff --git a/.claude/scripts/stop-checklist.ts b/.claude/scripts/stop-checklist.ts
index 58f7e85..2fb7e3f 100644
--- a/.claude/scripts/stop-checklist.ts
+++ b/.claude/scripts/stop-checklist.ts
@@ -22,22 +22,21 @@
*
* Who reads it: a Stop hook's systemMessage reaches the user and never the
* agent, so the drift the agent is best placed to fix never reached it
- * (#256). On a Stop whose findings changed, the hook 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 and a Stop without a session_id never block: SessionEnd has no
- * turn to give, and without a session_id nothing stops a block repeating.
+ * (#256). On a Stop whose findings changed, the user gets a
+ * one-line-per-section summary as the `systemMessage`, and the full report is
+ * saved for the session's next prompt, where classify-message hands it to the
+ * agent (why that channel: lib/stop-handoff.ts). If the report cannot be
+ * saved, it goes out as Stop feedback instead: visible, but not lost (Claude
+ * Code; Codex's handling of Stop feedback is unverified, lib/hook-io.ts).
+ * SessionEnd and a Stop without a session_id have no next prompt to ride: the
+ * user gets the full report.
*
* 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. 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).
+ * Claude Code otherwise files non-exempt stdout in the debug log.
+ * `systemMessage` is the one user-facing field all three agents share. Both it
+ * and the handed-over report are 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.
*/
@@ -48,12 +47,15 @@ import { fileURLToPath } from "node:url";
import {
readStdinJson,
writeSilentHookOutput,
- writeStopBlock,
+ writeStopFeedback,
writeSystemMessage,
} from "./lib/hook-io.ts";
import { triggerDebouncedRefresh } from "./lib/qmd-refresh.ts";
+import { HANDOFF_DIR, pruneHandoffs, writeHandoff } from "./lib/stop-handoff.ts";
+import { AGENT_PREFACE, FEEDBACK_PREFACE, FEEDBACK_TRAILER, stopSummary } from "./lib/stop-report.ts";
import {
formatActiveHygiene,
+ hygieneClaims,
parseMemoryRoot,
parseOpenLoopConfig,
scanActiveHygiene,
@@ -85,8 +87,8 @@ type HookInput = {
};
const input = await readStdinJson<HookInput>();
-// Re-entry (the Stop after a turn this hook forced, or a secondary agent's):
-// say nothing, which is what keeps a block from looping, spawn no second refresh,
+// Re-entry (the Stop after a turn some Stop hook forced, or a secondary
+// agent's): say nothing, which keeps a forced turn from looping, 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.
@@ -95,14 +97,16 @@ if (input?.stop_hook_active === true) {
process.exit(0);
}
-const 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)",
- "- 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");
+// Each item as the full report says it and as the user's summary says it.
+const CHECKLIST_ITEMS: readonly (readonly [full: string, short: string])[] = [
+ ["Archive completed projects? (work/active/ -> work/archive/YYYY/)", "archive completed work"],
+ ["Update indexes? (Index.md, Memories.md, People & Context, Brag Doc)", "update indexes"],
+ ["New notes linked? (orphans are bugs)", "link new notes"],
+ ["Ask the agent to run om-vault-audit if many notes were created/modified", "om-vault-audit if many notes changed"],
+ ["To act on any drift, ask the agent to run om-tidy", "ask the agent to run om-tidy for drift"],
+];
+const checklist = ["Wrap-up checklist:", ...CHECKLIST_ITEMS.map(([full]) => `- ${full}`)].join("\n");
+const CHECKLIST_SUMMARY = `Wrap-up checklist: ${CHECKLIST_ITEMS.map(([, short]) => short).join(" · ")}`;
// Concrete drift findings beat a generic checklist (#98/#103/#106): the
// same scan SessionStart runs, so the session closes against the same
@@ -151,12 +155,18 @@ const hasSession = typeof sessionId === "string" && sessionId !== "";
const show =
!isStop || !hasSession || claimChanged(STATE_PATH, sessionId, reportKey({ checklist, report }, VOLATILE_FIELDS));
-/** Framing for the agent: it decides what the report calls for. */
-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}`);
+else if (isStop && hasSession) {
+ // The summary now, the full report with the next prompt; Stop feedback if it cannot be saved.
+ const claims = hygieneClaims(report);
+ try {
+ pruneHandoffs(HANDOFF_DIR, Date.now());
+ writeHandoff(HANDOFF_DIR, sessionId, `${AGENT_PREFACE}\n\n${message}`);
+ writeSystemMessage(stopSummary(CHECKLIST_SUMMARY, claims));
+ } catch {
+ writeStopFeedback(`${FEEDBACK_PREFACE}\n\n${message}`, stopSummary(CHECKLIST_SUMMARY, claims, FEEDBACK_TRAILER));
+ }
+}
else writeSystemMessage(message);
triggerDebouncedRefresh({
diff --git a/.claude/scripts/tests/atomic-write.test.ts b/.claude/scripts/tests/atomic-write.test.ts
new file mode 100644
index 0000000..99c8b06
--- /dev/null
+++ b/.claude/scripts/tests/atomic-write.test.ts
@@ -0,0 +1,38 @@
+/**
+ * lib/atomic-write.ts writeFileAtomic: replace a file whole, or leave nothing behind.
+ */
+
+import { test, describe, beforeEach, afterEach } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { writeFileAtomic } from "../lib/atomic-write.ts";
+import { rmTemp } from "./_helpers.ts";
+
+describe("writeFileAtomic", () => {
+ let dir = "";
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), "atomic-write-"));
+ });
+ afterEach(() => {
+ rmTemp(dir);
+ });
+
+ test("writes a new file and replaces an existing one", () => {
+ const path = join(dir, "state.json");
+ writeFileAtomic(path, "first");
+ writeFileAtomic(path, "second");
+ assert.equal(readFileSync(path, "utf8"), "second");
+ assert.deepEqual(readdirSync(dir), ["state.json"], "no temp file left behind");
+ });
+
+ test("a write that cannot land throws and removes its temp file", () => {
+ // A directory where the file should be: the rename fails.
+ const path = join(dir, "taken");
+ mkdirSync(path);
+ writeFileSync(join(path, "keep"), "");
+ assert.throws(() => writeFileAtomic(path, "text"));
+ assert.deepEqual(readdirSync(dir), ["taken"], "the temp file was removed");
+ });
+});
diff --git a/.claude/scripts/tests/classify-message.test.ts b/.claude/scripts/tests/classify-message.test.ts
index e042af6..c242fcc 100644
--- a/.claude/scripts/tests/classify-message.test.ts
+++ b/.claude/scripts/tests/classify-message.test.ts
@@ -3,13 +3,16 @@
* subprocess integration coverage.
*/
-import { test, describe } from "node:test";
+import { test, describe, beforeEach, afterEach } from "node:test";
import assert from "node:assert/strict";
import { fileURLToPath } from "node:url";
-import { dirname, resolve } from "node:path";
+import { dirname, join, resolve } from "node:path";
+import { mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { takeHandoff, writeHandoff } from "../lib/stop-handoff.ts";
import { SIGNALS } from "../lib/signals.ts";
import { classify } from "../lib/matcher.ts";
-import { runScript as spawnHook } from "./_helpers.ts";
+import { rmTemp, runScript as spawnHook } from "./_helpers.ts";
const SCRIPT = resolve(
dirname(fileURLToPath(import.meta.url)),
@@ -394,3 +397,50 @@ describe("classify — performance", () => {
assert.ok(result.length > 0);
});
});
+
+// ---------------------------------------------------------------------------
+// The Stop report handoff: Stop shows the user a summary and saves the full
+// report; the next prompt in the same session hands it to the agent through
+// UserPromptSubmit, the one channel the user never sees.
+// ---------------------------------------------------------------------------
+describe("classify — the Stop report handoff", () => {
+ let dir = "";
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), "classify-handoff-"));
+ });
+ afterEach(() => {
+ rmTemp(dir);
+ });
+ const env = () => ({ STOP_HANDOFF_DIR: join(dir, "handoff"), CLASSIFY_HINT_STATE: join(dir, "hints.json") });
+ const ctxOf = (stdout: string): string =>
+ stdout ? ((JSON.parse(stdout) as { hookSpecificOutput: { additionalContext: string } }).hookSpecificOutput.additionalContext) : "";
+
+ test("a prompt with no signals still delivers a waiting report, once", () => {
+ writeHandoff(join(dir, "handoff"), "s-1", "Stop hook report, handed over with this message: FULL-REPORT-7");
+ const first = spawnHook(SCRIPT, { session_id: "s-1", hook_event_name: "UserPromptSubmit", prompt: "the weather is mild" }, env());
+ assert.match(ctxOf(first.stdout), /FULL-REPORT-7/);
+ const second = spawnHook(SCRIPT, { session_id: "s-1", hook_event_name: "UserPromptSubmit", prompt: "the weather is mild" }, env());
+ assert.equal(second.stdout, "", "delivered once, then gone");
+ });
+
+ test("a prompt with no usable text still delivers a waiting report", () => {
+ writeHandoff(join(dir, "handoff"), "s-4", "FULL-REPORT-9");
+ const r = spawnHook(SCRIPT, { session_id: "s-4", hook_event_name: "UserPromptSubmit", prompt: "" }, env());
+ assert.match(ctxOf(r.stdout), /^FULL-REPORT-9$/);
+ });
+
+ test("the report rides beside routing hints in one context", () => {
+ writeHandoff(join(dir, "handoff"), "s-2", "FULL-REPORT-8");
+ const r = spawnHook(SCRIPT, { session_id: "s-2", hook_event_name: "UserPromptSubmit", prompt: "we decided to use Redis" }, env());
+ const ctx = ctxOf(r.stdout);
+ assert.match(ctx, /^Content classification hints[^\n]*\n- DECISION/);
+ assert.match(ctx, /\n\nFULL-REPORT-8$/);
+ });
+
+ test("another session's report is never delivered", () => {
+ writeHandoff(join(dir, "handoff"), "s-other", "NOT-YOURS");
+ const r = spawnHook(SCRIPT, { session_id: "s-3", hook_event_name: "UserPromptSubmit", prompt: "the weather is mild" }, env());
+ assert.equal(r.stdout, "");
+ assert.equal(takeHandoff(join(dir, "handoff"), "s-other"), "NOT-YOURS", "left for its own session");
+ });
+});
diff --git a/.claude/scripts/tests/hook-io.test.ts b/.claude/scripts/tests/hook-io.test.ts
index 7a1fca0..324e6c9 100644
--- a/.claude/scripts/tests/hook-io.test.ts
+++ b/.claude/scripts/tests/hook-io.test.ts
@@ -7,7 +7,7 @@
import { test, describe, afterEach } from "node:test";
import assert from "node:assert/strict";
-import { debug, fitEncoded, HOOK_OUTPUT_MAX_CHARS, warn, writeHookOutput, writeStopBlock, writeSystemMessage, type PolicyResult } from "../lib/hook-io.ts";
+import { debug, fitEncoded, HOOK_OUTPUT_MAX_CHARS, warn, writeHookOutput, writeStopFeedback, writeSystemMessage, type PolicyResult } from "../lib/hook-io.ts";
/**
* Replace process.stderr.write with a capturer that records calls and returns
@@ -128,14 +128,16 @@ 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 fills the cap exactly, marked as cut, and is the only field", () => {
- const out = captureStdout(() => writeStopBlock("x".repeat(20_000)));
+describe("writeStopFeedback — the whole output fits", () => {
+ test("a huge report and summary fill the cap exactly, both marked as cut, and never as a block", () => {
+ const out = captureStdout(() => writeStopFeedback("x".repeat(20_000), "x".repeat(20_000)));
assert.equal(out.length, HOOK_OUTPUT_MAX_CHARS);
- 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\)$/);
+ const parsed = JSON.parse(out) as { decision?: string; systemMessage: string; hookSpecificOutput: { hookEventName: string; additionalContext: string } };
+ assert.equal(parsed.decision, undefined, "a block is printed in full and labelled an error");
+ assert.equal(parsed.hookSpecificOutput.hookEventName, "Stop");
+ assert.match(parsed.hookSpecificOutput.additionalContext, /truncated to fit the hook output cap\)$/);
+ assert.match(parsed.systemMessage, /truncated to fit the hook output cap\)$/);
+ assert.ok(parsed.hookSpecificOutput.additionalContext.length > parsed.systemMessage.length, "the agent's copy gets the larger share");
});
});
diff --git a/.claude/scripts/tests/stop-checklist.test.ts b/.claude/scripts/tests/stop-checklist.test.ts
index 39164ec..85d00dc 100644
--- a/.claude/scripts/tests/stop-checklist.test.ts
+++ b/.claude/scripts/tests/stop-checklist.test.ts
@@ -23,7 +23,9 @@
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { HOOK_OUTPUT_MAX_CHARS } from "../lib/hook-io.ts";
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { takeHandoff } from "../lib/stop-handoff.ts";
+import { AGENT_PREFACE, FEEDBACK_PREFACE, FEEDBACK_TRAILER, SUMMARY_TRAILER } from "../lib/stop-report.ts";
+import { existsSync, mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { fileURLToPath } from "node:url";
import { dirname, join, resolve } from "node:path";
@@ -33,6 +35,7 @@ const SCRIPT = resolve(
dirname(fileURLToPath(import.meta.url)),
"../stop-checklist.ts",
);
+const CLASSIFY = resolve(dirname(fileURLToPath(import.meta.url)), "../classify-message.ts");
// Route the debounce sentinel through a per-file tmp path. Every run of this
// hook calls triggerDebouncedRefresh, and without an override that lands on
@@ -50,6 +53,7 @@ const SCRIPT = resolve(
let TMP_DIR = "";
let SENTINEL = "";
let stateCounter = 0;
+let handoffCounter = 0;
before(() => {
TMP_DIR = mkdtempSync(join(tmpdir(), "stop-checklist-"));
@@ -73,13 +77,27 @@ function freshState(): string {
*/
function run(
stdin: string | object | null,
- opts: { readonly state?: string; readonly vault?: string } = {},
+ opts: { readonly state?: string; readonly vault?: string; readonly handoffDir?: string; readonly keep?: boolean } = {},
) {
- return spawnHook(SCRIPT, stdin, {
+ handoffCounter += 1;
+ const handoffDir = opts.handoffDir ?? join(TMP_DIR, `handoff-${handoffCounter}`);
+ const result = spawnHook(SCRIPT, stdin, {
QMD_REFRESH_SENTINEL: SENTINEL,
STOP_CHECKLIST_STATE: opts.state ?? freshState(),
+ STOP_HANDOFF_DIR: handoffDir,
...(opts.vault ? { CLAUDE_PROJECT_DIR: opts.vault } : {}),
});
+ // What the agent receives: the report Stop saved for the next prompt.
+ const sid = typeof stdin === "object" && stdin !== null ? (stdin as { session_id?: unknown }).session_id : undefined;
+ const handed = typeof sid === "string" && sid && opts.keep !== true ? takeHandoff(handoffDir, sid) : null;
+ return { ...result, handed };
+}
+
+/** The full report of a run: the handed-over report after its preface, or the systemMessage where nothing was handed over. */
+function reportOf(r: { readonly stdout: string; readonly handed: string | null }): string {
+ if (r.handed === null) return shownOf(r.stdout);
+ assert.ok(r.handed.startsWith(`${AGENT_PREFACE}\n\n`), `handed report lacks the preface: ${r.handed.slice(0, 80)}`);
+ return r.handed.slice(AGENT_PREFACE.length + 2);
}
/** Parse stdout as the hook envelope, failing loudly if it isn't JSON. */
@@ -93,17 +111,9 @@ function envelopeOf(stdout: string): Record<string, unknown> {
}
}
-/**
- * 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.
- */
+/** What the user sees: the systemMessage, failing loudly if absent. */
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,
@@ -150,7 +160,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 = shownOf(run(stop("s-first"), { vault: root }).stdout);
+ const message = reportOf(run(stop("s-first"), { vault: root }));
assert.match(message, /Wrap-up checklist:/);
assert.match(message, /work\/active\/Done\.md/);
});
@@ -161,7 +171,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(shownOf(first.stdout), /work\/active\/Done\.md/);
+ assert.match(reportOf(first), /work\/active\/Done\.md/);
assert.deepEqual(envelopeOf(second.stdout), {});
assert.deepEqual(envelopeOf(third.stdout), {});
});
@@ -171,7 +181,7 @@ describe("stop-checklist", () => {
const state = freshState();
run(stop("s-change"), { vault: root, state });
completeNote(root, "Also Done.md");
- const message = shownOf(run(stop("s-change"), { vault: root, state }).stdout);
+ const message = reportOf(run(stop("s-change"), { vault: root, state }));
assert.match(message, /work\/active\/Also Done\.md/);
});
@@ -185,9 +195,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(shownOf(a1.stdout), /work\/active\/Done\.md/);
- assert.doesNotMatch(shownOf(b.stdout), /Vault Hygiene/);
- assert.match(shownOf(a2.stdout), /work\/active\/Done\.md/);
+ assert.match(reportOf(a1), /work\/active\/Done\.md/);
+ assert.doesNotMatch(reportOf(b), /Vault Hygiene/);
+ assert.match(reportOf(a2), /work\/active\/Done\.md/);
});
test("a note growing past the threshold does not re-show the report", () => {
@@ -202,7 +212,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(shownOf(first.stdout), /notes\/Log\.md \(26KB\)/);
+ assert.match(reportOf(first), /notes\/Log\.md \(26KB\)/);
assert.deepEqual(envelopeOf(second.stdout), {});
});
@@ -217,37 +227,78 @@ 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(shownOf(first.stdout), /notes\/A\.md \(30KB\)[\s\S]*notes\/B\.md \(26KB\)/);
+ assert.match(reportOf(first), /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. Claude Code prints the reason in the transcript, so the
- // user reads it there; a systemMessage beside it showed the report twice.
+ test("a changed Stop shows the user a summary and saves the full report for the next prompt (#256)", () => {
+ // Every Stop output that reaches the model is printed in full for the
+ // user: a block reason as a "Stop hook error", Stop additionalContext as
+ // "Stop hook feedback". So Stop shows a summary, and the next prompt's
+ // UserPromptSubmit, which the user never sees, hands the report over.
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.match(reason, /work\/active\/Done\.md/);
+ const result = run(stop("s-block"), { vault: root });
+ const envelope = envelopeOf(result.stdout);
+ assert.deepEqual(Object.keys(envelope), ["systemMessage"], "no decision, no additionalContext: both are printed in full");
+ const summary = String(envelope["systemMessage"]);
+ assert.match(summary, /^Wrap-up checklist: archive completed work/);
+ assert.match(summary, /^Hygiene: 1 note\(s\) marked done but still in active\/$/m);
+ assert.doesNotMatch(summary, /work\/active\/Done\.md/, "the user sees the summary, not the listing");
+ assert.match(summary, /The full report reaches the agent with your next message\.$/);
+ assert.match(result.handed ?? "", /^Stop hook report, handed over with this message: .*ask the user when something needs their call/);
+ assert.match(result.handed ?? "", /work\/active\/Done\.md/);
});
- test("an unchanged Stop sends the agent nothing", () => {
- const root = vault("block-quiet", "Done.md");
+ test("a report that cannot be saved goes out as Stop feedback, framed for a turn with no user message", () => {
+ // A regular file where the directory should be: mkdir fails, so the
+ // next prompt would have nothing to hand over.
+ const root = vault("block-unsaved", "Done.md");
+ const blocked = join(TMP_DIR, "handoff-is-a-file");
+ writeFileSync(blocked, "");
+ const result = run(stop("s-unsaved"), { vault: root, handoffDir: blocked });
+ const envelope = envelopeOf(result.stdout);
+ // Both readers are told what is true here: the report went to the agent
+ // now, in a turn with no user message, and the user sees it in full.
+ const summary = String(envelope["systemMessage"]);
+ assert.match(summary, /^Hygiene: 1 note\(s\) marked done/m);
+ assert.ok(summary.endsWith(FEEDBACK_TRAILER), summary);
+ assert.ok(!summary.includes(SUMMARY_TRAILER), "it does not wait for the next message");
+ const output = envelope["hookSpecificOutput"] as Record<string, unknown>;
+ assert.equal(output["hookEventName"], "Stop");
+ const context = String(output["additionalContext"]);
+ assert.ok(context.startsWith(FEEDBACK_PREFACE), context.slice(0, 120));
+ assert.doesNotMatch(context, /handed over with this message/);
+ assert.match(context, /work\/active\/Done\.md/);
+ });
+
+ test("a saved report prunes the week-old ones a session never collected", () => {
+ const root = vault("block-prune", "Done.md");
+ const dir = join(TMP_DIR, "handoff-prune");
+ mkdirSync(dir, { recursive: true });
+ const stale = join(dir, "abandoned.txt");
+ writeFileSync(stale, "an old report");
+ const eightDaysAgo = (Date.now() - 8 * 24 * 60 * 60 * 1000) / 1000;
+ utimesSync(stale, eightDaysAgo, eightDaysAgo);
+ run(stop("s-prune"), { vault: root, handoffDir: dir });
+ assert.equal(existsSync(stale), false);
+ });
+
+ test("an unchanged Stop saves nothing for the next prompt", () => {
+ const root = vault("block-quiet-2", "Done.md");
const state = freshState();
- run(stop("s-block-quiet"), { vault: root, state });
- assert.deepEqual(envelopeOf(run(stop("s-block-quiet"), { vault: root, state }).stdout), {});
+ run(stop("s-quiet-2"), { vault: root, state });
+ const second = run(stop("s-quiet-2"), { vault: root, state });
+ assert.deepEqual(envelopeOf(second.stdout), {});
+ assert.equal(second.handed, null);
});
- test("the forced turn's own Stop does not block again", () => {
- // Fresh state, so the change check would block: only the
- // stop_hook_active exit keeps the forced turn's Stop silent.
+ test("a re-entered Stop is silent and saves nothing", () => {
+ // Fresh state, so the change check would report: only the
+ // stop_hook_active exit keeps a forced turn's Stop silent.
const root = vault("block-reentry", "Done.md");
const reentry = run({ session_id: "s-block-reentry", hook_event_name: "Stop", stop_hook_active: true }, { vault: root });
assert.deepEqual(envelopeOf(reentry.stdout), {});
+ assert.equal(reentry.handed, null);
});
test("a long hygiene list is capped, so the report stays under the hook output cap (#254)", () => {
@@ -255,22 +306,34 @@ describe("stop-checklist", () => {
// hygiene lists were capped; the headline keeps the full count.
const names = Array.from({ length: 400 }, (_, i) => `A completed note with a deliberately long descriptive title ${i}.md`);
const root = vault("block-huge", ...names);
- const { stdout } = run(stop("s-block-huge"), { vault: root });
- assert.ok(stdout.length <= HOOK_OUTPUT_MAX_CHARS, `stdout is ${stdout.length} chars`);
- const reason = String(envelopeOf(stdout)["reason"]);
- assert.match(reason, /⚠️ {2}400 note\(s\) marked done but still in active\//);
- assert.match(reason, /^ {3}- … and 390 more$/m);
- assert.doesNotMatch(reason, /truncated to fit/);
+ // The report is saved whole and cut only where it is delivered, beside the
+ // routing hints, so measure it there: a prompt that raises every hint at once.
+ const dir = join(TMP_DIR, "handoff-huge");
+ const stopRun = run(stop("s-block-huge"), { vault: root, handoffDir: dir, keep: true });
+ assert.ok(stopRun.stdout.length <= HOOK_OUTPUT_MAX_CHARS, `Stop stdout is ${stopRun.stdout.length} chars`);
+ const prompt =
+ "We decided on the new architecture after the outage incident. In my 1:1 with my manager we agreed we shipped it, a big win, and the project milestone is done.";
+ const delivered = spawnHook(CLASSIFY, { session_id: "s-block-huge", hook_event_name: "UserPromptSubmit", prompt }, {
+ STOP_HANDOFF_DIR: dir,
+ CLASSIFY_HINT_STATE: join(TMP_DIR, "hints-huge.json"),
+ });
+ assert.ok(delivered.stdout.length <= HOOK_OUTPUT_MAX_CHARS, `UserPromptSubmit stdout is ${delivered.stdout.length} chars`);
+ const context = String((envelopeOf(delivered.stdout)["hookSpecificOutput"] as Record<string, unknown>)["additionalContext"]);
+ assert.ok((context.match(/^- /gm) ?? []).length >= 5, "the prompt raised most of the routing hints");
+ assert.match(context, /⚠️ {2}400 note\(s\) marked done but still in active\//);
+ assert.match(context, /^ {3}- … and 390 more$/m);
+ assert.doesNotMatch(context, /truncated to fit/);
});
- test("SessionEnd and a Stop without a session_id never block", () => {
- // SessionEnd has no turn to give, and without a session_id nothing
- // stops a block from repeating every turn.
+ test("SessionEnd and a Stop without a session_id show the full report and save nothing", () => {
+ // Neither has a next prompt in this session for the report to ride.
const root = vault("block-never", "Done.md");
for (const payload of [stop(), { session_id: "s-end", hook_event_name: "SessionEnd" }]) {
- const envelope = envelopeOf(run(payload, { vault: root }).stdout);
- assert.equal(envelope["decision"], undefined);
+ const result = run(payload, { vault: root });
+ const envelope = envelopeOf(result.stdout);
+ assert.deepEqual(Object.keys(envelope), ["systemMessage"]);
assert.match(String(envelope["systemMessage"]), /work\/active\/Done\.md/);
+ assert.equal(result.handed, null);
}
});
@@ -279,7 +342,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(shownOf(other.stdout), /work\/active\/Done\.md/);
+ assert.match(reportOf(other), /work\/active\/Done\.md/);
});
test("a clean vault still gets the checklist once, then silence", () => {
@@ -287,8 +350,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(shownOf(first.stdout), /Wrap-up checklist:/);
- assert.doesNotMatch(shownOf(first.stdout), /Vault Hygiene/);
+ assert.match(reportOf(first), /Wrap-up checklist:/);
+ assert.doesNotMatch(reportOf(first), /Vault Hygiene/);
assert.deepEqual(envelopeOf(second.stdout), {});
});
@@ -298,8 +361,8 @@ describe("stop-checklist", () => {
const state = freshState();
const first = run(stop(), { state });
const second = run(stop(), { state });
- assert.match(shownOf(first.stdout), /Wrap-up checklist:/);
- assert.match(shownOf(second.stdout), /Wrap-up checklist:/);
+ assert.match(reportOf(first), /Wrap-up checklist:/);
+ assert.match(reportOf(second), /Wrap-up checklist:/);
});
test("an unreadable dedupe state fails open", () => {
@@ -320,8 +383,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(shownOf(first.stdout), /work\/active\/Done\.md/);
- assert.match(shownOf(second.stdout), /work\/active\/Done\.md/);
+ assert.match(reportOf(first), /work\/active\/Done\.md/);
+ assert.match(reportOf(second), /work\/active\/Done\.md/);
});
test("SessionEnd after a deduped Stop still reports", () => {
@@ -329,11 +392,11 @@ 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(shownOf(end.stdout), /work\/active\/Done\.md/);
+ assert.match(reportOf(end), /work\/active\/Done\.md/);
});
test("the checklist hands drift to om-tidy", () => {
- const message = shownOf(run(stop("s-handoff")).stdout);
+ const message = reportOf(run(stop("s-handoff")));
assert.match(message, /ask the agent to run om-tidy/i);
});
@@ -352,7 +415,7 @@ describe("stop-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 = shownOf(run({}).stdout);
+ const message = reportOf(run({}));
assert.equal(message, message.trimEnd());
});
@@ -401,22 +464,25 @@ describe("stop-checklist", () => {
},
];
+ // A Stop shows the user a summary and hands the full report over with the
+ // next prompt; SessionEnd (Gemini) shows the full report. The full report
+ // itself must not vary by agent.
const rendered = new Set<string>();
for (const { label, payload } of AGENT_PAYLOADS) {
- test(`${label} receives the same JSON envelope`, () => {
- const { stdout, code } = run(payload);
- assert.equal(code, 0);
- const message = shownOf(stdout);
+ test(`${label} receives the same full report`, () => {
+ const result = run(payload);
+ assert.equal(result.code, 0);
+ const message = reportOf(result);
assert.match(message, /Wrap-up checklist:/);
rendered.add(message);
});
}
- test("output does not vary by calling agent", () => {
+ test("the full report does not vary by calling agent", () => {
assert.equal(
rendered.size,
1,
- `every agent must get byte-identical output — got ${rendered.size} variants`,
+ `every agent must get the same full report — got ${rendered.size} variants`,
);
});
});
diff --git a/.claude/scripts/tests/stop-handoff.test.ts b/.claude/scripts/tests/stop-handoff.test.ts
new file mode 100644
index 0000000..4390bb1
--- /dev/null
+++ b/.claude/scripts/tests/stop-handoff.test.ts
@@ -0,0 +1,58 @@
+/**
+ * lib/stop-handoff.ts: a Stop report saved for the session's next prompt.
+ * Delivered once, never to another session, newest wins, stale ones pruned.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, readdirSync, utimesSync } from "node:fs";
+import { rmTemp } from "./_helpers.ts";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { HANDOFF_MAX_AGE_MS, handoffPath, pruneHandoffs, takeHandoff, writeHandoff } from "../lib/stop-handoff.ts";
+
+function withDir(fn: (dir: string) => void): void {
+ const dir = mkdtempSync(join(tmpdir(), "stop-handoff-"));
+ try {
+ fn(dir);
+ } finally {
+ rmTemp(dir);
+ }
+}
+
+describe("stop-handoff", () => {
+ test("a report is taken once, and nothing is left behind", () => withDir((dir) => {
+ writeHandoff(dir, "s1", "report");
+ assert.equal(takeHandoff(dir, "s1"), "report");
+ assert.equal(takeHandoff(dir, "s1"), null);
+ assert.deepEqual(readdirSync(dir), []);
+ }));
+
+ test("nothing waiting is null, not a throw, even with no directory", () => withDir((dir) => {
+ assert.equal(takeHandoff(join(dir, "missing"), "s1"), null);
+ }));
+
+ test("the newest report replaces an unread one", () => withDir((dir) => {
+ writeHandoff(dir, "s1", "old");
+ writeHandoff(dir, "s1", "new");
+ assert.equal(takeHandoff(dir, "s1"), "new");
+ }));
+
+ test("sessions are kept apart, and an id cannot escape the directory", () => withDir((dir) => {
+ writeHandoff(dir, "a", "for a");
+ assert.equal(takeHandoff(dir, "b"), null);
+ assert.ok(handoffPath(dir, "../../etc/x").startsWith(dir));
+ assert.equal(takeHandoff(dir, "a"), "for a");
+ }));
+
+ test("reports older than the window are pruned; fresh ones stay", () => withDir((dir) => {
+ writeHandoff(dir, "old", "x");
+ writeHandoff(dir, "fresh", "y");
+ const now = Date.now();
+ const stale = new Date(now - HANDOFF_MAX_AGE_MS - 60_000);
+ utimesSync(handoffPath(dir, "old"), stale, stale);
+ pruneHandoffs(dir, now);
+ assert.equal(takeHandoff(dir, "old"), null);
+ assert.equal(takeHandoff(dir, "fresh"), "y");
+ }));
+});
diff --git a/.claude/scripts/tests/stop-report.test.ts b/.claude/scripts/tests/stop-report.test.ts
new file mode 100644
index 0000000..d6ae7f7
--- /dev/null
+++ b/.claude/scripts/tests/stop-report.test.ts
@@ -0,0 +1,82 @@
+/**
+ * The user's one-line-per-section summary of a Stop report (lib/stop-report.ts),
+ * the hygiene claims it is made of (hygieneClaims in lib/active-hygiene.ts),
+ * and the preface the agent reads with the full report.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { AGENT_PREFACE, SUMMARY_TRAILER, stopSummary } from "../lib/stop-report.ts";
+import {
+ type ActiveHygieneReport,
+ formatActiveHygiene,
+ hygieneClaims,
+ INBOX_PRESSURE_DAYS,
+ MONOLITH_BYTES,
+} from "../lib/active-hygiene.ts";
+
+const CHECKLIST = "Wrap-up checklist: archive · indexes";
+
+/** A report with every finding the scan can raise. */
+const EVERY_FINDING: ActiveHygieneReport = {
+ completedInActive: ["work/active/Done.md", "work/active/Other.md"],
+ ungroupedClusters: [{ token: "alpha", files: ["Alpha Plan.md", "Alpha Risks.md"] }],
+ oversizedNotes: [{ path: "notes/Big.md", sizeKb: 30 }],
+ openLoops: [{ path: "work/1-1/Weekly.md", ageDays: 20, openItems: 2 }],
+ inboxPressure: { count: 2, oldestDays: 9 },
+ memoryInbox: { count: 4, oldestDays: 2, namedOnly: 1 },
+};
+
+describe("stopSummary", () => {
+ test("the checklist line, one Hygiene line of claims, then where the detail went", () => {
+ assert.deepEqual(stopSummary(CHECKLIST, ["2 notes done", "1 note too big"]).split("\n"), [
+ CHECKLIST,
+ "Hygiene: 2 notes done · 1 note too big",
+ SUMMARY_TRAILER,
+ ]);
+ });
+
+ test("a clean vault is the checklist line and the trailer", () => {
+ assert.deepEqual(stopSummary(CHECKLIST, []).split("\n"), [CHECKLIST, SUMMARY_TRAILER]);
+ });
+
+ test("the trailer is the caller's to set", () => {
+ assert.ok(stopSummary(CHECKLIST, [], "elsewhere.").endsWith("\nelsewhere."));
+ });
+});
+
+describe("hygieneClaims", () => {
+ test("every finding reduces to its claim: counts, no file lists, no instructions", () => {
+ assert.deepEqual(hygieneClaims(EVERY_FINDING), [
+ "2 note(s) marked done but still in active/",
+ "Loose active/ notes that look like one topic",
+ `1 note(s) past the ${MONOLITH_BYTES / 1000}KB organization threshold`,
+ "1 note(s) with open follow-ups untouched 14+ days",
+ `2 raw export(s) sitting in work/meetings/ for ${INBOX_PRESSURE_DAYS}+ days`,
+ "4 cross-repo memory capture(s) awaiting review",
+ ]);
+ });
+
+ test("each claim opens the headline the full report gives that finding", () => {
+ // One definition serves both, so the summary cannot drift from the report.
+ const headlines = formatActiveHygiene(EVERY_FINDING).filter((l) => l.startsWith("⚠️"));
+ const claims = hygieneClaims(EVERY_FINDING);
+ assert.equal(headlines.length, claims.length);
+ claims.forEach((claim, i) => assert.ok(headlines[i]?.startsWith(`⚠️ ${claim} `), `${headlines[i]} / ${claim}`));
+ });
+
+ test("a clean report has no claims", () => {
+ assert.deepEqual(
+ hygieneClaims({ completedInActive: [], ungroupedClusters: [], oversizedNotes: [], openLoops: [], inboxPressure: null, memoryInbox: null }),
+ [],
+ );
+ });
+});
+
+describe("AGENT_PREFACE", () => {
+ test("tells the agent the report arrived with the user's message, which comes first", () => {
+ assert.match(AGENT_PREFACE, /^Stop hook report, handed over with this message: /);
+ assert.match(AGENT_PREFACE, /Deal with the user's message first/);
+ assert.match(AGENT_PREFACE, /The user saw only a one-line summary of each section/);
+ });
+});
diff --git a/.gitignore b/.gitignore
index 327e452..bb93a58 100644
--- a/.gitignore
+++ b/.gitignore
@@ -36,6 +36,7 @@ node_modules/
# Hook runtime state (local, self-pruning / debounce sentinel)
.claude/scripts/.hint-state.json
.claude/scripts/.checklist-state.json
+.claude/scripts/.stop-handoff/
.claude/scripts/.qmd-refresh-sentinel
# MCP server audit log — every vault read, with the calling repo and the query
diff --git a/AGENTS.md b/AGENTS.md
index 6f0ad61..74b4115 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -17,7 +17,7 @@ The hook scripts in `.claude/scripts/` are agent-agnostic TypeScript and shell,
| Script | Purpose | Claude event | Codex event | Gemini event |
|--------|---------|--------------|-------------|--------------|
| `session-start.ts` | Inject vault context at startup | SessionStart | SessionStart | SessionStart |
-| `classify-message.ts` | Classify messages, inject routing hints | UserPromptSubmit | UserPromptSubmit | BeforeAgent |
+| `classify-message.ts` | Classify messages, inject routing hints, hand over the last Stop report (Claude Code and Codex: Gemini's checklist runs on SessionEnd and saves none) | UserPromptSubmit | UserPromptSubmit | BeforeAgent |
| `validate-write.ts` | Validate frontmatter and wikilinks | PostToolUse | PostToolUse | AfterTool |
| `pre-compact.ts` | Back up transcript before compaction | PreCompact | — | PreCompress |
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 960d872..402cb05 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -179,7 +179,7 @@ sequenceDiagram
User->>Agent: prompt
Agent->>Hooks: UserPromptSubmit
Hooks->>Hooks: classify (decision, incident, win, 1:1, ...)
- Hooks-->>Agent: routing hints
+ Hooks-->>Agent: routing hints + any Stop report saved last turn
end
loop each Write/Edit to .md
@@ -196,8 +196,8 @@ sequenceDiagram
loop each completed response
Agent->>Hooks: Stop
Hooks->>QMD: debounced refresh (detached)
- Hooks-->>User: checklist + hygiene, first time this session or when changed
- Hooks-->>Agent: same report as a block reason, one turn to act, ask, or pass
+ Hooks-->>User: short summary, one line per section, first time this session or when changed
+ Hooks->>Hooks: save the full report for the next prompt
end
```
@@ -208,7 +208,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` 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.
+- **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. And every `Stop` output that does reach the model is printed in full for the user: a `decision: "block"` reason under a "Stop hook error" label (v8.5.0 shipped that), `Stop` `additionalContext` under "Stop hook feedback". `UserPromptSubmit` `additionalContext` is the one channel that reaches the model and is never shown. So when the findings change, `Stop` shows the user a one-line-per-section summary and saves the full report for the session (`lib/stop-handoff.ts`: written atomically, claimed by rename so it is delivered once, the newest report wins, a week-old one is pruned). The next prompt's `classify-message` takes it and hands it to the agent beside any routing hints, with a preface telling it to deal with the user's message first. If the report cannot be saved, `Stop` sends it as feedback instead (Claude Code; Codex's handling of Stop feedback is unverified): visible, but never lost. `SessionEnd` and a `Stop` without a `session_id` have no next prompt to ride, so the user gets the full report.
- **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.
---
@@ -878,7 +878,7 @@ Step 2 is not documentation garnish. Measured: with the server wired and no repo
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-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.
+Session-boundary output is JSON-or-nothing on all three agents. `stop-checklist.ts` emits `{}` when a Stop has nothing new to say. What the user sees is `systemMessage`, the one user-facing field all three agents share: on a Stop whose findings changed, a one-line-per-section summary, with the full report saved for the next prompt's `UserPromptSubmit` to hand to the agent unseen. Only when the report cannot be saved does it go out as Stop feedback, which Claude Code prints in full; whether Codex honours Stop feedback is unverified. SessionEnd (Gemini) has no next prompt, so there the full report is `systemMessage` only. `om-wrap-up` still owns the deliberate acting pass at the end of a session.
```mermaid
flowchart TB
diff --git a/CLAUDE.md b/CLAUDE.md
index 4a7f7f3..d23a5a9 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -441,10 +441,10 @@ Five lifecycle hooks in `.claude/settings.json`:
| Hook | When | What |
|------|------|------|
| SessionStart | On startup/resume | QMD re-index + self-heal, inject North Star, active work, recent changes, tasks, file listing (folders past a note-count threshold collapse to one line), vault-hygiene drift flags (completed-not-archived, ungrouped clusters, 25KB oversize, stale open loops, meetings-inbox pressure); the whole injection is held under a byte budget that fits Claude Code's 10,000-character hook output cap — over it, low-priority sections degrade to pointers and the closing injection-size meter names each one it dropped |
-| UserPromptSubmit | Every message | Classifies content (decision, incident, win, 1:1, architecture, person, project update) and injects routing hints |
+| UserPromptSubmit | Every message | Classifies content (decision, incident, win, 1:1, architecture, person, project update) and injects routing hints; also hands the agent a Stop report saved since the last prompt |
| 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 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. |
+| 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, and every Stop output that reaches the agent is also printed in full for the user. So a changed report shows the user a one-line-per-section summary and saves the full report for the next prompt, where the UserPromptSubmit hook hands it to the agent unseen; the agent deals with the user's message first, then acts, asks, or leaves it. If the report cannot be saved, it goes out as Stop feedback instead. SessionEnd and a Stop without a session id show the full report. Also triggers the debounced QMD refresh. For thorough review, use `/om-wrap-up` instead. |
## Write-Correctness Laws
diff --git a/GEMINI.md b/GEMINI.md
index 6f0ad61..74b4115 100644
--- a/GEMINI.md
+++ b/GEMINI.md
@@ -17,7 +17,7 @@ The hook scripts in `.claude/scripts/` are agent-agnostic TypeScript and shell,
| Script | Purpose | Claude event | Codex event | Gemini event |
|--------|---------|--------------|-------------|--------------|
| `session-start.ts` | Inject vault context at startup | SessionStart | SessionStart | SessionStart |
-| `classify-message.ts` | Classify messages, inject routing hints | UserPromptSubmit | UserPromptSubmit | BeforeAgent |
+| `classify-message.ts` | Classify messages, inject routing hints, hand over the last Stop report (Claude Code and Codex: Gemini's checklist runs on SessionEnd and saves none) | UserPromptSubmit | UserPromptSubmit | BeforeAgent |
| `validate-write.ts` | Validate frontmatter and wikilinks | PostToolUse | PostToolUse | AfterTool |
| `pre-compact.ts` | Back up transcript before compaction | PreCompact | — | PreCompress |
diff --git a/README.ja.md b/README.ja.md
index aabfed1..4beda5c 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -195,10 +195,10 @@ QMDは**3つの小さなモデルをローカルで**実行します。設定す
| フック | タイミング | 内容 |
|------|------|------|
| 🚀 SessionStart | 起動/再開時 | QMD再インデックス+セルフヒール、North Starフォーカス・アクティブプロジェクト・最近の変更・タスク・ファイル一覧・ボールト衛生フラグを注入 — 全体はClaude Codeのフック出力上限に収まるバイトバジェットで抑えられ、最終行は注入サイズメーター |
-| 💬 UserPromptSubmit | 全メッセージ | コンテンツを分類(意思決定、インシデント、実績、1on1、アーキテクチャ、人物、プロジェクト更新)してルーティングヒントを注入 |
+| 💬 UserPromptSubmit | 全メッセージ | コンテンツを分類(意思決定、インシデント、実績、1on1、アーキテクチャ、人物、プロジェクト更新)してルーティングヒントを注入。前のターンのStopレポートもエージェントに渡す |
| ✍️ PostToolUse | `.md`書き込み後 | フロントマター+ウィキリンクの検証、誤配置メモリファイルのブロック、肥大ノート(削るのではなく分割)と書き込み時トピッククラスタのフラグ |
| 💾 PreCompact | コンテキスト圧縮前 | セッション記録を`thinking/session-logs/`にバックアップ |
-| 🏁 Stop | 各応答の終了時 | チェックリスト+具体的なドリフト検出(SessionStartと同じ衛生スキャン)。セッションごとに1回、内容が変わった時のみ再表示。エージェントにも届き、対応するかはエージェントが判断。対応は`om-tidy`へ |
+| 🏁 Stop | 各応答の終了時 | チェックリスト+具体的なドリフト検出(SessionStartと同じ衛生スキャン)。セッションごとに1回、内容が変わった時のみ再表示。あなたにはセクションごとに1行の短い要約、エージェントには次のメッセージと一緒に完全なレポートが届き、対応するかはエージェントが判断。対応は`om-tidy`へ |
> [!TIP]
> ただ話すだけ。フックがルーティングを処理します。
diff --git a/README.ko.md b/README.ko.md
index 8e95513..0c427a3 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -195,10 +195,10 @@ QMD는 **세 개의 작은 모델을 로컬에서** 실행하므로, 설정할 A
| 훅 | 시점 | 동작 |
|------|------|------|
| 🚀 SessionStart | 시작/재개 시 | QMD 재인덱싱+셀프힐, North Star 포커스·활성 작업·최근 변경사항·작업·파일 목록·볼트 위생 플래그 주입 — 전체는 Claude Code의 훅 출력 상한에 맞는 바이트 예산으로 제한되고, 마지막 줄은 주입 크기 미터 |
-| 💬 UserPromptSubmit | 매 메시지마다 | 콘텐츠 분류(의사결정, 인시던트, 성과, 1:1, 아키텍처, 인물, 프로젝트 업데이트) 및 라우팅 힌트 주입 |
+| 💬 UserPromptSubmit | 매 메시지마다 | 콘텐츠 분류(의사결정, 인시던트, 성과, 1:1, 아키텍처, 인물, 프로젝트 업데이트) 및 라우팅 힌트 주입. 이전 턴의 Stop 보고서도 에이전트에게 전달 |
| ✍️ PostToolUse | `.md` 작성 후 | 프론트매터+위키링크 검증, 잘못 배치된 메모리 파일 차단, 비대 노트(줄이지 말고 분할)와 작성 시점 토픽 클러스터 플래그 |
| 💾 PreCompact | 컨텍스트 압축 전 | 세션 트랜스크립트를 `thinking/session-logs/`에 백업 |
-| 🏁 Stop | 각 응답 종료 시 | 체크리스트+구체적인 드리프트 발견 (SessionStart와 동일한 위생 스캔). 세션당 한 번, 내용이 바뀔 때만 다시 표시. 에이전트에게도 전달되며 조치 여부는 에이전트가 판단. 조치는 `om-tidy`로 |
+| 🏁 Stop | 각 응답 종료 시 | 체크리스트+구체적인 드리프트 발견 (SessionStart와 동일한 위생 스캔). 세션당 한 번, 내용이 바뀔 때만 다시 표시. 사용자에게는 섹션별 한 줄 요약이, 에이전트에게는 다음 메시지와 함께 전체 보고서가 전달되며 조치 여부는 에이전트가 판단. 조치는 `om-tidy`로 |
> [!TIP]
> 그냥 이야기하세요. 훅이 라우팅을 처리합니다.
diff --git a/README.md b/README.md
index 3f821dc..a74c1c2 100644
--- a/README.md
+++ b/README.md
@@ -202,10 +202,10 @@ Five lifecycle hooks handle routing automatically:
| Hook | When | What |
|------|------|------|
| 🚀 SessionStart | On startup/resume | QMD re-index + self-heal, inject North Star focus, active work, recent changes, tasks, file listing, vault-hygiene drift flags — held under a byte budget that fits Claude Code's hook output cap, ending with an injection-size meter |
-| 💬 UserPromptSubmit | Every message | Classifies content (decision, incident, win, 1:1, architecture, person, project update) and injects routing hints |
+| 💬 UserPromptSubmit | Every message | Classifies content (decision, incident, win, 1:1, architecture, person, project update) and injects routing hints; also hands the agent the Stop report from the previous turn |
| ✍️ 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 | After every response | Checklist + concrete drift findings (same hygiene scan as SessionStart), shown once per session and again only when they change, to you and to the agent, which decides whether to act; hands drift to `om-tidy` |
+| 🏁 Stop | After every response | Checklist + concrete drift findings (same hygiene scan as SessionStart), shown once per session and again only when they change: you see a short summary, one line per section, and the agent gets the full report with your next message and decides whether to act; 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 e6eac6e..521c68a 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -195,10 +195,10 @@ QMD **在本地运行三个小模型**,因此不需要配置 API 密钥,没
| 钩子 | 触发时机 | 功能 |
|------|---------|------|
| 🚀 SessionStart | 启动/恢复时 | QMD 重新索引+自愈,注入北极星焦点、活跃工作、最近变更、任务、文件列表、仓库卫生标志 — 整体受字节预算约束(预算本身限制在 Claude Code 的钩子输出上限之内),末行为注入大小计量 |
-| 💬 UserPromptSubmit | 每条消息 | 对内容分类(决策、事件、成就、1:1、架构、人员、项目更新)并注入路由提示 |
+| 💬 UserPromptSubmit | 每条消息 | 对内容分类(决策、事件、成就、1:1、架构、人员、项目更新)并注入路由提示;同时把上一轮的 Stop 报告交给智能体 |
| ✍️ PostToolUse | 写入 `.md` 后 | 验证 frontmatter+wikilinks,拦截误放的记忆文件,标记过大笔记(拆分而非删减)与写入时的主题集群 |
| 💾 PreCompact | 上下文压缩前 | 将会话记录备份到 `thinking/session-logs/` |
-| 🏁 Stop | 每次响应结束后 | 检查清单+具体漂移发现(与 SessionStart 相同的卫生扫描),每个会话显示一次,仅在内容变化时再次显示;同时发送给智能体,由其判断是否处理;处理交给 `om-tidy` |
+| 🏁 Stop | 每次响应结束后 | 检查清单+具体漂移发现(与 SessionStart 相同的卫生扫描),每个会话显示一次,仅在内容变化时再次显示;你只看到简短摘要(每个部分一行),完整报告随你的下一条消息交给智能体,由其判断是否处理;处理交给 `om-tidy` |
> [!TIP]
> 你只需要正常对话。钩子会处理路由。