architecture-harness 0.20.2 → 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.
Files changed (41) hide show
  1. package/package.json +1 -1
  2. package/src/cli/bash-command-guard.mjs +70 -11
  3. package/src/cli/bash-command-guard.test.mjs +219 -0
  4. package/src/cli/bash-edit-guard.mjs +19 -16
  5. package/src/cli/bash-edit-guard.test.mjs +19 -0
  6. package/src/cli/ci-state.mjs +54 -0
  7. package/src/cli/ci-state.test.mjs +76 -0
  8. package/src/cli/cost-stop.mjs +98 -0
  9. package/src/cli/cost-stop.test.mjs +149 -0
  10. package/src/cli/dispatch-guard.mjs +3 -3
  11. package/src/cli/dispatch-guard.test.mjs +14 -6
  12. package/src/cli/dispatch-reminder.mjs +7 -3
  13. package/src/cli/dispatch-reminder.test.mjs +16 -1
  14. package/src/cli/git-read.mjs +41 -3
  15. package/src/cli/git-read.test.mjs +31 -1
  16. package/src/cli/ledger.mjs +52 -3
  17. package/src/cli/ledger.test.mjs +60 -0
  18. package/src/cli/merge-guard.mjs +1 -14
  19. package/src/cli/plugin-agents.test.mjs +11 -0
  20. package/src/cli/powershell-command.mjs +8 -13
  21. package/src/cli/powershell-command.test.mjs +12 -1
  22. package/src/cli/qc.mjs +1 -1
  23. package/src/cli/report-stop.test.mjs +2 -1
  24. package/src/cli/review-gate.mjs +224 -0
  25. package/src/cli/review-gate.test.mjs +334 -0
  26. package/src/cli/shell-command.mjs +77 -13
  27. package/src/cli/shell-command.test.mjs +44 -3
  28. package/src/cli/skill-guard.mjs +56 -0
  29. package/src/cli/skill-guard.test.mjs +87 -0
  30. package/src/cli/stop-gate.test.mjs +80 -0
  31. package/src/cli/task-gate-review.test.mjs +225 -0
  32. package/src/cli/task-gate.mjs +54 -16
  33. package/src/cli/task-gate.test.mjs +65 -6
  34. package/src/cli/test-brief.mjs +12 -0
  35. package/src/cli/transcript-usage.mjs +28 -0
  36. package/src/cli/transcript-usage.test.mjs +9 -0
  37. package/src/cli/workflow-hooks.test.mjs +38 -0
  38. package/src/cli/workflow-settings.mjs +14 -3
  39. package/src/cli/workflow-settings.test.mjs +24 -0
  40. package/src/config.mjs +13 -0
  41. package/templates/docs/enforcement.md +12 -1
