architecture-harness 0.25.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/package.json +3 -22
  2. package/src/cli/ask.mjs +42 -0
  3. package/src/cli/ask.test.mjs +40 -0
  4. package/src/cli/branch-sync.mjs +126 -0
  5. package/src/cli/branch-sync.test.mjs +428 -0
  6. package/src/cli/budget-guard.mjs +74 -5
  7. package/src/cli/budget-guard.test.mjs +185 -2
  8. package/src/cli/budget-report.mjs +85 -0
  9. package/src/cli/budget-report.test.mjs +173 -0
  10. package/src/cli/budget.mjs +8 -5
  11. package/src/cli/check-commands.mjs +123 -11
  12. package/src/cli/check-commands.test.mjs +360 -6
  13. package/src/cli/check-feature-switches.test.mjs +110 -0
  14. package/src/cli/check-full.test.mjs +152 -0
  15. package/src/cli/check-verdict.mjs +46 -0
  16. package/src/cli/check-verdict.test.mjs +32 -0
  17. package/src/cli/check.mjs +137 -4
  18. package/src/cli/check.test.mjs +45 -0
  19. package/src/cli/checkpoint.mjs +143 -0
  20. package/src/cli/checkpoint.test.mjs +146 -0
  21. package/src/cli/child-run.mjs +7 -2
  22. package/src/cli/child-run.test.mjs +17 -2
  23. package/src/cli/ci-failures.mjs +304 -0
  24. package/src/cli/ci-failures.test.mjs +615 -0
  25. package/src/cli/ci-preview.mjs +62 -0
  26. package/src/cli/ci-preview.test.mjs +85 -0
  27. package/src/cli/ci-state.mjs +25 -29
  28. package/src/cli/ci-state.test.mjs +174 -2
  29. package/src/cli/ci-template.test.mjs +86 -0
  30. package/src/cli/claude-core.test.mjs +37 -0
  31. package/src/cli/codex-implement.mjs +580 -47
  32. package/src/cli/codex-implement.test.mjs +1946 -29
  33. package/src/cli/codex-limit.mjs +85 -0
  34. package/src/cli/codex-limit.test.mjs +179 -0
  35. package/src/cli/codex-reset.mjs +78 -0
  36. package/src/cli/codex-reset.test.mjs +192 -0
  37. package/src/cli/codex-verify.mjs +230 -0
  38. package/src/cli/codex-verify.test.mjs +402 -0
  39. package/src/cli/comment-watch.mjs +391 -0
  40. package/src/cli/comment-watch.test.mjs +392 -0
  41. package/src/cli/commit-guard.mjs +219 -0
  42. package/src/cli/commit-guard.test.mjs +809 -0
  43. package/src/cli/context-budgets.mjs +47 -0
  44. package/src/cli/context-budgets.test.mjs +96 -0
  45. package/src/cli/context-watch.mjs +116 -0
  46. package/src/cli/context-watch.test.mjs +395 -0
  47. package/src/cli/contract-history.mjs +1 -1
  48. package/src/cli/controller-guard.mjs +38 -0
  49. package/src/cli/controller-guard.test.mjs +66 -2
  50. package/src/cli/cost-stop.mjs +5 -1
  51. package/src/cli/cost-stop.test.mjs +26 -0
  52. package/src/cli/diff-shape.mjs +162 -0
  53. package/src/cli/diff-shape.test.mjs +200 -0
  54. package/src/cli/direct-lane.mjs +32 -19
  55. package/src/cli/direct-lane.test.mjs +21 -3
  56. package/src/cli/dispatch-guard.mjs +11 -0
  57. package/src/cli/dispatch-guard.test.mjs +145 -10
  58. package/src/cli/dispatch-reminder.mjs +23 -10
  59. package/src/cli/dispatch-reminder.test.mjs +63 -11
  60. package/src/cli/dispatch-route.mjs +54 -0
  61. package/src/cli/dispatch-route.test.mjs +101 -0
  62. package/src/cli/dispatch-slot.mjs +2 -2
  63. package/src/cli/dispatch-slot.test.mjs +18 -19
  64. package/src/cli/dispatch.test.mjs +3 -3
  65. package/src/cli/e2e-affected.mjs +15 -0
  66. package/src/cli/e2e-affected.test.mjs +73 -0
  67. package/src/cli/fleet.mjs +180 -0
  68. package/src/cli/fleet.test.mjs +213 -0
  69. package/src/cli/gate-slot.mjs +2 -1
  70. package/src/cli/gh-merge-command.mjs +96 -31
  71. package/src/cli/gh-merge-command.test.mjs +74 -0
  72. package/src/cli/gh-run.mjs +64 -3
  73. package/src/cli/gh-run.test.mjs +66 -1
  74. package/src/cli/git-hooks.test.mjs +25 -3
  75. package/src/cli/git-read.mjs +2 -1
  76. package/src/cli/integrate-tree.mjs +47 -0
  77. package/src/cli/integrate.mjs +143 -40
  78. package/src/cli/integrate.test.mjs +347 -1
  79. package/src/cli/integration-lane.mjs +62 -0
  80. package/src/cli/integration-lane.test.mjs +213 -0
  81. package/src/cli/ledger.mjs +4 -2
  82. package/src/cli/ledger.test.mjs +12 -3
  83. package/src/cli/legs.mjs +53 -0
  84. package/src/cli/legs.test.mjs +70 -0
  85. package/src/cli/lint-changed.mjs +59 -10
  86. package/src/cli/lint-changed.test.mjs +112 -1
  87. package/src/cli/locked-tests.mjs +134 -0
  88. package/src/cli/locked-tests.test.mjs +188 -0
  89. package/src/cli/merge-guard.mjs +234 -62
  90. package/src/cli/merge-guard.test.mjs +768 -39
  91. package/src/cli/metrics.mjs +53 -0
  92. package/src/cli/metrics.test.mjs +73 -0
  93. package/src/cli/milestone.mjs +297 -0
  94. package/src/cli/milestone.test.mjs +294 -0
  95. package/src/cli/mutate.mjs +203 -0
  96. package/src/cli/mutate.test.mjs +134 -0
  97. package/src/cli/output-redaction.mjs +26 -0
  98. package/src/cli/output-redaction.test.mjs +117 -0
  99. package/src/cli/overview.mjs +131 -0
  100. package/src/cli/overview.test.mjs +137 -0
  101. package/src/cli/pause.mjs +93 -0
  102. package/src/cli/pause.test.mjs +109 -0
  103. package/src/cli/plan-check.mjs +84 -12
  104. package/src/cli/plan-check.test.mjs +152 -2
  105. package/src/cli/plan-stop.mjs +7 -4
  106. package/src/cli/plan-stop.test.mjs +87 -0
  107. package/src/cli/platform-risk.mjs +46 -0
  108. package/src/cli/platform-risk.test.mjs +38 -0
  109. package/src/cli/plugin-skills.test.mjs +25 -0
  110. package/src/cli/pr-guard.mjs +128 -0
  111. package/src/cli/pr-guard.test.mjs +154 -0
  112. package/src/cli/promotion-branch.mjs +2 -0
  113. package/src/cli/qc.mjs +160 -27
  114. package/src/cli/qc.test.mjs +93 -0
  115. package/src/cli/report-stop.mjs +5 -0
  116. package/src/cli/report-stop.test.mjs +23 -1
  117. package/src/cli/retry-failed.mjs +3 -1
  118. package/src/cli/review-gate.mjs +24 -6
  119. package/src/cli/review-gate.test.mjs +116 -0
  120. package/src/cli/review-promotion.mjs +107 -0
  121. package/src/cli/review-promotion.test.mjs +251 -0
  122. package/src/cli/role-budget.mjs +50 -0
  123. package/src/cli/role-budget.test.mjs +91 -0
  124. package/src/cli/run-log.mjs +73 -0
  125. package/src/cli/run-log.test.mjs +121 -0
  126. package/src/cli/secret-patterns.mjs +16 -0
  127. package/src/cli/secret-patterns.test.mjs +73 -0
  128. package/src/cli/setup-block.mjs +24 -0
  129. package/src/cli/setup-block.test.mjs +96 -0
  130. package/src/cli/setup-checks.mjs +65 -0
  131. package/src/cli/setup-checks.test.mjs +158 -0
  132. package/src/cli/setup-compaction.mjs +55 -0
  133. package/src/cli/setup-compaction.test.mjs +115 -0
  134. package/src/cli/setup-skills.mjs +65 -0
  135. package/src/cli/setup-skills.test.mjs +171 -0
  136. package/src/cli/setup.mjs +107 -0
  137. package/src/cli/setup.test.mjs +275 -0
  138. package/src/cli/skill-length.test.mjs +8 -0
  139. package/src/cli/spawn-command.mjs +47 -0
  140. package/src/cli/spawn-command.test.mjs +64 -0
  141. package/src/cli/task-gate-review.test.mjs +21 -2
  142. package/src/cli/task-gate.mjs +25 -12
  143. package/src/cli/task-gate.test.mjs +43 -5
  144. package/src/cli/tokens.mjs +46 -3
  145. package/src/cli/tokens.test.mjs +103 -3
  146. package/src/cli/tools.mjs +49 -0
  147. package/src/cli/tools.test.mjs +89 -0
  148. package/src/cli/transcript-usage.mjs +27 -0
  149. package/src/cli/transcript-usage.test.mjs +34 -0
  150. package/src/cli/user-config-package.mjs +1 -1
  151. package/src/cli/user-config-toml.mjs +63 -7
  152. package/src/cli/user-config.mjs +39 -7
  153. package/src/cli/user-config.test.mjs +238 -5
  154. package/src/cli/watch-arm.mjs +39 -0
  155. package/src/cli/watch-arm.test.mjs +87 -0
  156. package/src/cli/watch.mjs +80 -35
  157. package/src/cli/watch.test.mjs +233 -27
  158. package/src/cli/work-order-guard.mjs +2 -1
  159. package/src/cli/workflow-hooks.test.mjs +18 -4
  160. package/src/cli/workflow-settings.mjs +44 -8
  161. package/src/cli/workflow-settings.test.mjs +124 -1
  162. package/src/cli/worktree.mjs +14 -1
  163. package/src/cli/worktree.test.mjs +20 -1
  164. package/src/config.mjs +174 -7
  165. package/src/config.test.mjs +327 -5
  166. package/src/consumer-package.mjs +31 -0
  167. package/src/consumer-package.test.mjs +54 -0
  168. package/src/descriptions.mjs +2 -0
  169. package/src/eslint/index.mjs +12 -0
  170. package/src/eslint/jsx.mjs +20 -0
  171. package/src/eslint/preset.mjs +26 -2
  172. package/src/eslint/preset.test.mjs +104 -2
  173. package/src/eslint/rules/no-arbitrary-class-value.mjs +32 -0
  174. package/src/eslint/rules/no-literal-color.mjs +94 -0
  175. package/src/eslint/rules/no-static-inline-style.mjs +41 -0
  176. package/src/eslint/rules/one-component-per-file.mjs +70 -0
  177. package/src/eslint/rules/raw-element-in-primitive.mjs +31 -0
  178. package/src/eslint/rules/timeless-comment.mjs +92 -0
  179. package/src/eslint/rules.test.mjs +189 -0
  180. package/src/eslint/ui-regressions.test.mjs +39 -0
  181. package/src/gates/contract-operations.mjs +3 -3
  182. package/src/gates/contract-operations.test.mjs +28 -0
  183. package/src/gates/feature-switches.mjs +19 -0
  184. package/src/gates/feature-switches.test.mjs +55 -0
  185. package/src/gates/plain-language.mjs +396 -0
  186. package/src/gates/plain-language.test.mjs +210 -0
  187. package/src/gates/runtime-imports.test.mjs +114 -0
  188. package/src/gates/saga-key.test.mjs +1 -1
  189. package/src/global-skills.mjs +9 -0
  190. package/src/global-skills.test.mjs +53 -0
  191. package/src/plugin.test.mjs +3 -2
  192. package/src/ui/class-sites.mjs +38 -6
  193. package/src/ui/codemod.mjs +4 -1
  194. package/src/ui/codemod.test.mjs +52 -0
  195. package/src/ui/components.mjs +5 -3
  196. package/src/ui/components.test.mjs +8 -0
  197. package/src/ui/dupes.test.mjs +18 -0
  198. package/templates/docs/enforcement.md +12 -2
  199. package/templates/docs/ui.md +33 -0
  200. package/templates/githooks/pre-commit +1 -0
  201. package/templates/githooks/pre-push +11 -2
  202. package/templates/github/workflows/ci.yml +57 -3
  203. package/user-config/claude/CLAUDE.core.md +28 -0
  204. package/user-config/claude/settings.shared.json +41 -1
  205. package/src/cli/screens-discovery.mjs +0 -60
  206. package/src/cli/screens.mjs +0 -84
  207. package/src/cli/stack.mjs +0 -14
  208. package/src/cli/throwaway-db.mjs +0 -127
  209. package/src/cli/throwaway-db.test.mjs +0 -83
  210. package/src/screens/auth-context.test.mjs +0 -41
  211. package/src/screens/auth-run.test.mjs +0 -147
  212. package/src/screens/auth.mjs +0 -223
  213. package/src/screens/auth.test.mjs +0 -76
  214. package/src/screens/capture-idle.test.mjs +0 -27
  215. package/src/screens/capture.browser-test.mjs +0 -73
  216. package/src/screens/capture.mjs +0 -175
  217. package/src/screens/capture.test.mjs +0 -28
  218. package/src/screens/catalog.browser-test.mjs +0 -32
  219. package/src/screens/catalog.mjs +0 -72
  220. package/src/screens/catalog.test.mjs +0 -36
  221. package/src/screens/chrome.mjs +0 -21
  222. package/src/screens/compare.mjs +0 -40
  223. package/src/screens/compare.test.mjs +0 -30
  224. package/src/screens/discovery.browser-test.mjs +0 -29
  225. package/src/screens/discovery.mjs +0 -158
  226. package/src/screens/discovery.test.mjs +0 -27
  227. package/src/screens/inventory.mjs +0 -69
  228. package/src/screens/inventory.test.mjs +0 -10
  229. package/src/screens/map.mjs +0 -63
  230. package/src/screens/map.test.mjs +0 -35
  231. package/src/screens/open.browser-test.mjs +0 -50
  232. package/src/screens/regions.mjs +0 -137
  233. package/src/screens/regions.test.mjs +0 -38
  234. package/src/screens/session-files.mjs +0 -39
  235. package/src/screens/session-files.test.mjs +0 -39
  236. package/src/screens/setup.browser-test.mjs +0 -49
  237. package/src/screens/setup.mjs +0 -78
  238. package/src/screens/stack-auth.browser-test.mjs +0 -30
  239. package/src/screens/stack-auth.mjs +0 -106
  240. package/src/screens/stack-auth.test.mjs +0 -65
  241. package/src/screens/write-guard.mjs +0 -26
  242. package/src/stack/stack.mjs +0 -131
  243. package/src/stack/stack.test.mjs +0 -40
  244. package/src/stack/supervisor.mjs +0 -30
