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,188 @@
1
+ import assert from "node:assert/strict";
2
+ import { createHash } from "node:crypto";
3
+ import { execFileSync } from "node:child_process";
4
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import test from "node:test";
8
+ import { DONE_MARKER, runCodexImplement } from "./codex-implement.mjs";
9
+
10
+ const quiet = () => {};
11
+ const source = (n, pass = false) => `import test from 'node:test';\n${Array.from({ length: n }, (_, i) => `test('acceptance ${i}', () => { ${pass ? "" : "throw new Error('red');"} });`).join("\n")}\n`;
12
+
13
+ function fixture(t, role = "implement", config = {}) {
14
+ const root = mkdtempSync(path.join(os.tmpdir(), "qc-locked-tests-"));
15
+ t.after(() => rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
16
+ const worktree = path.join(root, "repo");
17
+ mkdirSync(worktree);
18
+ const git = (...args) => execFileSync("git", ["-c", "user.name=Test", "-c", "user.email=test@example.test", ...args], { cwd: worktree, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
19
+ git("init", "-qb", "feature/acceptance");
20
+ writeFileSync(path.join(worktree, "qc.config.json"), JSON.stringify({ check: { base: "base" }, ...config }));
21
+ writeFileSync(path.join(worktree, "value.mjs"), "export const value = false;\n");
22
+ git("add", "."); git("commit", "-qm", "base"); git("branch", "base");
23
+ const base = git("rev-parse", "HEAD");
24
+ const brief = path.join(root, "brief.md");
25
+ const progress = path.join(root, "progress.md");
26
+ writeFileSync(brief, "# Brief\nPaths: `*.mjs`, `qc.config.json`\n## Product decisions\n- Test the runner.\n## Task\n1. Run.\n## Design\nUse the existing dependencies.\n");
27
+ const lock = path.join(worktree, ".git", "qc", "locked-tests", `${encodeURIComponent("feature/acceptance")}.json`);
28
+ const file = path.join(worktree, "acceptance.test.mjs");
29
+ const seal = () => {
30
+ mkdirSync(path.dirname(lock), { recursive: true });
31
+ writeFileSync(lock, JSON.stringify({ "acceptance.test.mjs": createHash("sha256").update(readFileSync(file)).digest("hex") }));
32
+ };
33
+ const messages = [];
34
+ const checks = [];
35
+ const run = (change, extra = {}) => runCodexImplement(["--brief", brief, "--worktree", worktree, "--progress", progress, "--role", role], {
36
+ say: (line) => messages.push(line), out: quiet,
37
+ runCheck: async (command, cwd) => { checks.push({ command, cwd }); return 0; },
38
+ run: async () => { await change?.(); writeFileSync(progress, DONE_MARKER); return { status: 0 }; }, ...extra,
39
+ });
40
+ return { root, worktree, git, base, progress, lock, file, seal, run, messages, checks };
41
+ }
42
+
43
+ test("nine new cases in a tests run → exit 4 naming the cap 8", async (t) => {
44
+ for (const state of ["untracked", "staged", "committed"]) {
45
+ const f = fixture(t, "tests");
46
+ assert.equal(await f.run(() => {
47
+ writeFileSync(f.file, source(9));
48
+ if (state !== "untracked") f.git("add", ".");
49
+ if (state === "committed") f.git("commit", "-qm", "acceptance");
50
+ }), 4);
51
+ assert.match(f.messages.join("\n"), /maxNewCases.*8/);
52
+ assert.equal(existsSync(f.lock), false);
53
+ }
54
+ const f = fixture(t, "tests");
55
+ assert.equal(await f.run(() => writeFileSync(f.file, source(8))), 0);
56
+ const { addedTestCases, checkLockedTests } = await import("./locked-tests.mjs");
57
+ assert.equal(addedTestCases(f.worktree, f.base).length, 8);
58
+ assert.deepEqual(checkLockedTests(f.worktree), { problems: [] });
59
+ assert.deepEqual(Object.keys(JSON.parse(readFileSync(f.lock))), ["acceptance.test.mjs"]);
60
+ assert.equal(f.git("worktree", "list", "--porcelain").match(/^worktree /gm).length, 1);
61
+ const counted = fixture(t, "tests");
62
+ writeFileSync(counted.file, "// test('comment', () => {});\nconst text = \"test('string')\";\n test.only('only', () => {});\nit.skip('skip', () => {});\nit('plain', () => {});\n");
63
+ counted.git("add", ".");
64
+ counted.git("commit", "-qm", "registrations");
65
+ assert.deepEqual(addedTestCases(counted.worktree, counted.base).map((entry) => entry.name), ["only", "skip", "plain"]);
66
+ assert.deepEqual(addedTestCases(counted.worktree, counted.git("rev-parse", "HEAD")), []);
67
+ const option = fixture(t, "tests");
68
+ assert.equal(await option.run(() => writeFileSync(path.join(option.worktree, "--acceptance.test.mjs"), source(1, true))), 4);
69
+ assert.match(option.messages.join("\n"), /--acceptance.test.mjs.*acceptance 0/);
70
+ assert.equal(existsSync(option.lock), false);
71
+ const { lockTests } = await import("./locked-tests.mjs");
72
+ const linked = path.join(counted.root, "linked");
73
+ counted.git("worktree", "add", "-qb", "other/tests", linked);
74
+ lockTests(linked, ["acceptance.test.mjs"]);
75
+ assert.ok(existsSync(path.join(counted.worktree, ".git/qc/locked-tests/other%2Ftests.json")));
76
+ });
77
+
78
+ test("a new test that passes on the base → exit 4 naming the test", async (t) => {
79
+ const f = fixture(t, "tests");
80
+ assert.equal(await f.run(() => writeFileSync(f.file, source(1, true))), 4);
81
+ assert.match(f.messages.join("\n"), /acceptance.test.mjs.*acceptance 0/);
82
+ assert.equal(existsSync(f.lock), false);
83
+ assert.equal(f.git("worktree", "list", "--porcelain").match(/^worktree /gm).length, 1);
84
+ // The merge base, rather than the run-start HEAD, must supply implementation code.
85
+ const green = fixture(t, "tests");
86
+ writeFileSync(path.join(green.worktree, "value.mjs"), "export const value = true;\n");
87
+ green.git("add", "."); green.git("commit", "-qm", "implementation");
88
+ assert.equal(await green.run(() => writeFileSync(green.file, "import test from 'node:test';\nimport { value } from './value.mjs';\ntest('requires implementation', () => { if (!value) throw Error('base red'); });\n")), 0);
89
+ const escaped = fixture(t, "tests");
90
+ const outside = path.join(escaped.root, "outside");
91
+ mkdirSync(outside);
92
+ symlinkSync(outside, path.join(escaped.worktree, "suite"), "dir");
93
+ escaped.git("add", "."); escaped.git("commit", "-qm", "base symlink");
94
+ escaped.git("branch", "-f", "base", "HEAD");
95
+ rmSync(path.join(escaped.worktree, "suite"));
96
+ mkdirSync(path.join(escaped.worktree, "suite", "created-outside"), { recursive: true });
97
+ writeFileSync(path.join(escaped.worktree, "suite", "created-outside", "a.test.mjs"), source(1));
98
+ const { verifyBaseTests } = await import("./locked-tests.mjs");
99
+ await assert.rejects(verifyBaseTests(escaped.worktree, escaped.git("rev-parse", "base"), [{ path: "suite/created-outside/a.test.mjs", name: "acceptance 0" }]), /unsafe base test path/);
100
+ assert.equal(existsSync(path.join(outside, "created-outside")), false);
101
+ assert.equal(existsSync(escaped.lock), false);
102
+ assert.equal(escaped.git("worktree", "list", "--porcelain").match(/^worktree /gm).length, 1);
103
+ const mutation = fixture(t, "tests");
104
+ const external = path.join(mutation.root, "outside");
105
+ mkdirSync(external);
106
+ mkdirSync(path.join(mutation.worktree, "suite"));
107
+ writeFileSync(path.join(mutation.worktree, "a.test.mjs"), `import { symlinkSync } from 'node:fs';\nsymlinkSync(${JSON.stringify(external)}, 'suite', 'dir');\nprocess.exit(1);\n`);
108
+ writeFileSync(path.join(mutation.worktree, "suite", "b.test.mjs"), "process.exit(1);\n");
109
+ assert.deepEqual(await verifyBaseTests(mutation.worktree, mutation.base, [
110
+ { path: "a.test.mjs", name: "mutates parent" },
111
+ { path: "suite/b.test.mjs", name: "stays inside" },
112
+ ]), { problems: [] });
113
+ assert.equal(existsSync(path.join(external, "b.test.mjs")), false);
114
+ assert.equal(mutation.git("worktree", "list", "--porcelain").match(/^worktree /gm).length, 1);
115
+ const custom = fixture(t, "tests", { tests: { command: [process.execPath, "probe.mjs"] } });
116
+ writeFileSync(path.join(custom.worktree, "probe.mjs"), "import { appendFileSync } from 'node:fs';\nappendFileSync(process.argv[2] + '.ran', 'yes');\nprocess.exit(7);\n");
117
+ custom.git("add", "."); custom.git("commit", "-qm", "custom runner");
118
+ custom.git("branch", "-f", "base", "HEAD");
119
+ assert.equal(await custom.run(() => writeFileSync(custom.file, source(1))), 0);
120
+ assert.equal(custom.git("worktree", "list", "--porcelain").match(/^worktree /gm).length, 1);
121
+ });
122
+
123
+ test("locked file edited → exit 4", async (t) => {
124
+ for (const mode of ["edit", "delete", "cap", "tamper lock", "delete lock"]) {
125
+ const f = fixture(t);
126
+ writeFileSync(f.file, source(1, true)); f.git("add", "."); f.git("commit", "-qm", "tests"); f.seal();
127
+ assert.equal(await f.run(() => {
128
+ if (mode === "edit") writeFileSync(f.file, source(2, true));
129
+ if (mode === "delete") rmSync(f.file);
130
+ if (mode === "cap") writeFileSync(path.join(f.worktree, "extra.test.mjs"), source(5, true));
131
+ if (mode === "tamper lock") { writeFileSync(f.file, source(2, true)); f.seal(); }
132
+ if (mode === "delete lock") rmSync(f.lock);
133
+ }), 4);
134
+ assert.match(f.messages.join("\n"), mode === "cap" ? /maxExtraCases.*4/ : /acceptance.test.mjs/);
135
+ assert.equal(f.checks.length, 0);
136
+ }
137
+ });
138
+
139
+ test("locked file renamed → exit 4", async (t) => {
140
+ const f = fixture(t);
141
+ writeFileSync(f.file, source(1, true)); f.git("add", "."); f.git("commit", "-qm", "tests"); f.seal();
142
+ assert.equal(await f.run(() => renameSync(f.file, path.join(f.worktree, "renamed.test.mjs"))), 4);
143
+ assert.match(f.messages.join("\n"), /acceptance.test.mjs/);
144
+ });
145
+
146
+ test("marker written but a locked test fails → exit 3, not 0", async (t) => {
147
+ for (const existing of [false, true]) {
148
+ const option = fixture(t);
149
+ const optionFile = path.join(option.worktree, "--acceptance.test.mjs");
150
+ writeFileSync(optionFile, source(1, true));
151
+ option.git("add", "."); option.git("commit", "-qm", "option-like test");
152
+ mkdirSync(path.dirname(option.lock), { recursive: true });
153
+ writeFileSync(option.lock, JSON.stringify({ "--acceptance.test.mjs": createHash("sha256").update(readFileSync(optionFile)).digest("hex") }));
154
+ if (existing) writeFileSync(option.progress, DONE_MARKER);
155
+ assert.equal(await option.run(), 0);
156
+ assert.equal(option.checks.length, 1);
157
+ const f = fixture(t);
158
+ writeFileSync(f.file, source(1)); f.git("add", "."); f.git("commit", "-qm", "tests"); f.seal();
159
+ if (existing) writeFileSync(f.progress, DONE_MARKER);
160
+ assert.equal(await f.run(), 3);
161
+ }
162
+ for (const checkStatus of [0, 1]) {
163
+ const f = fixture(t);
164
+ writeFileSync(f.file, source(1, true)); f.git("add", "."); f.git("commit", "-qm", "tests"); f.seal();
165
+ writeFileSync(f.progress, DONE_MARKER);
166
+ assert.equal(await f.run(undefined, { runCheck: async (command, cwd) => {
167
+ assert.deepEqual(command, ["npx", "qc", "check"]); assert.equal(cwd, f.worktree); return checkStatus;
168
+ } }), checkStatus === 0 ? 0 : 3);
169
+ }
170
+ const custom = fixture(t, "implement", { tests: { command: [process.execPath, "probe.mjs", "--literal"] } });
171
+ writeFileSync(path.join(custom.worktree, "probe.mjs"), "import { writeFileSync } from 'node:fs';\nwriteFileSync('args.json', JSON.stringify(process.argv.slice(2)));\n");
172
+ writeFileSync(custom.file, source(1)); custom.git("add", "."); custom.git("commit", "-qm", "custom runner"); custom.seal();
173
+ assert.equal(await custom.run(), 0);
174
+ assert.deepEqual(JSON.parse(readFileSync(path.join(custom.worktree, "args.json"))), ["--literal", custom.file]);
175
+ assert.equal(custom.checks.length, 1);
176
+ const incomplete = fixture(t);
177
+ writeFileSync(incomplete.file, source(1, true)); incomplete.git("add", "."); incomplete.git("commit", "-qm", "tests"); incomplete.seal();
178
+ assert.equal(await incomplete.run(undefined, { run: async () => ({ status: 0 }) }), 3);
179
+ assert.equal(incomplete.checks.length, 1);
180
+ });
181
+
182
+ test("without a lock the runner keeps its existing exits and does not run tests", async (t) => {
183
+ for (const marked of [false, true]) {
184
+ const f = fixture(t);
185
+ assert.equal(await f.run(() => writeFileSync(f.file, source(9)), marked ? {} : { run: async () => ({ status: 0 }) }), marked ? 0 : 3);
186
+ assert.deepEqual(f.checks, []);
187
+ }
188
+ });
@@ -1,17 +1,30 @@
1
1
  #!/usr/bin/env node
2
2
  // The trigger that holds `gh pr merge` to its review. Before the call it needs `--match-head-commit` and an
3
- // APPROVED review of `swarm.review.merge` for that sha, or a head inside the direct lane of `swarm.direct`.
3
+ // APPROVED review of `swarm.review.merge` for that sha, or a head inside the direct or integration lane.
4
4
  // After the call it records the merge and its issues.
5
- // A merge that names another repository than the checkout's `origin` is that repository's own, so it passes.
6
- // With `swarm.dispatch` off, the record is still written for the worktree check of QC-015, and nothing is judged.
5
+ // A `gh pr merge` that names another repository than the checkout's `origin` is that repository's own, so it passes.
6
+ // A raw API merge, REST or GraphQL, reads the base policy of its PR. It passes with `swarm.dispatch` off.
7
+ // It denies with dispatch on, or when the guard cannot read the PR or its base.
8
+ // Any `gh api graphql` call that mixes `--input` with a field denies, whether it reads or writes.
9
+ // This applies in every checkout, with `swarm.dispatch` on or off.
7
10
 
11
+ import { commentWatch } from "./comment-watch.mjs";
8
12
  import { fileURLToPath } from "node:url";
13
+ import { defaults, PROMOTION_SCOPE } from "../config.mjs";
9
14
  import { PARSERS } from "./bash-command-guard.mjs";
10
- import { LANE_BUDGET_MS, mergeLane, sizeLine } from "./direct-lane.mjs";
15
+ import { checkoutRootOf } from "./checkout-root.mjs";
16
+ import { configAtBase, gitBy, LANE_BUDGET_MS, mergeLane, sizeLine } from "./direct-lane.mjs";
11
17
  import { ghApiMerges, ghMerges } from "./gh-merge-command.mjs";
12
- import { runGh } from "./gh-run.mjs";
13
- import { originOf, repoOfSpelling } from "./git-read.mjs";
14
- import { appendRecord, decidingVerdictFor, dispatchedScopesFor, latestVerdictFor, readLedger } from "./ledger.mjs";
18
+ import { runGh, runGhAsync, runGhResult } from "./gh-run.mjs";
19
+ import { gitOutWithin, originOf, repoOfSpelling } from "./git-read.mjs";
20
+ import { globMatcher } from "../glob.mjs";
21
+ import { MILESTONE_PATTERN } from "./milestone.mjs";
22
+ import { integrationLane } from "./integration-lane.mjs";
23
+ import { checkMergeTrees } from "./integrate-tree.mjs";
24
+ import { appendRecord, decidingVerdictFor, readLedger } from "./ledger.mjs";
25
+ import { promotionBranchName } from "./promotion-branch.mjs";
26
+ import { pauseRefusal, holdRefusal } from "./pause.mjs";
27
+ import { lessonRefusal, resolvedFailures } from "./ci-failures.mjs";
15
28
  import { workflowAt } from "./workflow-settings.mjs";
16
29
  import { worktreeRuleAt } from "./worktree-settings.mjs";
17
30
 
@@ -30,25 +43,20 @@ const context = (text) => ({ hookSpecificOutput: { hookEventName: "PreToolUse",
30
43
  * Judges each merge: an APPROVED review of `kind` on its head, or else the direct lane that `lane(merge)` decides.
31
44
  * @returns `{ refusal }` for the first merge that may not run, or `{ refusal: null, direct }` with the lane notes.
32
45
  */
33
- export function mergeVerdict(merges, records, kind, lane = null) {
46
+ export function mergeVerdict(merges, records, kind, lane = null, promotion = null, runtime = "claude") {
34
47
  const direct = [];
48
+ const kinds = runtime === "codex" ? [kind, "codex"] : [kind];
49
+ const reviews = records.filter((record) => record.kind !== "codex" || record.scope == null);
35
50
  for (const merge of merges) {
36
51
  if (!merge.sha) {
37
52
  return { refusal: `Merge guard: \`gh pr merge\` must pass \`--match-head-commit <sha>\` with the head the ${kind} review approved, so a push after the review cannot merge unreviewed. Add it.` };
38
53
  }
39
- const verdict = decidingVerdictFor(records, merge.sha, [kind]);
40
- const missing = dispatchedScopesFor(records, merge.sha).find(
41
- (scope) => latestVerdictFor(records, merge.sha, [kind], scope)?.verdict !== "APPROVED",
42
- );
43
- if (verdict?.verdict === "APPROVED" && missing === undefined) continue;
44
- if (missing !== undefined) {
45
- return {
46
- refusal:
47
- `Merge guard: the ledger holds no APPROVED ${kind} review of scope "${missing}" on ${merge.sha}, and a review of that scope was dispatched. ` +
48
- `Dispatch ${REVIEWER[kind]} with \`Scope: ${missing}\` on that head, and merge after every scope approves.`,
49
- };
54
+ const verdict = decidingVerdictFor(reviews, merge.sha, kinds);
55
+ if (verdict?.kind === "codex" && verdict.verdict === "CHANGES_REQUIRED") {
56
+ return { refusal: `Merge guard: the latest Codex review of ${merge.sha} is CHANGES_REQUIRED. Run a Codex review on that head, and merge after it approves.` };
50
57
  }
51
- const fit = lane ? lane(merge) : null;
58
+ if (verdict?.verdict === "APPROVED") continue;
59
+ const fit = !promotion && lane ? lane(merge) : null;
52
60
  if (fit && fit.problem === null) {
53
61
  direct.push(fit.note);
54
62
  continue;
@@ -69,29 +77,132 @@ export function mergeVerdict(merges, records, kind, lane = null) {
69
77
  /** @returns the reason the first of `merges` may not run, or null when each pins an approved head. */
70
78
  export const mergeRefusal = (merges, records, kind, lane = null) => mergeVerdict(merges, records, kind, lane).refusal;
71
79
 
72
- /** The base the PR of `merge` merges into, as gh reads it before the merge: `{ name, oid }`, or null. `oid` is null when gh names none. */
73
- function prBaseOf(merge, cwd, gh, timeoutMs) {
74
- const args = ["pr", "view", ...(merge.selector ? [merge.selector] : []), ...(merge.repo ? ["-R", merge.repo] : []), "--json", "baseRefName,baseRefOid"];
80
+ /** The PR base selects its review policy; its head identifies a promotion. Missing base details keep the guard closed. */
81
+ function prBaseOf(merge, cwd, gh, deadline) {
82
+ const read = (args) => {
83
+ const timeoutMs = deadline - Date.now();
84
+ if (timeoutMs <= 0) return null;
85
+ const options = { cwd, env: merge.env, timeoutMs };
86
+ if (gh !== runGh) return gh(args, options);
87
+ const result = runGhResult(args, options);
88
+ if (result.status !== 0) throw new Error(result.stderr?.trim() || result.error?.message || "gh failed to read the PR base");
89
+ return result.stdout;
90
+ };
91
+ const args = merge.nodeId
92
+ ? ["api", "graphql", "-f", "query=query($id: ID!) { node(id:$id){... on PullRequest{number baseRefName baseRefOid repository{nameWithOwner} labels(first:100){nodes{name} pageInfo{hasNextPage}} headRefName isCrossRepository}}}", "-f", `id=${merge.nodeId}`]
93
+ : ["pr", "view", ...(merge.selector ? [merge.selector] : []), ...(merge.repo ? ["-R", merge.repo] : []), "--json", "baseRefName,headRefName,number,isCrossRepository,labels"];
94
+ const answer = JSON.parse(read(args) ?? "null");
95
+ const pr = merge.nodeId ? answer?.data?.node : answer;
96
+ if (merge.nodeId && (answer?.errors?.length || !Number.isInteger(pr?.number) || pr.number <= 0 ||
97
+ typeof pr?.baseRefOid !== "string" || !pr.baseRefOid || typeof pr?.repository?.nameWithOwner !== "string" || !pr.repository.nameWithOwner)) return null;
98
+ if (typeof pr?.baseRefName !== "string") return null;
99
+ const ref = pr.baseRefName.split("/").map(encodeURIComponent).join("/");
100
+ const oid = merge.nodeId ? pr.baseRefOid : read(["api", `repos/${merge.repo || "{owner}/{repo}"}/git/ref/heads/${ref}`, ...(merge.host ? ["--hostname", merge.host] : []), "--jq", ".object.sha"])?.trim();
101
+ return { name: pr.baseRefName, oid: oid || null, head: pr.headRefName ?? null, number: Number.isInteger(pr.number) && pr.number > 0 ? pr.number : null, sameRepository: pr.isCrossRepository === false,
102
+ labels: merge.nodeId ? pr.labels?.nodes : pr.labels,
103
+ moreLabels: merge.nodeId ? pr.labels?.pageInfo?.hasNextPage !== false : pr.labels?.length >= 100 };
104
+ }
105
+
106
+ /** Record: a hold refusal that waits for the operator. */
107
+ class HoldRefusal extends Error {}
108
+
109
+ /** The fragment that reads one merge's PR base and workflow within the shared deadline. */
110
+ function policyOf(merge, root, cwd, gh, deadline) {
111
+ let pr;
75
112
  try {
76
- const pr = JSON.parse(gh(args, { cwd, env: merge.env, timeoutMs }) ?? "null");
77
- return typeof pr?.baseRefName === "string" ? { name: pr.baseRefName, oid: pr.baseRefOid ?? null } : null;
78
- } catch {
79
- return null;
113
+ pr = prBaseOf(merge, cwd, gh, deadline);
114
+ } catch (error) {
115
+ if (Date.now() >= deadline) throw new Error("gh cannot read the base branch of the PR within the time budget of the lane");
116
+ throw new Error(`gh cannot read the base branch of the PR: ${String(error.message ?? error).split(/\r?\n/)[0]}`);
117
+ }
118
+ if (Date.now() >= deadline) throw new Error("gh cannot read the base branch of the PR within the time budget of the lane");
119
+ if (!pr) throw new Error("gh cannot read the base branch of the PR");
120
+ const git = (dir, ...args) => {
121
+ const remaining = deadline - Date.now();
122
+ return remaining > 0 ? gitOutWithin(remaining, dir, ...args) : null;
123
+ };
124
+ git.late = () => Date.now() >= deadline;
125
+ const settings = configAtBase(root, pr.oid, git, "the PR base");
126
+ if (settings.problem) throw new Error(settings.problem);
127
+ const mergeConfig = settings.config?.merge;
128
+ if (mergeConfig !== undefined && (mergeConfig === null || typeof mergeConfig !== "object" || Array.isArray(mergeConfig))) {
129
+ throw new Error("merge in qc.config.json must be an object");
130
+ }
131
+ const holdLabel = mergeConfig?.holdLabel === undefined ? defaults.merge.holdLabel : mergeConfig.holdLabel;
132
+ if (typeof holdLabel !== "string" || !holdLabel.trim() || holdLabel !== holdLabel.trim()) {
133
+ throw new Error("merge.holdLabel must be a non-empty string without surrounding whitespace");
134
+ }
135
+ if (pr.moreLabels || !Array.isArray(pr.labels) || pr.labels.some((label) => typeof label?.name !== "string")) {
136
+ throw new Error("gh cannot read every PR label");
80
137
  }
138
+ if (pr.labels.some((label) => label.name.toLowerCase() === holdLabel.trim().toLowerCase())) {
139
+ throw new HoldRefusal(`PR label "${holdLabel}" holds this merge. Wait for the operator to remove the label.`);
140
+ }
141
+ const lessons = { ...defaults.lessons, ...settings.config?.lessons };
142
+ if (pr.head && pr.sameRepository) {
143
+ const hold = holdRefusal(root, pr.head);
144
+ if (hold) throw new HoldRefusal(hold);
145
+ const failures = resolvedFailures(root, pr.head, { merging: true });
146
+ if (failures.length) {
147
+ const text = /^[0-9a-f]{7,40}$/i.test(merge.sha ?? "") ? git(root, "show", `${merge.sha}:${lessons.file}`) : null;
148
+ const refusal = lessonRefusal(root, pr.head, text, failures);
149
+ if (refusal) throw new HoldRefusal(refusal.replace(/^Merge guard: /, ""));
150
+ }
151
+ }
152
+ return { pr, workflow: workflowAt(root, { baseOid: pr.oid, git }) };
81
153
  }
82
154
 
83
- /**
84
- * The direct lane of one workflow, as `mergeVerdict` asks it. Null while the checkout's `swarm.direct` is false; a wrong
85
- * value names itself. The lane judges against the base commit that gh names for the PR, so no local ref decides.
86
- * A PR into a branch other than `worktree.base` stays out of it. The merges of one call share one time budget.
87
- */
88
- function laneOf(workflow, records, cwd, gh) {
155
+ /** The fragment that names a REST or GraphQL merge's PR; null when the call cannot name one. */
156
+ function apiPrOf({ endpoint, env, nodeId }) {
157
+ const { GH_REPO, ...settings } = env;
158
+ const host = /^https?:\/\/([^/]+)\//.exec(endpoint)?.[1];
159
+ if (host) settings.GH_HOST = host === "api.github.com" ? "github.com" : host;
160
+ if (nodeId !== undefined) return nodeId ? { nodeId, env: settings } : null;
161
+ const match = /^(?:https?:\/\/([^/]+)\/(?:api\/v3\/)?)?\/?(?:repos\/([^/]+\/[^/]+)\/)?pulls\/(\d+)\/merge\/?(?:\?.*)?$/.exec(endpoint);
162
+ if (!match || /[{}]/.test(endpoint.replace("repos/{owner}/{repo}/", "repos/owner/repo/"))) return null;
163
+ const repo = match[2] === "{owner}/{repo}" ? GH_REPO ?? null : match[2] ?? GH_REPO ?? null;
164
+ return { selector: match[3], repo, env: settings };
165
+ }
166
+
167
+ /** A milestone must retain an approval on every pinned member, even if its aggregate head was reviewed. */
168
+ function milestoneLane(workflow, records, pr, sha, deadline) {
169
+ const git = gitBy(deadline - Date.now());
170
+ const policy = configAtBase(workflow.root, pr.oid, git, "the PR base");
171
+ if (policy.problem) return { problem: policy.problem };
172
+ if ((policy.config?.integrate?.review ?? defaults.integrate.review) !== true) return { problem: "milestone integration lane disabled by integrate.review" };
173
+ if (!pr.sameRepository) return { problem: "milestone must belong to the same repository" };
174
+ const root = workflow.root;
175
+ const commits = git(root, "log", "--first-parent", "--format=%H %P", sha, "--not", pr.oid);
176
+ if (commits === null) return { problem: "cannot read milestone history" };
177
+ const kinds = workflow.review.runtime === "codex" ? [workflow.review.merge, "codex"] : [workflow.review.merge];
178
+ const generated = globMatcher(policy.config?.generated?.globs ?? defaults.generated.globs);
179
+ const merges = [];
180
+ let heads = 0;
181
+ for (const line of commits.split("\n").filter(Boolean)) {
182
+ const [commit, ...parents] = line.split(" ");
183
+ if (parents.length === 2) {
184
+ const member = parents[1];
185
+ if (decidingVerdictFor(records, member, kinds)?.verdict !== "APPROVED") return { problem: `milestone member ${member} holds no APPROVED review` };
186
+ merges.push(commit);
187
+ heads++;
188
+ } else if (parents.length === 1) {
189
+ const subject = git(root, "show", "-s", "--format=%s", commit);
190
+ const files = git(root, "diff-tree", "--root", "-r", "--no-commit-id", "--raw", "-z", "--no-renames", commit);
191
+ if (subject !== "chore: regenerate the generated files" || files === null || !files.split("\0").filter((_, i) => i % 2 === 1).every(generated)) {
192
+ return { problem: `milestone commit ${commit} is outside approved members` };
193
+ }
194
+ } else return { problem: `milestone commit ${commit} is not a two-parent merge` };
195
+ }
196
+ if (!heads) return { problem: "milestone has no approved members" };
197
+ const problem = checkMergeTrees(root, merges.reverse(), { ...policy.config, generated: { globs: policy.config?.generated?.globs ?? defaults.generated.globs } }, git);
198
+ return problem ? { problem: `milestone ${problem}` } : { problem: null, heads };
199
+ }
200
+
201
+ /** The branch that tries the direct lane, then the integration lane, against the PR base policy within one shared deadline. */
202
+ function laneOf(workflow, records, pr, deadline) {
89
203
  const { direct, directProblem, base } = workflow;
90
- if (!direct) return directProblem ? () => ({ problem: directProblem }) : null;
91
- const deadline = Date.now() + LANE_BUDGET_MS;
92
- return (merge) => {
93
- const left = deadline - Date.now();
94
- const pr = left > 0 ? prBaseOf(merge, cwd, gh, left) : null;
204
+ const kind = workflow.review.merge;
205
+ const directLane = !direct ? (directProblem ? () => ({ problem: directProblem }) : null) : (merge) => {
95
206
  if (pr === null) return { problem: "gh cannot read the base branch of the PR within the time budget of the lane" };
96
207
  if (pr.name !== base && `origin/${pr.name}` !== base) return { problem: `the PR merges into ${pr.name}, and the lane measures against ${base}` };
97
208
  const fit = mergeLane({ root: workflow.root, baseOid: pr.oid, protectedBranches: workflow.protectedBranches, sha: merge.sha, records, budgetMs: deadline - Date.now() });
@@ -99,6 +210,23 @@ function laneOf(workflow, records, cwd, gh) {
99
210
  const reviewed = fit.review ? `the APPROVED ${fit.review.kind} review of ${fit.review.sha}` : "no review";
100
211
  return { problem: null, note: `Merge guard: ${merge.sha} merges through the direct lane, with ${sizeLine(fit.size, fit.direct)} and ${reviewed}.` };
101
212
  };
213
+ return (merge) => {
214
+ if (pr?.head && MILESTONE_PATTERN.test(pr.head)) {
215
+ const result = milestoneLane(workflow, records, pr, merge.sha, deadline);
216
+ return result.problem === null
217
+ ? { problem: null, note: `Merge guard: ${merge.sha} merges through the integration lane of ${pr.head}, with ${result.heads} reviewed heads.` }
218
+ : result;
219
+ }
220
+ const fit = directLane ? directLane(merge) : null;
221
+ if (fit?.problem === null) return fit;
222
+ if (pr === null || !pr.head) return fit;
223
+ const result = integrationLane({ root: workflow.root, baseOid: pr.oid, headBranch: pr.head, sha: merge.sha, records, kinds: [kind], budgetMs: deadline - Date.now() });
224
+ if (!result.applies) return fit;
225
+ if (result.problem === null) {
226
+ return { problem: null, note: `Merge guard: ${merge.sha} merges through the integration lane of ${pr.head}, with ${result.heads} reviewed heads and no commit past a review.` };
227
+ }
228
+ return { problem: (fit?.problem ? fit.problem + "; " : "") + "the integration lane does not apply: " + result.problem };
229
+ };
102
230
  }
103
231
 
104
232
  /**
@@ -122,15 +250,17 @@ export function namedIssues(pr, repo) {
122
250
  }
123
251
 
124
252
  /** Splits the merges into those of this checkout's repository and those that name another repository. */
125
- function partition(merges, root) {
126
- const origin = merges.some((merge) => merge.repo) ? originOf(root) : null;
253
+ function partition(merges, root, deadline) {
254
+ const left = deadline - Date.now();
255
+ const origin = left > 0 && merges.some((merge) => merge.repo) ? originOf(root, Math.min(5_000, left)) : null;
127
256
  const foreign = (merge) => origin !== null && merge.repo && repoOfSpelling(merge.repo) !== origin;
128
257
  return { origin, own: merges.filter((merge) => !foreign(merge)), other: merges.filter(foreign) };
129
258
  }
130
259
 
131
- function recordMerge(merge, call, workflow, gh) {
260
+ function recordMerge(merge, call, workflow, gh, deadline) {
132
261
  const args = ["pr", "view", ...(merge.selector ? [merge.selector] : []), ...(merge.repo ? ["-R", merge.repo] : []), "--json", VIEW_FIELDS];
133
- const out = gh(args, { cwd: call.cwd ?? process.cwd(), env: merge.env });
262
+ const left = deadline - Date.now();
263
+ const out = left > 0 ? gh(args, { cwd: call.cwd ?? process.cwd(), env: merge.env, timeoutMs: left }) : null;
134
264
  let pr = null;
135
265
  try {
136
266
  pr = out === null ? null : JSON.parse(out);
@@ -173,25 +303,56 @@ function recordMerge(merge, call, workflow, gh) {
173
303
  }
174
304
 
175
305
  /** The verdict on one Bash or PowerShell event. @returns the hook output, or null to let it pass with no message. */
176
- export function decide(call, { gh = runGh } = {}) {
306
+ export function decide(call, { gh = runGh, commentCheck = commentWatch } = {}) {
307
+ const deadline = Date.now() + LANE_BUDGET_MS;
177
308
  const event = call.hook_event_name;
178
309
  if (event !== "PreToolUse" && !POST_EVENTS.has(event)) return null;
179
310
  const parse = PARSERS[call.tool_name];
180
311
  const command = call.tool_input?.command;
181
312
  if (!parse || typeof command !== "string" || !MAYBE_GH.test(command)) return null;
313
+ const cwd = call.cwd ?? process.cwd();
314
+ const root = checkoutRootOf(cwd);
315
+ if (!root) return null;
316
+ const merges = ghMerges(command, parse);
317
+ const apiMerges = event === "PreToolUse" ? ghApiMerges(command, parse, { cwd }) : [];
318
+ const targets = [...merges, ...apiMerges.map(apiPrOf).filter(Boolean)];
319
+ const checked = event === "PreToolUse" && targets.length ? commentCheck(call, { gh: gh === runGh ? runGhAsync : gh, merges: targets }) : null;
320
+ if (checked instanceof Promise) return checked.then(result => decide(call, { gh, commentCheck: () => result }));
321
+ const commentResult = checked;
322
+ if (commentResult?.hookSpecificOutput?.permissionDecision === "deny") return commentResult;
323
+ if (event === "PreToolUse" && (merges.length > 0 || apiMerges.length > 0)) {
324
+ try {
325
+ const refusal = pauseRefusal(root);
326
+ if (refusal) return deny(`Merge guard: ${refusal}`);
327
+ } catch (error) {
328
+ return deny(`Merge guard: cannot read the operator pause (${error.message}). Wait for the operator to run \`qc resume\`.`);
329
+ }
330
+ }
182
331
  let workflow;
183
- try {
184
- workflow = workflowAt(call.cwd ?? process.cwd());
185
- } catch (error) {
186
- return event === "PreToolUse" ? context(`Merge guard is off: ${error.message}`) : null;
332
+ if (event !== "PreToolUse") {
333
+ try {
334
+ workflow = workflowAt(cwd);
335
+ } catch {
336
+ return null;
337
+ }
338
+ if (!workflow) workflow = worktreeRuleAt(cwd);
339
+ if (!workflow) return null;
187
340
  }
188
- // Only the record needs a ledger; the review check stays off with the workflow.
189
- if (!workflow && event !== "PreToolUse") workflow = worktreeRuleAt(call.cwd ?? process.cwd());
190
- if (!workflow) return null;
191
341
  if (event === "PreToolUse") {
192
- const [found] = ghApiMerges(command, parse, { cwd: call.cwd ?? process.cwd() });
193
- if (found) {
342
+ for (const found of apiMerges) {
194
343
  const use = "Run `gh pr merge <n> --match-head-commit <sha>` with the head an APPROVED review named.";
344
+ if (found.inputField !== undefined) {
345
+ return deny(`Merge guard: \`gh api ${found.endpoint}\` mixes \`--input\` with \`${found.inputField}\`. Fields enter the URL query string, so the guard cannot pin the body to one PR. ${use}`);
346
+ }
347
+ const merge = apiPrOf(found);
348
+ if (merge) {
349
+ try {
350
+ if (!policyOf(merge, root, cwd, gh, deadline).workflow) continue;
351
+ } catch (error) {
352
+ if (error instanceof HoldRefusal) return deny(`Merge guard: ${error.message}`);
353
+ return deny(`Merge guard: the base policy cannot be read (${error.message}). ${use}`);
354
+ }
355
+ }
195
356
  return deny(
196
357
  found.unreadable === undefined
197
358
  ? `Merge guard: \`gh api ${found.endpoint}\` merges with no review check and no head pin. ${use}`
@@ -199,21 +360,32 @@ export function decide(call, { gh = runGh } = {}) {
199
360
  );
200
361
  }
201
362
  }
202
- const merges = ghMerges(command, parse);
203
363
  if (merges.length === 0) return null;
204
- const { origin, own, other } = partition(merges, workflow.root);
364
+ const { origin, own, other } = partition(merges, root, deadline);
205
365
  if (event === "PreToolUse") {
206
- let verdict = { refusal: null, direct: [] };
207
- if (own.length > 0) {
366
+ const notes = [commentResult?.hookSpecificOutput?.additionalContext].filter(Boolean);
367
+ for (const merge of own) {
208
368
  try {
369
+ const policy = policyOf(merge, root, cwd, gh, deadline);
370
+ const { pr } = policy;
371
+ workflow = policy.workflow;
372
+ if (!workflow) continue;
209
373
  const records = readLedger(workflow.ledger);
210
- verdict = mergeVerdict(own, records, workflow.review.merge, laneOf(workflow, records, call.cwd ?? process.cwd(), gh));
374
+ if (merge.sha && MILESTONE_PATTERN.test(pr.head ?? "")) {
375
+ const fit = milestoneLane(workflow, records, pr, merge.sha, deadline);
376
+ if (fit.problem !== null) return deny(`Merge guard: milestone integration lane does not apply: ${fit.problem}.`);
377
+ }
378
+ const promotion = workflow.review.promotion;
379
+ const promotionScope = promotion && pr.sameRepository && promotionBranchName(pr.head) === promotionBranchName(promotion.integration) &&
380
+ promotionBranchName(pr.name) === promotionBranchName(promotion.release) ? PROMOTION_SCOPE : null;
381
+ const result = mergeVerdict([{ ...merge, number: pr.number }], records, workflow.review.merge, laneOf(workflow, records, pr, deadline), promotionScope, workflow.review.runtime);
382
+ if (result.refusal) return deny(result.refusal);
383
+ notes.push(...result.direct);
211
384
  } catch (error) {
212
- verdict = { refusal: `Merge guard: the ledger cannot be read (${error.message}), so no review can be checked. Fix the ledger file, and merge again.` };
385
+ if (error instanceof HoldRefusal) return deny(`Merge guard: ${error.message}`);
386
+ return deny(`Merge guard: the base policy or ledger cannot be read (${error.message}), so no review can be checked.`);
213
387
  }
214
388
  }
215
- if (verdict.refusal) return deny(verdict.refusal);
216
- const notes = [...verdict.direct];
217
389
  if (other.length > 0) {
218
390
  notes.push(
219
391
  `Merge guard passes ${[...new Set(other.map((merge) => merge.repo))].join(", ")}: it is not this checkout's repository (${origin}), ` +
@@ -222,7 +394,7 @@ export function decide(call, { gh = runGh } = {}) {
222
394
  }
223
395
  return notes.length > 0 ? context(notes.join(" ")) : null;
224
396
  }
225
- const notes = own.map((merge) => recordMerge(merge, call, workflow, gh)).filter(Boolean);
397
+ const notes = own.map((merge) => recordMerge(merge, call, workflow, gh, deadline)).filter(Boolean);
226
398
  return notes.length > 0 ? { systemMessage: notes.join(" ") } : null;
227
399
  }
228
400
 
@@ -240,6 +412,6 @@ if (isEntryPoint) {
240
412
  } catch {
241
413
  // Not hook input, so there is no command to judge.
242
414
  }
243
- const output = call ? decide(call) : null;
415
+ const output = call ? await decide(call) : null;
244
416
  if (output) process.stdout.write(JSON.stringify(output));
245
417
  }