architecture-harness 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,18 @@
1
1
  #!/usr/bin/env node
2
- // The trigger for `swarm.explore`'s search and output hints: PostToolUse on Grep adds context naming
3
- // the repository's own tools when the answer runs long, and PostToolUse on Bash or PowerShell adds
4
- // context naming the summarizer when the output runs long. Neither refuses anything; both are a
5
- // nudge the model can take or leave.
2
+ // The trigger for `swarm.explore`'s search and output hints: a long Grep answer names the repository's tools,
3
+ // and a long successful command output is saved to a file and shown as an excerpt, or named to the summarizer.
6
4
 
5
+ import { mkdirSync, writeFileSync } from "node:fs";
6
+ import os from "node:os";
7
+ import path from "node:path";
7
8
  import { fileURLToPath } from "node:url";
8
9
  import { exploreSettingsAt } from "./dispatch.mjs";
9
10
 
11
+ const FAILURE_LINE = /\b(?:fail(?:s|ed|ure|ing)?|errors?|not ok|panic|exception)\b|✖/i;
12
+ const MAX_SIGNAL_LINES = 20;
13
+ const MAX_SIGNAL_CHARS = 200;
14
+ const fileSafe = (id) => String(id).replace(/[^A-Za-z0-9_.-]/g, "_");
15
+
10
16
  const context = (text) => ({ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: text } });
11
17
 
12
18
  /** The tool's own answer, as plain text, from whatever shape `tool_response` carries. */
@@ -42,8 +48,57 @@ const grepHint = (tools) =>
42
48
 
43
49
  const outputHint = (summarizer) => `Explore hint: this output runs long. Pipe it through the summarizer instead: ${summarizer}`;
44
50
 
51
+ /** The head, the failure-shaped lines between, and the tail of a long output, in about `size` characters. */
52
+ export function excerptOf(text, size) {
53
+ const headSize = Math.floor(size / 4);
54
+ const tailStart = text.length - (size - headSize);
55
+ const middle = text.slice(headSize, tailStart);
56
+ const signal = middle
57
+ .split(/\r?\n/)
58
+ .filter((line) => FAILURE_LINE.test(line))
59
+ .slice(0, MAX_SIGNAL_LINES)
60
+ .map((line) => line.slice(0, MAX_SIGNAL_CHARS));
61
+ return { head: text.slice(0, headSize), signal, tail: text.slice(tailStart), omitted: middle.length };
62
+ }
63
+
64
+ const askLine = (summarizer, file) =>
65
+ summarizer === null ? "" : ` Ask the summarizer: ${summarizer.includes("<command>") ? summarizer.replace("<command>", `cat "${file}"`) : summarizer}.`;
66
+
67
+ /** What Claude sees in place of a long output: the excerpt, with a line that names the saved file. */
68
+ export function excerptText(text, size, file, summarizer) {
69
+ const { head, signal, tail, omitted } = excerptOf(text, size);
70
+ const found = signal.length > 0 ? ` Its lines that name a failure or an error:\n${signal.join("\n")}` : "";
71
+ return `${head}\n[Explore excerpt: ${omitted} characters of this output are left out here, and the whole output is in ${file}. Read a range of it or search it.${askLine(summarizer, file)}${found}]\n${tail}`;
72
+ }
73
+
74
+ /** The tool output with its text replaced, in the same shape, or null for an image or a shape the hook does not know. */
75
+ export function replacedOutput(response, replacement) {
76
+ if (typeof response === "string") return replacement;
77
+ if (response === null || typeof response !== "object" || response.isImage === true) return null;
78
+ if (typeof response.stdout === "string" || typeof response.stderr === "string") return { ...response, stdout: replacement, stderr: "" };
79
+ if (typeof response.output === "string") return { ...response, output: replacement };
80
+ return null;
81
+ }
82
+
83
+ /** Saves the whole output and shows its excerpt. @returns the hook output, or null when either step cannot run */
84
+ function excerptOutput(call, text, settings, tmp) {
85
+ if (replacedOutput(call.tool_response, "") === null) return null;
86
+ const scratch = typeof call.scratchpad_dir === "string" && call.scratchpad_dir !== "" ? call.scratchpad_dir : null;
87
+ const dir = scratch ? path.join(scratch, "outputs") : path.join(tmp, "architecture-kit", "outputs", fileSafe(call.session_id ?? "session"));
88
+ const file = path.join(dir, `${fileSafe(call.tool_use_id ?? Date.now())}.txt`);
89
+ try {
90
+ mkdirSync(dir, { recursive: true });
91
+ writeFileSync(file, text);
92
+ } catch {
93
+ // A folder the hook cannot write leaves the output whole, with the hint.
94
+ return null;
95
+ }
96
+ const replaced = replacedOutput(call.tool_response, excerptText(text, settings.excerptChars, file, settings.summarizer));
97
+ return { hookSpecificOutput: { hookEventName: "PostToolUse", updatedToolOutput: replaced } };
98
+ }
99
+
45
100
  /** The verdict on one finished Grep, Bash, or PowerShell call. @returns the hook output, or null for no change. */