@@ -0,0 +1,251 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { spawnSync } from "node:child_process";
3
+ import { existsSync, mkdtempSync, readFileSync, 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 { load } from "../config.mjs";
9
+ import { appendRecord, ledgerFileOf } from "./ledger.mjs";
10
+
11
+ const HEAD = "a".repeat(40);
12
+ const QC = fileURLToPath(new URL("./qc.mjs", import.meta.url));
13
+ const PROMOTION = { integration: "dev", release: "main" };
14
+ const PR = { number: 7, headRefName: "dev", baseRefName: "main", headRefOid: HEAD, url: "https://github.com/example/repo/pull/7", isCrossRepository: false, changedFiles: 3 };
15
+
16
+ async function fixture(t, { swarm = { dispatch: {}, review: { promotion: PROMOTION } }, pr = PR, diff = "infra/net.tf\ndb/migrations/0042.sql\nsrc/a.ts\n", records = [], increment = "infra/increment.tf\nsrc/a.ts\n" } = {}) {
17
+ const { runReview } = await import("./review-promotion.mjs");
18
+ const root = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-review-promotion-")));
19
+ t.after(() => rmSync(root, { recursive: true, force: true }));
20
+ const init = spawnSync("git", ["init", "--quiet"], { cwd: root, encoding: "utf8", windowsHide: true });
21
+ assert.equal(init.status, 0, init.stderr);
22
+ writeFileSync(path.join(root, "qc.config.json"), JSON.stringify({ swarm }));
23
+ for (const record of records) appendRecord(ledgerFileOf(root), record);
24
+ const out = [];
25
+ const err = [];
26
+ const calls = [];
27
+ const ghOptions = [];
28
+ const gitCalls = [];
29
+ const git = (cwd, ...args) => {
30
+ assert.equal(cwd, root);
31
+ gitCalls.push(args);
32
+ return increment;
33
+ };
34
+ const gh = (args, options) => {
35
+ assert.equal(options.cwd, root);
36
+ calls.push(args);
37
+ ghOptions.push(options);
38
+ if (args.join(" ") === "pr view 7 --json number,headRefName,baseRefName,headRefOid,url,isCrossRepository,changedFiles") return pr === null ? null : JSON.stringify(pr);
39
+ if (args.join(" ") === "api --paginate repos/{owner}/{repo}/pulls/7/files --jq .[].filename") return diff;
40
+ assert.fail(`Unexpected gh call: ${args.join(" ")}`);
41
+ };
42
+ const run = (args = ["promotion", "7"]) => runReview(load(root), args, { gh, git, out: (line) => out.push(line), err: (line) => err.push(line) });
43
+ return { root, out, err, calls, ghOptions, gitCalls, run, file: path.join(root, ".git", "qc", "promotion", "pr-7.md") };
44
+ }
45
+
46
+ test("promotion consumers import the shared branch fragment", async () => {
47
+ const { promotionBranchName } = await import("./promotion-branch.mjs");
48
+ assert.equal(promotionBranchName("origin/main"), "main");
49
+ assert.equal(promotionBranchName("main"), "main");
50
+ for (const name of ["merge-guard", "review-promotion", "workflow-settings"]) {
51
+ const source = readFileSync(new URL(`./${name}.mjs`, import.meta.url), "utf8");
52
+ assert.match(source, /import \{ promotionBranchName \} from "\.\/promotion-branch\.mjs"/);
53
+ assert.doesNotMatch(source, /from "\.\/review-promotion\.mjs"/);
54
+ }
55
+ });
56
+
57
+ test("the paginated file request gets 120 seconds and requests the PR count", async (t) => {
58
+ const f = await fixture(t);
59
+ assert.equal(f.run(), 0, f.err.join("\n"));
60
+ assert.ok(f.calls[0].at(-1).split(",").includes("changedFiles"));
61
+ assert.equal(f.ghOptions[1].timeoutMs, 120_000);
62
+ });
63
+
64
+ for (const [read, expected] of [[2, 3], [4, 3], [3000, 3000], [3000, 3100]]) {
65
+ test(`promotion refuses ${read} listed files against ${expected} changed files`, async (t) => {
66
+ const diff = Array.from({ length: read }, (_, i) => `infra/${i}.tf`).join("\n");
67
+ const f = await fixture(t, { diff, pr: { ...PR, changedFiles: expected } });
68
+ assert.equal(f.run(), 1);
69
+ assert.match(f.err.join("\n"), new RegExp(`read ${read}.*changedFiles ${expected}`));
70
+ if (read === 3000) assert.match(f.err.join("\n"), /3,000.*limit/);
71
+ assert.equal(existsSync(f.file), false);
72
+ assert.deepEqual(f.out, []);
73
+ });
74
+ }
75
+
76
+ for (const changedFiles of [undefined, null, "3", -1]) {
77
+ test(`promotion refuses an invalid changedFiles count: ${changedFiles}`, async (t) => {
78
+ const f = await fixture(t, { pr: { ...PR, changedFiles } });
79
+ assert.equal(f.run(), 1);
80
+ assert.match(f.err.join("\n"), /changedFiles/);
81
+ assert.equal(existsSync(f.file), false);
82
+ });
83
+ }
84
+
85
+ test("a repeated approved promotion names its verdict without a review file", async (t) => {
86
+ const f = await fixture(t, { records: [{ type: "verdict", session: "s", agentId: "reviewer", kind: "branch", verdict: "APPROVED", sha: "b".repeat(40), branch: "dev", redChecked: false, scope: "promotion" }] });
87
+ assert.equal(f.run(), 0);
88
+ const brief = readFileSync(f.file, "utf8");
89
+ assert.match(brief, /Previous verdict: APPROVED/);
90
+ assert.doesNotMatch(brief + f.out.join("\n"), /Previous review:/);
91
+ assert.doesNotMatch(brief, /Check each earlier finding/);
92
+ });
93
+
94
+ test("qc review promotion 7 writes the brief of the files on the risk surfaces", async (t) => {
95
+ const f = await fixture(t);
96
+ assert.equal(await f.run(), 0, f.err.join("\n"));
97
+ const brief = readFileSync(f.file, "utf8");
98
+ for (const text of ["# Promotion review", "#7", "dev", "main", `Head: ${HEAD}`, "Scope: promotion", "2 of 3", "infra/net.tf", "db/migrations/0042.sql", "## Review these files", "## Checks"]) {
99
+ assert.ok(brief.includes(text), text);
100
+ }
101
+ assert.doesNotMatch(brief, /src\/a\.ts/);
102
+ assert.doesNotMatch(brief + f.out.join("\n"), /Reviewed:/);
103
+ for (const check of [/infra:.*permissions.*public exposure.*removed protections/i, /migrations:.*order.*destructive statements.*rollback path/i,
104
+ /workflows:.*new triggers.*secret use.*unpinned actions/i, /secrets in logs:.*log or error output.*token.*key.*password.*personal data/i]) assert.match(brief, check);
105
+ assert.match(brief, new RegExp(`first line.*VERDICT: APPROVED ${HEAD}.*VERDICT: CHANGES_REQUIRED ${HEAD}`));
106
+ assert.equal(f.out.length, 3);
107
+ assert.equal(f.out[0], `Wrote ${f.file}`);
108
+ assert.match(f.out[1], /architecture:sdd-branch-reviewer.*model.*opus/);
109
+ assert.ok(f.out[1].includes(`Brief: ${f.file}\nScope: promotion\nWorktree:`));
110
+ assert.ok(f.out[1].includes(`dev at ${HEAD}`));
111
+ assert.equal(f.out[2], `Merge with --match-head-commit ${HEAD} after the review approves.`);
112
+ assert.equal(f.calls.length, 2);
113
+ });
114
+
115
+ for (const [name, swarm, cause] of [
116
+ ["promotion unset", { dispatch: {} }, /swarm\.review\.promotion/],
117
+ ["dispatch off", { dispatch: false, review: { promotion: PROMOTION } }, /swarm\.dispatch/],
118
+ ]) {
119
+ test(`qc review refuses ${name}`, async (t) => {
120
+ const f = await fixture(t, { swarm });
121
+ assert.equal(await f.run(), 1);
122
+ assert.match(f.err.join("\n"), cause);
123
+ assert.equal(f.calls.length, 0);
124
+ });
125
+ }
126
+
127
+ for (const field of ["headRefName", "baseRefName"]) {
128
+ test(`qc review refuses the wrong ${field} and names both configured branches`, async (t) => {
129
+ const f = await fixture(t, { pr: { ...PR, [field]: "other" } });
130
+ assert.equal(await f.run(), 1);
131
+ assert.match(f.err.join("\n"), /dev.*main/);
132
+ assert.match(f.err.join("\n"), /other/);
133
+ assert.equal(f.calls.length, 1);
134
+ });
135
+ }
136
+
137
+ for (const [name, options] of [["PR", { pr: null }], ["diff", { diff: null }]]) {
138
+ test(`qc review refuses a null gh ${name} answer`, async (t) => {
139
+ const f = await fixture(t, options);
140
+ assert.equal(await f.run(), 1);
141
+ assert.match(f.err.join("\n"), /gh/);
142
+ assert.match(f.err.join("\n"), /7/);
143
+ });
144
+ }
145
+
146
+ test("qc review promotion without a PR prints usage and exits 2", async (t) => {
147
+ const f = await fixture(t);
148
+ assert.equal(await f.run(["promotion"]), 2);
149
+ assert.match([...f.out, ...f.err].join("\n"), /qc review promotion <pr>/);
150
+ assert.equal(f.calls.length, 0);
151
+ const cli = spawnSync(process.execPath, [QC, "review", "promotion"], { cwd: f.root, encoding: "utf8", windowsHide: true });
152
+ assert.equal(cli.status, 2, cli.stderr);
153
+ assert.match(cli.stdout + cli.stderr, /qc review promotion <pr>/);
154
+ });
155
+
156
+ test("qc review accepts only promotion with one positive PR number", async (t) => {
157
+ const f = await fixture(t);
158
+ for (const args of [[], ["branch", "7"], ["promotion", "../7"], ["promotion", "0"], ["promotion", "7", "extra"]]) {
159
+ assert.equal(await f.run(args), 2);
160
+ }
161
+ assert.equal(f.calls.length, 0);
162
+ });
163
+
164
+ test("the brief limits the paths to 200 and names how to read the rest", async () => {
165
+ const { promotionBrief } = await import("./review-promotion.mjs");
166
+ const files = Array.from({ length: 203 }, (_, i) => `infra/${i}.tf`);
167
+ const brief = promotionBrief({ pr: 7, head: HEAD, ...PROMOTION, files, total: 205 });
168
+ assert.match(brief, /203 of 205/);
169
+ assert.equal(brief.match(/^- `infra\//gm).length, 200);
170
+ assert.doesNotMatch(brief, /infra\/200\.tf/);
171
+ assert.match(brief, /3 more.*gh api --paginate repos\/\{owner\}\/\{repo\}\/pulls\/7\/files --jq '\.\[\]\.filename'/);
172
+ });
173
+
174
+ test("qc review lists a thousand changed files through the paginated API", async (t) => {
175
+ const diff = Array.from({ length: 1000 }, (_, i) => `infra/${i}.tf`).join("\n");
176
+ const f = await fixture(t, { diff, pr: { ...PR, changedFiles: 1000 } });
177
+ assert.equal(await f.run(), 0, f.err.join("\n"));
178
+ assert.match(readFileSync(f.file, "utf8"), /1000 of 1000/);
179
+ assert.deepEqual(f.calls[1], ["api", "--paginate", "repos/{owner}/{repo}/pulls/7/files", "--jq", ".[].filename"]);
180
+ });
181
+
182
+ test("qc review uses configured surfaces", async (t) => {
183
+ const f = await fixture(t, { swarm: { dispatch: {}, review: { promotion: { ...PROMOTION, surfaces: ["src/**"] } } } });
184
+ assert.equal(await f.run(), 0);
185
+ const brief = readFileSync(f.file, "utf8");
186
+ assert.match(brief, /1 of 3/);
187
+ assert.match(brief, /src\/a\.ts/);
188
+ assert.doesNotMatch(brief, /infra\/net\.tf|db\/migrations\/0042\.sql/);
189
+ });
190
+
191
+ test("a repeated promotion names the newest scoped branch verdict and briefs its increment", async (t) => {
192
+ const reviewed = "b".repeat(40);
193
+ const record = { type: "verdict", session: "s", agentId: "reviewer", kind: "branch", verdict: "APPROVED", sha: "c".repeat(40), branch: "dev", redChecked: false, scope: "promotion" };
194
+ const f = await fixture(t, { records: [
195
+ record,
196
+ { ...record, sha: reviewed, verdict: "CHANGES_REQUIRED" },
197
+ { ...record, branch: "other" },
198
+ { ...record, kind: "task" },
199
+ { ...record, scope: "security" },
200
+ { ...record, type: "dispatch" },
201
+ ] });
202
+ assert.equal(await f.run(), 0, f.err.join("\n"));
203
+ const brief = readFileSync(f.file, "utf8");
204
+ assert.ok(brief.includes(`\nReviewed: ${reviewed}\n`));
205
+ assert.match(brief, /Previous verdict: CHANGES_REQUIRED/);
206
+ assert.doesNotMatch(brief, /^Previous review:/m);
207
+ assert.match(brief, /Check each earlier finding in the file named by `Previous review:`/);
208
+ assert.match(brief, /Check each earlier finding.*not only the increment/);
209
+ assert.ok(f.out[1].includes(`\nReviewed: ${reviewed}\n`));
210
+ assert.match(f.out[1], /Add a `Previous review: <path>` line naming the earlier review file/);
211
+ assert.match(brief, /1 of 2/);
212
+ assert.match(brief, /infra\/increment\.tf/);
213
+ assert.doesNotMatch(brief, /infra\/net\.tf|0042\.sql/);
214
+ assert.deepEqual(f.gitCalls, [["diff", "--name-only", `${reviewed}..${HEAD}`, "--"]]);
215
+ });
216
+
217
+ test("a repeated promotion refuses an unreadable increment", async (t) => {
218
+ const f = await fixture(t, { records: [{ type: "verdict", kind: "branch", branch: "dev", scope: "promotion", sha: "b".repeat(40) }], increment: null });
219
+ assert.equal(await f.run(), 1);
220
+ assert.match(f.err.join("\n"), /increment.*7/i);
221
+ });
222
+
223
+ test("a repeated promotion lists the full increment command after 200 paths", async () => {
224
+ const { promotionBrief } = await import("./review-promotion.mjs");
225
+ const reviewed = "b".repeat(40);
226
+ const files = Array.from({ length: 201 }, (_, i) => `infra/${i}.tf`);
227
+ const brief = promotionBrief({ pr: 7, head: HEAD, reviewed, ...PROMOTION, files, total: 201 });
228
+ assert.ok(brief.includes(`git diff --name-only ${reviewed}..${HEAD} --`));
229
+ });
230
+
231
+ test("qc review normalizes configured origin branches and finds the previous promotion", async (t) => {
232
+ const reviewed = "b".repeat(40);
233
+ const f = await fixture(t, {
234
+ swarm: { dispatch: {}, review: { promotion: { integration: "origin/dev", release: "origin/main" } } },
235
+ records: [{ type: "verdict", kind: "branch", branch: "dev", scope: "promotion", sha: reviewed }],
236
+ });
237
+ assert.equal(await f.run(), 0, f.err.join("\n"));
238
+ const brief = readFileSync(f.file, "utf8");
239
+ assert.match(brief, /dev -> main/);
240
+ assert.ok(brief.includes(`Reviewed: ${reviewed}`));
241
+ assert.ok(f.out[1].includes(`dev at ${HEAD}`));
242
+ });
243
+
244
+ for (const isCrossRepository of [true, undefined, null]) {
245
+ test(`qc review refuses a promotion without confirmed repository equality: ${isCrossRepository}`, async (t) => {
246
+ const f = await fixture(t, { pr: { ...PR, isCrossRepository } });
247
+ assert.equal(await f.run(), 1);
248
+ assert.match(f.err.join("\n"), /same repository/i);
249
+ assert.equal(f.calls.length, 1);
250
+ });
251
+ }
@@ -0,0 +1,50 @@
1
+ import { HANDOFF_STEPS, isHandoffCall } from "./budget.mjs";
2
+ import { contextDefaults } from "../config.mjs";
3
+ import { reviewSettings } from "./workflow-settings.mjs";
4
+
5
+ export function orchestratorVerdict({ tokens, compactAt, count, state }) {
6
+ if (count % contextDefaults.every !== 0 || !(tokens >= compactAt)) return null;
7
+ if (state.budgetFiredAt !== undefined && count - state.budgetFiredAt < contextDefaults.repeatEvery) return null;
8
+ state.budgetFiredAt = count;
9
+ return `Context budget: this session sends about ${Math.round(tokens / 1000)}K tokens per call, past budgets.orchestrator.compactAt (${compactAt}). ` +
10
+ "Run /compact at the next green step. Keep the plan path, the open PR numbers, each branch and its head, and the ledger path in the summary.";
11
+ }
12
+
13
+ export function budgetRoleOf(agentType, swarm) {
14
+ const settings = reviewSettings(swarm);
15
+ if (!settings) return null;
16
+ if (settings.implementerTypes.includes(agentType)) return "implementer";
17
+ if (Object.values(settings.reviewerTypes).some((types) => types.includes(agentType))) return "reviewer";
18
+ return null;
19
+ }
20
+
21
+ export function roleBudgetVerdict({ role, tokens, budget, call, state }) {
22
+ if (!budget) return null;
23
+ if (state.budgetClosed || tokens >= budget.handoffAt) {
24
+ state.budgetClosed = true;
25
+ if (isHandoffCall(call)) return null;
26
+ const steps = role === "reviewer"
27
+ ? "Put the full review in your final report. If files remain, open with `VERDICT: CHANGES_REQUIRED <sha>`, then add a line " +
28
+ "`UNREVIEWED:` listing the files left. The controller sends a fresh reviewer with `Scope:` for those files. " +
29
+ "The partial reviewer's scope needs a new APPROVED review on the head before merge."
30
+ : HANDOFF_STEPS;
31
+ return {
32
+ hookSpecificOutput: {
33
+ hookEventName: "PreToolUse",
34
+ permissionDecision: "deny",
35
+ permissionDecisionReason:
36
+ `Context budget spent: budgets.${role}.handoffAt (${budget.handoffAt}) in qc.config.json. Only the hand-off can run now. ${steps}`,
37
+ },
38
+ };
39
+ }
40
+ if (!(tokens >= budget.remindAt) || state.budgetReminded) return null;
41
+ state.budgetReminded = true;
42
+ return {
43
+ hookSpecificOutput: {
44
+ hookEventName: "PreToolUse",
45
+ additionalContext:
46
+ `Context budget: this agent's calls send about ${Math.round(tokens / 1000)}K tokens, past budgets.${role}.remindAt (${budget.remindAt}). ` +
47
+ `Finish the current item, commit and push green work, and plan the hand-off. At ${budget.handoffAt}, only the hand-off can run.`,
48
+ },
49
+ };
50
+ }
@@ -0,0 +1,91 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { test } from "node:test";
3
+ import { budgetRoleOf, orchestratorVerdict, roleBudgetVerdict } from "./role-budget.mjs";
4
+
5
+ const budget = { remindAt: 110_000, handoffAt: 150_000 };
6
+ const call = { tool_name: "Bash", tool_input: { command: "npm test" } };
7
+
8
+ test("the orchestrator stays quiet below compactAt and between checking calls", () => {
9
+ const state = {};
10
+ const input = { compactAt: 200_000, state };
11
+ assert.equal(orchestratorVerdict({ ...input, tokens: 199_999, count: 5 }), null);
12
+ assert.equal(orchestratorVerdict({ ...input, tokens: 213_000, count: 4 }), null);
13
+ assert.deepEqual(state, {});
14
+ });
15
+
16
+ test("the orchestrator reminds at compactAt and repeats after twenty calls", () => {
17
+ const state = {};
18
+ const input = { tokens: 213_000, compactAt: 200_000, state };
19
+ const note = orchestratorVerdict({ ...input, count: 5 });
20
+ assert.match(note, /Context budget: this session sends about 213K tokens per call, past budgets\.orchestrator\.compactAt \(200000\)\. Run \/compact/);
21
+ assert.match(note, /Keep the plan path, the open PR numbers, each branch and its head, and the ledger path in the summary\.$/);
22
+ assert.equal(state.budgetFiredAt, 5);
23
+ assert.equal(orchestratorVerdict({ ...input, count: 10 }), null);
24
+ assert.equal(state.budgetFiredAt, 5);
25
+ assert.equal(orchestratorVerdict({ ...input, count: 25 }), note);
26
+ assert.equal(state.budgetFiredAt, 25);
27
+ });
28
+
29
+ test("the orchestrator reminds exactly at compactAt", () => {
30
+ assert.match(orchestratorVerdict({ tokens: 200_000, compactAt: 200_000, count: 5, state: {} }), /about 200K tokens per call/);
31
+ });
32
+
33
+ test("budgetRoleOf resolves the configured roles only while dispatch is on", () => {
34
+ for (const [agentType, role] of [
35
+ ["architecture:sdd-implementer", "implementer"],
36
+ ["architecture:sdd-reviewer", "reviewer"],
37
+ ["sdd-branch-reviewer", "reviewer"],
38
+ ["general-purpose", null],
39
+ ]) {
40
+ assert.equal(budgetRoleOf(agentType, { dispatch: {} }), role);
41
+ assert.equal(budgetRoleOf(agentType, {}), null);
42
+ }
43
+ const swarm = { dispatch: { implementerTypes: ["builder"] }, review: { reviewerTypes: { task: ["checker"] } } };
44
+ assert.equal(budgetRoleOf("builder", swarm), "implementer");
45
+ assert.equal(budgetRoleOf("checker", swarm), "reviewer");
46
+ assert.equal(budgetRoleOf("architecture:sdd-implementer", swarm), null);
47
+ });
48
+
49
+ test("the role budget reminds at the line once", () => {
50
+ const state = {};
51
+ const input = { role: "implementer", budget, call, state };
52
+ assert.equal(roleBudgetVerdict({ ...input, tokens: 109_999 }), null);
53
+ assert.deepEqual(state, {});
54
+ const output = roleBudgetVerdict({ ...input, tokens: 110_000 });
55
+ assert.match(output.hookSpecificOutput.additionalContext, /Context budget: .*finish the current item/i);
56
+ assert.equal(state.budgetReminded, true);
57
+ assert.equal(roleBudgetVerdict({ ...input, tokens: 120_000 }), null);
58
+ });
59
+
60
+ test("each role closes work calls at handoffAt and permits the hand-off", () => {
61
+ for (const role of ["implementer", "reviewer"]) {
62
+ const state = {};
63
+ const input = { role, budget, call, state, tokens: 150_000 };
64
+ const output = roleBudgetVerdict(input).hookSpecificOutput;
65
+ assert.equal(output.permissionDecision, "deny");
66
+ assert.match(output.permissionDecisionReason, role === "implementer" ? /HANDOFF: <note path>/ : /VERDICT:.*UNREVIEWED:/);
67
+ assert.equal(state.budgetClosed, true);
68
+ for (const handoff of [
69
+ { tool_name: "Bash", tool_input: { command: "git push" } },
70
+ { tool_name: "Read", tool_input: { file_path: "src/a.mjs" } },
71
+ { tool_name: "SubagentHandback", tool_input: { message: "DONE" } },
72
+ ]) assert.equal(roleBudgetVerdict({ ...input, call: handoff }), null);
73
+ assert.equal(roleBudgetVerdict({ ...input, tokens: undefined }).hookSpecificOutput.permissionDecision, "deny");
74
+ }
75
+ });
76
+
77
+ test("a reviewer hand-off requires CHANGES_REQUIRED for files left unreviewed", () => {
78
+ const output = roleBudgetVerdict({ role: "reviewer", budget, call, state: {}, tokens: 150_000 });
79
+ assert.match(output.hookSpecificOutput.permissionDecisionReason, /VERDICT: CHANGES_REQUIRED <sha>.*UNREVIEWED:/);
80
+ assert.match(output.hookSpecificOutput.permissionDecisionReason, /partial reviewer's scope needs a new APPROVED review on the head before merge/);
81
+ });
82
+
83
+ test("a reviewer hand-off carries the full review in the final report", () => {
84
+ const output = roleBudgetVerdict({ role: "reviewer", budget, call, state: {}, tokens: 150_000 });
85
+ assert.match(output.hookSpecificOutput.permissionDecisionReason, /full review in (?:the|your) final report/i);
86
+ });
87
+
88
+ test("a disabled role budget or missing usage leaves the call alone", () => {
89
+ assert.equal(roleBudgetVerdict({ role: "implementer", budget: null, call, state: {}, tokens: 160_000 }), null);
90
+ assert.equal(roleBudgetVerdict({ role: "implementer", budget, call, state: {}, tokens: undefined }), null);
91
+ });
@@ -0,0 +1,73 @@
1
+ import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { redactOutput } from "./output-redaction.mjs";
4
+ import { commonDirOf } from "./ledger.mjs";
5
+ import { checkoutRootOf } from "./checkout-root.mjs";
6
+
7
+ export const RUN_ROLES = ["scout", "tests", "implement", "review", "fix"];
8
+ export const RUN_FIELDS = Object.freeze([
9
+ "kind", "time", "branch", "issue", "role", "effort", "exit", "refusal", "inputTokens",
10
+ "outputTokens", "minutes", "verify", "live", "verdict", "findings", "pr", "run", "head", "result",
11
+ ]);
12
+
13
+ /** @returns the local run log shared by this checkout's worktrees, or null outside git. */
14
+ export function runLogFileOf(cwd) {
15
+ const root = checkoutRootOf(cwd);
16
+ const common = root && commonDirOf(root);
17
+ return common ? path.join(common, "qc", "runs.jsonl") : null;
18
+ }
19
+
20
+ /** Append one complete JSON line; the caller owns warnings and exit policy. */
21
+ export function appendRun(file, record) {
22
+ if (!file) throw new Error("cannot find the git common directory");
23
+ record = Object.fromEntries(Object.entries(record).filter(([field]) => RUN_FIELDS.includes(field)));
24
+ const allowedBranch = (value) => value.length <= 100 &&
25
+ /^[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*$/.exec(value)?.[0] === value;
26
+ for (const field of ["branch", "pr", "run", "head"]) {
27
+ if (!Object.hasOwn(record, field)) continue;
28
+ const value = record[field];
29
+ let allowed = false;
30
+ if (field === "pr") {
31
+ allowed = Number.isSafeInteger(value) && value > 0;
32
+ } else if (typeof value === "string" && redactOutput(value) === value) {
33
+ if (field === "head") allowed = /^[0-9a-f]{7,40}$/.exec(value)?.[0] === value;
34
+ else if (field === "branch") allowed = allowedBranch(value);
35
+ else {
36
+ const [workflow, branch, sha, ...extra] = value.split("@");
37
+ allowed = /^[A-Za-z0-9_-]+\.ya?ml$/.exec(workflow)?.[0] === workflow &&
38
+ branch !== undefined && allowedBranch(branch) && extra.length === 0 &&
39
+ (sha === undefined || /^[0-9a-f]{7,40}$/.exec(sha)?.[0] === sha);
40
+ }
41
+ }
42
+ if (!allowed) record[field] = "[REDACTED]";
43
+ }
44
+ mkdirSync(path.dirname(file), { recursive: true });
45
+ appendFileSync(file, `${JSON.stringify(record)}\n`);
46
+ }
47
+
48
+ const valid = (row) => row && !Array.isArray(row) && Number.isFinite(Date.parse(row.time)) && (
49
+ row.kind === "codex" ? RUN_ROLES.includes(row.role) && Number.isInteger(row.exit) && row.exit >= 0 &&
50
+ (row.inputTokens === undefined || Number.isFinite(row.inputTokens) && row.inputTokens >= 0) :
51
+ row.kind === "ci" && ["pass", "fail"].includes(row.result) && Number.isFinite(row.minutes) && row.minutes >= 0
52
+ );
53
+
54
+ /** Missing logs are empty; malformed lines are counted and other read errors propagate. */
55
+ export function readRuns(file) {
56
+ let text;
57
+ try { text = file ? readFileSync(file, "utf8") : ""; }
58
+ catch (error) {
59
+ if (error.code === "ENOENT") return { runs: [], skipped: 0 };
60
+ throw error;
61
+ }
62
+ const runs = [];
63
+ let skipped = 0;
64
+ for (const line of text.split(/\r?\n/)) {
65
+ if (!line.trim()) continue;
66
+ try {
67
+ const row = JSON.parse(line);
68
+ if (!valid(row)) throw new Error("invalid run");
69
+ runs.push(row);
70
+ } catch { skipped += 1; }
71
+ }
72
+ return { runs, skipped };
73
+ }
@@ -0,0 +1,121 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { appendFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { test } from "node:test";
6
+ import { appendRun, readRuns, RUN_FIELDS, runLogFileOf } from "./run-log.mjs";
7
+
8
+ test("run lines share the git common directory, append, and count malformed records", (t) => {
9
+ const dir = mkdtempSync(path.join(os.tmpdir(), "qc-run-log-"));
10
+ t.after(() => rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
11
+ const root = path.join(dir, "root");
12
+ const linked = path.join(dir, "linked");
13
+ const gitDir = path.join(root, ".git", "worktrees", "linked");
14
+ mkdirSync(gitDir, { recursive: true });
15
+ mkdirSync(linked);
16
+ writeFileSync(path.join(linked, ".git"), `gitdir: ${gitDir}\n`);
17
+ writeFileSync(path.join(gitDir, "commondir"), "../..\n");
18
+ const file = runLogFileOf(root);
19
+ assert.equal(runLogFileOf(linked), file);
20
+ assert.equal(runLogFileOf(dir), null);
21
+ assert.deepEqual(readRuns(file), { runs: [], skipped: 0 });
22
+ const rows = [
23
+ { kind: "codex", time: "2026-11-20T00:00:00.000Z", role: "implement", exit: 0 },
24
+ { kind: "ci", time: "2026-11-21T00:00:00.000Z", pr: 249, head: "abcdef0", result: "pass", minutes: 1.2 },
25
+ ];
26
+ appendRun(file, rows[0]);
27
+ appendFileSync(file, "bad\nnull\n[]\n{}\n");
28
+ appendRun(file, rows[1]);
29
+ assert.deepEqual(readRuns(file), { runs: rows, skipped: 4 });
30
+ assert.throws(() => readRuns(path.dirname(file)), /EISDIR|EPERM|EACCES/);
31
+ });
32
+
33
+
34
+ test("run log keeps only allowlisted branch, PR and workflow fields", (t) => {
35
+ const dir = mkdtempSync(path.join(os.tmpdir(), "qc-run-fields-"));
36
+ t.after(() => rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
37
+ const file = path.join(dir, "runs.jsonl");
38
+ const redacted = "[REDACTED]";
39
+ const secrets = [
40
+ `AKIA${"A".repeat(16)}`, `aws_secret_access_key=${"a".repeat(40)}`,
41
+ `ghp_${"a".repeat(36)}`, `github_pat_${"a".repeat(40)}`,
42
+ ["-----BEGIN", "PRIVATE KEY-----"].join(" "), `sk-ant-${"a".repeat(20)}`,
43
+ `xoxb-${"a".repeat(10)}`, `npm_${"a".repeat(36)}`,
44
+ "private.example.com", "https://internal/path", "\\\\internal\\share",
45
+ ];
46
+ const rejected = [
47
+ "topic/\u4f8b\u5b50.\u6d4b\u8bd5", "topic/private.example.com_release", "topic/10.20.30.40",
48
+ "topic/fe80::1", "/tmp/x", "../x", "C:\\x", "a b", "release/1.2.3", "fix/readme.md",
49
+ "", "topic\n", "topic/", "topic//x", "a".repeat(101), ...secrets.map((secret) => `topic/${secret}`),
50
+ ];
51
+ const cases = [
52
+ ["branch", "feat/249-run-metrics", "feat/249-run-metrics"],
53
+ ["branch", "a".repeat(100), "a".repeat(100)],
54
+ ["run", "ci.yml@feat/249-x", "ci.yml@feat/249-x"],
55
+ ["run", `ci.yml@topic@${"a".repeat(40)}`, `ci.yml@topic@${"a".repeat(40)}`],
56
+ ["run", "ci.yaml@topic@abcdef0", "ci.yaml@topic@abcdef0"],
57
+ ["pr", 254, 254],
58
+ ["pr", Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
59
+ ...rejected.flatMap((value) => [["branch", value, redacted], ["run", `ci.yml@${value}`, redacted]]),
60
+ ...secrets.map((value) => ["pr", value, redacted]),
61
+ ...["12", 0, -1, 1.5, Number.MAX_SAFE_INTEGER + 1, null, true, {}, []]
62
+ .map((value) => ["pr", value, redacted]),
63
+ ...["/tmp/ci.yml@feat/x", "ci.yml@topic@abcdef", `ci.yml@topic@${"a".repeat(41)}`,
64
+ "ci.yml@topic@ABCDEF0", "ci.yml@topic@abcdef0@abcdef0", "ci.txt@topic", "ci.yml\n@topic", "ci.yml@topic@abcdef0\n", "topic", 254]
65
+ .map((value) => ["run", value, redacted]),
66
+ ...[254, null, true, {}, []].map((value) => ["branch", value, redacted]),
67
+ ];
68
+ for (const [field, value] of cases) {
69
+ appendRun(file, { kind: "ci", time: "2026-11-21T00:00:00Z", result: "pass", minutes: 1,
70
+ [field]: value });
71
+ }
72
+ const { runs } = readRuns(file);
73
+ assert.equal(runs.length, cases.length);
74
+ for (const [index, [field, value, expected]] of cases.entries()) {
75
+ assert.equal(runs[index][field], expected, `${field}: ${JSON.stringify(value)}`);
76
+ }
77
+ });
78
+
79
+
80
+ test("run log drops unknown fields without changing the caller's record", (t) => {
81
+ const dir = mkdtempSync(path.join(os.tmpdir(), "qc-run-unknown-"));
82
+ t.after(() => rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
83
+ const file = path.join(dir, "runs.jsonl");
84
+ const row = { kind: "ci", time: "2026-11-21T00:00:00Z", result: "pass", minutes: 1 };
85
+ const record = { ...row, unexpected: "private data" };
86
+ appendRun(file, record);
87
+ assert.deepEqual(readRuns(file).runs, [row]);
88
+ assert.equal(record.unexpected, "private data");
89
+ });
90
+
91
+ test("run log keeps lowercase hexadecimal heads of 7 to 40 characters", (t) => {
92
+ const dir = mkdtempSync(path.join(os.tmpdir(), "qc-run-good-head-"));
93
+ t.after(() => rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
94
+ const file = path.join(dir, "runs.jsonl");
95
+ const heads = ["abcdef0", "0123456789abcdef", "a".repeat(40)];
96
+ for (const head of heads) {
97
+ appendRun(file, { kind: "ci", time: "2026-11-21T00:00:00Z", result: "pass", minutes: 1, head });
98
+ }
99
+ assert.deepEqual(readRuns(file).runs.map((row) => row.head), heads);
100
+ });
101
+
102
+ test("run log redacts heads with invalid content or types", (t) => {
103
+ const dir = mkdtempSync(path.join(os.tmpdir(), "qc-run-bad-head-"));
104
+ t.after(() => rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
105
+ const file = path.join(dir, "runs.jsonl");
106
+ const heads = ["", "abcdef", "a".repeat(41), "ABCDEF0", "abcdefg", "abcdef0\n",
107
+ " abcdef0", "abcdef0 ", "private.example.com", 1234567, null, true, {}, [], undefined];
108
+ for (const head of heads) {
109
+ appendRun(file, { kind: "ci", time: "2026-11-21T00:00:00Z", result: "pass", minutes: 1, head });
110
+ }
111
+ assert.deepEqual(readRuns(file).runs.map((row) => row.head), heads.map(() => "[REDACTED]"));
112
+ });
113
+
114
+
115
+ test("run fields exports the frozen field contract", () => {
116
+ assert.equal(Object.isFrozen(RUN_FIELDS), true);
117
+ assert.deepEqual(RUN_FIELDS, [
118
+ "kind", "time", "branch", "issue", "role", "effort", "exit", "refusal", "inputTokens",
119
+ "outputTokens", "minutes", "verify", "live", "verdict", "findings", "pr", "run", "head", "result",
120
+ ]);
121
+ });
@@ -0,0 +1,16 @@
1
+ /** Fragment: finds the secret shapes shared with pr-autopilot's commit guard. */
2
+ export const secretPatterns = [
3
+ ["aws-access-key", /A[KS]IA[0-9A-Z]{16}/],
4
+ ["aws-secret-key", /(?<![A-Za-z0-9])aws[_-]secret[_-]access[_-]key\b["']?(?:\s*[:=?+!<>-]{1,3}\s*|\s+)["']?[A-Za-z0-9/+=]{40}(?![A-Za-z0-9/+=])/i],
5
+ ["github-token", /gh[pousr]_[A-Za-z0-9]{36,}/],
6
+ ["github-pat", /github_pat_[A-Za-z0-9_]{40,}/],
7
+ ["private-key", /-----BEGIN [A-Z ]*PRIVATE KEY-----/],
8
+ ["anthropic-key", /sk-ant-[A-Za-z0-9_-]{20,}/],
9
+ ["slack-token", /xox[abprs]-[A-Za-z0-9-]{10,}/],
10
+ ["npm-token", /npm_[A-Za-z0-9]{36}/],
11
+ ];
12
+
13
+ export function findSecrets(line) {
14
+ if (line.includes("qc-allow-secret")) return [];
15
+ return secretPatterns.filter(([, pattern]) => pattern.test(line)).map(([rule]) => rule);
16
+ }