#!/usr/bin/env node // SubagentStop hook: a delivery stage agent may not stop before its last message is its report // block. The block's first key names the agent: // // implementer issue: ... // reviewer PR: # Round: ... // hardware-verifier PR: # Hardware: ... // // An implementer's `mode: audit` report must also hold its `audit:` line: an audit given fixes // as well once did the fixes and skipped the audit. That line's `probed

/` must show every // test it added or changed probed: audits that skipped the probe left half of all review // findings to the reviewers. Unless its Assessment is incomplete, an implementer's `cycles // /` with b < t lists the t - b Tests lines not built under `remaining`, or an `open` line // `spec needs: ...`; an audit's `donewhen /` or `covered /` short of its total has an // `open` line per missing one. A reviewer's `Rerun:` starts with `round 2`, `fix-check` or `none`; // its Spec, Code and Claims review counts each start with ` findings ( blocking` or // `skipped`; and the first path after `Findings file:` exists (relative paths from the agent's // cwd); words after any of the three are not read. A report that names no path needs one only // when its Assessment is complete and it is no round 2 or fix-check that found nothing. // // A reviewer's round 1 or round 2 whose run started no lens agent is sent back to start the // lenses the round owes, whatever its Assessment says: the run's own transcript shows the Agent // calls it made. A fix-check may run no lens (REVIEW.md: every hunk mechanical). Sent back once // already, a report that still says incomplete may stop, so a run that cannot start a lens ends; // a prompt that prohibits sub-agents gets a report labelled self-check (reviewer.md). // Other agents stop freely. Claude Code ends the turn anyway after eight blocks in a row. import fs from "node:fs"; import os from "node:os"; import path from "node:path"; const OWED = "spawn the lenses this round owes"; const DELEGATION_BAN = /\b(?:prohibit\w*|forbid\w*|no|without|not use|never use|do not (?:use|start|spawn)|don't (?:use|start|spawn))\s+(?:any\s+)?(?:sub-?agents?|delegation)\b/i; const LENS_TYPES = new Set(["spec-reviewer", "code-reviewer", "claims-reviewer"]); const REPORT = { implementer: /^issue: \d+/m, reviewer: /^PR: #\d+\s+Round:/m, "hardware-verifier": /^PR: #\d+\s+Hardware:/m, }; // why: each check returns its block reason or null; the first reason found is the one given. const IMPLEMENTER_CHECKS = [ cyclesDefect, auditCount("donewhen", "Done when line"), auditCount("covered", "changed function no test covers"), ]; const REVIEWER_CHECKS = [rerunDefect, lensCountsDefect, findingsFileDefect]; const input = JSON.parse(fs.readFileSync(0, "utf8") || "{}"); const shape = REPORT[input.agent_type]; const message = input.last_assistant_message ?? ""; if (shape === undefined) process.exit(0); let blocked = false; if (!shape.test(message)) { block( "You stopped without your report block. If a helper agent or a command you started is " + "still running, wait for it in the foreground. Then finish the work and end with the " + "report block your instructions define, and nothing after it.", ); } else if (input.agent_type === "reviewer" && lensDefect() !== null) { block(lensDefect()); } else if ( input.agent_type === "reviewer" && !/^Assessment: (complete|incomplete)\b/m.test(message) ) { block( "Report Assessment: complete or incomplete with missing scope; budget exhaustion is not a pass.", ); } else if (input.agent_type === "reviewer" && reviewerDefect() !== null) { block(reviewerDefect()); } else if (/\bmode: audit\b/.test(message) && !/^Assessment: incomplete\b/m.test(message)) { const audit = /^audit: .*$/m.exec(message); const probed = audit === null ? null : /\bprobed (\d+)\/(\d+)/.exec(audit[0]); if (audit === null) { block( "Your report is an audit's but has no `audit:` line, so the audit did not run. Do the " + "audit in implement-audit.md on the whole diff, then report again with its `audit:` line.", ); } else if (probed === null) { block( "Your `audit:` line has no `probed` count. Probe every test you added or changed as " + "implement-audit.md says, then report again with `probed /`.", ); } else if (Number(probed[1]) < Number(probed[2])) { block( `You probed ${probed[1]} of ${probed[2]} tests. Probe the rest as implement-audit.md ` + "says: break the code each covers, run its file, see it fail on its assertion, restore.", ); } } if (!blocked && input.agent_type === "implementer" && !/^Assessment: incomplete\b/m.test(message)) { const defect = implementerDefect(); if (defect !== null) block(defect); } function implementerDefect() { return firstDefect(IMPLEMENTER_CHECKS); } function reviewerDefect() { return firstDefect(REVIEWER_CHECKS); } function firstDefect(checks) { for (const check of checks) { const defect = check(); if (defect !== null) return defect; } return null; } function cyclesDefect() { const cycles = /\bcycles: (\d+)\/(\d+)/.exec(message); const missing = cycles === null ? 0 : Number(cycles[2]) - Number(cycles[1]); if (missing <= 0 || items("remaining").length >= missing) return null; if (items("open").some((l) => l.startsWith("spec needs:"))) return null; return ( `Your report says \`cycles ${cycles[1]}/${cycles[2]}\`: list the ${missing} Tests lines not ` + "built under `remaining`, in build order, or name what stops them under `open` as " + "`spec needs: `." ); } function auditCount(name, what) { return () => { const audit = /^audit: .*$/m.exec(message)?.[0] ?? ""; const count = new RegExp(`\\b${name} (\\d+)/(\\d+)`).exec(audit); if (count === null || items("open").length >= Number(count[2]) - Number(count[1])) return null; return ( `Your \`audit:\` line says \`${name} ${count[1]}/${count[2]}\`: give each ${what} left ` + "under `open`, with why, or finish it and count it." ); }; } // why: a round 1 or 2 nobody but the coordinator read is not the blind review, yet such reports // came back as complete (PR #1862 round 1) and as incomplete, which parks the delivery. function lensDefect() { const run = reviewerRun(); if (run === null || !["1", "2"].includes(run.round) || run.lenses > 0) return null; if (run.sentBack && /^Assessment: incomplete\b/m.test(message)) return null; // why: a user who prohibits delegation gets the self-check reviewer.md asks for instead. if (DELEGATION_BAN.test(run.prompt) && /\bself-check\b/i.test(message)) return null; return ( `Round ${run.round} ran no lens: ${OWED} (REVIEW.md, "Routing"), each with its ledger ` + "tag, wait for them in the foreground, then report again. A round the coordinator alone " + "read is not a review, whatever its Assessment says." ); } // why: null when the run's transcript cannot be read, and then nothing is known about its lenses. function reviewerRun() { let records; try { records = fs.readFileSync(transcriptPath(), "utf8").split("\n").map(record).filter(Boolean); } catch { return null; } const prompt = text(records.find((r) => r.type === "user")?.message?.content); const calls = records .filter((r) => r.type === "assistant") .flatMap((r) => r.message?.content ?? []) .filter((b) => b.type === "tool_use" && (b.name === "Agent" || b.name === "Task")); return { prompt, round: roundOf(prompt), lenses: calls.filter((b) => startsLens(b.input ?? {})).length, sentBack: records.some((r) => r.type === "user" && text(r.message?.content).includes(OWED)), }; } function transcriptPath() { const named = input.agent_transcript_path; if (typeof named === "string") return named.replace(/^~(?=\/|$)/, os.homedir()); const session = String(input.transcript_path ?? "").replace(/\.jsonl$/, ""); return path.join( session, "subagents", `agent-${String(input.agent_id).replace(/^agent-/, "")}.jsonl`, ); } function record(line) { try { return JSON.parse(line); } catch { return null; } } function text(content) { if (typeof content === "string") return content; if (!Array.isArray(content)) return ""; return content.map((b) => (b.type === "text" ? b.text : "")).join("\n"); } // why: the prompt's ledger tag names the round; the report's own `Round:` stands in for it. function roundOf(prompt) { const first = prompt.replace(/^\s+/, "").split("\n")[0]; return ( /\bround=(\S+)/.exec(first)?.[1] ?? /^round:\s*`?([\w-]+)/m.exec(prompt)?.[1] ?? /^PR: #\d+\s+Round:\s*([\w-]+)/m.exec(message)?.[1] ?? "" ); } // why: a lens is a lens agent, or any agent whose prompt's tag gives it a lens's role. function startsLens(call) { const first = String(call.prompt ?? "") .replace(/^\s+/, "") .split("\n")[0]; return LENS_TYPES.has(call.subagent_type) || /\brole=(?:spec|code|claims)\b/.test(first); } function rerunDefect() { if (/^Rerun:\s*(?:round 2|fix-check|none)(?![\w-])/m.test(message)) return null; return "Your report's `Rerun:` line starts with `round 2`, `fix-check` or `none`. Report again with it."; } function lensCountsDefect() { const lens = ["Spec", "Code", "Claims"].find( (l) => !/^(?:\d+ (?:new )?findings? \(\d+ blocking\b|skipped(?![\w-]))/.test(lensCount(l)), ); if (lens === undefined) return null; return ( `Your report's \`${lens} review:\` is \` findings ( blocking)\` or \`skipped\`. ` + "Report again with the counts." ); } function lensCount(lens) { const value = new RegExp( `\\b${lens} review: (.+?)(?=\\s+(?:Spec|Code|Claims) review:|\\s*$)`, "m", ).exec(message)?.[1]; return value ?? ""; } // why: the path is the first word after the key, or the whole line when the path has spaces; a // first word with no extension and no folder (`none`, `not written`, `n/a`) names no file. function findingsFileDefect() { const value = /^Findings file: *(.*?)\s*$/m.exec(message)?.[1] ?? ""; const first = /^[`'"]?([^\s`'"]+)/.exec(value)?.[1] ?? ""; const onDisk = (file) => file !== "" && fs.existsSync(path.resolve(input.cwd ?? ".", file)); if (onDisk(first) || onDisk(value)) return null; const named = /\.\w+$|[\\/].*[\\/]/.test(first); if (!named && (!/^Assessment: complete\b/m.test(message) || cleanLaterCheck())) return null; return ( "Your report's `Findings file:` names no file on disk. Write the findings file REVIEW.md " + '"Measurement" describes and report its path.' ); } // why: a round 2 or fix-check that found nothing adds nothing to the findings file the earlier // check wrote, which the orchestrator already holds. function cleanLaterCheck() { const round = /^PR: #\d+\s+Round:\s*([\w-]+)/m.exec(message)?.[1]; if (round !== "2" && round !== "fix-check") return false; return ["Spec", "Code", "Claims"].every((l) => /^(?:0 findings? \(0 blocking\)|skipped)(?![\w-])/.test(lensCount(l)), ); } // why: a list key holds an inline value, or items indented under it; `none` is empty. function items(key) { const lines = message.split("\n"); const at = lines.findIndex((l) => l.startsWith(`${key}:`)); if (at === -1) return []; const inline = lines[at].slice(key.length + 1).trim(); const out = inline === "" || inline === "none" ? [] : [inline]; for (const l of lines.slice(at + 1)) { if (!/^\s{2,}\S/.test(l)) break; if (l.trim() !== "none") out.push(l.trim()); } return out; } function block(reason) { blocked = true; console.log(JSON.stringify({ decision: "block", reason })); }