46
- export function decide(call) {
101
+ export function decide(call, tmp = os.tmpdir()) {
47
102
  if (call.hook_event_name !== "PostToolUse") return null;
48
103
  const tool = call.tool_name;
49
104
  if (tool !== "Grep" && tool !== "Bash" && tool !== "PowerShell") return null;
@@ -62,8 +117,13 @@ export function decide(call) {
62
117
  return lineCountOf(text) > settings.maxGrepLines ? context(grepHint(settings.tools)) : null;
63
118
  }
64
119
 
65
- if (settings.summarizer === null) return null;
66
- return text.length > settings.maxOutputChars ? context(outputHint(settings.summarizer)) : null;
120
+ if (text.length <= settings.maxOutputChars) return null;
121
+ // Only an output at least twice the excerpt shrinks enough to be worth a file.
122
+ if (settings.longOutput === "excerpt" && text.length > 2 * settings.excerptChars) {
123
+ const excerpt = excerptOutput(call, text, settings, tmp);
124
+ if (excerpt) return excerpt;
125
+ }
126
+ return settings.summarizer === null ? null : context(outputHint(settings.summarizer));
67
127
  }
68
128
 
69
129
  async function readStdin() {
@@ -1,18 +1,18 @@
1
1
  import { strict as assert } from "node:assert";
2
2
  import { execFileSync } from "node:child_process";
3
- import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
3
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { test } from "node:test";
7
7
  import { fileURLToPath } from "node:url";
8
- import { decide } from "./explore-hint.mjs";
8
+ import { decide, excerptOf, replacedOutput } from "./explore-hint.mjs";
9
9
 
10
10
  const HOOKS = fileURLToPath(new URL("../../../../hooks/hooks.json", import.meta.url));
11
11
 
12
12
  const TOOLS = [{ name: "slm-rerank", use: "find the files for a concept", how: 'slm-rerank -q "<question>" --stub -k 5' }];
13
13
 
14
14
  /** A checkout with `swarm.explore` on, and one with no config. */
15
- function workspace(t, explore = { tools: TOOLS, maxGrepLines: 5, maxOutputChars: 20, summarizer: "lfm-ask" }) {
15
+ function workspace(t, explore = { tools: TOOLS, maxGrepLines: 5, maxOutputChars: 20, longOutput: "hint", summarizer: "lfm-ask" }) {
16
16
  const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-explore-hint-")));
17
17
  t.after(() => rmSync(base, { recursive: true, force: true }));
18
18
  const on = path.join(base, "on");
@@ -66,7 +66,7 @@ test("a command output at or under maxOutputChars sees no change", (t) => {
66
66
  });
67
67
 
68
68
  test("no summarizer configured means no output hint even over the limit", (t) => {
69
- const ws = workspace(t, { tools: TOOLS, maxGrepLines: 5, maxOutputChars: 20, summarizer: null });
69
+ const ws = workspace(t, { tools: TOOLS, maxGrepLines: 5, maxOutputChars: 20, longOutput: "hint", summarizer: null });
70
70
  assert.equal(decide(call(ws.on, "Bash", "x".repeat(30))), null);
71
71
  });
72
72
 
@@ -132,3 +132,103 @@ test("hooks.json runs the hint on PostToolUse Grep and Bash|PowerShell", () => {
132
132
  .map((entry) => entry.matcher);
133
133
  assert.deepEqual(matchers.sort(), ["Bash|PowerShell", "Grep"]);
134
134
  });
135
+
136
+ const bashResponse = (stdout) => ({ stdout, stderr: "", interrupted: false, isImage: false });
137
+ const longOutput = `${"h".repeat(50)}\n${"m".repeat(1000)}\nnot ok 3 - breaks\n${"m".repeat(2000)}\n${"t".repeat(80)}`;
138
+ const excerptWorkspace = (t, extra = {}) =>
139
+ workspace(t, { tools: TOOLS, maxOutputChars: 120, summarizer: '<command> | lfm-ask "<question>"', excerptChars: 100, ...extra });
140
+
141
+ test("a long successful output is saved whole and reaches Claude as its head, its failure lines, and its tail", (t) => {
142
+ const ws = excerptWorkspace(t);
143
+ const scratch = path.join(ws.on, "scratch");
144
+ const output = decide({ ...call(ws.on, "Bash", bashResponse(longOutput)), tool_use_id: "toolu_9", scratchpad_dir: scratch });
145
+ const replaced = output.hookSpecificOutput.updatedToolOutput;
146
+ const file = path.join(scratch, "outputs", "toolu_9.txt");
147
+ assert.equal(readFileSync(file, "utf8"), longOutput);
148
+ assert.equal(replaced.stderr, "");
149
+ assert.equal(replaced.isImage, false);
150
+ assert.ok(replaced.stdout.startsWith("h".repeat(25)));
151
+ assert.ok(replaced.stdout.endsWith("t".repeat(75)));
152
+ assert.match(replaced.stdout, /not ok 3 - breaks/);
153
+ assert.ok(replaced.stdout.includes(file));
154
+ assert.ok(replaced.stdout.includes(`cat "${file}" | lfm-ask`));
155
+ assert.ok(replaced.stdout.length < longOutput.length);
156
+ });
157
+
158
+ test("with no scratchpad folder, the whole output goes under the temp folder of the session", (t) => {
159
+ const ws = excerptWorkspace(t);
160
+ const tmp = path.join(ws.on, "tmp");
161
+ const output = decide({ ...call(ws.on, "Bash", bashResponse(longOutput)), session_id: "s/1", tool_use_id: "toolu_1" }, tmp);
162
+ assert.ok(output.hookSpecificOutput.updatedToolOutput.stdout.includes(path.join(tmp, "architecture-kit", "outputs", "s_1", "toolu_1.txt")));
163
+ assert.ok(existsSync(path.join(tmp, "architecture-kit", "outputs", "s_1", "toolu_1.txt")));
164
+ });
165
+
166
+ test("one long line with no failure is still cut, and a string output stays a string", (t) => {
167
+ const ws = excerptWorkspace(t);
168
+ const scratch = path.join(ws.on, "scratch");
169
+ const oneLine = "x".repeat(5000);
170
+ const output = decide({ ...call(ws.on, "PowerShell", oneLine), tool_use_id: "toolu_2", scratchpad_dir: scratch });
171
+ const replaced = output.hookSpecificOutput.updatedToolOutput;
172
+ assert.equal(typeof replaced, "string");
173
+ assert.ok(replaced.length < 1000);
174
+ assert.doesNotMatch(replaced, /name a failure/);
175
+ });
176
+
177
+ test("longOutput hint, an image, an unknown shape, or an output under twice excerptChars keeps the hint", (t) => {
178
+ const hint = excerptWorkspace(t, { longOutput: "hint" });
179
+ assert.match(contextOf(decide(call(hint.on, "Bash", bashResponse(longOutput)))) ?? "", /lfm-ask/);
180
+ const ws = excerptWorkspace(t);
181
+ assert.match(contextOf(decide(call(ws.on, "Bash", { ...bashResponse(longOutput), isImage: true }))) ?? "", /lfm-ask/);
182
+ assert.match(contextOf(decide(call(ws.on, "Bash", { lines: longOutput.split("\n") }))) ?? "", /lfm-ask/);
183
+ assert.match(contextOf(decide(call(ws.on, "Bash", bashResponse("y".repeat(150))))) ?? "", /lfm-ask/);
184
+ });
185
+
186
+ test("a wrong longOutput or excerptChars is a named config error, reported as context", (t) => {
187
+ for (const extra of [{ longOutput: "cut" }, { excerptChars: 0 }]) {
188
+ const ws = excerptWorkspace(t, extra);
189
+ assert.match(contextOf(decide(call(ws.on, "Bash", bashResponse(longOutput)))) ?? "", /Explore guard is off: swarm\.explore\./);
190
+ }
191
+ });
192
+
193
+ test("an excerptChars that is not smaller than maxOutputChars is a named config error, reported as context", (t) => {
194
+ for (const excerptChars of [120, 5000]) {
195
+ const ws = excerptWorkspace(t, { excerptChars });
196
+ assert.match(contextOf(decide(call(ws.on, "Bash", bashResponse(longOutput)))) ?? "", /Explore guard is off: swarm\.explore\.excerptChars .*smaller than maxOutputChars \(120\)/);
197
+ }
198
+ const fine = excerptWorkspace(t, { excerptChars: 119 });
199
+ assert.ok(decide(call(fine.on, "Bash", bashResponse(longOutput))).hookSpecificOutput.updatedToolOutput);
200
+ });
201
+
202
+ test("excerptOf keeps a quarter for the head, the rest for the tail, and at most 20 failure lines", () => {
203
+ const text = `${"a".repeat(100)}\n${Array.from({ length: 30 }, (_, index) => `error ${index}`).join("\n")}\n${"z".repeat(400)}`;
204
+ const { head, signal, tail, omitted } = excerptOf(text, 200);
205
+ assert.equal(head.length, 50);
206
+ assert.equal(tail.length, 150);
207
+ assert.equal(signal.length, 20);
208
+ assert.equal(omitted, text.length - 200);
209
+ assert.equal(replacedOutput({ output: "x" }, "y").output, "y");
210
+ assert.equal(replacedOutput(null, "y"), null);
211
+ });
212
+
213
+ test("replacedOutput blanks a non-empty stderr and keeps the other fields", () => {
214
+ const replaced = replacedOutput({ stdout: "out", stderr: "boom", interrupted: false, isImage: false }, "y");
215
+ assert.deepEqual(replaced, { stdout: "y", stderr: "", interrupted: false, isImage: false });
216
+ });
217
+
218
+ test("an excerpt with no summarizer names the file and offers no summarizer", (t) => {
219
+ const ws = excerptWorkspace(t, { summarizer: null });
220
+ const scratch = path.join(ws.on, "scratch");
221
+ const output = decide({ ...call(ws.on, "Bash", bashResponse(longOutput)), tool_use_id: "toolu_3", scratchpad_dir: scratch });
222
+ const { stdout } = output.hookSpecificOutput.updatedToolOutput;
223
+ assert.ok(stdout.includes(path.join(scratch, "outputs", "toolu_3.txt")));
224
+ assert.doesNotMatch(stdout, /Ask the summarizer/);
225
+ });
226
+
227
+ test("a save that fails leaves the output whole and shows the hint", (t) => {
228
+ const ws = excerptWorkspace(t);
229
+ const blocker = path.join(ws.on, "blocker");
230
+ writeFileSync(blocker, "a regular file");
231
+ const output = decide({ ...call(ws.on, "Bash", bashResponse(longOutput)), tool_use_id: "toolu_4" }, path.join(blocker, "tmp"));
232
+ assert.equal(output.hookSpecificOutput.updatedToolOutput, undefined);
233
+ assert.match(contextOf(output) ?? "", /lfm-ask/);
234
+ });
@@ -0,0 +1,69 @@
1
+ // The note an agent writes when it stops mid-task, and the check a hook runs on it. A fresh agent resumes
2
+ // from the note, so the note names the brief, the place, the head, what is done, and what comes next.
3
+
4
+ import { readFileSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { nativePath } from "./workflow-place.mjs";
7
+
8
+ export const HANDOFF_LINE = /^[ \t]*HANDOFF:[ \t]*(\S.*?)[ \t]*$/m;
9
+ const QUOTES = /^["'`]|["'`]$/g;
10
+ const FIELDS = ["Brief", "Worktree", "Branch", "Head"];
11
+ const SECTIONS = [["Done", "done"], ["Left", "left"], ["Next step", "next"]];
12
+ const SHA = /^[0-9a-fA-F]{7,40}$/;
13
+ const fieldLine = (name) => new RegExp(`^[ \\t]*${name}:[ \\t]*(\\S.*?)[ \\t]*$`, "im");
14
+
15
+ /** The path on a report's or a prompt's `HANDOFF:` line, without quotes, or null. */
16
+ export function handoffPathOf(text) {
17
+ const match = HANDOFF_LINE.exec(String(text ?? ""));
18
+ return match ? match[1].replace(QUOTES, "") : null;
19
+ }
20
+
21
+ /** The absolute path a spelled note path names, with a Git Bash drive path in Windows spelling. */
22
+ export const resolveHandoff = (spelled, cwd) => path.resolve(cwd, nativePath(spelled));
23
+
24
+ /** The lines under each `## <name>` heading, blank lines dropped. */
25
+ function sectionsOf(markdown) {
26
+ const sections = {};
27
+ let name = null;
28
+ for (const line of markdown.split(/\r?\n/)) {
29
+ const heading = /^##[ \t]+(.+?)[ \t]*$/.exec(line);
30
+ if (heading) {
31
+ name = heading[1];
32
+ sections[name] = [];
33
+ } else if (name !== null && line.trim() !== "") {
34
+ sections[name].push(line);
35
+ }
36
+ }
37
+ return sections;
38
+ }
39
+
40
+ /** The note's four lines and its three sections; a missing one is null. */
41
+ export function parseHandoff(markdown) {
42
+ const note = Object.fromEntries(FIELDS.map((name) => [name.toLowerCase(), fieldLine(name).exec(markdown)?.[1] ?? null]));
43
+ const sections = sectionsOf(markdown);
44
+ for (const [heading, key] of SECTIONS) note[key] = sections[heading] ?? null;
45
+ return note;
46
+ }
47
+
48
+ /** @returns each thing the note lacks, as a phrase; empty when the note is complete. */
49
+ export function handoffProblems(markdown) {
50
+ const note = parseHandoff(markdown);
51
+ const problems = FIELDS.filter((name) => !note[name.toLowerCase()]).map((name) => `a line \`${name}: <value>\``);
52
+ if (note.head && !SHA.test(note.head)) problems.push(`a \`Head:\` sha of 7 to 40 hex digits, not "${note.head}"`);
53
+ for (const [heading, key] of SECTIONS) {
54
+ if (!note[key] || note[key].length === 0) problems.push(`a \`## ${heading}\` section with at least one line`);
55
+ }
56
+ return problems;
57
+ }
58
+
59
+ /** Reads the note a `HANDOFF:` line names. `missing` is the read error's code when the file does not read. */
60
+ export function checkHandoffFile(spelled, cwd) {
61
+ const file = resolveHandoff(spelled, cwd);
62
+ let markdown;
63
+ try {
64
+ markdown = readFileSync(file, "utf8");
65
+ } catch (error) {
66
+ return { file, missing: error.code ?? error.message, problems: [] };
67
+ }
68
+ return { file, missing: null, problems: handoffProblems(markdown) };
69
+ }
@@ -0,0 +1,71 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { test } from "node:test";
6
+ import { checkHandoffFile, handoffPathOf, handoffProblems, parseHandoff, resolveHandoff } from "./handoff-note.mjs";
7
+
8
+ const NOTE = [
9
+ "# Hand-off: Task 3",
10
+ "Brief: C:/scratch/briefs/task-3.md",
11
+ "Worktree: C:/work/kit-85",
12
+ "Branch: feat/85-context",
13
+ "Head: 1a2b3c4",
14
+ "",
15
+ "## Done",
16
+ "- 1a2b3c4 the reader",
17
+ "",
18
+ "## Left",
19
+ "1. wire the guard",
20
+ "",
21
+ "## Next step",
22
+ "node --test packages/qc-harness/src/cli/budget-guard.test.mjs",
23
+ ].join("\n");
24
+
25
+ test("a complete note parses and has no problem", () => {
26
+ const note = parseHandoff(NOTE);
27
+ assert.equal(note.head, "1a2b3c4");
28
+ assert.equal(note.branch, "feat/85-context");
29
+ assert.deepEqual(note.left, ["1. wire the guard"]);
30
+ assert.deepEqual(handoffProblems(NOTE), []);
31
+ assert.deepEqual(handoffProblems(NOTE.replaceAll("\n", "\r\n")), []);
32
+ });
33
+
34
+ test("each missing line and each empty section is named", () => {
35
+ const problems = handoffProblems(NOTE.replace("Head: 1a2b3c4\n", "").replace("1. wire the guard\n", ""));
36
+ assert.ok(problems.includes("a line `Head: <value>`"), problems.join("; "));
37
+ assert.ok(problems.includes("a `## Left` section with at least one line"), problems.join("; "));
38
+ assert.match(handoffProblems(NOTE.replace("Head: 1a2b3c4", "Head: tbd")).join("; "), /Head:` sha of 7 to 40 hex digits/);
39
+ });
40
+
41
+ test("the HANDOFF line is read from a report or a prompt, with or without quotes", () => {
42
+ assert.equal(handoffPathOf("DONE_WITH_CONCERNS\nHANDOFF: C:/scratch/handoffs/t3-1.md\n"), "C:/scratch/handoffs/t3-1.md");
43
+ assert.equal(handoffPathOf('HANDOFF: "/tmp/handoffs/a b.md"'), "/tmp/handoffs/a b.md");
44
+ assert.equal(handoffPathOf("no line"), null);
45
+ assert.equal(resolveHandoff("notes/a.md", path.resolve("/base")), path.resolve("/base", "notes/a.md"));
46
+ });
47
+
48
+ test("the marker is spelled HANDOFF, in capitals", () => {
49
+ assert.equal(handoffPathOf("Handoff: none"), null);
50
+ assert.equal(handoffPathOf("handoff: C:/scratch/handoffs/t3-1.md"), null);
51
+ });
52
+
53
+ test("a HANDOFF word inside a line is not the HANDOFF line", () => {
54
+ assert.equal(handoffPathOf("see the HANDOFF: C:/scratch/handoffs/t3-1.md above"), null);
55
+ assert.equal(handoffPathOf("see the HANDOFF: C:/scratch/handoffs/t3-1.md above\nHANDOFF: C:/scratch/handoffs/real.md"), "C:/scratch/handoffs/real.md");
56
+ });
57
+
58
+ test("a field name inside a line is not that field, and the field line further down still counts", () => {
59
+ assert.equal(parseHandoff("the Head: 1a2b3c4 was tbd").head, null);
60
+ assert.equal(parseHandoff("the Head: deadbeef was tbd\nHead: 1a2b3c4").head, "1a2b3c4");
61
+ });
62
+
63
+ test("checkHandoffFile reads the note, and a missing file is one problem", (t) => {
64
+ const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-handoff-")));
65
+ t.after(() => rmSync(base, { recursive: true, force: true }));
66
+ const file = path.join(base, "note.md");
67
+ writeFileSync(file, NOTE);
68
+ assert.deepEqual(checkHandoffFile(file, base), { file, missing: null, problems: [] });
69
+ const gone = checkHandoffFile(path.join(base, "gone.md"), base);
70
+ assert.equal(gone.missing, "ENOENT");
71
+ });
@@ -107,8 +107,10 @@ const short = (sha) => (typeof sha === "string" ? sha.slice(0, MIN_SHA) : "");
107
107
 
108
108
  const SUMMARIES = {
109
109
  dispatch: (r) =>
110
- `${r.agentType} ${r.task ? `${r.branch} ${short(r.head)}` : "(no task)"}${r.resumeReason ? ` NO-RESUME: ${r.resumeReason}` : ""}`,
111
- stop: (r) => `${r.role} ${r.agentType} ${r.agentId}${r.plan ? ` ${r.plan}` : ""}`,
110
+ `${r.agentType} ${r.task ? `${r.branch} ${short(r.head)}` : "(no task)"}${r.resumeReason ? ` NO-RESUME: ${r.resumeReason}` : ""}${
111
+ r.handoff ? ` HANDOFF: ${r.handoff}` : ""
112
+ }`,
113
+ stop: (r) => `${r.role} ${r.agentType} ${r.agentId}${r.plan ? ` ${r.plan}` : ""}${r.handoff ? ` HANDOFF: ${r.handoff}` : ""}`,
112
114
  verdict: (r) => `${r.kind} ${r.verdict} ${short(r.sha)} ${r.branch ?? "(no branch)"}`,
113
115
  merge: (r) =>
114
116
  `${r.repo}#${r.pr} ${short(r.sha)} ${r.branch ?? ""} into ${r.base ?? "?"} names ${
@@ -146,3 +146,12 @@ test("the default allowed types are the shipped types, bare and scoped", () => {
146
146
  assert.deepEqual([...dispatchDefaults.allowedTypes].sort(), shipped.sort());
147
147
  assert.deepEqual(dispatchDefaults.implementerTypes, ["sdd-implementer", `${PLUGIN}:sdd-implementer`]);
148
148
  });
149
+
150
+ test("no type pins a prompt cache lifetime, so a user's own setting decides it", () => {
151
+ // The measured one-hour lifetime cost more for all four types; `qc tokens` reports it per session.
152
+ for (const name of Object.keys(EXPECTED)) {
153
+ const front = frontOf(name);
154
+ assert.equal(front.experimental, undefined, `${name} sets experimental`);
155
+ assert.equal(front.cacheTtl, undefined, `${name} sets cacheTtl`);
156
+ }
157
+ });
package/src/cli/qc.mjs CHANGED
@@ -22,6 +22,8 @@ const USAGE = `qc — architecture gates
22
22
  qc decisions [id] where decisions are cited; --squash closes the gaps
23
23
  qc ledger [branch] the workflow ledger: dispatches, stops, verdicts, merges, issue updates
24
24
  qc plan-check <plan.md> each task names files, a test step and a commit step, within the tool-call budget
25
+ qc tokens [--session <id>] [--project <dir>] [--claude-dir <dir>] [--json]
26
+ one session's tokens and cache hit rate per agent type, from its transcripts
25
27
  qc worktree add <name> <branch> [--from <ref>]
26
28
  fetch, add ../<name> beside the main checkout, install, print the path
27
29
  qc worktree remove <name>
@@ -97,6 +99,10 @@ async function main() {
97
99
  const { runPlanCheck } = await import("./plan-check.mjs");
98
100
  process.exit(runPlanCheck(config, rest));
99
101
  }
102
+ case "tokens": {
103
+ const { runTokens } = await import("./tokens.mjs");
104
+ process.exit(runTokens(config, rest));
105
+ }
100
106
  case "decisions": {
101
107
  const { runDecisions } = await import("./decisions.mjs");
102
108
  process.exit(await runDecisions(config, rest));
@@ -6,6 +6,7 @@ import os from "node:os";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { checkoutRootOf } from "./checkout-root.mjs";
8
8
  import { branchAt, branchesAt, gitOut, pathKey } from "./git-read.mjs";
9
+ import { checkHandoffFile, handoffPathOf } from "./handoff-note.mjs";
9
10
  import { appendRecord, readLedger } from "./ledger.mjs";
10
11
  import { dropReport, keepReport, reportOf } from "./report-stash.mjs";
11
12
  import { commitLookup, firstUserText, resolveNamedWorktree, workflowOfRepo } from "./workflow-place.mjs";
@@ -40,10 +41,16 @@ export function verdictOf(text) {
40
41
  /**
41
42
  * @param lookup the read of the verdict's sha, `{ sha }`, `{ unknown }`, `{ error }`, or null
42
43
  * @param named true when the dispatch names the worktree whose repository the sha must belong to
44
+ * @param handoff the check of the note an implementer's `HANDOFF:` line names, or null
43
45
  * @returns each line the report still needs, as a phrase; empty when it carries every line its role owes
44
46
  */
45
- export function reportProblems(role, text, verdict, lookup, named) {
47
+ export function reportProblems(role, text, verdict, lookup, named, handoff = null) {
46
48
  if (role === "implementer") {
49
+ // A hand-off stops before GREEN, so its checked note stands in for both lines.
50
+ if (handoff) {
51
+ if (handoff.missing) return [`a hand-off note at ${handoff.spelled} that exists and reads (${handoff.missing})`];
52
+ return handoff.problems.map((problem) => `${problem} in the hand-off note at ${handoff.spelled}`);
53
+ }
47
54
  const problems = [];
48
55
  if (!RED_LINE.test(text)) problems.push("a line that starts `RED:` with the test command and the line that shows it failing before the code");
49
56
  if (!GREEN_LINE.test(text)) problems.push("a line that starts `GREEN:` with the same command and the line that shows it passing after");
@@ -146,10 +153,11 @@ function offNote(call, root, event, tmp) {
146
153
  return event === "SubagentStop" ? { systemMessage: note } : null;
147
154
  }
148
155
 
149
- function recordStop({ workflow, call, session, agentId, role, worktree, verdict, lookup, text, tmp, records, notes }) {
156
+ function recordStop({ workflow, call, session, agentId, role, worktree, verdict, lookup, text, tmp, records, notes, handoff = null }) {
150
157
  try {
151
158
  const place = worktree ? (role === "implementer" ? implementerPlace(records, worktree) : { worktree }) : {};
152
- appendRecord(workflow.ledger, { type: "stop", session, agentType: call.agent_type, agentId, role, ...place });
159
+ const handedOff = handoff ? { handoff: handoff.file } : {};
160
+ appendRecord(workflow.ledger, { type: "stop", session, agentType: call.agent_type, agentId, role, ...place, ...handedOff });
153
161
  // A failed read keeps the sha as the reviewer wrote it, which the gates match by prefix.
154
162
  const sha = lookup?.sha ?? (lookup?.error ? verdict.sha : null);
155
163
  if (verdict && sha) {
@@ -216,6 +224,8 @@ export function decide(call, tmp = os.tmpdir(), deps = {}) {
216
224
  const worktree = prior?.worktree ?? named;
217
225
  const text = event === "PreToolUse" ? String(call.tool_input?.message ?? "") : reportOf(call, tmp);
218
226
  const verdict = role === "implementer" ? null : verdictOf(text);
227
+ const spelled = role === "implementer" ? handoffPathOf(text) : null;
228
+ const handoff = spelled === null ? null : { spelled, ...checkHandoffFile(spelled, call.cwd ?? process.cwd()) };
219
229
  const lookup = verdict ? commit(worktree ?? workflow.root, verdict.sha) : null;
220
230
  const notes = [];
221
231
  if (lookup?.error) {
@@ -228,13 +238,13 @@ export function decide(call, tmp = os.tmpdir(), deps = {}) {
228
238
  if (event === "SubagentStop" && role === "implementer" && !worktree) {
229
239
  notes.push("Workflow report: the prompt of this implementer has no readable `Worktree:` line, so the stop records no head.");
230
240
  }
231
- const problems = reportProblems(role, text, verdict, lookup, worktree !== null);
241
+ const problems = reportProblems(role, text, verdict, lookup, worktree !== null, handoff);
232
242
  if (problems.length > 0) {
233
243
  if (event === "PreToolUse") return deny(refusal(role, problems));
234
244
  return call.stop_hook_active === true ? held(role, problems) : block(refusal(role, problems));
235
245
  }
236
246
  if (event === "PreToolUse") return notes.length > 0 ? preContext(notes.join(" ")) : null;
237
- return recordStop({ workflow, call, session, agentId, role, worktree, verdict, lookup, text, tmp, records, notes });
247
+ return recordStop({ workflow, call, session, agentId, role, worktree, verdict, lookup, text, tmp, records, notes, handoff });
238
248
  }
239
249
 
240
250
  async function readStdin() {
@@ -430,3 +430,42 @@ test("an implementer that edits qc.config.json in its worktree is still judged",
430
430
  const output = decide(stop(ws.on, IMPLEMENTER, "DONE", namesWorktree(ws, "cfg", linked)), ws.tmp);
431
431
  assert.equal(output.decision, "block");
432
432
  });
433
+
434
+ const NOTE = [
435
+ "# Hand-off: Task 3",
436
+ "Brief: C:/scratch/briefs/task-3.md",
437
+ "Worktree: C:/work/kit-85",
438
+ "Branch: feat/85-context",
439
+ "Head: 1a2b3c4",
440
+ "",
441
+ "## Done",
442
+ "- 1a2b3c4 the reader",
443
+ "",
444
+ "## Left",
445
+ "1. wire the guard",
446
+ "",
447
+ "## Next step",
448
+ "node --test packages/qc-harness/src/cli/budget-guard.test.mjs",
449
+ ].join("\n");
450
+
451
+ test("an implementer that hands off reports a checked note in place of the RED and GREEN lines", (t) => {
452
+ const ws = workspace(t);
453
+ const note = path.join(ws.tmp, "handoffs", "t3-1.md");
454
+ mkdirSync(path.dirname(note), { recursive: true });
455
+ const missing = decide(handback(ws.on, "architecture:sdd-implementer", `DONE_WITH_CONCERNS\nHANDOFF: ${note}`), ws.tmp);
456
+ assert.match(denied(missing) ?? "", /a hand-off note at .*t3-1\.md that exists and reads \(ENOENT\)/);
457
+ writeFileSync(note, NOTE.replace("Head: 1a2b3c4\n", ""));
458
+ assert.match(denied(decide(handback(ws.on, "architecture:sdd-implementer", `DONE\nHANDOFF: ${note}`), ws.tmp)) ?? "", /a line `Head: <value>` in the hand-off note/);
459
+ writeFileSync(note, NOTE);
460
+ assert.equal(decide(handback(ws.on, "architecture:sdd-implementer", `DONE\nHANDOFF: ${note}`), ws.tmp), null);
461
+ const stopped = decide(stop(ws.on, "sdd-implementer", `DONE\nHANDOFF: ${note}`), ws.tmp);
462
+ assert.equal(stopped?.decision, undefined);
463
+ const [record] = readLedger(ws.ledger);
464
+ assert.equal(record.handoff, note);
465
+ });
466
+
467
+ test("the implementer definition names the HANDOFF line and the resume from a note", () => {
468
+ const body = readFileSync(path.join(AGENTS, "sdd-implementer.md"), "utf8");
469
+ assert.match(body, /`HANDOFF: <note path>`/);
470
+ assert.match(body, /git log --oneline <Head>\.\.HEAD/);
471
+ });
@@ -5,6 +5,7 @@ import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { checkoutRootOf } from "./checkout-root.mjs";
7
7
  import { typeOf } from "./dispatch.mjs";
8
+ import { handoffPathOf, resolveHandoff } from "./handoff-note.mjs";
8
9
  import { branchAt, gitOut, linkedWorktrees, pathKey } from "./git-read.mjs";
9
10
  import { appendRecord, latestVerdictFor, latestVerdictOn, readLedger, shaMatches } from "./ledger.mjs";
10
11
  import { resolveNamedWorktree, workflowOfRepo, worktreeNamed } from "./workflow-place.mjs";
@@ -26,15 +27,16 @@ const fixRoundRefusal = (branch, sha, type) =>
26
27
  const unreviewedRefusal = (branch, stopHead, head) =>
27
28
  `Task gate: an implementer stopped on ${branch} at ${short(stopHead)}, and no review in the ledger names ${short(stopHead)} or a later commit. ` +
28
29
  `Dispatch the task reviewer on ${short(head)} first; its first line \`VERDICT: <APPROVED|CHANGES_REQUIRED> <sha>\` records the review. ` +
30
+ `If that stop handed off, its report named \`HANDOFF: <note path>\`; the same line in the next implementer prompt continues the task. ` +
29
31
  `\`qc ledger ${branch}\` lists what is recorded.`;
30
32
 
31
33
  const HISTORY_LIMIT = 5000;
32
34
 
33
35
  /**
34
- * The head of the newest implementer stop in this branch's history that no later verdict on the branch covers,
36
+ * The newest implementer stop in this branch's history that no later verdict on the branch covers,
35
37
  * or null. Older stops are ancestors of it, so its verdict covers them. Two git calls at most; a git error passes.
36
38
  */
37
- function unreviewedImplementerHead({ records, branch, head, cwd, git }) {
39
+ function unreviewedImplementerStop({ records, branch, head, cwd, git }) {
38
40
  if (cwd === undefined) return null;
39
41
  const history = git(cwd, "rev-list", `--max-count=${HISTORY_LIMIT}`, head);
40
42
  if (history === null) return null;
@@ -44,28 +46,45 @@ function unreviewedImplementerHead({ records, branch, head, cwd, git }) {
44
46
  record.type === "stop" && record.role === "implementer" && record.branch === branch && typeof record.head === "string" && inHistory.has(record.head.toLowerCase()),
45
47
  );
46
48
  if (stopAt < 0) return null;
47
- const stopHead = records[stopAt].head;
49
+ const stop = records[stopAt];
50
+ const stopHead = stop.head;
48
51
  // A commit is reviewed once, wherever and whenever the verdict on it was written.
49
52
  if (records.some((record) => record.type === "verdict" && shaMatches(record.sha, stopHead))) return null;
50
53
  const later = records.slice(stopAt + 1).filter((record) => record.type === "verdict" && record.branch === branch && typeof record.sha === "string");
51
- if (later.length === 0 || shaMatches(stopHead, head)) return stopHead;
54
+ if (later.length === 0 || shaMatches(stopHead, head)) return stop;
52
55
  const below = git(cwd, "rev-list", "--ancestry-path", `${stopHead}..${head}`);
53
56
  if (below === null) return null;
54
57
  const descendants = below.split(/\r?\n/).filter(Boolean);
55
- return later.some((verdict) => descendants.some((sha) => shaMatches(verdict.sha, sha))) ? null : stopHead;
58
+ return later.some((verdict) => descendants.some((sha) => shaMatches(verdict.sha, sha))) ? null : stop;
59
+ }
60
+
61
+ /**
62
+ * The newest implementer stop on `branch` when it left the note `handoff` and no verdict came after it, else null.
63
+ * A later verdict on the branch, or one that names the stop's head, reviewed the stop, so its note is spent.
64
+ */
65
+ export function continuedStop(records, branch, handoff) {
66
+ if (handoff === null) return null;
67
+ const stopAt = records.findLastIndex((record) => record.type === "stop" && record.role === "implementer" && record.branch === branch);
68
+ const stop = records[stopAt];
69
+ if (!stop || typeof stop.handoff !== "string" || pathKey(stop.handoff) !== pathKey(handoff)) return null;
70
+ const reviewed = records.slice(stopAt + 1).some((record) => record.type === "verdict" && (record.branch === branch || shaMatches(record.sha, stop.head)));
71
+ return reviewed ? null : stop;
56
72
  }
57
73
 
58
74
  /**
59
75
  * @returns the reason an implementer may not start on `branch` now, or null. Only implementer commits need a
60
76
  * review, so a controller commit after a reviewed head passes. `cwd` is any checkout; `git` reads it.
61
77
  */
62
- export function gateRefusal({ records, branch, head, reason, type, cwd, git = gitOut }) {
78
+ export function gateRefusal({ records, branch, head, reason, type, cwd, git = gitOut, handoff = null }) {
79
+ // A continuation of the newest stop's hand-off is the same task, so it is neither a fix round nor a new task.
80
+ const continued = continuedStop(records, branch, handoff);
81
+ const why = reason ?? (continued ? `continues the hand-off ${continued.handoff}` : null);
63
82
  const last = latestVerdictOn(records, branch);
64
- if (last?.verdict === "CHANGES_REQUIRED" && reason === null) return fixRoundRefusal(branch, last.sha, type);
65
- const unreviewed = unreviewedImplementerHead({ records, branch, head, cwd, git });
66
- if (unreviewed) return unreviewedRefusal(branch, unreviewed, head);
83
+ if (last?.verdict === "CHANGES_REQUIRED" && why === null) return fixRoundRefusal(branch, last.sha, type);
84
+ const unreviewed = unreviewedImplementerStop({ records, branch, head, cwd, git });
85
+ if (unreviewed && unreviewed !== continued) return unreviewedRefusal(branch, unreviewed.head, head);
67
86
  const current = latestVerdictFor(records, head, ["task", "branch"]);
68
- if (current?.verdict === "CHANGES_REQUIRED" && reason === null) return fixRoundRefusal(branch, current.sha, type);
87
+ if (current?.verdict === "CHANGES_REQUIRED" && why === null) return fixRoundRefusal(branch, current.sha, type);
69
88
  return null;
70
89
  }
71
90
 
@@ -140,9 +159,12 @@ export function judgeTask(call, tmp = os.tmpdir()) {
140
159
  return pass(null, null, `Task gate could not read the ledger (${error.message}), so this dispatch is not judged.`);
141
160
  }
142
161
  const reason = noResumeReason(prompt);
143
- const refusal = gateRefusal({ records, branch: worktree.branch, head: worktree.head, reason, type, cwd: workflow.root });
162
+ const spelled = handoffPathOf(prompt);
163
+ const handoff = spelled === null ? null : resolveHandoff(spelled, cwd);
164
+ const refusal = gateRefusal({ records, branch: worktree.branch, head: worktree.head, reason, type, cwd: workflow.root, handoff });
144
165
  if (refusal) return refuse(refusal);
145
- return pass(workflow, { ...base, task: true, worktree: worktree.path, branch: worktree.branch, head: worktree.head, resumeReason: reason });
166
+ const continues = handoff ? { handoff } : {};
167
+ return pass(workflow, { ...base, task: true, worktree: worktree.path, branch: worktree.branch, head: worktree.head, resumeReason: reason, ...continues });
146
168
  }
147
169
 
148
170
  /** Writes the dispatch record of a judged call. @returns a note for the session, or null. */