architecture-harness 0.20.3 → 0.20.4
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/bash-command-guard.mjs +28 -5
- package/src/cli/bash-command-guard.test.mjs +100 -0
- package/src/cli/bash-edit-guard.mjs +19 -16
- package/src/cli/bash-edit-guard.test.mjs +19 -0
- package/src/cli/ci-state.mjs +17 -9
- package/src/cli/ci-state.test.mjs +15 -1
- package/src/cli/cost-stop.mjs +98 -0
- package/src/cli/cost-stop.test.mjs +149 -0
- package/src/cli/dispatch-guard.mjs +3 -3
- package/src/cli/dispatch-guard.test.mjs +14 -6
- package/src/cli/dispatch-reminder.mjs +5 -3
- package/src/cli/dispatch-reminder.test.mjs +5 -1
- package/src/cli/git-read.mjs +28 -3
- package/src/cli/git-read.test.mjs +31 -1
- package/src/cli/ledger.mjs +50 -3
- package/src/cli/ledger.test.mjs +46 -0
- package/src/cli/powershell-command.mjs +8 -13
- package/src/cli/powershell-command.test.mjs +11 -1
- package/src/cli/qc.mjs +1 -1
- package/src/cli/report-stop.test.mjs +2 -1
- package/src/cli/review-gate.mjs +224 -0
- package/src/cli/review-gate.test.mjs +334 -0
- package/src/cli/shell-command.mjs +65 -9
- package/src/cli/shell-command.test.mjs +21 -1
- package/src/cli/skill-guard.mjs +56 -0
- package/src/cli/skill-guard.test.mjs +87 -0
- package/src/cli/stop-gate.test.mjs +80 -0
- package/src/cli/task-gate-review.test.mjs +225 -0
- package/src/cli/task-gate.mjs +35 -11
- package/src/cli/task-gate.test.mjs +6 -5
- package/src/cli/test-brief.mjs +12 -0
- package/src/cli/transcript-usage.mjs +28 -0
- package/src/cli/transcript-usage.test.mjs +9 -0
- package/src/cli/workflow-hooks.test.mjs +38 -0
- package/src/cli/workflow-settings.mjs +14 -3
- package/src/cli/workflow-settings.test.mjs +24 -0
- package/src/config.mjs +13 -0
- package/templates/docs/enforcement.md +11 -0
package/package.json
CHANGED
|
@@ -46,6 +46,12 @@ const NESTED = Object.fromEntries([
|
|
|
46
46
|
]);
|
|
47
47
|
|
|
48
48
|
export const programName = (word) => path.basename(word ?? "").toLowerCase().replace(/\.exe$/, "");
|
|
49
|
+
/** Git reads the repository from these settings, wherever the command spells them. */
|
|
50
|
+
const REPOSITORY_SETTING = /GIT_DIR|GIT_COMMON_DIR|GIT_WORK_TREE|core\.worktree|core\.bare/i;
|
|
51
|
+
/** A shell variable or command substitution in a path: `$K`, `${K}`, `$env:K`, `$(cmd)`, a backtick, or `%K%`. */
|
|
52
|
+
const UNEXPANDED = /[$`]|%[A-Za-z_][^%\s]*%/;
|
|
53
|
+
const WORKTREE_ADD = /\bworktree\s+add\b/i;
|
|
54
|
+
const EXPLICIT_DIR = /--git-dir|--work-tree|GIT_DIR|GIT_COMMON_DIR|GIT_WORK_TREE|core\.worktree|core\.bare/i;
|
|
49
55
|
const isNoVerify = (arg) => arg.length >= NO_VERIFY_MIN && NO_VERIFY.startsWith(arg);
|
|
50
56
|
|
|
51
57
|
/** True when a commit or push names `--no-verify`, or a commit names `-n` alone or in a flag cluster. */
|
|
@@ -142,9 +148,13 @@ const REASONS = {
|
|
|
142
148
|
"a hand run of a hook script writes a lease or a ledger record under a made-up session id, and that lease blocks later " +
|
|
143
149
|
"edits in the worktree for hours. Test a hook only through its own suite (`node --test`), in temporary folders.",
|
|
144
150
|
explicitDir:
|
|
145
|
-
"`--git-dir`, `GIT_DIR`, `--work-tree`, and `
|
|
146
|
-
"so this guard cannot tell which repository gets the worktree.
|
|
151
|
+
"`--git-dir`, `GIT_DIR`, `GIT_COMMON_DIR`, `--work-tree`, `GIT_WORK_TREE`, `core.worktree`, and `core.bare` make git read the repository from a path it resolves " +
|
|
152
|
+
"after every `-C`, so this guard cannot tell which repository gets the worktree. It looks for them in the whole command, in any order. " +
|
|
153
|
+
"Run `git worktree add` from inside the target repository instead: " +
|
|
147
154
|
"use `-C <repository>`, `cd <repository>`, or `Set-Location <repository>`, and drop the git directory and work tree settings.",
|
|
155
|
+
variable:
|
|
156
|
+
"a `-C`, `cd`, or `Set-Location` path holds a variable the guard cannot expand (`$K`, `${K}`, `$env:K`, `%K%`, or a command substitution), " +
|
|
157
|
+
"so it cannot tell which repository gets the worktree. Write the path literally.",
|
|
148
158
|
worktree:
|
|
149
159
|
"a worktree lives in the worktree folder of the main checkout, so git ignores it and `qc worktree remove` finds it. " +
|
|
150
160
|
"Run `npx qc worktree add <name> <branch>` from the repository, or give `git worktree add` a path one level under that folder.",
|
|
@@ -172,17 +182,30 @@ function folderFor(place, from) {
|
|
|
172
182
|
export function violations(command, parse = segmentsOf, place = null, refused = []) {
|
|
173
183
|
const segments = parse(command);
|
|
174
184
|
const found = new Set();
|
|
185
|
+
const scoped = Boolean(place) && (place.scoped === true || REPOSITORY_SETTING.test(command));
|
|
175
186
|
let cwd = place?.cwd;
|
|
187
|
+
// A move into a path with a variable leaves the repository unknown, until a literal absolute path names it again.
|
|
188
|
+
let unknown = place?.unknown === true;
|
|
176
189
|
for (const segment of segments) {
|
|
177
190
|
const moved = place ? MOVES.get(parse)?.(segment) : null;
|
|
178
|
-
if (moved != null
|
|
191
|
+
if (moved != null && UNEXPANDED.test(moved)) {
|
|
192
|
+
unknown = true;
|
|
193
|
+
} else if (moved != null) {
|
|
194
|
+
cwd = resolveFrom(cwd, moved, parse);
|
|
195
|
+
if (path.isAbsolute(spelledPath(moved, parse))) unknown = false;
|
|
196
|
+
}
|
|
179
197
|
const git = gitCall(segment);
|
|
180
198
|
if (git && skipsHooks(git)) found.add("hooks");
|
|
181
199
|
if (git && setsHooksPath(git)) found.add("hooksPath");
|
|
182
200
|
const added = place && git?.sub === "worktree" ? worktreeAddPath(git.args) : null;
|
|
183
|
-
|
|
201
|
+
// A subexpression after `-C` ends the git segment, so the `worktree add` after it never parses as git.
|
|
202
|
+
if (place && git?.sub === null && git.dirs.some((dir) => !dir || UNEXPANDED.test(dir)) && WORKTREE_ADD.test(command)) found.add("variable");
|
|
203
|
+
if (place && git?.sub === null && WORKTREE_ADD.test(command) && EXPLICIT_DIR.test(command)) found.add("explicitDir");
|
|
204
|
+
if (added !== null && (scoped || git.explicitDir)) {
|
|
184
205
|
// The session is guarded, because `place` exists only then.
|
|
185
206
|
found.add("explicitDir");
|
|
207
|
+
} else if (added !== null && (unknown || git.dirs.some((dir) => UNEXPANDED.test(dir)))) {
|
|
208
|
+
found.add("variable");
|
|
186
209
|
} else if (added !== null) {
|
|
187
210
|
const from = git.dirs.filter(Boolean).reduce((dir, next) => resolveFrom(dir, next, parse), cwd);
|
|
188
211
|
const folder = folderFor(place, from);
|
|
@@ -192,7 +215,7 @@ export function violations(command, parse = segmentsOf, place = null, refused =
|
|
|
192
215
|
}
|
|
193
216
|
}
|
|
194
217
|
const nested = nestedCommand(segment);
|
|
195
|
-
if (nested) for (const key of violations(nested.command, nested.parse, place && { ...place, cwd }, refused)) found.add(key);
|
|
218
|
+
if (nested) for (const key of violations(nested.command, nested.parse, place && { ...place, cwd, scoped, unknown }, refused)) found.add(key);
|
|
196
219
|
}
|
|
197
220
|
if (!segments.some(runsTests) && segments.some(runsHookScript)) found.add("script");
|
|
198
221
|
return Object.keys(REASONS).filter((key) => found.has(key));
|
|
@@ -353,3 +353,103 @@ test("a worktree add in a repository with no qc.config.json is not guarded", (t)
|
|
|
353
353
|
}
|
|
354
354
|
assert.equal(decide(bash(ws.plain, "git worktree add ../x")), null, "a session in it is not guarded either");
|
|
355
355
|
});
|
|
356
|
+
|
|
357
|
+
test("a worktree add is refused when its command text sets GIT_DIR, GIT_WORK_TREE, core.worktree, or core.bare in any segment", (t) => {
|
|
358
|
+
const ws = twoRepos(t);
|
|
359
|
+
const kit = ws.slash(ws.kit);
|
|
360
|
+
for (const command of [
|
|
361
|
+
`export GIT_DIR=${kit}/.git; git worktree add .worktree/x`,
|
|
362
|
+
`export GIT_WORK_TREE=${kit}; cd ${kit} && git worktree add .worktree/x`,
|
|
363
|
+
`env GIT_DIR=${kit}/.git bash -c 'cd ${kit}'; git worktree add .worktree/x`,
|
|
364
|
+
`git worktree add .worktree/x; export GIT_DIR=${kit}/.git`,
|
|
365
|
+
`export GIT_DIR=${kit}/.git; bash -c 'git worktree add .worktree/x'`,
|
|
366
|
+
`bash -c 'export GIT_DIR=${kit}/.git'; git worktree add .worktree/x`,
|
|
367
|
+
`git -c core.worktree=${kit} worktree add .worktree/x`,
|
|
368
|
+
`git -c core.bare=true worktree add .worktree/x`,
|
|
369
|
+
`git config core.worktree ${kit} && git worktree add .worktree/x`,
|
|
370
|
+
`set GIT_DIR=${kit}/.git && git worktree add .worktree/x`,
|
|
371
|
+
`export git_dir=${kit}/.git; git worktree add .worktree/x`,
|
|
372
|
+
`export GIT_COMMON_DIR=${kit}/.git; git worktree add .worktree/x`,
|
|
373
|
+
"git -c core.worktree=$(pwd) worktree add ../out",
|
|
374
|
+
"git --git-dir=$(pwd)/.git worktree add ../out",
|
|
375
|
+
"git --work-tree=$(pwd) worktree add ../out",
|
|
376
|
+
]) {
|
|
377
|
+
explicitDirReason(decide(bash(ws.adopted, command)));
|
|
378
|
+
}
|
|
379
|
+
for (const command of [
|
|
380
|
+
`$env:GIT_DIR = "${kit}/.git"; git worktree add .worktree/x`,
|
|
381
|
+
`$env:GIT_WORK_TREE = "${kit}"; Set-Location ${kit}; git worktree add .worktree/x`,
|
|
382
|
+
`git -c core.worktree=${kit} worktree add .worktree/x`,
|
|
383
|
+
`$env:git_dir="${kit}/.git"; git worktree add .worktree/x`,
|
|
384
|
+
]) {
|
|
385
|
+
explicitDirReason(decide(powershell(ws.adopted, command)));
|
|
386
|
+
}
|
|
387
|
+
});
|
|
388
|
+
|
|
389
|
+
test("a worktree add with none of those settings still passes, and so does a mention without a worktree add", (t) => {
|
|
390
|
+
const ws = twoRepos(t);
|
|
391
|
+
const kit = ws.slash(ws.kit);
|
|
392
|
+
assert.equal(decide(bash(ws.adopted, "git worktree add .worktree/x")), null);
|
|
393
|
+
assert.equal(decide(bash(ws.adopted, `export GIT_DIR=${kit}/.git; git status`)), null);
|
|
394
|
+
assert.equal(decide(bash(ws.adopted, `git -c core.bare=true status`)), null);
|
|
395
|
+
assert.equal(decide(bash(ws.plain, `export GIT_DIR=${kit}/.git; git worktree add ../x`)), null, "a repository with no qc.config.json is not guarded");
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
/** The refusal for a path that holds an unexpanded variable: it says to write the path literally. */
|
|
399
|
+
const variableReason = (output) => {
|
|
400
|
+
const reason = reasonOf(output) ?? "";
|
|
401
|
+
assert.match(reason, /literally/, reason);
|
|
402
|
+
assert.match(reason, /variable/, reason);
|
|
403
|
+
return reason;
|
|
404
|
+
};
|
|
405
|
+
|
|
406
|
+
test("a worktree add after a -C, cd, or Set-Location path with an unexpanded variable is refused, and the reason says to write the path literally", (t) => {
|
|
407
|
+
const ws = twoRepos(t);
|
|
408
|
+
const kit = ws.slash(ws.kit);
|
|
409
|
+
for (const command of [
|
|
410
|
+
"git -C $K worktree add .worktree/x",
|
|
411
|
+
"git -C ${K} worktree add .worktree/x",
|
|
412
|
+
`git -C "$HOME/kit" worktree add .worktree/x`,
|
|
413
|
+
"cd $K && git worktree add .worktree/x",
|
|
414
|
+
"cd ${K}/sub && git worktree add .worktree/x",
|
|
415
|
+
"cd $(git rev-parse --show-toplevel) && git worktree add .worktree/x",
|
|
416
|
+
`bash -c 'cd $K && git worktree add .worktree/x'`,
|
|
417
|
+
"cd %K% && git worktree add .worktree/x",
|
|
418
|
+
`cd $K; cd sub; git worktree add .worktree/x`,
|
|
419
|
+
"cd `pwd` && git worktree add .worktree/x",
|
|
420
|
+
"cd $(pwd)/sub && git worktree add .worktree/x",
|
|
421
|
+
"pushd $(pwd) && git worktree add .worktree/x",
|
|
422
|
+
"git -C $(git rev-parse --show-toplevel) worktree add ../out",
|
|
423
|
+
"git -C `pwd` worktree add ../out",
|
|
424
|
+
]) {
|
|
425
|
+
variableReason(decide(bash(ws.adopted, command)));
|
|
426
|
+
}
|
|
427
|
+
for (const command of [
|
|
428
|
+
"Set-Location $env:K; git worktree add .worktree/x",
|
|
429
|
+
"Set-Location $K; git worktree add .worktree/x",
|
|
430
|
+
"git -C $env:K worktree add .worktree/x",
|
|
431
|
+
"cd %K%; git worktree add .worktree/x",
|
|
432
|
+
"Set-Location (Join-Path $K 'sub'); git worktree add .worktree/x",
|
|
433
|
+
"Push-Location ($env:K + '\\sub'); git worktree add .worktree/x",
|
|
434
|
+
"Set-Location -Path (Join-Path $K sub); git worktree add .worktree/x",
|
|
435
|
+
"Set-Location -LiteralPath (Get-Location); git worktree add .worktree/x",
|
|
436
|
+
"cd (Resolve-Path ..); git worktree add .worktree/x",
|
|
437
|
+
"Set-Location $(Join-Path $K sub); git worktree add .worktree/x",
|
|
438
|
+
"git -C (Join-Path $K 'x') worktree add ../out",
|
|
439
|
+
"git -C $(Get-Location) worktree add ../out",
|
|
440
|
+
]) {
|
|
441
|
+
variableReason(decide(powershell(ws.adopted, command)));
|
|
442
|
+
}
|
|
443
|
+
// A literal path after the variable names the repository again.
|
|
444
|
+
assert.equal(decide(bash(ws.adopted, `cd $K; cd ${kit} && git worktree add .worktree/x`)), null);
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
test("a variable in a path of a command that adds no worktree, or in the worktree path alone, is no refusal for it", (t) => {
|
|
448
|
+
const ws = twoRepos(t);
|
|
449
|
+
for (const command of ["cd $K && git status", "git -C $K worktree list", "cd $HOME && ls", "git worktree add .worktree/$NAME"]) {
|
|
450
|
+
assert.doesNotMatch(reasonOf(decide(bash(ws.adopted, command))) ?? "", /literally/, command);
|
|
451
|
+
}
|
|
452
|
+
const plain = ws.slash(ws.plain);
|
|
453
|
+
assert.equal(decide(bash(ws.plain, "cd $K && git worktree add ../x")), null, "a repository with no qc.config.json is not guarded");
|
|
454
|
+
assert.equal(decide(bash(ws.adopted, `git -C ${plain} worktree add ../x`)), null);
|
|
455
|
+
});
|
|
@@ -144,25 +144,28 @@ export async function report(call, projectRoot) {
|
|
|
144
144
|
const findings = [];
|
|
145
145
|
const isMainSession = !(typeof call.agent_id === "string" && call.agent_id !== "");
|
|
146
146
|
for (const root of checkoutsOf(cwd, command, dialect)) findings.push(...(await findingsIn(root, manifest, project, isMainSession)));
|
|
147
|
-
|
|
147
|
+
const unresolved = dialect.unresolvedGitDirs(command);
|
|
148
|
+
if (findings.length === 0 && unresolved.length === 0) return null;
|
|
148
149
|
|
|
149
150
|
const listed = findings.slice(0, MAX_LISTED).map((line) => `- ${line}`);
|
|
150
151
|
if (findings.length > MAX_LISTED) listed.push(`- and ${findings.length - MAX_LISTED} more`);
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
152
|
+
const lines = [];
|
|
153
|
+
if (findings.length > 0) {
|
|
154
|
+
lines.push("Bash edit guard: the checkout holds uncommitted changes that the swarm rules do not allow.", ...listed);
|
|
155
|
+
lines.push(
|
|
156
|
+
findings.some((line) => line.includes(CONTROLLER_RULE))
|
|
157
|
+
? "Dispatch an implementer for a change outside the controller paths. Revert a change only if you made it by mistake. The guard does not revert anything."
|
|
158
|
+
: "Revert a change only if your work order made it and should not have. " +
|
|
159
|
+
"For any other change, stop and tell the orchestrator. The guard does not revert anything.",
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
if (unresolved.length > 0) {
|
|
163
|
+
lines.push(
|
|
164
|
+
`Bash edit guard: the command names a git directory with no work tree (${unresolved.join(", ")}), ` +
|
|
165
|
+
"so the guard cannot tell which checkout it changed. Run `git status` in that repository.",
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
return { hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: lines.join("\n") } };
|
|
166
169
|
}
|
|
167
170
|
|
|
168
171
|
async function readStdin() {
|
|
@@ -136,3 +136,22 @@ test("porcelain output names each changed path, and both sides of a rename", ()
|
|
|
136
136
|
const status = [" M src/a.ts", "?? docs/new file.md", "R lib/new.ts", "lib/old.ts", ""].join("\u0000");
|
|
137
137
|
assert.deepEqual(changedPaths(status), ["src/a.ts", "docs/new file.md", "lib/new.ts", "lib/old.ts"]);
|
|
138
138
|
});
|
|
139
|
+
|
|
140
|
+
test("a --work-tree directory is a checkout the command could have changed", async (t) => {
|
|
141
|
+
const ws = workspace(t);
|
|
142
|
+
ws.put(ws.linked, "docs/b.md");
|
|
143
|
+
const slash = (dir) => dir.replaceAll("\\", "/");
|
|
144
|
+
const output = await report(bash(ws.outside, `git --work-tree=${slash(ws.linked)} checkout -- docs`), ws.linked);
|
|
145
|
+
assert.match(contextOf(output), /docs\/b\.md: outside the work order's declared paths/);
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
test("a git dir with no work tree is reported as unresolved, not dropped", async (t) => {
|
|
149
|
+
const ws = workspace(t);
|
|
150
|
+
const slash = (dir) => dir.replaceAll("\\", "/");
|
|
151
|
+
const text = contextOf(await report(bash(ws.outside, `git --git-dir=${slash(ws.primary)}/.git checkout main`), ws.linked));
|
|
152
|
+
assert.match(text, /git directory with no work tree/);
|
|
153
|
+
assert.ok(text.includes(`${slash(ws.primary)}/.git`), text);
|
|
154
|
+
assert.match(text, /cannot tell which checkout/);
|
|
155
|
+
const withTree = await report(bash(ws.outside, `git --git-dir=${slash(ws.primary)}/.git --work-tree=${slash(ws.outside)} checkout main`), ws.linked);
|
|
156
|
+
assert.doesNotMatch(contextOf(withTree), /git directory with no work tree/);
|
|
157
|
+
});
|
package/src/cli/ci-state.mjs
CHANGED
|
@@ -24,23 +24,31 @@ export function notGreenReason(runs) {
|
|
|
24
24
|
}
|
|
25
25
|
|
|
26
26
|
/**
|
|
27
|
-
*
|
|
28
|
-
* unknown: gh fails
|
|
27
|
+
* What CI says about `sha`: `reason` names a run that failed or still runs, as `CI on <short sha>: <why>`.
|
|
28
|
+
* `unknown` says why nothing is known: no sha, no `origin`, a gh that fails or times out, a reply that does not parse, or no check runs.
|
|
29
29
|
* `gh` and `origin` replace the real reads, for a test.
|
|
30
30
|
*/
|
|
31
|
-
export function
|
|
32
|
-
|
|
31
|
+
export function ciState(sha, cwd, { gh = runGh, origin = originOf } = {}) {
|
|
32
|
+
const unknown = (why) => ({ reason: null, unknown: why });
|
|
33
|
+
if (typeof sha !== "string" || sha === "") return unknown("there is no commit to ask about");
|
|
33
34
|
const repo = origin(cwd, ORIGIN_TIMEOUT_MS);
|
|
34
|
-
if (repo === null) return
|
|
35
|
+
if (repo === null) return unknown("the checkout has no readable origin");
|
|
35
36
|
const out = gh(["api", `repos/${repo}/commits/${sha}/check-runs?per_page=100`], { cwd, timeoutMs: GH_TIMEOUT_MS });
|
|
36
|
-
if (out === null) return
|
|
37
|
+
if (out === null) return unknown("gh failed or timed out");
|
|
37
38
|
let runs;
|
|
38
39
|
try {
|
|
39
40
|
runs = JSON.parse(out)?.check_runs;
|
|
40
41
|
} catch {
|
|
41
|
-
return
|
|
42
|
+
return unknown("gh answered with text that is not JSON");
|
|
42
43
|
}
|
|
43
|
-
if (!Array.isArray(runs)) return
|
|
44
|
+
if (!Array.isArray(runs)) return unknown("gh answered with no check_runs list");
|
|
45
|
+
if (runs.length === 0) return unknown(`${short(sha)} has no check runs`);
|
|
44
46
|
const why = notGreenReason(runs);
|
|
45
|
-
return why === null ? null : `CI on ${short(sha)}: ${why}
|
|
47
|
+
return { reason: why === null ? null : `CI on ${short(sha)}: ${why}`, unknown: null };
|
|
46
48
|
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @returns the reason CI on `sha` is not green, as `CI on <short sha>: <why>`, or null when it is green or
|
|
52
|
+
* unknown. `ciState` tells those two apart.
|
|
53
|
+
*/
|
|
54
|
+
export const ciNotGreen = (sha, cwd, deps) => ciState(sha, cwd, deps).reason;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { strict as assert } from "node:assert";
|
|
2
2
|
import { test } from "node:test";
|
|
3
|
-
import { ciNotGreen, notGreenReason } from "./ci-state.mjs";
|
|
3
|
+
import { ciNotGreen, ciState, notGreenReason } from "./ci-state.mjs";
|
|
4
4
|
|
|
5
5
|
const SHA = "a".repeat(40);
|
|
6
6
|
const run = (name, status, conclusion = null) => ({ name, status, conclusion });
|
|
@@ -60,3 +60,17 @@ test("ciNotGreen bounds its reads so the whole gate stays under the hook's 10 se
|
|
|
60
60
|
assert.ok(originTimeout > 0 && originTimeout <= 1000, `origin timeout ${originTimeout}`);
|
|
61
61
|
assert.ok(ghOptions.timeoutMs + originTimeout < 5000);
|
|
62
62
|
});
|
|
63
|
+
|
|
64
|
+
test("ciState separates a head that is not green, a green head, and a head it cannot read", () => {
|
|
65
|
+
const origin = () => "o/r";
|
|
66
|
+
const state = (gh, from = origin) => ciState(SHA, "/c", { gh, origin: from });
|
|
67
|
+
assert.deepEqual(state(() => reply(run("a", "completed", "success"))), { reason: null, unknown: null });
|
|
68
|
+
assert.match(state(() => reply(run("build", "in_progress"))).reason, /^CI on aaaaaaa: build is in_progress/);
|
|
69
|
+
assert.match(state(() => reply()).unknown, /no check runs/);
|
|
70
|
+
assert.match(state(() => null).unknown, /gh/);
|
|
71
|
+
assert.match(state(() => "not json").unknown, /gh/);
|
|
72
|
+
assert.match(state(() => "{}").unknown, /gh/);
|
|
73
|
+
assert.match(state(() => reply(), () => null).unknown, /origin/);
|
|
74
|
+
assert.match(ciState("", "/c", { gh: () => null, origin }).unknown, /no commit/);
|
|
75
|
+
for (const answer of [state(() => null), state(() => reply())]) assert.equal(answer.reason, null);
|
|
76
|
+
});
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The SubagentStop trigger that adds one cost record to the ledger: the tokens and tool calls of the agent,
|
|
3
|
+
// by role. It reads the transcript and never blocks. `qc ledger --cost` totals the records.
|
|
4
|
+
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import { checkoutRootOf } from "./checkout-root.mjs";
|
|
7
|
+
import { pathKey } from "./git-read.mjs";
|
|
8
|
+
import { appendRecord, readLedger } from "./ledger.mjs";
|
|
9
|
+
import { roleOf } from "./report-stop.mjs";
|
|
10
|
+
import { agentTranscriptOf, agentTypeOf, readRequests, toolCallsIn } from "./transcript-usage.mjs";
|
|
11
|
+
import { firstUserText, resolveNamedWorktree, workflowOfRepo } from "./workflow-place.mjs";
|
|
12
|
+
import { workflowOf } from "./workflow-settings.mjs";
|
|
13
|
+
import { fileURLToPath } from "node:url";
|
|
14
|
+
|
|
15
|
+
const ROLES = { implementer: "implementer", task: "reviewer", branch: "branch-reviewer" };
|
|
16
|
+
|
|
17
|
+
/** The role a cost record names: the review roles of the workflow, the planner, or other. */
|
|
18
|
+
function costRole(agentType, review) {
|
|
19
|
+
const role = roleOf(agentType, review);
|
|
20
|
+
if (role) return ROLES[role];
|
|
21
|
+
return review.plannerTypes.includes(agentType) ? "planner" : "other";
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const sum = (requests, key) => requests.reduce((total, { usage }) => total + (usage?.[key] ?? 0), 0);
|
|
25
|
+
|
|
26
|
+
/** The newest dispatch of this session and type that named the worktree, or null. */
|
|
27
|
+
const dispatchOf = (records, session, agentType, worktree) =>
|
|
28
|
+
worktree === null
|
|
29
|
+
? null
|
|
30
|
+
: (records.findLast(
|
|
31
|
+
(record) =>
|
|
32
|
+
record.type === "dispatch" &&
|
|
33
|
+
record.session === session &&
|
|
34
|
+
record.agentType === agentType &&
|
|
35
|
+
typeof record.worktree === "string" &&
|
|
36
|
+
pathKey(record.worktree) === pathKey(worktree),
|
|
37
|
+
) ?? null);
|
|
38
|
+
|
|
39
|
+
/** Writes the cost record of one SubagentStop. @returns null always: a cost record never blocks an agent. */
|
|
40
|
+
export function decide(call, tmp = os.tmpdir()) {
|
|
41
|
+
try {
|
|
42
|
+
record(call, tmp);
|
|
43
|
+
} catch {
|
|
44
|
+
// A failed read or write records nothing, and the agent still stops.
|
|
45
|
+
}
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function record(call, tmp) {
|
|
50
|
+
const agentId = call.agent_id;
|
|
51
|
+
if (call.hook_event_name !== "SubagentStop" || typeof agentId !== "string" || agentId === "") return;
|
|
52
|
+
const transcript = agentTranscriptOf(call);
|
|
53
|
+
if (transcript === null) return;
|
|
54
|
+
const requests = readRequests(transcript);
|
|
55
|
+
if (requests.length === 0) return;
|
|
56
|
+
const own = workflowOf(call, tmp);
|
|
57
|
+
if (!own) return;
|
|
58
|
+
// The worktree the prompt names decides the repository, and so the ledger, as it does for the report stop.
|
|
59
|
+
const text = firstUserText(transcript);
|
|
60
|
+
const place = text === null ? null : resolveNamedWorktree(text, call.cwd ?? process.cwd());
|
|
61
|
+
const root = place?.found ? checkoutRootOf(place.abs) : null;
|
|
62
|
+
const workflow = root ? (workflowOfRepo(root, own) ?? own) : own;
|
|
63
|
+
const session = call.session_id ?? "session";
|
|
64
|
+
const agentType = call.agent_type ?? agentTypeOf(transcript) ?? "unknown";
|
|
65
|
+
const dispatch = dispatchOf(readLedger(workflow.ledger), session, agentType, place?.found ? place.abs : null);
|
|
66
|
+
appendRecord(workflow.ledger, {
|
|
67
|
+
type: "cost",
|
|
68
|
+
session,
|
|
69
|
+
agentId,
|
|
70
|
+
agentType,
|
|
71
|
+
role: costRole(agentType, workflow.review),
|
|
72
|
+
model: requests.findLast((request) => request.model)?.model ?? null,
|
|
73
|
+
input: sum(requests, "input_tokens"),
|
|
74
|
+
output: sum(requests, "output_tokens"),
|
|
75
|
+
cacheRead: sum(requests, "cache_read_input_tokens"),
|
|
76
|
+
cacheCreation: sum(requests, "cache_creation_input_tokens"),
|
|
77
|
+
toolCalls: toolCallsIn(transcript),
|
|
78
|
+
branch: dispatch?.branch ?? null,
|
|
79
|
+
head: dispatch?.head ?? null,
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function readStdin() {
|
|
84
|
+
let data = "";
|
|
85
|
+
for await (const chunk of process.stdin) data += chunk;
|
|
86
|
+
return data;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const isEntryPoint = process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1];
|
|
90
|
+
if (isEntryPoint) {
|
|
91
|
+
let call = null;
|
|
92
|
+
try {
|
|
93
|
+
call = JSON.parse(await readStdin());
|
|
94
|
+
} catch {
|
|
95
|
+
// Not hook input, so there is no stop to record.
|
|
96
|
+
}
|
|
97
|
+
if (call) decide(call);
|
|
98
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { strict as assert } from "node:assert";
|
|
2
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
3
|
+
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { test } from "node:test";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { decide } from "./cost-stop.mjs";
|
|
9
|
+
import { appendRecord, readLedger } from "./ledger.mjs";
|
|
10
|
+
|
|
11
|
+
const HOOK = fileURLToPath(new URL("./cost-stop.mjs", import.meta.url));
|
|
12
|
+
const git = (cwd, ...args) => execFileSync("git", args, { cwd, stdio: "pipe", encoding: "utf8" }).trim();
|
|
13
|
+
|
|
14
|
+
/** A checkout with the workflow on (or off), and a folder for transcripts. */
|
|
15
|
+
function workspace(t, on = true) {
|
|
16
|
+
const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-cost-stop-")));
|
|
17
|
+
t.after(() => rmSync(base, { recursive: true, force: true }));
|
|
18
|
+
const repo = path.join(base, "repo");
|
|
19
|
+
git(base, "init", "-q", "-b", "main", repo);
|
|
20
|
+
for (const [key, value] of [["user.name", "qc"], ["user.email", "qc@example.com"], ["commit.gpgsign", "false"]]) git(repo, "config", key, value);
|
|
21
|
+
writeFileSync(path.join(repo, "a.txt"), "a\n");
|
|
22
|
+
git(repo, "add", ".");
|
|
23
|
+
git(repo, "commit", "-q", "-m", "init");
|
|
24
|
+
git(repo, "branch", "feat/1-x");
|
|
25
|
+
writeFileSync(path.join(repo, "qc.config.json"), JSON.stringify(on ? { swarm: { dispatch: {} } } : { swarm: {} }));
|
|
26
|
+
const tmp = path.join(base, "tmp");
|
|
27
|
+
mkdirSync(tmp);
|
|
28
|
+
return { base, repo, tmp, head: git(repo, "rev-parse", "HEAD"), ledger: path.join(repo, ".git", "qc", "ledger.jsonl") };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const usage = (input, output, read, write) => ({
|
|
32
|
+
input_tokens: input,
|
|
33
|
+
output_tokens: output,
|
|
34
|
+
cache_read_input_tokens: read,
|
|
35
|
+
cache_creation_input_tokens: write,
|
|
36
|
+
});
|
|
37
|
+
const assistant = (id, model, use, tools = []) =>
|
|
38
|
+
JSON.stringify({
|
|
39
|
+
type: "assistant",
|
|
40
|
+
timestamp: "2026-10-09T10:00:00.000Z",
|
|
41
|
+
message: { id, model, usage: use, content: tools.map((toolId) => ({ type: "tool_use", id: toolId, name: "Read", input: {} })) },
|
|
42
|
+
});
|
|
43
|
+
const prompt = (text) => JSON.stringify({ type: "user", message: { role: "user", content: text } });
|
|
44
|
+
|
|
45
|
+
/** A subagent transcript: the dispatch prompt, then two requests, one of them split over two lines of one message id. */
|
|
46
|
+
function transcript(ws, name, prompts) {
|
|
47
|
+
const file = path.join(ws.base, `${name}.jsonl`);
|
|
48
|
+
writeFileSync(
|
|
49
|
+
file,
|
|
50
|
+
[
|
|
51
|
+
prompt(prompts),
|
|
52
|
+
assistant("m1", "claude-sonnet-5-5", usage(10, 100, 1000, 200), ["t1"]),
|
|
53
|
+
assistant("m1", "claude-sonnet-5-5", usage(10, 100, 1000, 200), ["t2"]),
|
|
54
|
+
assistant("m2", "claude-sonnet-5-5", usage(5, 50, 3000, 0), ["t3", "t4"]),
|
|
55
|
+
].join("\n") + "\n",
|
|
56
|
+
);
|
|
57
|
+
return file;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const stop = (ws, file, agentType, extra = {}) => ({
|
|
61
|
+
hook_event_name: "SubagentStop",
|
|
62
|
+
session_id: "s",
|
|
63
|
+
cwd: ws.repo,
|
|
64
|
+
agent_id: "agent-1",
|
|
65
|
+
agent_type: agentType,
|
|
66
|
+
agent_transcript_path: file,
|
|
67
|
+
...extra,
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
const costs = (ws) => readLedger(ws.ledger).filter((record) => record.type === "cost");
|
|
71
|
+
|
|
72
|
+
test("a subagent stop records its tokens once per request, its tool calls, and the branch and head of its dispatch", (t) => {
|
|
73
|
+
const ws = workspace(t);
|
|
74
|
+
appendRecord(ws.ledger, { type: "dispatch", session: "s", agentType: "sdd-implementer", task: true, worktree: ws.repo, branch: "feat/1-x", head: ws.head });
|
|
75
|
+
const file = transcript(ws, "a", `Worktree: ${ws.repo}\nBuild it.`);
|
|
76
|
+
assert.equal(decide(stop(ws, file, "sdd-implementer"), ws.tmp), null);
|
|
77
|
+
const [record] = costs(ws);
|
|
78
|
+
assert.deepEqual(
|
|
79
|
+
{ ...record, at: undefined },
|
|
80
|
+
{
|
|
81
|
+
type: "cost",
|
|
82
|
+
at: undefined,
|
|
83
|
+
session: "s",
|
|
84
|
+
agentId: "agent-1",
|
|
85
|
+
agentType: "sdd-implementer",
|
|
86
|
+
role: "implementer",
|
|
87
|
+
model: "claude-sonnet-5-5",
|
|
88
|
+
input: 15,
|
|
89
|
+
output: 150,
|
|
90
|
+
cacheRead: 4000,
|
|
91
|
+
cacheCreation: 200,
|
|
92
|
+
toolCalls: 4,
|
|
93
|
+
branch: "feat/1-x",
|
|
94
|
+
head: ws.head,
|
|
95
|
+
},
|
|
96
|
+
);
|
|
97
|
+
assert.equal(typeof record.at, "string");
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
test("each agent type maps to its role, and a type the workflow does not know is other", (t) => {
|
|
101
|
+
const ws = workspace(t);
|
|
102
|
+
const file = transcript(ws, "a", "No worktree named.");
|
|
103
|
+
for (const [agentType, role] of [
|
|
104
|
+
["sdd-implementer", "implementer"],
|
|
105
|
+
["sdd-reviewer", "reviewer"],
|
|
106
|
+
["sdd-branch-reviewer", "branch-reviewer"],
|
|
107
|
+
["sdd-planner", "planner"],
|
|
108
|
+
["Explore", "other"],
|
|
109
|
+
]) {
|
|
110
|
+
decide(stop(ws, file, agentType, { agent_id: `id-${agentType}` }), ws.tmp);
|
|
111
|
+
}
|
|
112
|
+
assert.deepEqual(
|
|
113
|
+
costs(ws).map((record) => [record.agentType, record.role]),
|
|
114
|
+
[["sdd-implementer", "implementer"], ["sdd-reviewer", "reviewer"], ["sdd-branch-reviewer", "branch-reviewer"], ["sdd-planner", "planner"], ["Explore", "other"]],
|
|
115
|
+
);
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
test("a stop with no matching dispatch records a null branch and head", (t) => {
|
|
119
|
+
const ws = workspace(t);
|
|
120
|
+
appendRecord(ws.ledger, { type: "dispatch", session: "other", agentType: "sdd-implementer", task: true, worktree: ws.repo, branch: "feat/9-z", head: ws.head });
|
|
121
|
+
const file = transcript(ws, "a", `Worktree: ${ws.repo}\nBuild it.`);
|
|
122
|
+
decide(stop(ws, file, "sdd-implementer"), ws.tmp);
|
|
123
|
+
assert.deepEqual([costs(ws)[0].branch, costs(ws)[0].head], [null, null]);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
test("nothing is recorded while swarm.dispatch is off, or when the transcript does not read", (t) => {
|
|
127
|
+
const off = workspace(t, false);
|
|
128
|
+
assert.equal(decide(stop(off, transcript(off, "a", "x"), "sdd-implementer"), off.tmp), null);
|
|
129
|
+
assert.deepEqual(costs(off), []);
|
|
130
|
+
const on = workspace(t);
|
|
131
|
+
assert.equal(decide(stop(on, path.join(on.base, "missing.jsonl"), "sdd-implementer"), on.tmp), null);
|
|
132
|
+
writeFileSync(path.join(on.base, "empty.jsonl"), "");
|
|
133
|
+
assert.equal(decide(stop(on, path.join(on.base, "empty.jsonl"), "sdd-implementer"), on.tmp), null);
|
|
134
|
+
assert.deepEqual(costs(on), []);
|
|
135
|
+
assert.equal(decide({ hook_event_name: "SubagentStop", session_id: "s", cwd: on.repo, agent_type: "x" }, on.tmp), null, "the main session has no agent id");
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
test("the hook script writes the record and prints nothing", (t) => {
|
|
139
|
+
const ws = workspace(t);
|
|
140
|
+
const file = transcript(ws, "a", "No worktree named.");
|
|
141
|
+
const result = spawnSync(process.execPath, [HOOK], {
|
|
142
|
+
input: JSON.stringify(stop(ws, file, "sdd-implementer")),
|
|
143
|
+
env: { ...process.env, TEMP: ws.tmp, TMP: ws.tmp, TMPDIR: ws.tmp },
|
|
144
|
+
encoding: "utf8",
|
|
145
|
+
});
|
|
146
|
+
assert.equal(result.status, 0, result.stderr);
|
|
147
|
+
assert.equal(result.stdout, "");
|
|
148
|
+
assert.equal(costs(ws).length, 1);
|
|
149
|
+
});
|
|
@@ -27,8 +27,8 @@ function onSubagent(call, dir, now) {
|
|
|
27
27
|
}
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
-
/** The verdict on one hook event. @returns the hook output, or null to let the call run with no message. */
|
|
31
|
-
export function decide(call, tmp = os.tmpdir(), now = Date.now()) {
|
|
30
|
+
/** The verdict on one hook event. `reads` replaces the task gate's CI and base reads, for a test. @returns the hook output, or null to let the call run with no message. */
|
|
31
|
+
export function decide(call, tmp = os.tmpdir(), now = Date.now(), reads = {}) {
|
|
32
32
|
const dir = slotDirOf(call.session_id ?? "session", tmp);
|
|
33
33
|
if (call.hook_event_name === "SubagentStart" || call.hook_event_name === "SubagentStop") {
|
|
34
34
|
onSubagent(call, dir, now);
|
|
@@ -51,7 +51,7 @@ export function decide(call, tmp = os.tmpdir(), now = Date.now()) {
|
|
|
51
51
|
const refusal = dispatchRefusal(input, settings);
|
|
52
52
|
if (refusal) return deny(refusal);
|
|
53
53
|
// The task gate judges before the slot is claimed, so a refused task holds no slot.
|
|
54
|
-
const task = judgeTask(call, tmp);
|
|
54
|
+
const task = judgeTask(call, tmp, reads);
|
|
55
55
|
if (task.refusal) return deny(task.refusal);
|
|
56
56
|
const note = dispatchNote(input, settings);
|
|
57
57
|
const type = typeOf(input);
|