From 035445297158b5557efebd6d766d03474d79911a Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Mon, 16 Nov 2026 15:45:09 -0600 Subject: [PATCH 1/4] fix(unslop-hook): the Claude Stop hook waits for the turn to reach the transcript Claude Code 2.1.319, 2.1.322 and 2.1.325 can run the Stop hook before they write the turn to the transcript. The hook then read the last turn's reply, logged it a second time, and missed this turn's reply. That made claude-session.test.mjs row 66 red in most runs. The hook now reads the transcript again, for up to 2 s, until its last reply matches last_assistant_message. If it never does, it checks last_assistant_message alone with an empty entryId, never the last turn again. (#1873, lane triage-followups) --- tools/unslop-hook/README.md | 9 ++++-- tools/unslop-hook/claude-hook.js | 30 ++++++++++++++++---- tools/unslop-hook/test-unslop-check.js | 38 ++++++++++++++++++++++++++ 3 files changed, 69 insertions(+), 8 deletions(-) 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`); -- 2.54.0 From b7649ecd73df1c94ce03f430290cf9e9889f5f46 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Mon, 16 Nov 2026 15:46:57 -0600 Subject: [PATCH 2/4] fix(webui): the workflows read leaves out system-only templates The workflows read listed the triage template, which only the client hid. The read handler now drops every template the organization vocabulary marks system-only, and the Console's read supplier in cli.mjs drops them too. The client filter stays. (#1873, lane triage-followups) --- packages/webui/src/cli.mjs | 7 ++++--- packages/webui/src/packs-http.mjs | 5 ++++- packages/webui/src/public/workflows.js | 4 ++-- packages/webui/tests/packs-http.test.mjs | 8 +++++--- 4 files changed, 15 insertions(+), 9 deletions(-) diff --git a/packages/webui/src/cli.mjs b/packages/webui/src/cli.mjs index 3986214b1..4fc839b81 100644 --- a/packages/webui/src/cli.mjs +++ b/packages/webui/src/cli.mjs @@ -39,7 +39,7 @@ import { composeSnapshot, readSystemConfig, readOrgConfig } from './triage-snaps import { busesStopped } from '../../cli/src/proxy-admin-host.mjs'; import { agentLevelsWriteRoutes } from './agent-levels-write.mjs'; import { RESTART_EXIT } from '../../cli/src/org-console.mjs'; -import { ID_PATTERN } from '../../organization/src/vocabulary.mjs'; +import { ID_PATTERN, systemOnly } from '../../organization/src/vocabulary.mjs'; import { selectorScope } from '../../organization/src/selector.mjs'; // The bus verifies the Console's exact same-tree script in /proc, whose argv preserves a // relative shell argument even though Node's process.argv resolves it. Re-exec the same @@ -204,8 +204,9 @@ try { // and the preview are reads over requestRead. templatesWrite: session.user === undefined && sendOn ? templatesCaller(consoleCall({ dataRoot: root, socket: paths.socket, business: id })) : null, // Starter packs SP6 (#1873): the owner's workflow read, the organization file and its revision as the - // writer reads them (the read `mosaic org workflow set` takes its revision from), and the V2 template names. - workflowsRead: session.user === undefined ? () => ({ ...organizationWriter({ dir: configDir(), rolesDir: rolesDir() }).read(id), templates: templateHashes(rolesDir()).map(t => t.template) }) : null, + // writer reads them (the read `mosaic org workflow set` takes its revision from), and the V2 template names + // less the system-only ones. + workflowsRead: session.user === undefined ? () => ({ ...organizationWriter({ dir: configDir(), rolesDir: rolesDir() }).read(id), templates: templateHashes(rolesDir()).map(t => t.template).filter(t => !systemOnly(t)) }) : null, reads: consoleReads({ root: REPO, queueRoot: options.checkout ?? REPO, system, configDir: configDir(), rolesDir: rolesDir(), business: id, orgRoot: root }), }; }, diff --git a/packages/webui/src/packs-http.mjs b/packages/webui/src/packs-http.mjs index 432dd9bdd..ea6cba950 100644 --- a/packages/webui/src/packs-http.mjs +++ b/packages/webui/src/packs-http.mjs @@ -24,6 +24,8 @@ // console cap alone, and runs the merge, the digest and the held-credential check itself. `workflows` // (SP6) is the owner's read of the organization file as the writer reads it ({document, revision, // templates}), the same read `mosaic org workflow set` takes its revision from; no bus verb answers it. +import { systemOnly } from '../../organization/src/vocabulary.mjs'; + export const PACKS_ROUTE = /^\/api\/(?:packs(?:\/(preview|apply|hire))?|board|workflows(?:\/([^/]+))?)$/; // Which requests the pack route answers. GET and HEAD /api/board stay the Board read (the Console's own task // board through its upstream); every other method on /api/board is this route's (POST writes, the rest 405). @@ -171,7 +173,8 @@ async function workflowsRead(res, { workflows, live, session, writable }) { } const roles = { definitions: Object.keys(plain(doc.definitions) ? doc.definitions : {}).sort(), - templates: current.templates.filter(n => typeof n === 'string').sort(), + // #1873 triage-followups: a system-only template (organization vocabulary SYSTEM_ONLY) is never offered. + templates: current.templates.filter(n => typeof n === 'string' && !systemOnly(n)).sort(), }; return json(res, 200, { workflows: flowsOf(doc), projects, roles, revision: current.revision, writable }); } diff --git a/packages/webui/src/public/workflows.js b/packages/webui/src/public/workflows.js index 1756b220d..f58f1e870 100644 --- a/packages/webui/src/public/workflows.js +++ b/packages/webui/src/public/workflows.js @@ -40,8 +40,8 @@ return value; } const plain = v => v !== null && typeof v === 'object' && !Array.isArray(v); - // #1873: the templates no organization may hold (organization vocabulary SYSTEM_ONLY). The read may still - // list them; a step role never resolves to one and the picker never offers one. + // #1873: the templates no organization may hold (organization vocabulary SYSTEM_ONLY). The server leaves + // them out of the read; this filter stays so a step role never resolves to one and the picker never offers one. const SYSTEM_ONLY = ['triage']; const offered = list => (list || []).filter(r => !SYSTEM_ONLY.includes(r)); async function read(org, s) { diff --git a/packages/webui/tests/packs-http.test.mjs b/packages/webui/tests/packs-http.test.mjs index e46c6bf08..7ef4d9135 100644 --- a/packages/webui/tests/packs-http.test.mjs +++ b/packages/webui/tests/packs-http.test.mjs @@ -262,8 +262,10 @@ test('SP6 GET /workflows returns the org and code-project workflows, the role na assert.deepEqual(body.projects, Object.fromEntries(Object.entries(doc.projects).map(([id, p]) => [id, p.workflows ?? {}]))); assert.deepEqual(body.projects.stack, doc.projects.stack.workflows); assert.deepEqual(body.roles.definitions, ['triage']); - assert.deepEqual(body.roles.templates, templateHashes(join(f.root, 'roles')).map(x => x.template).sort()); - assert.ok(body.roles.templates.includes('coder') && !body.roles.templates.includes('ghost')); + // #1873 triage-followups: the shipped triage template is system-only, so the read leaves it out. + assert.ok(templateHashes(join(f.root, 'roles')).some(x => x.template === 'triage'), 'the fixture ships the triage template'); + assert.deepEqual(body.roles.templates, templateHashes(join(f.root, 'roles')).map(x => x.template).filter(n => n !== 'triage').sort()); + assert.ok(body.roles.templates.includes('coder') && !body.roles.templates.includes('ghost') && !body.roles.templates.includes('triage')); assert.equal(body.revision, createHash('sha256').update(readFileSync(f.file)).digest('hex'), 'the revision is the writer\'s: the hash of the file bytes'); assert.equal(body.writable, true); assert.equal(JSON.stringify(body).includes(f.root), false, 'no host path leaves'); @@ -283,7 +285,7 @@ test('SP6 GET /workflows returns the org and code-project workflows, the role na test('SP6 GET /workflows leaves out a library project and answers outcome-unknown for a read it cannot trust', async t => { const REV = 'a'.repeat(64); - const read = { document: { projects: { code: { workflows: { w: FLOW('W') } }, lib: { kind: 'library', workflows: { never: FLOW('N') } }, bare: {} } }, revision: REV, templates: ['coder', 7] }; + const read = { document: { projects: { code: { workflows: { w: FLOW('W') } }, lib: { kind: 'library', workflows: { never: FLOW('N') } }, bare: {} } }, revision: REV, templates: ['coder', 7, 'triage'] }; const f = await fixture(t, { workflows: () => read }); const [status, body] = await call(f, `${ORG}/workflows`); assert.equal(status, 200, JSON.stringify(body)); -- 2.54.0 From c85c768a4adbd02517a68d2f5c452a5d0f133980 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Mon, 16 Nov 2026 15:54:12 -0600 Subject: [PATCH 3/4] fix(webui): the first render's heading focus leaves an open drawer or dialog alone: a reader who opened the Triage drawer, an agent drawer, the narrow-screen menu or a dialog before the first render ended keeps focus there; on load a second render can draw the agents rows while the first still reads, so the agent drawer had the same fault (#1873, lane triage-followups) --- packages/webui/src/public/bus.js | 6 +++- .../webui/tests/agent-drawer-browser.test.mjs | 18 ++++++++++++ .../tests/triage-drawer-browser.test.mjs | 28 +++++++++++++++++++ 3 files changed, 51 insertions(+), 1 deletion(-) diff --git a/packages/webui/src/public/bus.js b/packages/webui/src/public/bus.js index b546af884..b2d498976 100644 --- a/packages/webui/src/public/bus.js +++ b/packages/webui/src/public/bus.js @@ -2246,5 +2246,9 @@ window.addEventListener('hashchange', e => render(!agentOnly(e.oldURL, e.newURL))); $('refresh').addEventListener('click', () => render(false)); $('pause').addEventListener('click', () => setTimeout(schedule)); // after app.js flips aria-pressed - render(false).then(() => { if (!$('bus-view').hidden) { const h1 = $('bus-view').querySelector('h1'); if (h1 && location.hash.startsWith('#/')) h1.focus(); } }); + // #1873 triage-followups: the first render ends by focusing the page's heading. A drawer or dialog the + // reader opened before then keeps its focus: the Triage drawer, an agent drawer, the narrow-screen + // menu or any open dialog. + const holdsFocus = () => { const a = document.activeElement; return !!a && (!!a.closest('.ws-drawer:not([hidden]), [data-ws-drawer], dialog[open], [role="dialog"], [role="alertdialog"]') || (drawerOpen && nav.contains(a))); }; + render(false).then(() => { if (!$('bus-view').hidden && !holdsFocus()) { const h1 = $('bus-view').querySelector('h1'); if (h1 && location.hash.startsWith('#/')) h1.focus(); } }); })(); diff --git a/packages/webui/tests/agent-drawer-browser.test.mjs b/packages/webui/tests/agent-drawer-browser.test.mjs index 31b6d93c3..ea2564ef6 100644 --- a/packages/webui/tests/agent-drawer-browser.test.mjs +++ b/packages/webui/tests/agent-drawer-browser.test.mjs @@ -577,3 +577,21 @@ test('at 390 wide the drawer is a full-width sheet', async t => { assert.equal(box[1], box[2]); assert.ok(box[3] <= box[2], `no horizontal page scroll: ${box[3]} > ${box[2]}`); }); + +// #1873 triage-followups: the page focuses its heading when its first render ends. On load the page +// starts a second render that reads GET /api/workspace again, so when the first render's read is slow +// the second draws the rows first and a reader can open a drawer before the first render ends. Its late +// end must not take the drawer's focus. The page holds the first GET /api/workspace until __go. +const HOLD_FIRST = `(() => { const f = window.fetch; let first = true; window.__firstDone = false; window.fetch = (u, o) => { if (first && String(u?.url ?? u).includes('/api/workspace')) { first = false; return new Promise(r => { const t = setInterval(() => { if (window.__go) { clearInterval(t); r(f(u, o).finally(() => setTimeout(() => { window.__firstDone = true; }, 0))); } }, 20); }); } return f(u, o); }; })()`; + +test('triage-followups: a drawer opened before the first render ends keeps focus when that render ends', async t => { + const { b, wait } = await setup(t, { scripts: [HOLD_FIRST] }); + await wait(`document.querySelector(${JSON.stringify(rowLink('acme:coder'))})`); + assert.notEqual(await b.evaluate('document.activeElement?.tagName'), 'H1', 'the first render has not ended'); + await b.evaluate(`document.querySelector(${JSON.stringify(rowLink('acme:coder'))}).click()`); + await wait(`${open('acme:coder')} && ${drawer('acme:coder')}.contains(document.activeElement)`); + await b.evaluate('window.__go = true'); + await wait('window.__firstDone'); + await new Promise(r => setTimeout(r, 400)); + assert.equal(await b.evaluate(`${drawer('acme:coder')}.contains(document.activeElement)`), true, `focus stays in the drawer, not on ${await b.evaluate('document.activeElement?.tagName')}`); +}); diff --git a/packages/webui/tests/triage-drawer-browser.test.mjs b/packages/webui/tests/triage-drawer-browser.test.mjs index dca0f8965..65f899237 100644 --- a/packages/webui/tests/triage-drawer-browser.test.mjs +++ b/packages/webui/tests/triage-drawer-browser.test.mjs @@ -409,3 +409,31 @@ test('item 5: markup and control characters in every field stay text: no element await sleep(500); assert.equal(await f.b.evaluate('window.__pwned ?? null'), null); }); + +// #1873 triage-followups: the page focuses its heading when its first render ends. A reader who opened +// the drawer before then keeps focus in the drawer. The page holds GET /api/workspace, which the first +// render waits on, until the drawer has opened and taken focus. +const HOLD_WORKSPACE = `(() => { const f = window.fetch; window.__held = 0; window.fetch = (u, o) => { if (String(u?.url ?? u).includes('/api/workspace') && !window.__go) { window.__held += 1; return new Promise(r => { const t = setInterval(() => { if (window.__go) { clearInterval(t); r(f(u, o)); } }, 20); }); } return f(u, o); }; })()`; + +test('triage-followups: a drawer opened before the first render ends keeps focus when the render ends', async t => { + const f = await setup(t, { init: HOLD_WORKSPACE }); + await f.wait('document.querySelector("#triage-open") && window.__held > 0'); + const heading = () => f.b.evaluate('document.querySelector("#bus-view h1")?.textContent ?? null'); + await sleep(300); + assert.equal(await heading(), 'Reading…', 'the first render has not ended'); + await f.click('#triage-open'); + await f.wait('document.querySelector("#triage-drawer")?.contains(document.activeElement)'); + await f.b.evaluate('window.__go = true'); + await f.wait('document.querySelector("#bus-view h1")?.textContent === "Dashboard"'); + await sleep(400); + assert.equal(await f.b.evaluate('document.querySelector("#triage-drawer").contains(document.activeElement)'), true, `focus stays in the drawer, not on ${await f.b.evaluate('document.activeElement?.tagName')}`); + // Escape still closes it and puts focus back on the entry. + await f.b.call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 }); + await f.wait('document.querySelector("#triage-drawer").hidden'); + assert.equal(await f.b.evaluate('document.activeElement?.id'), 'triage-open'); +}); + +test('triage-followups: with no drawer open the first render still focuses the heading', async t => { + const f = await setup(t); + await f.wait('document.activeElement?.tagName === "H1"'); +}); -- 2.54.0 From b39d5e2ff37c7a7a6da249d703c4a8e23f10aee2 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Mon, 16 Nov 2026 16:05:43 -0600 Subject: [PATCH 4/4] fix(unslop-hook): review round, the Stop fallback logs late: true and the comment names the two stale cases left: an input with no last_assistant_message, and a reply whose text equals the last turn's last reply; cli.mjs notes that the packs-http read is the tested gate for system-only templates (#1873, lane triage-followups) --- packages/webui/src/cli.mjs | 2 +- tools/unslop-hook/README.md | 6 ++++-- tools/unslop-hook/claude-hook.js | 14 ++++++++++---- tools/unslop-hook/test-unslop-check.js | 4 ++-- 4 files changed, 17 insertions(+), 9 deletions(-) diff --git a/packages/webui/src/cli.mjs b/packages/webui/src/cli.mjs index 4fc839b81..bef2d9fdd 100644 --- a/packages/webui/src/cli.mjs +++ b/packages/webui/src/cli.mjs @@ -205,7 +205,7 @@ try { templatesWrite: session.user === undefined && sendOn ? templatesCaller(consoleCall({ dataRoot: root, socket: paths.socket, business: id })) : null, // Starter packs SP6 (#1873): the owner's workflow read, the organization file and its revision as the // writer reads them (the read `mosaic org workflow set` takes its revision from), and the V2 template names - // less the system-only ones. + // less the system-only ones. packs-http's workflowsRead drops them again and is the tested gate. workflowsRead: session.user === undefined ? () => ({ ...organizationWriter({ dir: configDir(), rolesDir: rolesDir() }).read(id), templates: templateHashes(rolesDir()).map(t => t.template).filter(t => !systemOnly(t)) }) : null, reads: consoleReads({ root: REPO, queueRoot: options.checkout ?? REPO, system, configDir: configDir(), rolesDir: rolesDir(), business: id, orgRoot: root }), }; diff --git a/tools/unslop-hook/README.md b/tools/unslop-hook/README.md index 332b989d8..e670289f6 100644 --- a/tools/unslop-hook/README.md +++ b/tools/unslop-hook/README.md @@ -117,8 +117,10 @@ lists. 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. + alone, logs an empty `entryId` and `late: true`, and the turn's earlier + replies go unchecked. Two stale cases remain: a hook input with no + `last_assistant_message`, and a reply whose text equals the last turn's + last reply. Either can log the last turn's replies again. - 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 14d01a23b..5b9af26bf 100644 --- a/tools/unslop-hook/claude-hook.js +++ b/tools/unslop-hook/claude-hook.js @@ -88,7 +88,11 @@ function turnReplies(path) { // 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. +// never catches up gives last_assistant_message alone, logged with late: true so a release where +// it never matches shows in the log. +// Two stale cases remain: an input with no last_assistant_message is not waited for, and a reply +// whose text equals the last turn's last reply matches a stale transcript at once. Either can log +// 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); @@ -96,10 +100,11 @@ const pause = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 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); + let turn = turnReplies(input.transcript_path), late = false; while (told !== null && !(turn.length && flat(turn.at(-1).text) === flat(told))) { if (Date.now() >= deadline) { turn = [{ id: "", text: told }]; + late = true; break; } pause(25); @@ -108,8 +113,9 @@ function stop(input) { for (const r of turn) { const result = check(r.text, "stop"); if (result === null) return; - if (result.clean) log({ ev: "checked", clean: true, entryId: r.id, charsChecked: result.charsChecked }); - else log({ ev: "flagged", clean: false, entryId: r.id, charsChecked: result.charsChecked, findings: result.findings }); + const extra = late ? { late: true } : {}; + if (result.clean) log({ ev: "checked", clean: true, entryId: r.id, charsChecked: result.charsChecked, ...extra }); + else log({ ev: "flagged", clean: false, entryId: r.id, charsChecked: result.charsChecked, findings: result.findings, ...extra }); } } diff --git a/tools/unslop-hook/test-unslop-check.js b/tools/unslop-hook/test-unslop-check.js index e289e764c..227585d42 100644 --- a/tools/unslop-hook/test-unslop-check.js +++ b/tools/unslop-hook/test-unslop-check.js @@ -331,13 +331,13 @@ t("claude-hook: Stop with a transcript that never catches up checks last_assista 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", ""]]); + assert.deepStrictEqual(events(log).map((e) => [e.ev, e.entryId, e.late]), [["flagged", "", true]]); // 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"]]); + assert.deepStrictEqual(events(now).map((e) => [e.ev, e.entryId, e.late]), [["checked", "a1", undefined]]); }); let failed = 0; -- 2.54.0