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.
Files changed (39) hide show
  1. package/package.json +1 -1
  2. package/src/cli/bash-command-guard.mjs +28 -5
  3. package/src/cli/bash-command-guard.test.mjs +100 -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 +17 -9
  7. package/src/cli/ci-state.test.mjs +15 -1
  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 +5 -3
  13. package/src/cli/dispatch-reminder.test.mjs +5 -1
  14. package/src/cli/git-read.mjs +28 -3
  15. package/src/cli/git-read.test.mjs +31 -1
  16. package/src/cli/ledger.mjs +50 -3
  17. package/src/cli/ledger.test.mjs +46 -0
  18. package/src/cli/powershell-command.mjs +8 -13
  19. package/src/cli/powershell-command.test.mjs +11 -1
  20. package/src/cli/qc.mjs +1 -1
  21. package/src/cli/report-stop.test.mjs +2 -1
  22. package/src/cli/review-gate.mjs +224 -0
  23. package/src/cli/review-gate.test.mjs +334 -0
  24. package/src/cli/shell-command.mjs +65 -9
  25. package/src/cli/shell-command.test.mjs +21 -1
  26. package/src/cli/skill-guard.mjs +56 -0
  27. package/src/cli/skill-guard.test.mjs +87 -0
  28. package/src/cli/stop-gate.test.mjs +80 -0
  29. package/src/cli/task-gate-review.test.mjs +225 -0
  30. package/src/cli/task-gate.mjs +35 -11
  31. package/src/cli/task-gate.test.mjs +6 -5
  32. package/src/cli/test-brief.mjs +12 -0
  33. package/src/cli/transcript-usage.mjs +28 -0
  34. package/src/cli/transcript-usage.test.mjs +9 -0
  35. package/src/cli/workflow-hooks.test.mjs +38 -0
  36. package/src/cli/workflow-settings.mjs +14 -3
  37. package/src/cli/workflow-settings.test.mjs +24 -0
  38. package/src/config.mjs +13 -0
  39. package/templates/docs/enforcement.md +11 -0
@@ -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
  });
@@ -12,10 +12,12 @@ export const REMINDER =
12
12
  "architecture:sdd-reviewer to review it; before merge, dispatch architecture:sdd-branch-reviewer to review the " +
13
13
  "whole branch. " +
14
14
  "Run one implementer at a time: a hook refuses a second. 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 " +
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 " +
16
17
  "`VERDICT: <APPROVED|CHANGES_REQUIRED> <sha>`, and a merge passes `--match-head-commit <sha>`. " +
17
- "Review a head only once CI on it is green: fix a CI failure first. After an APPROVED review, review each fix round " +
18
- "once, by its increment: add `Reviewed: <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.";
19
21
 
20
22
  const ROLES = ["sdd-planner", "sdd-implementer", "sdd-reviewer", "sdd-branch-reviewer"];
21
23
 
@@ -60,7 +60,7 @@ 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
64
  });
65
65
 
66
66
  test("the note says to review a green head only, to fix CI first, and to review a fix round by its increment", () => {
@@ -69,6 +69,10 @@ test("the note says to review a green head only, to fix CI first, and to review
69
69
  /fix a CI failure first/,
70
70
  /`Reviewed: <sha>`/,
71
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/,
72
76
  ]) {
73
77
  assert.match(REMINDER, phrase);
74
78
  }
@@ -14,6 +14,31 @@ export function gitOutWithin(timeoutMs, cwd, ...args) {
14
14
  return result.status === 0 ? (result.stdout ?? "").trim() : null;
15
15
  }
16
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
+
17
42
  /** @returns git's trimmed stdout, or null on a non-zero exit or a timeout. */
18
43
  export const gitOut = (cwd, ...args) => gitOutWithin(GIT_TIMEOUT_MS, cwd, ...args);
19
44
 
@@ -39,9 +64,9 @@ export const branchAt = (dir) => gitOut(dir, "branch", "--show-current") || null
39
64
  export const branchesAt = (cwd, sha, read = gitOut) =>
40
65
  (read(cwd, "for-each-ref", "--points-at", sha, "--format=%(refname:short)", "refs/heads") ?? "").split(/\r?\n/).filter(Boolean);
41
66
 
42
- /** @returns each linked worktree of the repository at `root`, with its branch and head; the primary checkout is left out. */
43
- export function linkedWorktrees(root) {
44
- 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");
45
70
  if (out === null) return [];
46
71
  return out
47
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
 
@@ -119,14 +119,55 @@ const SUMMARIES = {
119
119
  (r.issues ?? []).map((issue) => `${issue.repo}#${issue.number}`).join(" ") || "no issue"
120
120
  }`,
121
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}`,
122
124
  };
123
125
 
124
126
  /** One line of `qc ledger`: the time, the type, and the fields that say what happened. */
125
127
  export const formatRecord = (record) =>
126
128
  `${record.at} ${record.type.padEnd(12)} ${SUMMARIES[record.type](record).replace(/\s+/g, " ").trim()}`;
127
129
 
128
- /** `qc ledger [branch]`: every record, or those that name the branch. @returns the exit code */
129
- 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");
130
171
  const root = checkoutRootOf(config.root ?? process.cwd());
131
172
  const file = root ? ledgerFileOf(root) : null;
132
173
  if (!file) {
@@ -134,6 +175,12 @@ export function runLedger(config, [branch] = []) {
134
175
  return 1;
135
176
  }
136
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
+ }
137
184
  for (const record of records) console.log(formatRecord(record));
138
185
  if (records.length === 0) console.log(branch ? `No record in ${file} names ${branch}.` : `The ledger at ${file} is empty.`);
139
186
  return 0;
@@ -139,3 +139,49 @@ test("a dispatch that passed on a CI failure shows the sha and the reason in the
139
139
  });
