architecture-harness 0.17.0 → 0.18.1
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.
- package/package.json +1 -1
- package/src/cli/budget-counter.mjs +25 -4
- package/src/cli/budget-guard.mjs +79 -4
- package/src/cli/budget-guard.test.mjs +146 -0
- package/src/cli/budget.mjs +3 -2
- package/src/cli/context-signal.mjs +92 -0
- package/src/cli/context-signal.test.mjs +99 -0
- package/src/cli/dispatch-guard.mjs +9 -5
- package/src/cli/dispatch-guard.test.mjs +5 -6
- package/src/cli/dispatch.mjs +20 -2
- package/src/cli/dispatch.test.mjs +25 -1
- package/src/cli/explore-hint.mjs +67 -7
- package/src/cli/explore-hint.test.mjs +104 -4
- package/src/cli/handoff-note.mjs +69 -0
- package/src/cli/handoff-note.test.mjs +71 -0
- package/src/cli/ledger.mjs +4 -2
- package/src/cli/plugin-agents.test.mjs +9 -0
- package/src/cli/qc.mjs +6 -0
- package/src/cli/report-stop.mjs +30 -10
- package/src/cli/report-stop.test.mjs +112 -1
- package/src/cli/stop-gate.test.mjs +167 -3
- package/src/cli/task-gate.mjs +34 -12
- package/src/cli/task-gate.test.mjs +88 -2
- package/src/cli/tokens.mjs +258 -0
- package/src/cli/tokens.test.mjs +322 -0
- package/src/cli/transcript-usage.mjs +135 -0
- package/src/cli/transcript-usage.test.mjs +138 -0
- package/src/config.mjs +15 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { strict as assert } from "node:assert";
|
|
2
2
|
import { test } from "node:test";
|
|
3
3
|
import { defaults, dispatchDefaults, merge } from "../config.mjs";
|
|
4
|
-
import { dispatchRefusal, dispatchSettings, exploreToolLines, familyOf, isImplementer, slotRefusal, typeOf } from "./dispatch.mjs";
|
|
4
|
+
import { dispatchNote, dispatchRefusal, dispatchSettings, exploreSettings, exploreToolLines, familyOf, isImplementer, slotRefusal, typeOf } from "./dispatch.mjs";
|
|
5
5
|
|
|
6
6
|
test("a swarm section with no dispatch key keeps the guard off", () => {
|
|
7
7
|
assert.equal(dispatchSettings({}), null);
|
|
@@ -206,3 +206,27 @@ test("exploreToolLines gives one `- name: use (how)` line per tool, in config or
|
|
|
206
206
|
);
|
|
207
207
|
assert.deepEqual(exploreToolLines([]), []);
|
|
208
208
|
});
|
|
209
|
+
|
|
210
|
+
test("a shipped type that names a full model id gets a cache note, never a refusal", () => {
|
|
211
|
+
const settings = { ...dispatchDefaults };
|
|
212
|
+
const note = dispatchNote({ subagent_type: "architecture:sdd-implementer", model: "claude-sonnet-5", prompt: "x" }, settings);
|
|
213
|
+
assert.match(note, /share no prompt cache/);
|
|
214
|
+
assert.equal(dispatchNote({ subagent_type: "architecture:sdd-implementer", model: "sonnet", prompt: "x" }, settings), null);
|
|
215
|
+
assert.equal(dispatchNote({ subagent_type: "architecture:sdd-implementer", prompt: "x" }, settings), null);
|
|
216
|
+
assert.equal(dispatchNote({ subagent_type: "general-purpose", model: "claude-sonnet-5", prompt: "x" }, settings), null);
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
test("an excerptChars the repository leaves out is half of maxOutputChars, at most 4000, and never an error", () => {
|
|
220
|
+
assert.equal(exploreSettings({ explore: { maxOutputChars: 20 } }).excerptChars, 10);
|
|
221
|
+
assert.equal(exploreSettings({ explore: { maxOutputChars: 7 } }).excerptChars, 3);
|
|
222
|
+
assert.equal(exploreSettings({ explore: { maxOutputChars: 7999 } }).excerptChars, 3999);
|
|
223
|
+
assert.equal(exploreSettings({ explore: { maxOutputChars: 20000 } }).excerptChars, 4000);
|
|
224
|
+
assert.equal(exploreSettings({ explore: {} }).excerptChars, 4000);
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
test("an excerptChars the repository sets must be smaller than maxOutputChars", () => {
|
|
228
|
+
assert.equal(exploreSettings({ explore: { maxOutputChars: 20, excerptChars: 19 } }).excerptChars, 19);
|
|
229
|
+
for (const excerptChars of [20, 21]) {
|
|
230
|
+
assert.throws(() => exploreSettings({ explore: { maxOutputChars: 20, excerptChars } }), /swarm\.explore\.excerptChars .*smaller than maxOutputChars \(20\)/);
|
|
231
|
+
}
|
|
232
|
+
});
|
package/src/cli/explore-hint.mjs
CHANGED
|
@@ -1,12 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// The trigger for `swarm.explore`'s search and output hints:
|
|
3
|
-
//
|
|
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 (
|
|
66
|
-
|
|
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
|
+
});
|
package/src/cli/ledger.mjs
CHANGED
|
@@ -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
|
-
|
|
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));
|
package/src/cli/report-stop.mjs
CHANGED
|
@@ -6,9 +6,11 @@ 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";
|
|
13
|
+
import { agentTranscriptOf } from "./transcript-usage.mjs";
|
|
12
14
|
import { workflowOf } from "./workflow-settings.mjs";
|
|
13
15
|
|
|
14
16
|
const HANDBACK = "SubagentHandback";
|
|
@@ -40,10 +42,16 @@ export function verdictOf(text) {
|
|
|
40
42
|
/**
|
|
41
43
|
* @param lookup the read of the verdict's sha, `{ sha }`, `{ unknown }`, `{ error }`, or null
|
|
42
44
|
* @param named true when the dispatch names the worktree whose repository the sha must belong to
|
|
45
|
+
* @param handoff the check of the note an implementer's `HANDOFF:` line names, or null
|
|
43
46
|
* @returns each line the report still needs, as a phrase; empty when it carries every line its role owes
|
|
44
47
|
*/
|
|
45
|
-
export function reportProblems(role, text, verdict, lookup, named) {
|
|
48
|
+
export function reportProblems(role, text, verdict, lookup, named, handoff = null) {
|
|
46
49
|
if (role === "implementer") {
|
|
50
|
+
// A hand-off stops before GREEN, so its checked note stands in for both lines.
|
|
51
|
+
if (handoff) {
|
|
52
|
+
if (handoff.missing) return [`a hand-off note at ${handoff.spelled} that exists and reads (${handoff.missing})`];
|
|
53
|
+
return handoff.problems.map((problem) => `${problem} in the hand-off note at ${handoff.spelled}`);
|
|
54
|
+
}
|
|
47
55
|
const problems = [];
|
|
48
56
|
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
57
|
if (!GREEN_LINE.test(text)) problems.push("a line that starts `GREEN:` with the same command and the line that shows it passing after");
|
|
@@ -62,8 +70,8 @@ const refusal = (role, problems) =>
|
|
|
62
70
|
"Add it and send the report again.";
|
|
63
71
|
|
|
64
72
|
/** A block already held this stop once, so it ends now, records nothing, and says what is still missing. */
|
|
65
|
-
const held = (role, problems) => ({
|
|
66
|
-
systemMessage: `${refusal(role, problems)} A block already held this stop once, so it ends now and the ledger records nothing
|
|
73
|
+
const held = (role, problems, lost = null) => ({
|
|
74
|
+
systemMessage: `${refusal(role, problems)} A block already held this stop once, so it ends now and the ledger records nothing.${lost ? ` ${lost}` : ""}`,
|
|
67
75
|
});
|
|
68
76
|
|
|
69
77
|
const MAX_BRANCH_PROBES = 10;
|
|
@@ -115,7 +123,7 @@ function implementerPlace(records, worktree) {
|
|
|
115
123
|
* @returns `{ workflow, named }`, `{ off }` for a repository with no workflow, or null; throws on a wrong config
|
|
116
124
|
*/
|
|
117
125
|
function locate(call, tmp) {
|
|
118
|
-
const text = firstUserText(call
|
|
126
|
+
const text = firstUserText(agentTranscriptOf(call));
|
|
119
127
|
const place = text === null ? null : resolveNamedWorktree(text, call.cwd ?? process.cwd());
|
|
120
128
|
const root = place?.found ? checkoutRootOf(place.abs) : null;
|
|
121
129
|
if (root) {
|
|
@@ -132,6 +140,10 @@ function locate(call, tmp) {
|
|
|
132
140
|
return workflow ? { workflow, named: null } : null;
|
|
133
141
|
}
|
|
134
142
|
|
|
143
|
+
/** The line for a report the hook judges with no transcript to place the agent, so it cannot name the agent's worktree. */
|
|
144
|
+
const noTranscriptLine = (root) =>
|
|
145
|
+
`Workflow report: the hook input names no transcript for this agent, so the checks judge against the repository of the cwd or the session, ${root}.`;
|
|
146
|
+
|
|
135
147
|
/** The note for an agent whose work is in a repository with no workflow, or null when the cwd's workflow does not track its type. */
|
|
136
148
|
function offNote(call, root, event, tmp) {
|
|
137
149
|
let own = null;
|
|
@@ -146,10 +158,11 @@ function offNote(call, root, event, tmp) {
|
|
|
146
158
|
return event === "SubagentStop" ? { systemMessage: note } : null;
|
|
147
159
|
}
|
|
148
160
|
|
|
149
|
-
function recordStop({ workflow, call, session, agentId, role, worktree, verdict, lookup, text, tmp, records, notes }) {
|
|
161
|
+
function recordStop({ workflow, call, session, agentId, role, worktree, verdict, lookup, text, tmp, records, notes, handoff = null }) {
|
|
150
162
|
try {
|
|
151
163
|
const place = worktree ? (role === "implementer" ? implementerPlace(records, worktree) : { worktree }) : {};
|
|
152
|
-
|
|
164
|
+
const handedOff = handoff ? { handoff: handoff.file } : {};
|
|
165
|
+
appendRecord(workflow.ledger, { type: "stop", session, agentType: call.agent_type, agentId, role, ...place, ...handedOff });
|
|
153
166
|
// A failed read keeps the sha as the reviewer wrote it, which the gates match by prefix.
|
|
154
167
|
const sha = lookup?.sha ?? (lookup?.error ? verdict.sha : null);
|
|
155
168
|
if (verdict && sha) {
|
|
@@ -216,8 +229,14 @@ export function decide(call, tmp = os.tmpdir(), deps = {}) {
|
|
|
216
229
|
const worktree = prior?.worktree ?? named;
|
|
217
230
|
const text = event === "PreToolUse" ? String(call.tool_input?.message ?? "") : reportOf(call, tmp);
|
|
218
231
|
const verdict = role === "implementer" ? null : verdictOf(text);
|
|
232
|
+
const spelled = role === "implementer" ? handoffPathOf(text) : null;
|
|
233
|
+
const handoff = spelled === null ? null : { spelled, ...checkHandoffFile(spelled, call.cwd ?? process.cwd()) };
|
|
219
234
|
const lookup = verdict ? commit(worktree ?? workflow.root, verdict.sha) : null;
|
|
220
235
|
const notes = [];
|
|
236
|
+
// A prior stop already placed a resumed agent, so only an agent with no worktree at all lacks a place.
|
|
237
|
+
const lost = worktree === null && agentTranscriptOf(call) === null ? noTranscriptLine(workflow.root) : null;
|
|
238
|
+
const withLost = (text) => (lost ? `${text} ${lost}` : text);
|
|
239
|
+
if (lost) notes.push(lost);
|
|
221
240
|
if (lookup?.error) {
|
|
222
241
|
notes.push(`Workflow report: git could not read ${verdict.sha} (${lookup.error}), so the verdict is not checked and is recorded as written.`);
|
|
223
242
|
} else if (lookup?.unknown && !worktree) {
|
|
@@ -228,13 +247,14 @@ export function decide(call, tmp = os.tmpdir(), deps = {}) {
|
|
|
228
247
|
if (event === "SubagentStop" && role === "implementer" && !worktree) {
|
|
229
248
|
notes.push("Workflow report: the prompt of this implementer has no readable `Worktree:` line, so the stop records no head.");
|
|
230
249
|
}
|
|
231
|
-
const problems = reportProblems(role, text, verdict, lookup, worktree !== null);
|
|
250
|
+
const problems = reportProblems(role, text, verdict, lookup, worktree !== null, handoff);
|
|
232
251
|
if (problems.length > 0) {
|
|
233
|
-
if (event === "PreToolUse") return deny(refusal(role, problems));
|
|
234
|
-
|
|
252
|
+
if (event === "PreToolUse") return deny(withLost(refusal(role, problems)));
|
|
253
|
+
if (call.stop_hook_active !== true) return block(withLost(refusal(role, problems)));
|
|
254
|
+
return held(role, problems, lost);
|
|
235
255
|
}
|
|
236
256
|
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 });
|
|
257
|
+
return recordStop({ workflow, call, session, agentId, role, worktree, verdict, lookup, text, tmp, records, notes, handoff });
|
|
238
258
|
}
|
|
239
259
|
|
|
240
260
|
async function readStdin() {
|