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
@@ -1,31 +1,60 @@
1
1
  import { strict as assert } from "node:assert";
2
- import { execFileSync, spawnSync } from "node:child_process";
3
- import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
2
+ import { execFileSync as execFile, spawnSync as spawn } from "node:child_process";
3
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
- import { test } from "node:test";
7
- import { fileURLToPath } from "node:url";
6
+ import { after, test } from "node:test";
7
+ import { fileURLToPath, pathToFileURL } from "node:url";
8
8
  import { appendRecord, readLedger } from "./ledger.mjs";
9
- import { decide, mergeVerdict, namedIssues } from "./merge-guard.mjs";
9
+ import { decide as decideMerge, mergeVerdict, namedIssues } from "./merge-guard.mjs";
10
+ import { recordRun, resolveFailures } from "./ci-failures.mjs";
11
+ import { holdBranch } from "./pause.mjs";
12
+ import { mergeStep } from "./integrate.mjs";
10
13
 
11
14
  const HOOK = fileURLToPath(new URL("./merge-guard.mjs", import.meta.url));
12
15
  const SHA = "0123456789abcdef0123456789abcdef01234567";
16
+ const bases = new Map();
17
+ const configDir = mkdtempSync(path.join(os.tmpdir(), "qc-merge-config-"));
18
+ const gitEnv = { GIT_CONFIG_GLOBAL: path.join(configDir, "gitconfig"), GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_COUNT: "0" };
19
+ const previousGitEnv = Object.fromEntries(Object.keys(gitEnv).map(key => [key, process.env[key]]));
20
+ Object.assign(process.env, gitEnv);
21
+ after(() => {
22
+ for (const [key, value] of Object.entries(previousGitEnv)) {
23
+ if (value === undefined) delete process.env[key];
24
+ else process.env[key] = value;
25
+ }
26
+ });
27
+ after(() => rmSync(configDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
28
+ const isolated = (options = {}) => ({ ...options, env: { ...process.env, ...options.env, GIT_CONFIG_GLOBAL: path.join(configDir, "gitconfig"), GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_COUNT: "0" } });
29
+ const execFileSync = (program, args, options) => execFile(program, args, isolated(options));
30
+ const spawnSync = (program, args, options) => spawn(program, args, isolated(options));
31
+ const decide = (call, options = {}) => decideMerge(call, { commentCheck: () => null, gh: fakeGh(prView(bases.get(call.cwd))).gh, ...options });
13
32
 
14
33
  /** Checkouts with the checks on (merge kind branch, and task), one with them off, each with a git dir. */
15
34
  function workspace(t) {
16
35
  const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-merge-guard-")));
17
- t.after(() => rmSync(base, { recursive: true, force: true }));
36
+ t.after(() => rmSync(base, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
37
+ const checkouts = new Map();
18
38
  const make = (name, config) => {
39
+ if (checkouts.has(name)) return checkouts.get(name);
19
40
  const dir = path.join(base, name);
20
41
  execFileSync("git", ["init", "-q", dir], { stdio: "pipe" });
21
42
  writeFileSync(path.join(dir, "qc.config.json"), JSON.stringify(config));
43
+ for (const args of [["config", "user.name", "qc"], ["config", "user.email", "qc@example.com"], ["config", "commit.gpgsign", "false"], ["add", "."], ["commit", "-q", "-m", "init"]]) {
44
+ execFileSync("git", args, { cwd: dir, stdio: "pipe" });
45
+ }
46
+ bases.set(dir, execFileSync("git", ["rev-parse", "HEAD"], { cwd: dir, encoding: "utf8" }).trim());
47
+ if (name === "on") execFileSync("git", ["remote", "add", "origin", "git@github.com-personal:o/r.git"], { cwd: dir, stdio: "pipe" });
48
+ checkouts.set(name, dir);
22
49
  return dir;
23
50
  };
24
- const on = make("on", { swarm: { dispatch: {} } });
25
- execFileSync("git", ["remote", "add", "origin", "git@github.com-personal:o/r.git"], { cwd: on, stdio: "pipe" });
26
- const task = make("task", { swarm: { dispatch: {}, review: { merge: "task" } } });
27
- const off = make("off", { swarm: {} });
28
- return { on, task, off, ledgerOf: (dir) => path.join(dir, ".git", "qc", "ledger.jsonl") };
51
+ return {
52
+ get on() { return make("on", { swarm: { dispatch: {} } }); },
53
+ get task() { return make("task", { swarm: { dispatch: {}, review: { merge: "task" } } }); },
54
+ get off() { return make("off", { swarm: {} }); },
55
+ get promo() { return make("promo", { swarm: { dispatch: {}, review: { promotion: { integration: "dev", release: "main" } } } }); },
56
+ ledgerOf: (dir) => path.join(dir, ".git", "qc", "ledger.jsonl"),
57
+ };
29
58
  }
30
59
 
31
60
  const shell = (cwd, command, hook_event_name = "PreToolUse", tool_name = "Bash") => ({
@@ -38,10 +67,125 @@ const shell = (cwd, command, hook_event_name = "PreToolUse", tool_name = "Bash")
38
67
  const denied = (output) => output?.hookSpecificOutput?.permissionDecisionReason ?? null;
39
68
  const verdict = (kind, value, sha = SHA) => ({ type: "verdict", kind, verdict: value, sha, branch: "feat/62-x" });
40
69
 
70
+ test("codex CHANGES_REQUIRED on the head refuses a direct-lane merge", () => {
71
+ const result = mergeVerdict(
72
+ [{ sha: SHA }],
73
+ [verdict("codex", "CHANGES_REQUIRED")],
74
+ "branch",
75
+ () => ({ problem: null, note: "direct lane" }),
76
+ null,
77
+ "codex",
78
+ );
79
+ assert.match(result.refusal, /CHANGES_REQUIRED/);
80
+ });
81
+
82
+ test("a lesson refusal prints at most four lines with multiline test names", (t) => {
83
+ const { off, ledgerOf } = workspace(t);
84
+ const branch = "feat/ci";
85
+ appendRecord(ledgerOf(off), { type: "ci-failure", id: "multi", branch, head: "aaaaaaa", test: "first\nsecond\nthird\nfourth\nfifth" });
86
+ resolveFailures(off, branch, "bbbbbbb");
87
+ const gh = fakeGh(prView(bases.get(off), "main", branch)).gh;
88
+ const reason = denied(decide(shell(off, `gh pr merge 60 --match-head-commit ${bases.get(off)}`), { gh }));
89
+ assert.match(reason, /lesson.*first/i);
90
+ assert.ok(reason.split(/\r?\n/).length <= 4);
91
+ });
92
+
93
+ test("merge requires lessons for resolved failures at the pinned head even with dispatch off", (t) => {
94
+ const { off } = workspace(t);
95
+ const branch = "feat/ci";
96
+ recordRun(off, { id: 1, branch, head: "aaaaaaa" }, { gh: () => "not ok 1 - cleanup retries\n error: EBUSY" });
97
+ resolveFailures(off, branch, "bbbbbbb");
98
+ const gh = fakeGh(prView(bases.get(off), "main", branch)).gh;
99
+ assert.match(denied(decide(shell(off, `gh pr merge 60 --match-head-commit ${bases.get(off)}`), { gh })), /lesson.*cleanup retries/i);
100
+ assert.match(denied(decide(shell(off, "gh api -X PUT repos/o/r/pulls/60/merge"), { gh })), /lesson.*cleanup retries/i);
101
+ const graphql = (args) => JSON.stringify({ data: { node: {
102
+ number: 60, baseRefName: "main", baseRefOid: bases.get(off), repository: { nameWithOwner: "o/r" },
103
+ labels: { nodes: [], pageInfo: { hasNextPage: false } },
104
+ ...(args.join(" ").includes("headRefName isCrossRepository") ? { headRefName: branch, isCrossRepository: false } : {}),
105
+ } } });
106
+ assert.match(denied(decide(shell(off, `gh api graphql -f query='mutation { mergePullRequest(input: {pullRequestId: "PR_60"}) { clientMutationId } }'`), { gh: graphql })), /lesson.*cleanup retries/i);
107
+ mkdirSync(path.join(off, "docs"));
108
+ writeFileSync(path.join(off, "docs", "ci-lessons.md"), "## cleanup retries\nSymptom: EBUSY on Windows\nCause: open handle\nRule: Retry cleanup.\n");
109
+ execFileSync("git", ["add", "."], { cwd: off });
110
+ execFileSync("git", ["commit", "-qm", "lesson"], { cwd: off });
111
+ const sha = execFileSync("git", ["rev-parse", "HEAD"], { cwd: off, encoding: "utf8" }).trim();
112
+ assert.equal(decide(shell(off, `gh pr merge 60 --match-head-commit ${sha}`), { gh }), null);
113
+ holdBranch(off, branch, "repeat");
114
+ assert.match(denied(decide(shell(off, `gh pr merge 60 --match-head-commit ${sha}`), { gh })), /Operator:.*qc resume --branch/);
115
+ });
116
+
117
+ test("merge requires each same-repository head lesson before the branch reaches the base", (t) => {
118
+ const { off, ledgerOf } = workspace(t);
119
+ const git = (...args) => execFileSync("git", args, { cwd: off, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
120
+ git("remote", "add", "origin", "https://github.com/o/r.git");
121
+ const base = bases.get(off);
122
+ git("checkout", "-qb", "feat/ci");
123
+ git("commit", "--allow-empty", "-qm", "green head");
124
+ const head = git("rev-parse", "HEAD");
125
+ assert.equal(spawnSync("git", ["merge-base", "--is-ancestor", head, base], { cwd: off }).status, 1);
126
+ for (const [id, repository, branch, name] of [
127
+ ["first", "o/r", "feat/ci", "cleanup retries"],
128
+ ["second", "o/r", "feat/ci", "connection closes"],
129
+ ["fork", "fork/r", "feat/ci", "fork failure"],
130
+ ["other", "o/r", "feat/other", "other failure"],
131
+ ]) appendRecord(ledgerOf(off), { type: "ci-failure", id, repository, branch, head: base, test: name });
132
+ const gh = fakeGh(prView(base, "main", "feat/ci")).gh;
133
+ const call = (sha) => decide(shell(off, `gh pr merge 60 --match-head-commit ${sha}`), { gh });
134
+ assert.match(denied(call(head)), /lesson.*cleanup retries.*connection closes/i);
135
+ mkdirSync(path.join(off, "docs"));
136
+ const lesson = (name) => `## ${name}\nSymptom: failure\nCause: open handle\nRule: Close the handle.\n`;
137
+ writeFileSync(path.join(off, "docs", "ci-lessons.md"), lesson("cleanup retries"));
138
+ git("add", ".");
139
+ git("commit", "-qm", "first lesson");
140
+ assert.match(denied(call(git("rev-parse", "HEAD"))), /lesson.*connection closes/i);
141
+ writeFileSync(path.join(off, "docs", "ci-lessons.md"), lesson("cleanup retries") + lesson("connection closes"));
142
+ git("add", ".");
143
+ git("commit", "-qm", "each lesson");
144
+ assert.equal(call(git("rev-parse", "HEAD")), null);
145
+ });
146
+
147
+ test("an operator pause refuses manual and reviewed merges with dispatch on or off", (t) => {
148
+ const ws = workspace(t);
149
+ for (const dir of [ws.on, ws.off]) {
150
+ mkdirSync(path.join(dir, ".git", "qc"), { recursive: true });
151
+ writeFileSync(path.join(dir, ".git", "qc", "pause"), "operator investigation\n");
152
+ appendRecord(ws.ledgerOf(dir), verdict("branch", "APPROVED"));
153
+ for (const tool of ["Bash", "PowerShell"]) {
154
+ for (const command of [
155
+ `gh pr merge 60 --match-head-commit ${SHA}`,
156
+ "gh pr merge 60 --auto --squash",
157
+ "gh api -X PUT repos/o/r/pulls/60/merge",
158
+ 'gh api graphql -f query="mutation { mergePullRequest(input: {pullRequestId: \\"PR_1\\"}) { clientMutationId } }"',
159
+ ]) {
160
+ assert.match(denied(decide(shell(dir, command, "PreToolUse", tool))) ?? "", /operator investigation.*qc resume/, command);
161
+ }
162
+ assert.equal(decide(shell(dir, "gh pr view 60", "PreToolUse", tool)), null);
163
+ }
164
+ }
165
+ });
166
+
167
+ test("a pause read error refuses merges and waits for the operator", (t) => {
168
+ const { off } = workspace(t);
169
+ mkdirSync(path.join(off, ".git", "qc", "pause"), { recursive: true });
170
+ const reason = denied(decide(shell(off, "gh pr merge 60")));
171
+ assert.match(reason, /^Merge guard: cannot read the operator pause \(.+\)\. Wait for the operator to run `qc resume`\.$/);
172
+ });
173
+
41
174
  /** A gh stand-in that logs each call and answers with `answer`. */
42
175
  function fakeGh(answer) {
43
176
  const calls = [];
44
- return { calls, gh: (args, options) => (calls.push({ args, options }), typeof answer === "function" ? answer(args) : answer) };
177
+ let baseTip = null;
178
+ return { calls, gh: (args, options) => {
179
+ calls.push({ args, options });
180
+ if (args[0] === "api" && args[1].includes("/git/ref/heads/")) return baseTip;
181
+ const result = typeof answer === "function" ? answer(args) : answer;
182
+ if (args[0] === "pr" && args.at(-1) === "baseRefName,headRefName,number,isCrossRepository,labels" && result) {
183
+ const { baseRefOid, ...pr } = JSON.parse(result);
184
+ baseTip = baseRefOid ?? null;
185
+ return JSON.stringify(pr);
186
+ }
187
+ return result;
188
+ } };
45
189
  }
46
190
 
47
191
  const MERGED = JSON.stringify({
@@ -61,10 +205,10 @@ const MERGED = JSON.stringify({
61
205
  test("with swarm.dispatch off, a merge is not judged, and the merge is recorded for the worktree check", (t) => {
62
206
  const ws = workspace(t);
63
207
  const { gh, calls } = fakeGh(MERGED);
64
- assert.equal(decide(shell(ws.off, "gh pr merge 60"), { gh }), null);
65
- assert.equal(decide(shell(ws.off, "gh api -X PUT repos/o/r/pulls/60/merge"), { gh }), null);
66
- assert.equal(calls.length, 0, "a PreToolUse call reads nothing");
208
+ assert.equal(decide(shell(ws.off, "gh pr merge 60")), null);
209
+ assert.equal(decide(shell(ws.off, "gh api -X PUT repos/o/r/pulls/60/merge")), null);
67
210
  assert.equal(decide(shell(ws.off, "gh pr merge 60", "PostToolUse"), { gh }), null);
211
+ assert.equal(calls.length, 1);
68
212
  const records = readLedger(ws.ledgerOf(ws.off));
69
213
  assert.deepEqual(records.map(({ type, pr, repo, branch }) => ({ type, pr, repo, branch })), [{ type: "merge", pr: 60, repo: "o/r", branch: "feat/62-x" }]);
70
214
  });
@@ -73,7 +217,7 @@ test("with swarm.dispatch off and worktree.enforce false, a merge is neither jud
73
217
  const ws = workspace(t);
74
218
  writeFileSync(path.join(ws.off, "qc.config.json"), JSON.stringify({ swarm: {}, worktree: { enforce: false } }));
75
219
  const { gh, calls } = fakeGh(MERGED);
76
- assert.equal(decide(shell(ws.off, "gh pr merge 60"), { gh }), null);
220
+ assert.equal(decide(shell(ws.off, "gh pr merge 60")), null);
77
221
  assert.equal(decide(shell(ws.off, "gh pr merge 60", "PostToolUse"), { gh }), null);
78
222
  assert.equal(calls.length, 0);
79
223
  assert.equal(existsSync(ws.ledgerOf(ws.off)), false);
@@ -99,6 +243,72 @@ test("a merge passes only on an APPROVED review of the configured kind for its s
99
243
  assert.match(denied(decide(shell(ws.on, command))) ?? "", /the latest is CHANGES_REQUIRED/);
100
244
  });
101
245
 
246
+ test("an approved merge passes with gh 2.45 rejecting baseRefOid in pr view", (t) => {
247
+ const ws = workspace(t);
248
+ appendRecord(ws.ledgerOf(ws.on), verdict("branch", "APPROVED"));
249
+ const results = [];
250
+ for (const [selector, name, endpoint, host] of [
251
+ ["60", "main", "repos/{owner}/{repo}/git/ref/heads/main", null],
252
+ ["https://ghe.example.com/o/r/pull/60", "main", "repos/o/r/git/ref/heads/main", "ghe.example.com"],
253
+ ["60", "release#1", "repos/{owner}/{repo}/git/ref/heads/release%231", null],
254
+ ]) {
255
+ const gh = (args) => {
256
+ if (args[0] === "pr") {
257
+ if (args.at(-1).split(",").includes("baseRefOid")) throw new Error('Unknown JSON field: "baseRefOid"');
258
+ return JSON.stringify({ baseRefName: name, headRefName: "feat/62-x", number: 60, isCrossRepository: false, labels: [] });
259
+ }
260
+ assert.deepEqual(args, ["api", endpoint, ...(host ? ["--hostname", host] : []), "--jq", ".object.sha"]);
261
+ return bases.get(ws.on);
262
+ };
263
+ results.push({ selector, name, result: decide(shell(ws.on, `gh pr merge ${selector} --match-head-commit ${SHA}`), { gh }) });
264
+ }
265
+ assert.deepEqual(results.map(({ result }) => result), [null, null, null], JSON.stringify(results));
266
+ });
267
+
268
+ test("a failed PR or base-tip lookup names only the first error line before the deadline", (t) => {
269
+ const ws = workspace(t);
270
+ const command = shell(ws.on, `gh pr merge 60 --match-head-commit ${SHA}`);
271
+ for (const failing of ["pr", "api"]) {
272
+ const gh = (args) => {
273
+ if (args[0] === failing) throw new Error("gh: authentication failed\nsecret diagnostic details");
274
+ return prView(bases.get(ws.on));
275
+ };
276
+ const reason = denied(decide(command, { gh }));
277
+ assert.match(reason, /gh: authentication failed/);
278
+ assert.doesNotMatch(reason, /time budget|secret diagnostic details/);
279
+ }
280
+ });
281
+
282
+ test("a missing or empty base tip keeps an approved merge closed", (t) => {
283
+ const ws = workspace(t);
284
+ appendRecord(ws.ledgerOf(ws.on), verdict("branch", "APPROVED"));
285
+ for (const tip of [null, "", "\n "]) {
286
+ const gh = (args) => args[0] === "pr" ? prView(bases.get(ws.on)) : tip;
287
+ const reason = denied(decide(shell(ws.on, `gh pr merge 60 --match-head-commit ${SHA}`), { gh }));
288
+ assert.match(reason, /base/);
289
+ assert.doesNotMatch(reason, /time budget/);
290
+ }
291
+ });
292
+
293
+ test("the PR and base-tip lookups share one deadline", (t) => {
294
+ const ws = workspace(t);
295
+ const start = Date.now();
296
+ const clock = t.mock.method(Date, "now", () => start);
297
+ const timeouts = [];
298
+ const gh = (args, options) => {
299
+ timeouts.push(options.timeoutMs);
300
+ if (args[0] === "pr") {
301
+ clock.mock.mockImplementation(() => start + 100);
302
+ return prView(bases.get(ws.on));
303
+ }
304
+ clock.mock.mockImplementation(() => start + 60_000);
305
+ throw new Error("lookup timed out\nmore details");
306
+ };
307
+ assert.match(denied(decide(shell(ws.on, `gh pr merge 60 --match-head-commit ${SHA}`), { gh })), /within the time budget/);
308
+ assert.equal(timeouts.length, 2);
309
+ assert.equal(timeouts[1], timeouts[0] - 100);
310
+ });
311
+
102
312
  test("a short sha in upper case matches the full sha the review approved", (t) => {
103
313
  const ws = workspace(t);
104
314
  appendRecord(ws.ledgerOf(ws.on), verdict("branch", "APPROVED", SHA.toUpperCase()));
@@ -127,6 +337,187 @@ test("a gh api call to a PR's merge endpoint is refused outright, even after an
127
337
  assert.equal(decide(shell(ws.on, "gh api repos/o/r/pulls/60/comments")), null);
128
338
  });
129
339
 
340
+ test("an API merge reads the endpoint PR's base and settings before enforcing dispatch", (t) => {
341
+ const { dir, base } = laneRepo(t, { swarm: {} });
342
+ writeFileSync(path.join(dir, "qc.config.json"), JSON.stringify({ swarm: { dispatch: {} } }));
343
+ const { gh, calls } = fakeGh(prView(base));
344
+ const command = "GH_CONFIG_DIR=account gh api --hostname ghe.example.com -X PUT repos/other/project/pulls/23/merge";
345
+ assert.equal(decide(shell(dir, command), { gh }), null);
346
+ assert.deepEqual(calls[0].args, ["pr", "view", "23", "-R", "other/project", "--json", "baseRefName,headRefName,number,isCrossRepository,labels"]);
347
+ assert.deepEqual(calls[0].options.env, { GH_CONFIG_DIR: "account", GH_HOST: "ghe.example.com" });
348
+ assert.equal(calls.length, 2);
349
+ assert.deepEqual(calls[1].args, ["api", "repos/other/project/git/ref/heads/main", "--jq", ".object.sha"]);
350
+ assert.deepEqual(calls[1].options.env, calls[0].options.env);
351
+ assert.equal(calls[1].options.cwd, dir);
352
+ assert.ok(calls[1].options.timeoutMs > 0 && calls[1].options.timeoutMs <= calls[0].options.timeoutMs);
353
+ });
354
+
355
+ test("an API merge passes when the base has no config and denies an unreadable PR or base", (t) => {
356
+ const { dir, base } = laneRepo(t, { swarm: { dispatch: {} } }, { tracked: false });
357
+ const command = shell(dir, "gh api -X PUT https://api.github.com/repos/o/r/pulls/23/merge");
358
+ const { gh, calls } = fakeGh(prView(base));
359
+ assert.equal(decide(command, { gh }), null);
360
+ assert.deepEqual(calls[0].args.slice(0, 5), ["pr", "view", "23", "-R", "o/r"]);
361
+ assert.equal(calls[0].options.env.GH_HOST, "github.com");
362
+ assert.match(denied(decide(command, { gh: () => null })) ?? "", /gh cannot read the base branch/);
363
+ assert.match(denied(decide(command, { gh: fakeGh(prView("f".repeat(40))).gh })) ?? "", /base commit.*not in this repository/);
364
+ });
365
+
366
+ test("a placeholder REST merge reads its PR base with the inline or current repository", (t) => {
367
+ const { dir, base } = laneRepo(t, { swarm: { dispatch: {} } }, { tracked: false });
368
+ for (const [prefix, repo] of [["", null], ["GH_REPO=other/project ", "other/project"]]) {
369
+ const { gh, calls } = fakeGh(prView(base));
370
+ assert.equal(decide(shell(dir, `${prefix}gh api -X PUT repos/{owner}/{repo}/pulls/5/merge`), { gh }), null);
371
+ assert.deepEqual(calls[0].args, ["pr", "view", "5", ...(repo ? ["-R", repo] : []), "--json", "baseRefName,headRefName,number,isCrossRepository,labels"]);
372
+ assert.deepEqual(calls[0].options.env, {});
373
+ assert.equal(calls.length, 2);
374
+ assert.deepEqual(calls[1].args, ["api", `repos/${repo || "{owner}/{repo}"}/git/ref/heads/main`, "--jq", ".object.sha"]);
375
+ assert.deepEqual(calls[1].options.env, {});
376
+ }
377
+ gitIn(dir, "add", ".");
378
+ gitIn(dir, "commit", "-q", "-m", "enable dispatch");
379
+ const enabled = gitIn(dir, "rev-parse", "HEAD");
380
+ const command = shell(dir, "gh api -X PUT repos/{owner}/{repo}/pulls/5/merge");
381
+ assert.match(denied(decide(command, { gh: fakeGh(prView(enabled)).gh })) ?? "", /gh pr merge/);
382
+ const { gh, calls } = fakeGh(prView(base));
383
+ assert.match(denied(decide(shell(dir, "gh api -X PUT repos/{owner}/project/pulls/5/merge"), { gh })) ?? "", /gh pr merge/);
384
+ assert.equal(calls.length, 0);
385
+ });
386
+
387
+ test("every API merge in a command reads its own base policy", (t) => {
388
+ const { dir, base } = laneRepo(t, { swarm: { dispatch: {} } });
389
+ writeFileSync(path.join(dir, "qc.config.json"), JSON.stringify({ swarm: {} }));
390
+ gitIn(dir, "commit", "-q", "-am", "dispatch off");
391
+ const off = gitIn(dir, "rev-parse", "HEAD");
392
+ const gh = fakeGh((args) => prView(args[2] === "23" ? off : base)).gh;
393
+ assert.match(denied(decide(shell(dir, "gh api repos/o/r/pulls/23/merge; gh api repos/o/r/pulls/24/merge"), { gh })) ?? "", /gh pr merge/);
394
+ });
395
+
396
+ test("a GraphQL merge reads its node and base policy within the shared deadline", (t) => {
397
+ const { dir, base } = laneRepo(t, { swarm: { dispatch: {} } }, { tracked: false });
398
+ const command = shell(dir, 'GH_CONFIG_DIR=account GH_REPO=ignored/repo gh api https://ghe.example.com/api/graphql -f query=\'mutation($id: ID!) { mergePullRequest(input: {pullRequestId: $id}) { clientMutationId } }\' -F id=PR_123');
399
+ const node = (oid) => JSON.stringify({ data: { node: { number: 5, baseRefName: "main", baseRefOid: oid, repository: { nameWithOwner: "o/r" }, labels: { nodes: [], pageInfo: { hasNextPage: false } } } } });
400
+ const { gh, calls } = fakeGh(node(base));
401
+ assert.equal(decide(command, { gh }), null);
402
+ assert.equal(calls.length, 1);
403
+ assert.deepEqual(calls[0].args.slice(0, 2), ["api", "graphql"]);
404
+ assert.match(calls[0].args.join(" "), /node\(id:\s*\$id\)\s*\{\s*\.\.\. on PullRequest\s*\{\s*number baseRefName baseRefOid repository\s*\{\s*nameWithOwner/);
405
+ assert.ok(calls[0].args.includes("id=PR_123"));
406
+ assert.deepEqual(calls[0].options.env, { GH_CONFIG_DIR: "account", GH_HOST: "ghe.example.com" });
407
+ assert.ok(calls[0].options.timeoutMs > 0);
408
+ gitIn(dir, "add", ".");
409
+ gitIn(dir, "commit", "-q", "-m", "enable dispatch");
410
+ const enabled = gitIn(dir, "rev-parse", "HEAD");
411
+ assert.match(denied(decide(command, { gh: fakeGh(node(enabled)).gh })) ?? "", /gh pr merge/);
412
+ for (const answer of [null, "invalid", JSON.stringify({ data: { node: { id: "issue" } } }), JSON.stringify({ data: { node: null } }), node("f".repeat(40))]) {
413
+ assert.match(denied(decide(command, { gh: fakeGh(answer).gh })) ?? "", /base policy cannot be read/);
414
+ }
415
+ assert.match(denied(decide(command, { gh: () => { throw new Error("lookup failed"); } })) ?? "", /base policy cannot be read/);
416
+ const missing = fakeGh(node(base));
417
+ assert.match(denied(decide(shell(dir, "gh api graphql -f query='mutation { mergePullRequest(input: {}) { clientMutationId } }'"), { gh: missing.gh })) ?? "", /gh pr merge/);
418
+ assert.equal(missing.calls.length, 0);
419
+ });
420
+
421
+ test("a GraphQL endpoint with a fragment and stdin denies with dispatch on", (t) => {
422
+ const { on } = workspace(t);
423
+ for (const tool of ["Bash", "PowerShell"]) {
424
+ assert.match(denied(decide(shell(on, "gh api 'graphql#x' --input -", "PreToolUse", tool))) ?? "", /gh pr merge/);
425
+ }
426
+ });
427
+
428
+ test("a GraphQL endpoint with a fragment keeps its GHE host for the node lookup", (t) => {
429
+ const { dir, base } = laneRepo(t, { swarm: {} });
430
+ const node = JSON.stringify({ data: { node: { number: 5, baseRefName: "main", baseRefOid: base, repository: { nameWithOwner: "o/r" }, labels: { nodes: [], pageInfo: { hasNextPage: false } } } } });
431
+ for (const tool of ["Bash", "PowerShell"]) {
432
+ const { gh, calls } = fakeGh(node);
433
+ const command = `gh api 'https://ghe.example.com/api/graphql#x' -f query='mutation { mergePullRequest(input: {pullRequestId: "PR_ON"}) { clientMutationId } }'`;
434
+ assert.equal(decide(shell(dir, command, "PreToolUse", tool), { gh }), null);
435
+ assert.equal(calls.length, 1);
436
+ assert.ok(calls[0].args.includes("id=PR_ON"));
437
+ assert.equal(calls[0].options.env.GH_HOST, "ghe.example.com");
438
+ }
439
+ });
440
+
441
+ test("a REST endpoint with a fragment reads the PR base policy", (t) => {
442
+ const { dir, base } = laneRepo(t, { swarm: { dispatch: {} } }, { tracked: false });
443
+ for (const tool of ["Bash", "PowerShell"]) {
444
+ const { gh, calls } = fakeGh(prView(base));
445
+ assert.equal(decide(shell(dir, "gh api 'repos/o/r/pulls/1/merge#x' -X PUT", "PreToolUse", tool), { gh }), null);
446
+ assert.equal(calls.length, 2);
447
+ assert.deepEqual(calls[0].args, ["pr", "view", "1", "-R", "o/r", "--json", "baseRefName,headRefName,number,isCrossRepository,labels"]);
448
+ assert.deepEqual(calls[1].args, ["api", "repos/o/r/git/ref/heads/main", "--jq", ".object.sha"]);
449
+ }
450
+ });
451
+
452
+ test("the merge guard documents the unconditional GraphQL input-field denial", () => {
453
+ const reference = readFileSync(new URL("../../../../docs/reference.md", import.meta.url), "utf8");
454
+ const header = readFileSync(HOOK, "utf8").split("import ")[0].replace(/^\/\/ ?/gm, "").replace(/\s+/g, " ");
455
+ for (const text of [reference, header]) {
456
+ assert.ok(text.includes("Any `gh api graphql` call that mixes `--input` with a field denies, whether it reads or writes."));
457
+ assert.ok(text.includes("This applies in every checkout, with `swarm.dispatch` on or off."));
458
+ }
459
+ });
460
+
461
+ test("a GraphQL node lookup uses the endpoint host after a decoy header", (t) => {
462
+ const { dir, base } = laneRepo(t, { swarm: {} });
463
+ const node = JSON.stringify({ data: { node: { number: 5, baseRefName: "main", baseRefOid: base, repository: { nameWithOwner: "o/r" }, labels: { nodes: [], pageInfo: { hasNextPage: false } } } } });
464
+ for (const tool of ["Bash", "PowerShell"]) {
465
+ const { gh, calls } = fakeGh(node);
466
+ const command = shell(dir, 'gh api -H https://github.com/graphql https://ghe.example.com/api/graphql -f query=\'mutation { mergePullRequest(input: {pullRequestId: "PR_ON"}) { clientMutationId } }\'', "PreToolUse", tool);
467
+ assert.equal(decide(command, { gh }), null);
468
+ assert.equal(calls.length, 1);
469
+ assert.ok(calls[0].args.includes("id=PR_ON"));
470
+ assert.equal(calls[0].options.env.GH_HOST, "ghe.example.com");
471
+ }
472
+ });
473
+
474
+ test("GraphQL input mixed with fields denies before a decoy node lookup", (t) => {
475
+ const { dir, base } = laneRepo(t, { swarm: {} });
476
+ const query = 'mutation($id: ID!) { mergePullRequest(input: {pullRequestId: $id}) { clientMutationId } }';
477
+ writeFileSync(path.join(dir, "body.json"), JSON.stringify({ query, variables: { id: "PR_ON" } }));
478
+ const node = JSON.stringify({ data: { node: { number: 5, baseRefName: "main", baseRefOid: base, repository: { nameWithOwner: "o/r" }, labels: { nodes: [], pageInfo: { hasNextPage: false } } } } });
479
+ const fields = ["-f id=PR_OFF", "-F id=PR_OFF", "--field=id=PR_OFF", "--raw-field id=PR_OFF", "-fid=PR_OFF", "-iFid=PR_OFF",
480
+ `-f query='mutation { mergePullRequest(input: {pullRequestId: "PR_OFF"}) { clientMutationId } }'`];
481
+ for (const field of fields) {
482
+ for (const tool of ["Bash", "PowerShell"]) {
483
+ const { gh, calls } = fakeGh(node);
484
+ const command = shell(dir, `gh api graphql --input body.json ${field}`, "PreToolUse", tool);
485
+ assert.match(denied(decide(command, { gh })) ?? "", /--input.*(?:-f|-F|--field|--raw-field)/, field);
486
+ assert.equal(calls.length, 0, field);
487
+ }
488
+ }
489
+ writeFileSync(path.join(dir, "body.json"), JSON.stringify({ query: "query { viewer { login } }" }));
490
+ assert.match(denied(decide(shell(dir, "gh api graphql -f id=PR_OFF --input=body.json"))) ?? "", /--input.*-f/);
491
+ });
492
+
493
+ test("GraphQL input-field denial covers reads and writes with dispatch on or off", (t) => {
494
+ const { on, off } = workspace(t);
495
+ for (const dir of [on, off]) {
496
+ for (const query of ["query { viewer { login } }", 'mutation { mergePullRequest(input: {pullRequestId: "PR_ON"}) { clientMutationId } }']) {
497
+ writeFileSync(path.join(dir, "body.json"), JSON.stringify({ query }));
498
+ for (const tool of ["Bash", "PowerShell"]) {
499
+ const { gh, calls } = fakeGh(null);
500
+ const command = shell(dir, "gh api graphql --input body.json -f id=PR_OFF", "PreToolUse", tool);
501
+ assert.match(denied(decide(command, { gh })) ?? "", /--input.*-f/);
502
+ assert.equal(calls.length, 0);
503
+ }
504
+ }
505
+ }
506
+ });
507
+
508
+ test("a GraphQL lookup shares the policy deadline and denies an expired read", (t) => {
509
+ const { dir, base } = laneRepo(t, { swarm: {} });
510
+ const start = Date.now();
511
+ const clock = t.mock.method(Date, "now", () => start);
512
+ const { gh, calls } = fakeGh(() => {
513
+ clock.mock.mockImplementation(() => start + 60_000);
514
+ return JSON.stringify({ data: { node: { number: 5, baseRefName: "main", baseRefOid: base, repository: { nameWithOwner: "o/r" }, labels: { nodes: [], pageInfo: { hasNextPage: false } } } } });
515
+ });
516
+ const command = shell(dir, 'gh api graphql -f query=\'mutation { mergePullRequest(input: {pullRequestId: "PR_123"}) { clientMutationId } }\'');
517
+ assert.match(denied(decide(command, { gh })) ?? "", /base policy cannot be read/);
518
+ assert.equal(calls.length, 1);
519
+ });
520
+
130
521
  test("a merge inside a nested shell is judged too", (t) => {
131
522
  const ws = workspace(t);
132
523
  assert.match(denied(decide(shell(ws.on, `bash -c "gh pr merge 60 --match-head-commit ${SHA}"`))) ?? "", /no APPROVED/);
@@ -218,7 +609,21 @@ test("namedIssues drops the PR's own number and each repeat", () => {
218
609
 
219
610
  test("the hook process prints the deny", (t) => {
220
611
  const ws = workspace(t);
221
- const result = spawnSync(process.execPath, [HOOK], { input: JSON.stringify(shell(ws.on, "gh pr merge 60")), encoding: "utf8" });
612
+ const mock = path.join(ws.on, "mock-gh.mjs");
613
+ writeFileSync(mock, `
614
+ import cp from 'node:child_process';
615
+ import { syncBuiltinESMExports } from 'node:module';
616
+ const spawn = cp.spawnSync;
617
+ cp.spawnSync = (program, args, options) => program === 'gh'
618
+ ? { status: 1, stdout: '', stderr: 'mock gh unavailable' }
619
+ : spawn(program, args, options);
620
+ cp.execFile = (program, args, options, callback) => {
621
+ if (program !== 'gh') throw new Error('unexpected async process');
622
+ callback(new Error('mock gh unavailable'), '', '');
623
+ };
624
+ syncBuiltinESMExports();
625
+ `);
626
+ const result = spawnSync(process.execPath, ["--import", pathToFileURL(mock).href, HOOK], { input: JSON.stringify(shell(ws.on, "gh pr merge 60")), encoding: "utf8", timeout: 10_000 });
222
627
  assert.equal(result.status, 0, result.stderr);
223
628
  assert.equal(JSON.parse(result.stdout).hookSpecificOutput.permissionDecision, "deny");
224
629
  });
@@ -347,11 +752,11 @@ test("with swarm.dispatch off, a merge whose command failed after GitHub merged
347
752
  });
348
753
 
349
754
  /** A checkout with the checks on, `origin/main` at its first commit, and a small fix on `feat/1-x`. `tracked: false` keeps the config out of that commit. */
350
- function laneRepo(t, config = { swarm: { dispatch: {} } }, { tracked = true } = {}) {
755
+ function laneRepo(t, config = { swarm: { dispatch: {} } }, { tracked = true, objectFormat = "sha1" } = {}) {
351
756
  const dir = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-merge-lane-")));
352
- t.after(() => rmSync(dir, { recursive: true, force: true }));
757
+ t.after(() => rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
353
758
  const git = (...args) => execFileSync("git", args, { cwd: dir, stdio: "pipe", encoding: "utf8" }).trim();
354
- git("init", "-q", "-b", "main");
759
+ git("init", "-q", "-b", "main", `--object-format=${objectFormat}`);
355
760
  for (const [key, value] of [["user.name", "qc"], ["user.email", "qc@example.com"], ["commit.gpgsign", "false"]]) git("config", key, value);
356
761
  if (tracked) writeFileSync(path.join(dir, "qc.config.json"), JSON.stringify(config));
357
762
  writeFileSync(path.join(dir, "a.ts"), "one\ntwo\n");
@@ -362,18 +767,199 @@ function laneRepo(t, config = { swarm: { dispatch: {} } }, { tracked = true } =
362
767
  git("switch", "-q", "-c", "feat/1-x");
363
768
  writeFileSync(path.join(dir, "a.ts"), "one\n2\n");
364
769
  git("commit", "-q", "-am", "fix");
770
+ bases.set(dir, git("rev-parse", "origin/main"));
365
771
  return { dir, head: git("rev-parse", "HEAD"), base: git("rev-parse", "origin/main"), ledger: path.join(dir, ".git", "qc", "ledger.jsonl") };
366
772
  }
367
773
 
368
- /** What `gh pr view --json baseRefName,baseRefOid` answers for a PR into `main` whose base commit is `oid`. */
369
- const prView = (oid, name = "main") => JSON.stringify({ baseRefName: name, baseRefOid: oid });
774
+ /** PR details and the base tip that fakeGh serves through separate view and ref requests. */
775
+ const prView = (oid, name = "main", head) => JSON.stringify({ baseRefName: name, baseRefOid: oid, headRefName: head, isCrossRepository: false, labels: [] });
776
+
777
+ test("a hold label refuses manual and approved merges with dispatch on or off", (t) => {
778
+ const ws = workspace(t);
779
+ for (const dir of [ws.on, ws.off]) {
780
+ appendRecord(ws.ledgerOf(dir), verdict("branch", "APPROVED"));
781
+ const pr = { ...JSON.parse(prView(bases.get(dir))), labels: [{ name: "hold" }] };
782
+ const { gh } = fakeGh(JSON.stringify(pr));
783
+ for (const command of [`gh pr merge 60 --match-head-commit ${SHA}`, "gh pr merge 60 --auto --squash", "gh api -X PUT repos/o/r/pulls/60/merge"]) {
784
+ assert.match(denied(decide(shell(dir, command), { gh })) ?? "", /label.*hold/, command);
785
+ assert.equal(denied(decide(shell(dir, command), { gh })), 'Merge guard: PR label "hold" holds this merge. Wait for the operator to remove the label.');
786
+ }
787
+ }
788
+ });
789
+
790
+ test("the PR base config selects the hold label even when the head changes it", (t) => {
791
+ const { dir, base, head } = laneRepo(t, { swarm: {}, merge: { holdLabel: "operator-hold" } });
792
+ writeFileSync(path.join(dir, "qc.config.json"), JSON.stringify({ swarm: {}, merge: { holdLabel: "bypass" } }));
793
+ const pr = { ...JSON.parse(prView(base)), labels: [{ name: "operator-hold" }] };
794
+ assert.match(denied(decide(shell(dir, `gh pr merge 1 --match-head-commit ${head}`), { gh: fakeGh(JSON.stringify(pr)).gh })) ?? "", /label.*operator-hold/);
795
+ pr.labels = [{ name: "hold" }];
796
+ assert.equal(decide(shell(dir, `gh pr merge 1 --match-head-commit ${head}`), { gh: fakeGh(JSON.stringify(pr)).gh }), null);
797
+ });
798
+
799
+ test("a GraphQL API merge also checks the hold label with dispatch off", (t) => {
800
+ const { dir, base } = laneRepo(t, { swarm: {} });
801
+ const pr = { number: 1, baseRefName: "main", baseRefOid: base, repository: { nameWithOwner: "o/r" }, labels: { nodes: [{ name: "hold" }], pageInfo: { hasNextPage: false } } };
802
+ const command = 'gh api graphql -f query="mutation { mergePullRequest(input: {pullRequestId: \\"PR_1\\"}) { clientMutationId } }"';
803
+ assert.match(denied(decide(shell(dir, command), { gh: fakeGh(JSON.stringify({ data: { node: pr } })).gh })) ?? "", /label.*hold/);
804
+ assert.equal(denied(decide(shell(dir, command), { gh: fakeGh(JSON.stringify({ data: { node: pr } })).gh })), 'Merge guard: PR label "hold" holds this merge. Wait for the operator to remove the label.');
805
+ });
806
+
807
+ test("a GraphQL label page refuses a merge when another page exists", (t) => {
808
+ const { dir, base } = laneRepo(t, { swarm: {} });
809
+ const pr = { number: 1, baseRefName: "main", baseRefOid: base, repository: { nameWithOwner: "o/r" }, labels: { nodes: [], pageInfo: { hasNextPage: true } } };
810
+ const command = 'gh api graphql -f query="mutation { mergePullRequest(input: {pullRequestId: \\"PR_1\\"}) { clientMutationId } }"';
811
+ assert.match(denied(decide(shell(dir, command), { gh: fakeGh(JSON.stringify({ data: { node: pr } })).gh })), /gh cannot read every PR label/);
812
+ });
813
+
814
+ test("missing labels refuse CLI, REST, and GraphQL merges", (t) => {
815
+ const { dir, base } = laneRepo(t, { swarm: {} });
816
+ const pr = { number: 1, baseRefName: "main", baseRefOid: base, repository: { nameWithOwner: "o/r" } };
817
+ for (const command of ["gh pr merge 1", "gh api -X PUT repos/o/r/pulls/1/merge"]) {
818
+ assert.match(denied(decide(shell(dir, command), { gh: fakeGh(JSON.stringify(pr)).gh })), /gh cannot read every PR label/);
819
+ }
820
+ const command = 'gh api graphql -f query="mutation { mergePullRequest(input: {pullRequestId: \\"PR_1\\"}) { clientMutationId } }"';
821
+ assert.match(denied(decide(shell(dir, command), { gh: fakeGh(JSON.stringify({ data: { node: pr } })).gh })), /gh cannot read every PR label/);
822
+ });
823
+
824
+ test("a full CLI label page refuses a merge because further labels may exist", (t) => {
825
+ const { off } = workspace(t);
826
+ const pr = { ...JSON.parse(prView(bases.get(off))), labels: Array.from({ length: 100 }, () => ({ name: "other" })) };
827
+ assert.match(denied(decide(shell(off, "gh pr merge 1"), { gh: fakeGh(JSON.stringify(pr)).gh })), /gh cannot read every PR label/);
828
+ });
829
+
830
+ test("the base policy rejects a hold label with surrounding whitespace", (t) => {
831
+ const { dir, base } = laneRepo(t, { swarm: {}, merge: { holdLabel: " hold " } });
832
+ const pr = { ...JSON.parse(prView(base)), labels: [{ name: "hold" }] };
833
+ assert.match(denied(decide(shell(dir, "gh pr merge 1"), { gh: fakeGh(JSON.stringify(pr)).gh })), /merge.holdLabel must be a non-empty string without surrounding whitespace/);
834
+ });
835
+
836
+ test("one review per issue head replaces dispatched and promotion scope requirements", (t) => {
837
+ const ws = workspace(t);
838
+ const command = shell(ws.promo, `gh pr merge 7 --match-head-commit ${SHA}`);
839
+ const { gh } = fakeGh(prView(bases.get(ws.promo), "main", "dev"));
840
+ assert.match(denied(decide(command, { gh })) ?? "", /no APPROVED branch review/);
841
+ appendRecord(ws.ledgerOf(ws.promo), { type: "dispatch", task: false, agentType: "sdd-branch-reviewer", branch: "feat/62-x", head: SHA, scope: "unreviewed" });
842
+ appendRecord(ws.ledgerOf(ws.promo), { ...verdict("branch", "APPROVED"), scope: "ui" });
843
+ assert.equal(decide(command, { gh }), null);
844
+ for (const promotion of [null, "promotion"]) {
845
+ const records = [
846
+ { type: "dispatch", task: false, agentType: "sdd-branch-reviewer", branch: "feat/62-x", head: SHA, scope: "unreviewed" },
847
+ { ...verdict("branch", "APPROVED"), scope: "ui" },
848
+ ];
849
+ assert.equal(mergeVerdict([{ sha: SHA }], records, "branch", null, promotion).refusal, null);
850
+ records.push({ ...verdict("branch", "CHANGES_REQUIRED"), scope: "security" });
851
+ assert.match(mergeVerdict([{ sha: SHA }], records, "branch", null, promotion).refusal, /CHANGES_REQUIRED/);
852
+ }
853
+ assert.match(mergeVerdict([{ sha: SHA }], [], "branch", () => assert.fail("promotion must skip direct lane"), "promotion").refusal, /no APPROVED/);
854
+ const repo = laneRepo(t, { swarm: { dispatch: {}, review: { promotion: { integration: "origin/dev", release: "origin/main" } } } });
855
+ const merge = merge7(repo.dir, repo.head);
856
+ assert.equal(denied(decide(merge, { gh: fakeGh(prView(repo.base, "main", "feat/x")).gh })), null);
857
+ for (const base of ["main", "origin/main"]) {
858
+ for (const head of ["dev", "origin/dev"]) {
859
+ const reason = denied(decide(merge, { gh: fakeGh(prView(repo.base, base, head)).gh }));
860
+ assert.match(reason, /no APPROVED branch review/);
861
+ assert.doesNotMatch(reason, /direct lane/);
862
+ }
863
+ }
864
+ });
865
+
866
+ for (const [checkout, head] of [["promo", "feat/x"], ["on", "dev"], ["promo", undefined]]) {
867
+ test(`the ${checkout} checkout keeps the old review rules with head ${head}`, (t) => {
868
+ const ws = workspace(t);
869
+ const cwd = ws[checkout];
870
+ const { gh } = fakeGh(prView(bases.get(cwd), "main", head));
871
+ const command = shell(cwd, `gh pr merge 7 --match-head-commit ${SHA}`);
872
+ assert.match(denied(decide(command, { gh })) ?? "", /no APPROVED branch review/);
873
+ appendRecord(ws.ledgerOf(cwd), { ...verdict("branch", "APPROVED"), scope: "ui" });
874
+ assert.equal(decide(command, { gh }), null);
875
+ });
876
+ }
877
+
878
+ const prViewWithHead = (oid, head) => JSON.stringify({ ...JSON.parse(prView(oid)), headRefName: head });
879
+
880
+ function integrationMergeRepo(t, { integrate, kind = "branch", unreviewed = false, runtime = "claude", migrations = false, generated = false, objectFormat = "sha1" } = {}) {
881
+ const repo = laneRepo(t, { swarm: { dispatch: {}, direct: false, review: { runtime } }, ...(integrate ? { integrate } : {}), ...(migrations ? { paths: { migrations: "db" } } : {}), ...(generated ? { generated: { globs: ["generated.txt"] } } : {}) }, { objectFormat });
882
+ const { dir, base, ledger } = repo;
883
+ const git = (...args) => execFileSync("git", args, { cwd: dir, stdio: "pipe", encoding: "utf8" }).trim();
884
+ git("branch", "-m", "task/7-a");
885
+ if (migrations) {
886
+ mkdirSync(path.join(dir, "db"));
887
+ writeFileSync(path.join(dir, "db/0001_a.sql"), "select 1;\n");
888
+ git("add", "."); git("commit", "-qm", "migration a");
889
+ repo.head = git("rev-parse", "HEAD");
890
+ }
891
+ git("switch", "-q", "-c", "feat/7-integration", base);
892
+ git("merge", "--no-ff", "-m", "merge a", "task/7-a");
893
+ appendRecord(ledger, { ...verdict(kind, "APPROVED", repo.head), scope: "a" });
894
+ git("switch", "-q", "-c", "task/7-b", base);
895
+ writeFileSync(path.join(dir, "b.ts"), "feature b\n");
896
+ if (migrations) {
897
+ mkdirSync(path.join(dir, "db"));
898
+ writeFileSync(path.join(dir, "db/0001_b.sql"), "select 2;\n");
899
+ }
900
+ git("add", ".");
901
+ git("commit", "-q", "-m", "add b");
902
+ const taskHead = git("rev-parse", "HEAD");
903
+ if (!unreviewed) appendRecord(ledger, { ...verdict(kind, "APPROVED", taskHead), scope: "b" });
904
+ git("switch", "-q", "feat/7-integration");
905
+ if (migrations) mergeStep({ root: dir, paths: { migrations: "db" } }, "task/7-b", { base, email: git("config", "user.email"), say: () => {} });
906
+ else git("merge", "--no-ff", "-m", "merge b", "task/7-b");
907
+ return { ...repo, head: git("rev-parse", "HEAD") };
908
+ }
909
+
910
+ test("the integration lane accepts scoped branch reviews of both task heads with the direct lane off", (t) => {
911
+ const { dir, head, base } = integrationMergeRepo(t);
912
+ const gh = fakeGh(prViewWithHead(base, "feat/7-integration")).gh;
913
+ const output = decide(shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`), { gh });
914
+ assert.equal(denied(output), null);
915
+ assert.match(output?.hookSpecificOutput?.additionalContext ?? "", /integration lane of feat\/7-integration, with 2 reviewed heads/);
916
+ });
917
+
918
+ test("the integration lane refuses a task commit without an APPROVED review", (t) => {
919
+ const { dir, head, base } = integrationMergeRepo(t, { unreviewed: true });
920
+ const gh = fakeGh(prViewWithHead(base, "feat/7-integration")).gh;
921
+ const reason = denied(decide(shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`), { gh })) ?? "";
922
+ assert.match(reason, /integration lane .*does not apply: .*hold no APPROVED review/);
923
+ });
924
+
925
+ test("the integration lane ignores a PR head outside the integration branch pattern", (t) => {
926
+ const { dir, head, base } = integrationMergeRepo(t);
927
+ const gh = fakeGh(prViewWithHead(base, "feat/8-other")).gh;
928
+ const reason = denied(decide(shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`), { gh })) ?? "";
929
+ assert.match(reason, /no APPROVED branch review/);
930
+ assert.doesNotMatch(reason, /integration lane/);
931
+ });
932
+
933
+ test("the integration lane stays off when the base disables integrate.review", (t) => {
934
+ const { dir, head, base } = integrationMergeRepo(t, { integrate: { review: false } });
935
+ const gh = fakeGh(prViewWithHead(base, "feat/7-integration")).gh;
936
+ const reason = denied(decide(shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`), { gh })) ?? "";
937
+ assert.match(reason, /no APPROVED branch review/);
938
+ assert.doesNotMatch(reason, /integration lane/);
939
+ });
940
+
941
+ test("the integration lane needs the PR head from gh", (t) => {
942
+ const { dir, head, base } = integrationMergeRepo(t);
943
+ const gh = fakeGh(prView(base)).gh;
944
+ const reason = denied(decide(shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`), { gh })) ?? "";
945
+ assert.match(reason, /no APPROVED branch review/);
946
+ assert.doesNotMatch(reason, /integration lane/);
947
+ });
948
+
949
+ test("the integration lane counts only the merge guard's review kind", (t) => {
950
+ const { dir, head, base } = integrationMergeRepo(t, { kind: "task" });
951
+ const gh = fakeGh(prViewWithHead(base, "feat/7-integration")).gh;
952
+ const reason = denied(decide(shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`), { gh })) ?? "";
953
+ assert.match(reason, /no APPROVED branch review/);
954
+ assert.match(reason, /integration lane .*does not apply/);
955
+ });
370
956
 
371
957
  test("a small head with no review merges through the direct lane, with a note", (t) => {
372
958
  const { dir, head, base } = laneRepo(t);
373
- const { gh, calls } = fakeGh(prView(base));
959
+ const { gh, calls } = fakeGh(prViewWithHead(base, "feat/7-integration"));
374
960
  const output = decide(shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`), { gh });
375
961
  assert.equal(denied(output), null);
376
- assert.deepEqual(calls[0].args, ["pr", "view", "7", "--json", "baseRefName,baseRefOid"]);
962
+ assert.deepEqual(calls[0].args, ["pr", "view", "7", "--json", "baseRefName,headRefName,number,isCrossRepository,labels"]);
377
963
  assert.match(output?.hookSpecificOutput?.additionalContext ?? "", /merges through the direct lane, with 2 of 20 lines in 1 of 2 files and no review/);
378
964
  assert.match(denied(decide(shell(dir, "gh pr merge 7 --squash"))) ?? "", /--match-head-commit <sha>/);
379
965
  });
@@ -438,10 +1024,17 @@ test("a head that changes qc.config.json stays out of the direct lane", (t) => {
438
1024
  assert.match(reason, /does not apply: qc\.config\.json changes on the branch, so it runs the subagent workflow/);
439
1025
  });
440
1026
 
441
- test("a base that holds no qc.config.json keeps the head out of the direct lane", (t) => {
1027
+ test("a base that holds no qc.config.json leaves the merge guard off", (t) => {
442
1028
  const { dir, head, base } = laneRepo(t, { swarm: { dispatch: {} } }, { tracked: false });
1029
+ assert.equal(decide(shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`), { gh: fakeGh(prView(base)).gh }), null);
1030
+ });
1031
+
1032
+ test("a failed read of qc.config.json at the base denies the merge", (t) => {
1033
+ const { dir, head, base } = laneRepo(t);
1034
+ const blob = gitIn(dir, "rev-parse", `${base}:qc.config.json`);
1035
+ rmSync(path.join(dir, ".git", "objects", blob.slice(0, 2), blob.slice(2)));
443
1036
  const reason = denied(decide(shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`), { gh: fakeGh(prView(base)).gh })) ?? "";
444
- assert.match(reason, /does not apply: git cannot read qc\.config\.json at the PR base/);
1037
+ assert.match(reason, /git cannot read qc\.config\.json at the PR base/);
445
1038
  });
446
1039
 
447
1040
  test("the note states the size against the limits of the base, not the checkout", (t) => {
@@ -454,6 +1047,59 @@ test("the note states the size against the limits of the base, not the checkout"
454
1047
  const gitIn = (dir, ...args) => execFileSync("git", args, { cwd: dir, stdio: "pipe", encoding: "utf8" }).trim();
455
1048
  const merge7 = (dir, head) => shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`);
456
1049
 
1050
+ test("the merge policy at the PR base survives a removed dispatch or a weaker checkout review", (t) => {
1051
+ const { dir, head, base, ledger } = laneRepo(t, { swarm: { dispatch: {}, direct: false } });
1052
+ appendRecord(ledger, verdict("task", "APPROVED", head));
1053
+ for (const config of [{ swarm: {} }, { swarm: { dispatch: {}, review: { merge: "task" } } }]) {
1054
+ writeFileSync(path.join(dir, "qc.config.json"), JSON.stringify(config));
1055
+ assert.match(denied(decide(merge7(dir, head), { gh: fakeGh(prView(base)).gh })) ?? "", /no APPROVED branch review/);
1056
+ }
1057
+ appendRecord(ledger, verdict("branch", "APPROVED", head));
1058
+ assert.equal(decide(merge7(dir, head), { gh: fakeGh(prView(base)).gh }), null);
1059
+ });
1060
+
1061
+ test("each merge in one command uses its own PR base policy", (t) => {
1062
+ const { dir, head, base, ledger } = laneRepo(t, { swarm: { dispatch: {}, direct: false } });
1063
+ writeFileSync(path.join(dir, "qc.config.json"), JSON.stringify({ swarm: {} }));
1064
+ gitIn(dir, "commit", "-q", "-am", "disable dispatch");
1065
+ const offBase = gitIn(dir, "rev-parse", "HEAD");
1066
+ const gh = fakeGh((args) => prView(args[2] === "7" ? offBase : base)).gh;
1067
+ const command = `gh pr merge 7 --match-head-commit ${head}; gh pr merge 8 --match-head-commit ${head}`;
1068
+ assert.match(denied(decide(shell(dir, command), { gh })) ?? "", /no APPROVED branch review/);
1069
+ appendRecord(ledger, verdict("branch", "APPROVED", head));
1070
+ assert.equal(decide(shell(dir, command), { gh }), null);
1071
+ });
1072
+
1073
+ test("the hook budget includes the reads before the lane and is shared by every merge", (t) => {
1074
+ const { dir, head, base } = laneRepo(t);
1075
+ gitIn(dir, "remote", "add", "origin", "https://github.com/o/r.git");
1076
+ let now = 0;
1077
+ t.mock.method(Date, "now", () => (now += 100));
1078
+ const timeouts = [];
1079
+ const gh = (args, options) => {
1080
+ timeouts.push(options.timeoutMs);
1081
+ now += 2_000;
1082
+ return prView(base);
1083
+ };
1084
+ decide(shell(dir, `gh pr merge 7 -R o/r --match-head-commit ${head}; gh pr merge 8 --match-head-commit ${head}`), { gh });
1085
+ assert.ok(timeouts[0] < 5_900, `the first read gets ${timeouts[0]} ms`);
1086
+ assert.ok(timeouts.length < 2 || timeouts[1] < timeouts[0] - 2_000);
1087
+ });
1088
+
1089
+ test("merge records share the hook budget and stop gh reads when it expires", (t) => {
1090
+ const ws = workspace(t);
1091
+ let now = 0;
1092
+ t.mock.method(Date, "now", () => now);
1093
+ const timeouts = [];
1094
+ const gh = (args, options) => {
1095
+ timeouts.push(options.timeoutMs);
1096
+ now = 6_001;
1097
+ return MERGED;
1098
+ };
1099
+ decide(shell(ws.on, "gh pr merge 60; gh pr merge 61", "PostToolUse"), { gh });
1100
+ assert.deepEqual(timeouts, [6_000]);
1101
+ });
1102
+
457
1103
  test("a loosening commit on the local base ref, absent from the PR base commit, does not open the lane", (t) => {
458
1104
  const strict = { swarm: { dispatch: {}, direct: { reviewPaths: ["**"] } }, worktree: { base: "main" } };
459
1105
  const { dir, base } = laneRepo(t, strict);
@@ -480,16 +1126,17 @@ test("a stale local base ref does not hide the review paths that the PR base com
480
1126
  assert.match(reason, /does not apply: a\.ts matches swarm\.direct\.reviewPaths/);
481
1127
  });
482
1128
 
483
- test("a PR base commit that the local repository lacks closes the lane and says to fetch", (t) => {
484
- const { dir, head } = laneRepo(t);
1129
+ test("a PR base commit that the local repository lacks blocks an approved merge and says to fetch", (t) => {
1130
+ const { dir, head, ledger } = laneRepo(t);
1131
+ appendRecord(ledger, verdict("branch", "APPROVED", head));
485
1132
  const reason = denied(decide(merge7(dir, head), { gh: fakeGh(prView("1234567890123456789012345678901234567890")).gh })) ?? "";
486
- assert.match(reason, /does not apply: the PR base commit 1234567890\w* is not in this repository, so run `git fetch`/);
1133
+ assert.match(reason, /the PR base commit 1234567890\w* is not in this repository, so run `git fetch`/);
487
1134
  });
488
1135
 
489
- test("a gh answer with no base commit closes the lane", (t) => {
1136
+ test("a gh answer with no base commit blocks the merge policy check", (t) => {
490
1137
  const { dir, head } = laneRepo(t);
491
1138
  const reason = denied(decide(merge7(dir, head), { gh: fakeGh(JSON.stringify({ baseRefName: "main" })).gh })) ?? "";
492
- assert.match(reason, /does not apply: gh returned no base commit for the PR/);
1139
+ assert.match(reason, /gh returned no base commit for the PR/);
493
1140
  });
494
1141
 
495
1142
  test("a merge waits while the newest review of any scope on the head asks for changes", () => {
@@ -503,14 +1150,96 @@ test("a merge waits while the newest review of any scope on the head asks for ch
503
1150
  assert.equal(mergeVerdict([{ sha }], records, "branch").refusal, null);
504
1151
  });
505
1152
 
506
- test("a merge needs an APPROVED review of every scope dispatched on the branch", () => {
507
- const sha = "c".repeat(40);
1153
+ test("task merge reviews pass despite a scoped branch dispatch", (t) => {
1154
+ const ws = workspace(t);
1155
+ const command = `gh pr merge 60 --match-head-commit ${SHA}`;
1156
+ appendRecord(ws.ledgerOf(ws.task), {
1157
+ type: "dispatch", task: false, agentType: "sdd-branch-reviewer", branch: "feat/62-x", head: SHA, scope: "security",
1158
+ });
1159
+ assert.match(denied(decide(shell(ws.task, command))) ?? "", /no APPROVED task review/);
1160
+ appendRecord(ws.ledgerOf(ws.task), verdict("task", "APPROVED"));
1161
+ assert.equal(decide(shell(ws.task, command)), null);
1162
+ appendRecord(ws.ledgerOf(ws.task), verdict("task", "CHANGES_REQUIRED"));
1163
+ assert.match(denied(decide(shell(ws.task, command))) ?? "", /CHANGES_REQUIRED/);
1164
+ });
1165
+
1166
+ test("Codex merge verdicts are opt-in, SHA pinned, and ordered with configured reviews", () => {
1167
+ const merges = [{ sha: SHA }];
1168
+ const judge = (records, runtime = "codex") => mergeVerdict(merges, records, "branch", null, null, runtime).refusal;
1169
+ assert.equal(judge([verdict("codex", "APPROVED")]), null);
1170
+ assert.ok(judge([verdict("codex", "APPROVED")], "claude"));
1171
+ assert.ok(judge([verdict("codex", "APPROVED", "a".repeat(40))]));
1172
+ assert.ok(judge([verdict("branch", "APPROVED"), verdict("codex", "CHANGES_REQUIRED")]));
1173
+ assert.equal(judge([verdict("branch", "CHANGES_REQUIRED"), verdict("codex", "APPROVED")]), null);
1174
+ assert.ok(judge([verdict("codex", "APPROVED"), verdict("branch", "CHANGES_REQUIRED")]));
1175
+ });
1176
+
1177
+ test("a scoped Codex record cannot override a named branch scope", () => {
508
1178
  const records = [
509
- { type: "dispatch", task: false, agentType: "sdd-branch-reviewer", branch: "f", head: sha, scope: "a" },
510
- { type: "dispatch", task: false, agentType: "sdd-branch-reviewer", branch: "f", head: sha, scope: "b" },
511
- { type: "verdict", kind: "branch", verdict: "APPROVED", sha, branch: "f", scope: "a" },
1179
+ { ...verdict("branch", "CHANGES_REQUIRED"), scope: "security" },
1180
+ { ...verdict("codex", "APPROVED"), scope: "security" },
1181
+ verdict("codex", "APPROVED"),
512
1182
  ];
513
- assert.match(mergeVerdict([{ sha }], records, "branch").refusal ?? "", /scope "b"/);
514
- records.push({ type: "verdict", kind: "branch", verdict: "APPROVED", sha, branch: "f", scope: "b" });
515
- assert.equal(mergeVerdict([{ sha }], records, "branch").refusal, null);
1183
+ assert.match(mergeVerdict([{ sha: SHA }], records, "branch", null, null, "codex").refusal, /CHANGES_REQUIRED/);
1184
+ assert.ok(mergeVerdict([{ sha: SHA }], [records[1]], "branch", null, null, "codex").refusal);
1185
+ });
1186
+
1187
+ for (const runtime of ["claude", "codex"]) {
1188
+ test(`the PR base runtime ${runtime} decides whether Codex counts`, (t) => {
1189
+ const { dir, head, base, ledger } = laneRepo(t, { swarm: { dispatch: {}, direct: false, review: { runtime } } });
1190
+ writeFileSync(path.join(dir, "qc.config.json"), JSON.stringify({ swarm: { dispatch: {}, direct: false, review: { runtime: runtime === "codex" ? "claude" : "codex" } } }));
1191
+ appendRecord(ledger, verdict("codex", "APPROVED", head));
1192
+ const output = decide(shell(dir, `gh pr merge 7 --match-head-commit ${head}`), { gh: fakeGh(prView(base)).gh });
1193
+ if (runtime === "codex") assert.equal(denied(output), null);
1194
+ else assert.match(denied(output), /no APPROVED branch review/);
1195
+ });
1196
+ }
1197
+
1198
+ test("Codex constituent verdicts do not satisfy the integration lane", (t) => {
1199
+ const { dir, head, base } = integrationMergeRepo(t, { kind: "codex", runtime: "codex" });
1200
+ const output = decide(shell(dir, `gh pr merge 7 --match-head-commit ${head}`), { gh: fakeGh(prViewWithHead(base, "feat/7-integration")).gh });
1201
+ assert.match(denied(output), /integration lane .*does not apply: .*holds? no APPROVED review/);
1202
+ });
1203
+
1204
+ test("a milestone validates approved member trees, migrations and aggregate policy", (t) => {
1205
+ const failures = [];
1206
+ for (const mode of ["branch", "sha256", "codex", "codex disabled", "scopes", "missing", "revoked", "disabled", "unreviewed commit", "tampered merge", "migrations", "generated"]) {
1207
+ const repo = integrationMergeRepo(t, { objectFormat: mode === "sha256" ? "sha256" : "sha1", kind: mode.startsWith("codex") ? "codex" : "branch", runtime: ["codex", "revoked"].includes(mode) ? "codex" : "claude", unreviewed: mode === "missing", migrations: mode === "migrations", generated: mode === "generated", ...(mode === "disabled" ? { integrate: { review: false } } : {}) });
1208
+ let head = repo.head;
1209
+ const git = (...args) => execFileSync("git", args, { cwd: repo.dir, encoding: "utf8", stdio: "pipe" }).trim();
1210
+ if (mode === "scopes") appendRecord(repo.ledger, { type: "dispatch", task: false, agentType: "sdd-branch-reviewer", branch: "task/7-b", head: git("rev-parse", "HEAD^2"), scope: "unreviewed" });
1211
+ if (mode === "revoked") appendRecord(repo.ledger, verdict("codex", "CHANGES_REQUIRED", git("rev-parse", "HEAD^2")));
1212
+ if (mode === "unreviewed commit") {
1213
+ writeFileSync(path.join(repo.dir, "extra.txt"), "extra"); git("add", "."); git("commit", "-qm", "extra"); head = git("rev-parse", "HEAD");
1214
+ }
1215
+ if (mode === "tampered merge") {
1216
+ git("restore", "--source=HEAD^2", "--staged", "--worktree", "a.ts");
1217
+ git("rm", "b.ts"); git("commit", "--amend", "--no-edit", "-q"); head = git("rev-parse", "HEAD");
1218
+ assert.equal(git("diff-tree", "--cc", "-r", "--no-commit-id", "--name-only", head), "");
1219
+ }
1220
+ if (mode === "migrations") {
1221
+ assert.equal(git("show", "HEAD:db/0002_b.sql"), "select 2;");
1222
+ assert.throws(() => git("show", "HEAD:db/0001_b.sql"));
1223
+ }
1224
+ if (mode === "generated") {
1225
+ writeFileSync(path.join(repo.dir, "generated.txt"), "generated output\n");
1226
+ git("add", "."); git("commit", "-qm", "chore: regenerate the generated files"); head = git("rev-parse", "HEAD");
1227
+ }
1228
+ const accepted = ["branch", "sha256", "codex", "scopes", "migrations", "generated"].includes(mode);
1229
+ if (!accepted) appendRecord(repo.ledger, verdict("branch", "APPROVED", head));
1230
+ const branches = ["milestone/2026-11-23-1", ...(["sha256", "tampered merge", "migrations", "generated"].includes(mode) ? ["feat/7-integration"] : [])];
1231
+ for (const branch of branches) {
1232
+ // Exercise the integration tree check without an aggregate approval bypass.
1233
+ if (branch === "feat/7-integration" && !accepted) rmSync(repo.ledger);
1234
+ if (branch === "feat/7-integration" && !accepted) {
1235
+ for (const member of [git("rev-parse", "HEAD^1^2"), git("rev-parse", "HEAD^2")]) appendRecord(repo.ledger, verdict("branch", "APPROVED", member));
1236
+ }
1237
+ const output = decide(shell(repo.dir, `gh pr merge 7 --squash --match-head-commit ${head}`), { gh: fakeGh(prViewWithHead(repo.base, branch)).gh });
1238
+ if (accepted) {
1239
+ if (denied(output) !== null) failures.push({ mode, branch, reason: denied(output) });
1240
+ else assert.match(output?.hookSpecificOutput?.additionalContext ?? "", /integration lane/, mode);
1241
+ } else if (!/milestone|integration lane/.test(denied(output) ?? "")) failures.push({ mode, branch, reason: denied(output) });
1242
+ }
1243
+ }
1244
+ assert.deepEqual(failures, []);
516
1245
  });