@@ -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);
@@ -14,7 +14,7 @@ const HOOKS = fileURLToPath(new URL("../../../../hooks/hooks.json", import.meta.
14
14
  // The guard process below runs under Codex, whatever runtime runs the test.
15
15
  process.env.QC_RUNTIME = "codex";
16
16
 
17
- function workspace(t, dispatch = { maxPromptChars: 80 }) {
17
+ function workspace(t, dispatch = { maxPromptChars: 300 }) {
18
18
  const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-dispatch-")));
19
19
  t.after(() => rmSync(base, { recursive: true, force: true }));
20
20
  const on = path.join(base, "on");
@@ -28,6 +28,9 @@ function workspace(t, dispatch = { maxPromptChars: 80 }) {
28
28
  mkdirSync(tmp);
29
29
  mkdirSync(path.join(on, "src"));
30
30
  writeFileSync(path.join(on, "qc.config.json"), JSON.stringify({ swarm: { dispatch } }));
31
+ writeFileSync(path.join(on, "brief.md"), "## Product decisions\n\nNone.\n");
32
+ const identity = ["-c", "user.name=qc", "-c", "user.email=qc@example.com", "-c", "commit.gpgsign=false"];
33
+ execFileSync("git", [...identity, "commit", "-q", "--allow-empty", "-m", "init"], { cwd: on, stdio: "pipe" });
31
34
  writeFileSync(path.join(off, "qc.config.json"), JSON.stringify({ swarm: { toolCallBudget: 50 } }));
32
35
  return { on, off, plain, tmp, slots: path.join(tmp, "architecture-kit", "dispatch") };
33
36
  }
@@ -52,8 +55,10 @@ const reasonOf = (output) =>
52
55
  const implementer = {
53
56
  subagent_type: "architecture:sdd-implementer",
54
57
  description: "Task 1",
55
- prompt: "Read the brief at plans/task-1-brief.md.",
58
+ prompt: "Brief: brief.md",
56
59
  };
60
+ /** A reviewer prompt that names the checkout, so the task gate can read its branch and head. */
61
+ const reviewerOf = (ws, subagent_type) => ({ subagent_type, prompt: `Worktree: ${ws.on}` });
57
62
 
58
63
  test("a checkout with no config, or a swarm section with no dispatch key, sees no change", (t) => {
59
64
  const ws = workspace(t);
@@ -87,8 +92,8 @@ test("the config of the checkout that holds the cwd decides", (t) => {
87
92
 
88
93
  test("a prompt over the limit is refused, and the refusal claims no slot", (t) => {
89
94
  const ws = workspace(t);
90
- const long = { ...implementer, prompt: "x".repeat(81) };
91
- assert.match(reasonOf(decide(agentCall(ws.on, long), ws.tmp)) ?? "", /81 characters/);
95
+ const long = { ...implementer, prompt: "x".repeat(301) };
96
+ assert.match(reasonOf(decide(agentCall(ws.on, long), ws.tmp)) ?? "", /301 characters/);
92
97
  assert.equal(existsSync(ws.slots), false);
93
98
  assert.equal(decide(agentCall(ws.on, implementer), ws.tmp), null);
94
99
  });
@@ -116,7 +121,7 @@ test("a stop in a worktree with no config still frees the slot", (t) => {
116
121
  test("a planner and a reviewer run beside an implementer", (t) => {
117
122
  const ws = workspace(t);
118
123
  decide(agentCall(ws.on, implementer), ws.tmp);
119
- assert.equal(decide(agentCall(ws.on, { subagent_type: "architecture:sdd-reviewer", prompt: "p" }), ws.tmp), null);
124
+ assert.equal(reasonOf(decide(agentCall(ws.on, reviewerOf(ws, "architecture:sdd-reviewer")), ws.tmp)), null);
120
125
  assert.equal(decide(agentCall(ws.on, { subagent_type: "architecture:sdd-planner", prompt: "p" }), ws.tmp), null);
121
126
  });
122
127
 
@@ -131,7 +136,10 @@ test("the tier guard refuses a type on the wrong family, naming the type, the mo
131
136
  test("every shipped role accepts GPT 6.1 Sol without a cache note", (t) => {
132
137
  const ws = workspace(t);
133
138
  for (const subagent_type of ["architecture:sdd-planner", "architecture:sdd-branch-reviewer", "architecture:sdd-reviewer", "architecture:sdd-implementer"]) {
134
- assert.equal(decide(agentCall(ws.on, { subagent_type, model: "gpt-6.1-sol", prompt: "p" }), ws.tmp), null, subagent_type);
139
+ const prompt = subagent_type.endsWith("reviewer") ? reviewerOf(ws, subagent_type).prompt : implementer.prompt;
140
+ const output = decide(agentCall(ws.on, { subagent_type, model: "gpt-6.1-sol", prompt }), ws.tmp);
141
+ assert.equal(reasonOf(output), null, subagent_type);
142
+ assert.doesNotMatch(output?.hookSpecificOutput?.additionalContext ?? "", /cache/i, subagent_type);
135
143
  }
136
144
  assert.equal(decide(agentCall(ws.on, { model: "gpt-6.1-sol", prompt: "p" }), ws.tmp), null);
137
145
  });
@@ -11,9 +11,13 @@ export const REMINDER =
11
11
  "Dispatch architecture:sdd-planner to write a plan, architecture:sdd-implementer for one task, and " +
12
12
  "architecture:sdd-reviewer to review it; before merge, dispatch architecture:sdd-branch-reviewer to review the " +
13
13
  "whole branch. " +
14
- "Run one implementer at a time: a hook refuses a second while one runs. Name a model on any other dispatch, and " +
15
- "pass each brief as a file path. Name the worktree on a prompt line `Worktree: <path>`. A reviewer starts with " +
16
- "`VERDICT: <APPROVED|CHANGES_REQUIRED> <sha>`, and a merge passes `--match-head-commit <sha>`.";
14
+ "Run one implementer at a time: a hook refuses a second. Name a model on any other dispatch, and " +
15
+ "write each brief to a file and name its path on a prompt line `Brief: <path>`; a dispatch with no such line, or a missing file, is refused. " +
16
+ "Name the worktree on a prompt line `Worktree: <path>`; a reviewer whose worktree, branch, or head the gate cannot read is refused. A reviewer starts with " +
17
+ "`VERDICT: <APPROVED|CHANGES_REQUIRED> <sha>`, and a merge passes `--match-head-commit <sha>`. " +
18
+ "Ask the user the product questions first, in one question, and record the answers under `## Product decisions` in each brief. " +
19
+ "Review a head only once CI on it is green, with the base merged in: fix a CI failure first, and merge `origin/<base>` at Step 0 of a fix round. " +
20
+ "A PR gets one branch review. After it, review each fix round once, by its increment: add `Reviewed: <sha>`, the last head a branch review named.";
17
21
 
18
22
  const ROLES = ["sdd-planner", "sdd-implementer", "sdd-reviewer", "sdd-branch-reviewer"];
19
23
 
@@ -60,7 +60,22 @@ test("the note names the workflow, the four types, and the one-implementer rule,
60
60
  ]) {
61
61
  assert.ok(REMINDER.includes(word), word);
62
62
  }
63
- assert.ok(REMINDER.length < 800, `${REMINDER.length} characters`);
63
+ assert.ok(REMINDER.length < 1300, `${REMINDER.length} characters`);
64
+ });
65
+
66
+ test("the note says to review a green head only, to fix CI first, and to review a fix round by its increment", () => {
67
+ for (const phrase of [
68
+ /only once CI on it is green/,
69
+ /fix a CI failure first/,
70
+ /`Reviewed: <sha>`/,
71
+ /review each fix round once, by its increment/,
72
+ /product questions first, in one question/,
73
+ /`## Product decisions`/,
74
+ /merge `origin\/<base>` at Step 0 of a fix round/,
75
+ /A PR gets one branch review/,
76
+ ]) {
77
+ assert.match(REMINDER, phrase);
78
+ }
64
79
  });
65
80
 
66
81
  test("with swarm.explore also on, the note names its tools", (t) => {
@@ -6,6 +6,7 @@ import { spawnSync } from "node:child_process";
6
6
  export { keyOf as pathKey } from "./worktree.mjs";
7
7
 
8
8
  const GIT_TIMEOUT_MS = 10_000;
9
+ const ORIGIN_TIMEOUT_MS = 5_000;
9
10
 
10
11
  /** @returns git's trimmed stdout, or null on a non-zero exit or after `timeoutMs`. */
11
12
  export function gitOutWithin(timeoutMs, cwd, ...args) {
@@ -13,9 +14,46 @@ export function gitOutWithin(timeoutMs, cwd, ...args) {
13
14
  return result.status === 0 ? (result.stdout ?? "").trim() : null;
14
15
  }
15
16
 
17
+ /**
18
+ * Runs git and keeps its exit status, for a read where a non-zero exit is an answer.
19
+ * @returns `{ status, stdout }`, or `{ error }` when git does not run or passes `timeoutMs`.
20
+ */
21
+ export function gitStatusWithin(timeoutMs, cwd, ...args) {
22
+ const env = { ...process.env, GIT_TERMINAL_PROMPT: "0" };
23
+ const result = spawnSync("git", args, { cwd, encoding: "utf8", windowsHide: true, timeout: timeoutMs, env });
24
+ if (result.error) return { error: result.error.code === "ETIMEDOUT" ? `git timed out after ${timeoutMs} ms` : result.error.message };
25
+ if (result.signal) return { error: `git ended on ${result.signal}` };
26
+ return { status: result.status, stdout: (result.stdout ?? "").trim() };
27
+ }
28
+
29
+ /** @returns true when `ancestor` is in the history of `descendant`, false when it is not, null when git cannot say. */
30
+ export function isAncestor(cwd, ancestor, descendant, timeoutMs = GIT_TIMEOUT_MS) {
31
+ const { status } = gitStatusWithin(timeoutMs, cwd, "merge-base", "--is-ancestor", ancestor, descendant);
32
+ return status === 0 ? true : status === 1 ? false : null;
33
+ }
34
+
35
+ /** @returns the sha that `branch` names on `remote`, or null when the remote does not answer in `timeoutMs` or lacks the branch. */
36
+ export function remoteTip(cwd, remote, branch, timeoutMs = ORIGIN_TIMEOUT_MS) {
37
+ const { status, stdout } = gitStatusWithin(timeoutMs, cwd, "ls-remote", remote, `refs/heads/${branch}`);
38
+ if (status !== 0) return null;
39
+ return /^([0-9a-f]{40,64})\s/i.exec(stdout.split(/\r?\n/)[0] ?? "")?.[1] ?? null;
40
+ }
41
+
16
42
  /** @returns git's trimmed stdout, or null on a non-zero exit or a timeout. */
17
43
  export const gitOut = (cwd, ...args) => gitOutWithin(GIT_TIMEOUT_MS, cwd, ...args);
18
44
 
45
+ /** `owner/repo` from a git remote URL in the https, ssh, or scp spelling, or from gh's `[HOST/]OWNER/REPO`; lower case. */
46
+ export function repoOfSpelling(spelled) {
47
+ const parts = String(spelled).trim().replace(/\/+$/, "").replace(/\.git$/i, "").split(/[/:]/).filter(Boolean);
48
+ return parts.length >= 2 ? parts.slice(-2).join("/").toLowerCase() : null;
49
+ }
50
+
51
+ /** The repository of the checkout's `origin` remote, or null when git cannot say or `timeoutMs` passes. */
52
+ export const originOf = (root, timeoutMs = ORIGIN_TIMEOUT_MS) => {
53
+ const url = gitOutWithin(timeoutMs, root, "remote", "get-url", "origin");
54
+ return url === null ? null : repoOfSpelling(url);
55
+ };
56
+
19
57
  /** @returns the full sha that `ref` names as a commit, or null when the repository holds none. */
20
58
  export const commitOf = (cwd, ref) => gitOut(cwd, "rev-parse", "--verify", "--quiet", `${ref}^{commit}`);
21
59
 
@@ -26,9 +64,9 @@ export const branchAt = (dir) => gitOut(dir, "branch", "--show-current") || null
26
64
  export const branchesAt = (cwd, sha, read = gitOut) =>
27
65
  (read(cwd, "for-each-ref", "--points-at", sha, "--format=%(refname:short)", "refs/heads") ?? "").split(/\r?\n/).filter(Boolean);
28
66
 
29
- /** @returns each linked worktree of the repository at `root`, with its branch and head; the primary checkout is left out. */
30
- export function linkedWorktrees(root) {
31
- const out = gitOut(root, "worktree", "list", "--porcelain");
67
+ /** @returns each linked worktree of the repository at `root`, with its branch and head; the primary checkout is left out. A read that fails or passes `timeoutMs` finds none. */
68
+ export function linkedWorktrees(root, timeoutMs = GIT_TIMEOUT_MS) {
69
+ const out = gitOutWithin(timeoutMs, root, "worktree", "list", "--porcelain");
32
70
  if (out === null) return [];
33
71
  return out
34
72
  .split(/\r?\n[ \t]*\r?\n/)
@@ -4,7 +4,7 @@ import { mkdtempSync, 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
- import { branchAt, branchesAt, commitOf, gitOut, gitOutWithin, linkedWorktrees, pathKey } from "./git-read.mjs";
7
+ import { branchAt, branchesAt, commitOf, gitOut, gitOutWithin, gitStatusWithin, isAncestor, linkedWorktrees, pathKey, remoteTip } from "./git-read.mjs";
8
8
 
9
9
  const git = (cwd, ...args) => execFileSync("git", args, { cwd, stdio: "pipe", encoding: "utf8" }).trim();
10
10
 
@@ -92,3 +92,33 @@ test("a git call that outlives its timeout answers null", (t) => {
92
92
  assert.ok(Date.now() - started < 2500);
93
93
  assert.equal(gitOutWithin(10_000, main, "rev-parse", "--is-inside-work-tree"), "true");
94
94
  });
95
+
96
+ test("gitStatusWithin tells an exit status from a failed read", (t) => {
97
+ const { main, head } = repo(t);
98
+ assert.deepEqual(gitStatusWithin(5000, main, "rev-parse", "HEAD"), { status: 0, stdout: head });
99
+ assert.equal(gitStatusWithin(5000, main, "rev-parse", "--verify", "--quiet", "nope^{commit}").status, 1);
100
+ const slow = ["-c", 'alias.slow=!node -e "setTimeout(() => {}, 3000)"', "slow"];
101
+ assert.equal(typeof gitStatusWithin(200, main, ...slow).error, "string");
102
+ });
103
+
104
+ test("isAncestor answers true, false, or null for a failed read", (t) => {
105
+ const { main, linked, head } = repo(t);
106
+ writeFileSync(path.join(linked, "b.txt"), "b\n");
107
+ git(linked, "add", ".");
108
+ git(linked, "commit", "-q", "-m", "b");
109
+ const moved = git(linked, "rev-parse", "HEAD");
110
+ assert.equal(isAncestor(main, head, moved), true);
111
+ assert.equal(isAncestor(main, moved, head), false);
112
+ assert.equal(isAncestor(main, "0".repeat(40), moved), null);
113
+ });
114
+
115
+ test("remoteTip reads a branch tip from origin, and answers null when the remote or the branch is missing", (t) => {
116
+ const { main, head } = repo(t);
117
+ assert.equal(remoteTip(main, "origin", "main"), null);
118
+ const bare = path.join(path.dirname(main), "origin.git");
119
+ git(path.dirname(main), "init", "-q", "--bare", bare);
120
+ git(main, "remote", "add", "origin", bare);
121
+ git(main, "push", "-q", "origin", "main");
122
+ assert.equal(remoteTip(main, "origin", "main"), head);
123
+ assert.equal(remoteTip(main, "origin", "gone"), null);
124
+ });
@@ -5,7 +5,7 @@ import { appendFileSync, closeSync, mkdirSync, openSync, readFileSync, readSync,
5
5
  import path from "node:path";
6
6
  import { checkoutRootOf } from "./checkout-root.mjs";
7
7
 
8
- export const RECORD_TYPES = ["dispatch", "stop", "verdict", "merge", "issue-update"];
8
+ export const RECORD_TYPES = ["dispatch", "stop", "verdict", "merge", "issue-update", "cost"];
9
9
  const MIN_SHA = 7;
10
10
  const HEX = /^[0-9a-f]+$/;
11
11
 
@@ -108,6 +108,8 @@ const short = (sha) => (typeof sha === "string" ? sha.slice(0, MIN_SHA) : "");
108
108
  const SUMMARIES = {
109
109
  dispatch: (r) =>
110
110
  `${r.agentType} ${r.task ? `${r.branch} ${short(r.head)}` : "(no task)"}${r.resumeReason ? ` NO-RESUME: ${r.resumeReason}` : ""}${
111
+ r.ciPass ? ` CI-PASS: ${short(r.ciPass.sha)} ${r.ciPass.reason}` : ""
112
+ }${
111
113
  r.handoff ? ` HANDOFF: ${r.handoff}` : ""
112
114
  }`,
113
115
  stop: (r) => `${r.role} ${r.agentType} ${r.agentId}${r.plan ? ` ${r.plan}` : ""}${r.handoff ? ` HANDOFF: ${r.handoff}` : ""}`,
@@ -117,14 +119,55 @@ const SUMMARIES = {
117
119
  (r.issues ?? []).map((issue) => `${issue.repo}#${issue.number}`).join(" ") || "no issue"
118
120
  }`,
119
121
  "issue-update": (r) => `${r.repo}#${r.number} ${r.how} after ${r.prRepo}#${r.pr}`,
122
+ cost: (r) =>
123
+ `${r.role} ${r.agentType} ${r.agentId} ${r.branch ?? "(no branch)"} in ${r.input} out ${r.output} cache-read ${r.cacheRead} cache-write ${r.cacheCreation} tools ${r.toolCalls}`,
120
124
  };
121
125
 
122
126
  /** One line of `qc ledger`: the time, the type, and the fields that say what happened. */
123
127
  export const formatRecord = (record) =>
124
128
  `${record.at} ${record.type.padEnd(12)} ${SUMMARIES[record.type](record).replace(/\s+/g, " ").trim()}`;
125
129
 
126
- /** `qc ledger [branch]`: every record, or those that name the branch. @returns the exit code */
127
- export function runLedger(config, [branch] = []) {
130
+ const COST_KEYS = ["input", "output", "cacheRead", "cacheCreation", "toolCalls"];
131
+ const emptyTotal = () => ({ agents: 0, input: 0, output: 0, cacheRead: 0, cacheCreation: 0, toolCalls: 0 });
132
+
133
+ /** The cost records, one per agent: a resumed agent stops again with its whole transcript, so its newest record replaces the older. */
134
+ function latestCosts(records) {
135
+ const latest = new Map();
136
+ for (const record of records) if (record.type === "cost") latest.set(`${record.session}/${record.agentId}`, record);
137
+ return [...latest.values()];
138
+ }
139
+
140
+ /** The token and tool-call totals of the cost records, per branch and per role. @returns the lines to print */
141
+ export function costReport(records) {
142
+ const costs = latestCosts(records);
143
+ if (costs.length === 0) return [];
144
+ const total = emptyTotal();
145
+ const groups = new Map();
146
+ const group = (key) => {
147
+ if (!groups.has(key)) groups.set(key, emptyTotal());
148
+ return groups.get(key);
149
+ };
150
+ for (const record of costs) {
151
+ const branch = record.branch ?? "(no branch)";
152
+ for (const target of [total, group(branch), group(`${branch}\u0000${record.role}`)]) {
153
+ target.agents += 1;
154
+ for (const key of COST_KEYS) target[key] += record[key] ?? 0;
155
+ }
156
+ }
157
+ const line = (label, t) =>
158
+ `${label.padEnd(34)} agents ${t.agents} in ${t.input} out ${t.output} cache-read ${t.cacheRead} cache-write ${t.cacheCreation} tools ${t.toolCalls}`;
159
+ const lines = [...groups.keys()].sort().map((key) => {
160
+ const [branch, role] = key.split("\u0000");
161
+ return line(role === undefined ? branch : ` ${role}`, groups.get(key));
162
+ });
163
+ lines.push(line("total", total));
164
+ return lines;
165
+ }
166
+
167
+ /** `qc ledger [--cost] [branch]`: every record, or those that name the branch, or the cost totals. @returns the exit code */
168
+ export function runLedger(config, args = []) {
169
+ const cost = args.includes("--cost");
170
+ const [branch] = args.filter((arg) => arg !== "--cost");
128
171
  const root = checkoutRootOf(config.root ?? process.cwd());
129
172
  const file = root ? ledgerFileOf(root) : null;
130
173
  if (!file) {
@@ -132,6 +175,12 @@ export function runLedger(config, [branch] = []) {
132
175
  return 1;
133
176
  }
134
177
  const records = readLedger(file).filter((record) => branch === undefined || record.branch === branch);
178
+ if (cost) {
179
+ const lines = costReport(records);
180
+ for (const line of lines) console.log(line);
181
+ if (lines.length === 0) console.log(branch ? `No cost record in ${file} names ${branch}.` : `The ledger at ${file} holds no cost record.`);
182
+ return 0;
183
+ }
135
184
  for (const record of records) console.log(formatRecord(record));
136
185
  if (records.length === 0) console.log(branch ? `No record in ${file} names ${branch}.` : `The ledger at ${file} is empty.`);
137
186
  return 0;
@@ -8,6 +8,7 @@ import { fileURLToPath } from "node:url";
8
8
  import {
9
9
  appendRecord,
10
10
  commonDirOf,
11
+ formatRecord,
11
12
  lastTaskDispatchOn,
12
13
  latestVerdictFor,
13
14
  latestVerdictOn,
@@ -125,3 +126,62 @@ test("an append after a torn last line keeps the new record whole", (t) => {
125
126
  appendRecord(file, { type: "stop", role: "task" });
126
127
  assert.equal(readLedger(file).length, 3, "a file that ends in a newline gets no blank line");
127
128
  });
129
+
130
+ test("a dispatch that passed on a CI failure shows the sha and the reason in the ledger line", () => {
131
+ const line = formatRecord({
132
+ at: "t",
133
+ type: "dispatch",
134
+ agentType: "sdd-implementer",
135
+ task: true,
136
+ branch: "feat/1-x",
137
+ head: "abcdef1234",
138
+ ciPass: { sha: "1234567890abcdef", reason: "CI on 1234567: build ended failure" },
139
+ });
140
+ assert.match(line, /CI-PASS: 1234567 CI on 1234567: build ended failure/);
141
+ });
142
+
143
+ const cost = (agentId, role, branch, input, output, toolCalls, extra = {}) => ({
144
+ type: "cost",
145
+ session: "s",
146
+ agentId,
147
+ agentType: `sdd-${role}`,
148
+ role,
149
+ model: "m",
150
+ input,
151
+ output,
152
+ cacheRead: input * 10,
153
+ cacheCreation: input,
154
+ toolCalls,
155
+ branch,
156
+ head: null,
157
+ ...extra,
158
+ });
159
+
160
+ test("qc ledger --cost totals tokens and tool calls per branch and per role, with a grand total", (t) => {
161
+ const { main } = repo(t);
162
+ const file = ledgerFileOf(main);
163
+ appendRecord(file, cost("a1", "implementer", "feat/1-x", 10, 100, 5));
164
+ appendRecord(file, cost("a2", "implementer", "feat/1-x", 20, 200, 7));
165
+ appendRecord(file, cost("a3", "reviewer", "feat/1-x", 1, 2, 3));
166
+ appendRecord(file, cost("a4", "planner", null, 4, 5, 6));
167
+ // A resumed agent stops again with its whole transcript, so only its newest record counts.
168
+ appendRecord(file, cost("a1", "implementer", "feat/1-x", 15, 150, 9));
169
+ const all = spawnSync(process.execPath, [QC, "ledger", "--cost"], { cwd: main, encoding: "utf8" });
170
+ assert.equal(all.status, 0, all.stderr);
171
+ const lines = all.stdout.trim().split(/\r?\n/);
172
+ assert.match(lines.find((line) => /^feat\/1-x/.test(line)), /agents 3 {2}in 36 {2}out 352 {2}cache-read 360 {2}cache-write 36 {2}tools 19/);
173
+ assert.match(lines.find((line) => /^\s+implementer/.test(line)), /agents 2 {2}in 35 {2}out 350/);
174
+ assert.match(lines.find((line) => /^\s+reviewer/.test(line)), /agents 1 {2}in 1 /);
175
+ assert.match(lines.find((line) => /^\(no branch\)/.test(line)), /agents 1 {2}in 4 /);
176
+ assert.match(lines.at(-1), /^total .*agents 4 {2}in 40 {2}out 357 .*tools 25/);
177
+ const one = spawnSync(process.execPath, [QC, "ledger", "--cost", "feat/1-x"], { cwd: main, encoding: "utf8" });
178
+ assert.match(one.stdout, /total .*agents 3 /);
179
+ assert.doesNotMatch(one.stdout, /no branch/);
180
+ const none = spawnSync(process.execPath, [QC, "ledger", "--cost", "feat/none"], { cwd: main, encoding: "utf8" });
181
+ assert.match(none.stdout, /No cost record .* names feat\/none/);
182
+ });
183
+
184
+ test("a cost record prints as one line in the plain ledger listing", () => {
185
+ const line = formatRecord({ ...cost("a1", "implementer", "feat/1-x", 10, 100, 5), at: "2026-10-09T10:00:00.000Z" });
186
+ assert.match(line, /^2026-10-09T10:00:00.000Z {2}cost {10}implementer sdd-implementer a1 feat\/1-x in 10 out 100 .* tools 5$/);
187
+ });