140
140
  assert.match(line, /CI-PASS: 1234567 CI on 1234567: build ended failure/);
141
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
+ });
@@ -1,7 +1,7 @@
1
1
  // A fragment that reads a PowerShell command the way shell-command.mjs reads a POSIX one, for the
2
2
  // Bash edit guard. It shares that parser and its git vocabulary, and an unknown name counts as a write.
3
3
 
4
- import { GIT_READS, commandWords, gitCall, segmentsOf } from "./shell-command.mjs";
4
+ import { GIT_READS, checkoutDirsOf, commandWords, gitCall, homeOrGroup, segmentsOf, unresolvedGitDirsOf } from "./shell-command.mjs";
5
5
 
6
6
  const DIALECT = { escape: "`" };
7
7
 
@@ -27,10 +27,10 @@ export function locationTarget(segment) {
27
27
  const [program, ...args] = commandWords(segment);
28
28
  if (!LOCATION_NAMES.has(program?.toLowerCase())) return null;
29
29
  for (let i = 0; i < args.length; i++) {
30
- if (PATH_PARAMETERS.has(args[i].toLowerCase())) return args[i + 1] ?? "~";
30
+ if (PATH_PARAMETERS.has(args[i].toLowerCase())) return args[i + 1] ?? homeOrGroup(segment);
31
31
  if (!args[i].startsWith("-")) return args[i];
32
32
  }
33
- return "~";
33
+ return homeOrGroup(segment);
34
34
  }
35
35
 
