diff --git a/tools/unslop-hook/README.md b/tools/unslop-hook/README.md index 2f5ca166b..332b989d8 100644 --- a/tools/unslop-hook/README.md +++ b/tools/unslop-hook/README.md @@ -113,9 +113,12 @@ lists. can write. The counts are the session's own report, not host evidence. - The extension's per-reply dedupe is in memory. After a restart the same reply can get a second notice. -- On the first turn of a new Claude Code session the transcript may not - hold the reply when Stop runs; the hook then checks - `last_assistant_message` and logs an empty `entryId`. +- Claude Code can run the Stop hook before it writes the turn to the + transcript (seen on 2.1.319 to 2.1.325, on any turn). The hook reads the + transcript again until its last reply matches `last_assistant_message`, + for up to 2 s. If it never does, the hook checks `last_assistant_message` + alone and logs an empty `entryId`, and the turn's earlier replies go + unchecked. - The word/phrase lists are the mechanical subset of ms-unslop only, keyed to pattern ids in lists.json. Style judgments (voice, rhythm, structure) stay in the skill, not the gate. diff --git a/tools/unslop-hook/claude-hook.js b/tools/unslop-hook/claude-hook.js index 88cdfc160..14d01a23b 100644 --- a/tools/unslop-hook/claude-hook.js +++ b/tools/unslop-hook/claude-hook.js @@ -77,13 +77,33 @@ function check(text, at) { } } -function stop(input) { - const list = entries(input.transcript_path); +// The assistant messages with text since the transcript's last prompt. +function turnReplies(path) { + const list = entries(path); let start = -1; list.forEach((e, i) => { if (isPrompt(e)) start = i; }); - const turn = replies(list.slice(start + 1)); - if (!turn.length && typeof input.last_assistant_message === "string" && input.last_assistant_message.trim()) { - turn.push({ id: "", text: input.last_assistant_message }); + return replies(list.slice(start + 1)); +} + +// Claude Code can run the Stop hook before it writes the turn to the transcript, so the +// transcript may still end with the last turn. Read it again until its last reply is the one +// the hook input names, for up to STOP_WAIT_MS (the hook's own limit is 10 s). A transcript that +// never catches up gives last_assistant_message alone, never the last turn's replies again. +const STOP_WAIT_MS = 2000; +const flat = (s) => s.replace(/\s+/g, ""); +const pause = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); + +function stop(input) { + const told = typeof input.last_assistant_message === "string" && input.last_assistant_message.trim() ? input.last_assistant_message : null; + const deadline = Date.now() + STOP_WAIT_MS; + let turn = turnReplies(input.transcript_path); + while (told !== null && !(turn.length && flat(turn.at(-1).text) === flat(told))) { + if (Date.now() >= deadline) { + turn = [{ id: "", text: told }]; + break; + } + pause(25); + turn = turnReplies(input.transcript_path); } for (const r of turn) { const result = check(r.text, "stop"); diff --git a/tools/unslop-hook/test-unslop-check.js b/tools/unslop-hook/test-unslop-check.js index acc8014df..e289e764c 100644 --- a/tools/unslop-hook/test-unslop-check.js +++ b/tools/unslop-hook/test-unslop-check.js @@ -302,6 +302,44 @@ t("claude-hook: a broken lists.json logs broken_lists and no verdict; bad input assert.deepStrictEqual(events(bad).map((e) => e.ev), ["hook_failed"]); }); +// Claude Code can run the Stop hook before it writes the turn to the transcript (seen on 2.1.319, +// 2.1.322 and 2.1.325). The hook then saw the last turn's reply and logged it again. +const jsonl = (list) => list.map((x) => JSON.stringify(x)).join("\n") + "\n"; +const lastTurn = [ + { type: "user", uuid: "p1", message: { role: "user", content: "status?" } }, + line("assistant", "m1", "a1", [{ type: "text", text: "The build is green." }]), +]; +const TELL_REPLY = "Let me delve into it. A pivotal step."; + +t("claude-hook: Stop waits for a late transcript and checks this turn's reply, not the last turn's", () => { + const transcript = writeTmp("transcript-late.jsonl", jsonl(lastTurn)); + const late = writeTmp("transcript-late-tail.jsonl", jsonl([ + { type: "user", uuid: "p2", message: { role: "user", content: "and now?" } }, + line("assistant", "m2", "a2", [{ type: "text", text: TELL_REPLY }]), + ])); + const log = tmp("hook-late.jsonl"); + // The writer runs on its own while the hook blocks, as claude's transcript writer does. + const writer = require("node:child_process").spawn("sh", ["-c", 'sleep 0.3; cat "$1" >> "$2"', "sh", late, transcript], { stdio: "ignore" }); + const r = hook("stop", { transcript_path: transcript, last_assistant_message: TELL_REPLY }, { MOSAIC_UNSLOP_LOG: log }); + writer.kill(); + assert.strictEqual(r.status, 0, r.stderr); + assert.deepStrictEqual(events(log).map((e) => [e.ev, e.entryId]), [["flagged", "a2"]]); +}); + +t("claude-hook: Stop with a transcript that never catches up checks last_assistant_message alone", () => { + const transcript = writeTmp("transcript-stale.jsonl", jsonl(lastTurn)); + const log = tmp("hook-stale.jsonl"); + const r = hook("stop", { transcript_path: transcript, last_assistant_message: TELL_REPLY }, { MOSAIC_UNSLOP_LOG: log }); + assert.strictEqual(r.status, 0, r.stderr); + assert.deepStrictEqual(events(log).map((e) => [e.ev, e.entryId]), [["flagged", ""]]); + // A turn already in the transcript is checked at once, with its entry id. + const now = tmp("hook-current.jsonl"); + const started = Date.now(); + hook("stop", { transcript_path: transcript, last_assistant_message: "The build is green." }, { MOSAIC_UNSLOP_LOG: now }); + assert.ok(Date.now() - started < 1500, "no wait when the transcript is current"); + assert.deepStrictEqual(events(now).map((e) => [e.ev, e.entryId]), [["checked", "a1"]]); +}); + let failed = 0; for (const [name, ok] of results) { console.log(`${ok ? "PASS" : "FAIL"} ${name}`); if (!ok) failed++; } console.log(`${results.length - failed}/${results.length} passed`);