36
36
  function isReadOnly(segment) {
@@ -48,13 +48,8 @@ function isReadOnly(segment) {
48
48
  /** False only when every segment is known to read, so an unknown command counts as a write. */
49
49
  export const mayWrite = (command) => !segmentsOf(command, DIALECT).every(isReadOnly);
50
50
 
51
- /** Every directory the command names through a location change or `git -C`, in order, as written. */
52
- export function checkoutDirs(command) {
53
- const dirs = [];
54
- for (const segment of segmentsOf(command, DIALECT)) {
55
- const target = locationTarget(segment);
56
- if (target !== null) dirs.push(target);
57
- dirs.push(...(gitCall(segment)?.dirs ?? []).filter(Boolean));
58
- }
59
- return dirs;
60
- }
51
+ /** Every directory the command names through a location change, `git -C` or a work tree, in order, as written. */
52
+ export const checkoutDirs = (command) => checkoutDirsOf(powershellSegments(command), locationTarget);
53
+
54
+ /** The git directories a command sets with no work tree. */
55
+ export const unresolvedGitDirs = (command) => unresolvedGitDirsOf(powershellSegments(command));
@@ -1,6 +1,6 @@
1
1
  import { strict as assert } from "node:assert";
2
2
  import { test } from "node:test";
3
- import { checkoutDirs, mayWrite } from "./powershell-command.mjs";
3
+ import { checkoutDirs, mayWrite, unresolvedGitDirs } from "./powershell-command.mjs";
4
4
 
5
5
  test("a PowerShell command that only reads skips the check, in any letter case", () => {
6
6
  for (const command of [
@@ -51,3 +51,13 @@ test("the checkout directories are each location change and each git -C director
51
51
  assert.deepEqual(checkoutDirs("Get-ChildItem"), []);
52
52
  assert.deepEqual(checkoutDirs("Set-Content f x; git -C"), []);
53
53
  });
54
+
55
+ test("a work tree counts as a checkout directory in PowerShell, and a bare git dir is unresolved", () => {
56
+ const W = String.raw`C:\w`;
57
+ const R = String.raw`C:\r\.git`;
58
+ assert.deepEqual(checkoutDirs(`git --work-tree=${W} checkout main`), [W]);
59
+ assert.deepEqual(checkoutDirs(`$env:GIT_WORK_TREE = "${W}"; git checkout main`), [W]);
60
+ assert.deepEqual(unresolvedGitDirs(`$env:GIT_DIR = "${R}"; git checkout main`), [R]);
61
+ assert.deepEqual(unresolvedGitDirs(`git --git-dir=${R} --work-tree=${W} checkout main`), []);
62
+ assert.deepEqual(checkoutDirs("git -C"), []);
63
+ });
package/src/cli/qc.mjs CHANGED
@@ -22,7 +22,7 @@ const USAGE = `qc — architecture gates
22
22
  Vale on the lines a diff adds to the docs, and on a PR body; needs the vale binary
23
23
  qc commit-msg <file> conventional (commitlint), English, and the trailer when attribution is on
24
24
  qc decisions [id] where decisions are cited; --squash closes the gaps
25
- qc ledger [branch] the workflow ledger: dispatches, stops, verdicts, merges, issue updates
25
+ qc ledger [--cost] [branch] the workflow ledger: dispatches, stops, verdicts, merges, issue updates; --cost totals tokens and tool calls
26
26
  qc plan-check <plan.md> each task names files, a test step and a commit step, within the tool-call budget
27
27
  qc tokens [--session <id>] [--project <dir>] [--claude-dir <dir>] [--json]
28
28
  one session's tokens and cache hit rate per agent type, from its transcripts
@@ -8,6 +8,7 @@ import { fileURLToPath } from "node:url";
8
8
  import { appendRecord, readLedger } from "./ledger.mjs";
9
9
  import { branchOf, decide, verdictOf } from "./report-stop.mjs";
10
10
  import { judgeTask } from "./task-gate.mjs";
11
+ import { BRIEF } from "./test-brief.mjs";
11
12
  import { rememberSession } from "./workflow-settings.mjs";
12
13
 
13
14
  const HOOK = fileURLToPath(new URL("./report-stop.mjs", import.meta.url));
@@ -336,7 +337,7 @@ test("a stop with no new commit writes a worktree and a branch but no head, so i
336
337
  cwd: ws.on,
337
338
  hook_event_name: "PreToolUse",
338
339
  tool_name: "Agent",
339
- tool_input: { subagent_type: IMPLEMENTER, description: "t", prompt: `Worktree: ${a.dir}` },
340
+ tool_input: { subagent_type: IMPLEMENTER, description: "t", prompt: `Brief: ${BRIEF}\nWorktree: ${a.dir}` },
340
341
  },
341
342
  ws.tmp,
342
343
  );
@@ -0,0 +1,224 @@
1
+ // The checks of `swarm.review` that read a dispatch prompt and its branch: one branch review, a head that
2
+ // is green and holds the base tip, and a brief with product decisions. The task gate calls them.
3
+
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { gitOutWithin, isAncestor, remoteTip } from "./git-read.mjs";
7
+ import { shaMatches } from "./ledger.mjs";
8
+ import { commitLookup, nativePath } from "./workflow-place.mjs";
9
+
10
+ // Every read of a reviewer dispatch is capped, so the whole guard ends inside the Agent hook's 30 second limit.
11
+ // Worst case: head 2 + branch 2 + origin tip 8 + lookup 2 + ancestor 2 + CI (origin 1, gh 3) = 20 s.
12
+ export const READ_MS = 2_000;
13
+ const REMOTE_MS = 8_000;
14
+
15
+ const REVIEWED_LINE = /^[ \t]*Reviewed:[ \t]*([0-9a-f]{7,40})[ \t]*$/im;
16
+ const BRIEF_LINE = /^[ \t]*Brief:[ \t]*(\S.*?)[ \t]*$/im;
17
+ const QUOTES = /^["'`]|["'`]$/g;
18
+ const PRODUCT_HEADING = /^##[ \t]+Product decisions[ \t]*$/i;
19
+ const SECTION_END = /^#{1,2}[ \t]/;
20
+ const FINDING_LINE = /^[ \t]*\d+\.[ \t]/gm;
21
+ const URL_TEXT = /https?:\/\/\S+/gi;
22
+ const TOKEN_CHARS = /[^\w@~./\\-]+/;
23
+ const EXTENSION = /\.([A-Za-z][A-Za-z0-9]+)$/;
24
+ const KNOWN_EXTENSIONS = new Set(
25
+ "mjs cjs js jsx ts tsx json md yml yaml sh sql css html cs py go rs toml txt xml csv".split(" "),
26
+ );
27
+
28
+ const short = (sha) => (typeof sha === "string" ? sha.slice(0, 7) : "(none)");
29
+ const pass = (note = null) => ({ refusal: null, note });
30
+ const refuse = (refusal) => ({ refusal, note: null });
31
+
32
+ /** The sha on a prompt's `Reviewed: <sha>` line, or null. */
33
+ export const reviewedShaOf = (prompt) => REVIEWED_LINE.exec(String(prompt ?? ""))?.[1] ?? null;
34
+
35
+ /** The real reads of the base check, each with its own time limit. */
36
+ export const defaultReads = {
37
+ remoteTip: (cwd, remote, branch) => remoteTip(cwd, remote, branch, REMOTE_MS),
38
+ lookup: (cwd, ref) => commitLookup(cwd, ref, { timeoutMs: READ_MS }),
39
+ isAncestor: (cwd, ancestor, descendant) => isAncestor(cwd, ancestor, descendant, READ_MS),
40
+ };
41
+
42
+ /** The head of a checkout, or null when git cannot say within the time limit. */
43
+ export const headOf = (root) => gitOutWithin(READ_MS, root, "rev-parse", "HEAD");
44
+
45
+ /** The branch checked out at a checkout, or null. */
46
+ export const branchOfCheckout = (root) => gitOutWithin(READ_MS, root, "branch", "--show-current") || null;
47
+
48
+ /** The refusal of a reviewer whose worktree, branch, or head cannot be read: no check that needs them can run. */
49
+ export const unreadableRefusal = (type, why) =>
50
+ `Task gate: the ${type} prompt does not name a checkout the gate can read (${why}). ` +
51
+ "Add a line `Worktree: <path>` that names a worktree whose checked-out branch is the branch under review, then dispatch.";
52
+
53
+ function branchReviewRefusal({ records, branch, prompt }) {
54
+ const last = records.findLast((record) => record.type === "verdict" && record.kind === "branch" && record.branch === branch);
55
+ if (!last) return null;
56
+ const named = reviewedShaOf(prompt);
57
+ if (named === null) {
58
+ return (
59
+ `Task gate: ${branch} already has a branch review in the ledger (${short(last.sha)}), and a PR gets one. ` +
60
+ `Send the incremental review: add a line \`Reviewed: ${short(last.sha)}\`, the last head a branch review named, and pass the delta diff ${short(last.sha)}..<head> in place of the whole branch.`
61
+ );
62
+ }
63
+ const known = records.some((record) => record.type === "verdict" && record.kind === "branch" && record.branch === branch && shaMatches(record.sha, named));
64
+ if (known) return null;
65
+ return (
66
+ `Task gate: \`Reviewed: ${short(named)}\` is no head a branch review of ${branch} named. ` +
67
+ `Write the last head a branch review named: \`Reviewed: ${short(last.sha)}\`.`
68
+ );
69
+ }
70
+
71
+ /** The remote and branch to ask for the tip of `base`: `origin/<branch>`, or a bare name on origin. Null for any other spelling. */
72
+ function remoteBranchOf(base) {
73
+ const named = /^origin\/(.+)$/.exec(base);
74
+ if (named) return named[1];
75
+ return base.includes("/") ? null : base;
76
+ }
77
+
78
+ /**
79
+ * Judges that `head` holds the tip of `base`. The tip is read from origin, or from the local ref when origin does not answer.
80
+ * Only a tip that is known and missing refuses; a read that fails passes with a note.
81
+ * @returns `{ refusal, note }`
82
+ */
83
+ export function baseCheck({ root, base, head, reads = defaultReads }) {
84
+ const remoteBranch = remoteBranchOf(base);
85
+ let tip = remoteBranch === null ? null : reads.remoteTip(root, "origin", remoteBranch);
86
+ let note = null;
87
+ if (tip === null) {
88
+ const local = reads.lookup(root, base);
89
+ if (!local.sha) {
90
+ const why = local.error ?? "the ref is unknown";
91
+ return pass(`Task gate could not read the tip of ${base} (${why}), so the base check did not run.`);
92
+ }
93
+ tip = local.sha;
94
+ note = `Task gate read the tip of ${base} from local ${base}, because origin did not answer; run \`git fetch\` to make the check current.`;
95
+ } else {
96
+ const found = reads.lookup(root, tip);
97
+ if (found.error) return pass(`Task gate could not look up the tip of ${base} (${found.error}), so the base check did not run.`);
98
+ if (!found.sha) {
99
+ return refuse(
100
+ `Task gate: the tip of ${base} (${short(tip)}) is not in this checkout. Run \`git fetch\`, then merge ${base} into the branch, then dispatch the review.`,
101
+ );
102
+ }
103
+ }
104
+ const contained = reads.isAncestor(root, tip, head);
105
+ if (contained === false) {
106
+ return refuse(
107
+ `Task gate: the head ${short(head)} lacks the tip of ${base} (${short(tip)}): merge ${base} into the branch first. CI tests the merge ref, so a review of a head that lacks the tip judges a different commit.`,
108
+ );
109
+ }
110
+ if (contained === null) return pass(`Task gate could not tell whether ${short(head)} holds the tip of ${base}, so the base check did not run.`);
111
+ return pass(note);
112
+ }
113
+
114
+ /**
115
+ * The reviewer checks, in cheap-first order: one branch review, the base tip, green CI.
116
+ * `ciState(sha)` is `{ reason, unknown }`; `reads` answers the base check.
117
+ * @returns `{ refusal, note }`
118
+ */
119
+ export function reviewerCheck({ type, prompt, review, base, records, root, branch, head, ciState, reads = defaultReads }) {
120
+ if (!branch) return refuse(unreadableRefusal(type, "git read no branch there: a detached head, or git did not answer"));
121
+ if (!head) return refuse(unreadableRefusal(type, "git read no head there"));
122
+ if (review.oneBranchReview && review.reviewerTypes.branch.includes(type)) {
123
+ const refusal = branchReviewRefusal({ records, branch, prompt });
124
+ if (refusal) return refuse(refusal);
125
+ }
126
+ const notes = [];
127
+ if (review.requireBase) {
128
+ const result = baseCheck({ root, base, head, reads });
129
+ if (result.refusal) return result;
130
+ if (result.note) notes.push(result.note);
131
+ }
132
+ if (review.requireGreen) {
133
+ const state = ciState(head);
134
+ if (state.reason) {
135
+ return refuse(
136
+ `Task gate: ${state.reason}. A review waits for green CI on the head, since a red head changes before it is reviewed. Wait for the run, or fix the failure, then dispatch the review.`,
137
+ );
138
+ }
139
+ if (state.unknown) notes.push(`Task gate: CI on ${short(head)} is unknown: ${state.unknown}. The review proceeds.`);
140
+ }
141
+ return pass(notes.length > 0 ? notes.join(" ") : null);
142
+ }
143
+
144
+ /** The numbered findings of a brief: the lines that start with a number and a dot. */
145
+ export const countFindings = (text) => (String(text ?? "").match(FINDING_LINE) ?? []).length;
146
+
147
+ /** The distinct files a brief names: a path with a separator, or a name with a known extension. */
148
+ export function countFiles(text) {
149
+ const files = new Set();
150
+ for (const token of String(text ?? "").replace(URL_TEXT, " ").split(TOKEN_CHARS)) {
151
+ const name = token.replace(/\.+$/, "");
152
+ const extension = EXTENSION.exec(name)?.[1];
153
+ if (extension === undefined) continue;
154
+ if (/[\\/]/.test(name) || KNOWN_EXTENSIONS.has(extension.toLowerCase())) files.add(name.replaceAll("\\", "/"));
155
+ }
156
+ return files.size;
157
+ }
158
+
159
+ /** The path on a prompt's `Brief: <path>` line, without quotes, or null. */
160
+ export const briefPathOf = (prompt) => BRIEF_LINE.exec(String(prompt ?? ""))?.[1].replace(QUOTES, "") ?? null;
161
+
162
+ /** The text under a brief's `## Product decisions` heading, up to the next heading of level 1 or 2, trimmed. Null when the heading is absent. */
163
+ function productDecisionsOf(text) {
164
+ const lines = text.split(/\r?\n/);
165
+ const at = lines.findIndex((line) => PRODUCT_HEADING.test(line));
166
+ if (at < 0) return null;
167
+ const end = lines.findIndex((line, index) => index > at && SECTION_END.test(line));
168
+ return lines.slice(at + 1, end < 0 ? lines.length : end).join("\n").trim();
169
+ }
170
+
171
+ const BRIEF_LINE_HINT = "Write the brief to a file and name its path on a prompt line `Brief: <path>`, then dispatch.";
172
+
173
+ /** Reads the file the prompt's `Brief:` line names. @returns `{ text, source }` or `{ refusal }`. */
174
+ function briefOf(prompt, dirs, exists, read) {
175
+ const spelled = briefPathOf(prompt);
176
+ if (spelled === null) return { refusal: `Task gate: the implementer prompt has no \`Brief: <path>\` line. ${BRIEF_LINE_HINT}` };
177
+ const file = dirs.map((dir) => path.resolve(dir, nativePath(spelled))).find((candidate) => exists(candidate));
178
+ if (file === undefined) {
179
+ return { refusal: `Task gate: the \`Brief: <path>\` line names ${spelled}, and no such file exists. ${BRIEF_LINE_HINT}` };
180
+ }
181
+ try {
182
+ return { text: read(file), source: spelled };
183
+ } catch (error) {
184
+ return { refusal: `Task gate: the \`Brief: <path>\` line names ${spelled}, and the file cannot be read (${error.message}). ${BRIEF_LINE_HINT}` };
185
+ }
186
+ }
187
+
188
+ /**
189
+ * The implementer checks on a dispatch: its `Brief:` line names a file, the file holds a `## Product decisions` section
190
+ * with text, and its round stays a size one implementer finishes. A missing brief or section refuses; a long brief only
191
+ * warns. `dirs` resolve a relative brief path. With every brief check off, the brief is not read.
192
+ * @returns `{ refusal, note }`
193
+ */
194
+ export function briefCheck({ prompt, dirs, review, exists = existsSync, read = (file) => readFileSync(file, "utf8") }) {
195
+ if (!review.productDecisions && review.roundFindings <= 0 && review.roundFiles <= 0) return pass();
196
+ const brief = briefOf(prompt, dirs, exists, read);
197
+ if (brief.refusal) return refuse(brief.refusal);
198
+ const { text, source } = brief;
199
+ const decisions = review.productDecisions ? productDecisionsOf(text) : undefined;
200
+ if (decisions === null) {
201
+ return refuse(
202
+ `Task gate: the brief (${source}) has no \`## Product decisions\` heading. Ask the user the product questions first, in one question, ` +
203
+ "and record the answers under `## Product decisions` in the brief; write the rulings that bind the task, or `none` with the reason. Then dispatch.",
204
+ );
205
+ }
206
+ if (decisions === "") {
207
+ return refuse(
208
+ `Task gate: the \`## Product decisions\` section of the brief (${source}) is empty. ` +
209
+ "Write the rulings that bind the task under it, or `none` with the reason. Then dispatch.",
210
+ );
211
+ }
212
+ const findings = review.roundFindings > 0 ? countFindings(text) : 0;
213
+ const files = review.roundFiles > 0 ? countFiles(text) : 0;
214
+ const parts = [];
215
+ if (review.roundFindings > 0 && findings > review.roundFindings) {
216
+ parts.push(`${findings} numbered findings, over swarm.review.roundFindings (${review.roundFindings})`);
217
+ }
218
+ if (review.roundFiles > 0 && files > review.roundFiles) parts.push(`${files} files, over swarm.review.roundFiles (${review.roundFiles})`);
219
+ if (parts.length === 0) return pass();
220
+ return pass(
221
+ `Task gate: the brief (${source}) names ${parts.join(", and ")}. One implementer finishes a smaller round. ` +
222
+ "Split it: parallel implementers on disjoint paths, sub-branches in separate worktrees, merged by the controller.",
223
+ );
224
+ }