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,213 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { spawnSync } from "node:child_process";
3
+ import { createHash } from "node:crypto";
4
+ import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { test } from "node:test";
8
+ import { fileURLToPath } from "node:url";
9
+ import { fleetPath, validateFleet, ownerOf, freeIssues, runFleet } from "./fleet.mjs";
10
+
11
+ const nodes = [
12
+ { id: "a1", weight: 1, maxSize: "L", active: true },
13
+ { id: "b2", weight: 1, maxSize: "L", active: true },
14
+ { id: "c3", weight: 2, maxSize: "L", active: true },
15
+ ];
16
+ const issue = (number, labels = [], createdAt = "2026-01-01T00:00:00Z") => ({ number, labels: labels.map(name => ({ name })), createdAt });
17
+ const qc = fileURLToPath(new URL("./qc.mjs", import.meta.url));
18
+
19
+ function fixture(t) {
20
+ const cwd = mkdtempSync(path.join(os.tmpdir(), "qc-fleet-"));
21
+ t.after(() => rmSync(cwd, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
22
+ const env = { QC_FLEET_FILE: path.join(cwd, "config", "fleet.json") };
23
+ const lines = [], errors = [];
24
+ const deps = { cwd, env, say: line => lines.push(line), warn: line => errors.push(line) };
25
+ const run = (args, extra = {}) => {
26
+ lines.length = errors.length = 0;
27
+ const code = runFleet(args, { ...deps, ...extra });
28
+ return { code, lines: [...lines], errors: [...errors] };
29
+ };
30
+ return { cwd, env, run };
31
+ }
32
+
33
+ function fakeGh(issues, prs = []) {
34
+ return (args, options) => {
35
+ assert.ok(options.cwd);
36
+ const expected = args[0] === "issue"
37
+ ? ["issue", "list", "--state", "open", "--limit", "500", "--json", "number,labels,createdAt", "--repo", "o/r"]
38
+ : ["pr", "list", "--state", "open", "--limit", "200", "--json", "number,headRefName,body", "--repo", "o/r"];
39
+ assert.deepEqual(args, expected);
40
+ return JSON.stringify(args[0] === "issue" ? issues : prs);
41
+ };
42
+ }
43
+
44
+ test("fleet validates every field, defaults, paths, missing file and unreadable inputs", t => {
45
+ const valid = { self: "a1", nodes: [{ id: "a1", weight: 1 }] };
46
+ assert.deepEqual(validateFleet(valid), { self: "a1", nodes: [nodes[0]] });
47
+ for (const [value, field] of [
48
+ [null, "fleet"], [{}, "nodes"], [{ self: "a1", nodes: [] }, "self"],
49
+ [{ ...valid, self: "other" }, "self"],
50
+ ...["A", "a/b", "a".repeat(33), ""].map(id => [{ ...valid, nodes: [{ id, weight: 1 }] }, "id"]),
51
+ [{ ...valid, nodes: [nodes[0], nodes[0]] }, "id"],
52
+ ...[0, -1, 101, "1", NaN, Infinity].map(weight => [{ ...valid, nodes: [{ id: "a1", weight }] }, "weight"]),
53
+ [{ ...valid, nodes: [null] }, "nodes"],
54
+ [{ ...valid, nodes: [{ ...nodes[0], maxSize: "XL" }] }, "maxSize"],
55
+ [{ ...valid, nodes: [{ ...nodes[0], active: "false" }] }, "active"],
56
+ ]) assert.throws(() => validateFleet(value), new RegExp(field));
57
+ assert.equal(fleetPath({ QC_FLEET_FILE: "/fleet" }, "linux", "/home/test"), "/fleet");
58
+ assert.equal(fleetPath({ APPDATA: "/app" }, "win32", "/home/test"), path.join("/app", "qc", "fleet.json"));
59
+ assert.equal(fleetPath({ XDG_CONFIG_HOME: "/xdg" }, "linux", "/home/test"), path.join("/xdg", "qc", "fleet.json"));
60
+ assert.equal(fleetPath({}, "linux", "/home/test"), path.join("/home/test", ".config", "qc", "fleet.json"));
61
+ const f = fixture(t);
62
+ for (const verb of ["next", "status"]) {
63
+ const result = f.run([verb]);
64
+ assert.equal(result.code, 1);
65
+ assert.deepEqual(result.errors, [`fleet is off: no ${f.env.QC_FLEET_FILE}`]);
66
+ }
67
+ assert.equal(f.run(["init", "--self", "a1", "--nodes", "a1:1:L"]).code, 0);
68
+ writeFileSync(f.env.QC_FLEET_FILE, "{");
69
+ assert.match(f.run(["status"]).errors.join(""), /fleet.*JSON/i);
70
+ writeFileSync(f.env.QC_FLEET_FILE, JSON.stringify(valid));
71
+ assert.equal(f.run(["next", "--wat"]).code, 1);
72
+ assert.equal(f.run(["next", "--repo"]).code, 1);
73
+ assert.equal(f.run(["next", "--repo", "bad"]).code, 1);
74
+ for (const gh of [() => null, () => "{}", () => "bad"]) {
75
+ assert.equal(f.run(["status", "--repo", "o/r"], { gh, git: () => "" }).code, 1);
76
+ }
77
+ assert.equal(f.run(["next", "--repo", "o/r"], { gh: fakeGh([]), git: () => null }).code, 1);
78
+ assert.equal(f.run(["status", "--repo", "o/r"], { gh: args => args[0] === "issue" ? "[]" : null, git: () => "" }).code, 1);
79
+ assert.equal(f.run(["next"], { origin: () => null }).code, 1);
80
+ });
81
+
82
+ test("ownerOf repeats across calls and repo case, using the specified SHA-256 score", () => {
83
+ for (let number = 1; number <= 100; number++) {
84
+ const expected = [...nodes].sort((a, b) => {
85
+ const score = node => {
86
+ const bytes = createHash("sha256").update(`o/r#${number}:${node.id}`).digest().readBigUInt64BE();
87
+ const u = Number(bytes + 1n) / Number(2n ** 64n + 2n);
88
+ return -node.weight / Math.log(u);
89
+ };
90
+ return score(b) - score(a);
91
+ })[0].id;
92
+ assert.equal(ownerOf("O/R", number, "M", nodes), expected);
93
+ assert.equal(ownerOf("o/r", number, "M", [...nodes].reverse()), expected);
94
+ }
95
+ });
96
+
97
+ test("weights 1,1,2 give the weight-2 node 45% to 55% of 3000 issues", () => {
98
+ let count = 0;
99
+ for (let number = 1; number <= 3000; number++) if (ownerOf("o/r", number, "M", nodes) === "c3") count++;
100
+ assert.ok(count >= 1350 && count <= 1650, `c3 owns ${count}/3000`);
101
+ });
102
+
103
+ test("deactivation moves only the inactive node's issues", () => {
104
+ const reduced = nodes.map(node => ({ ...node, active: node.id !== "b2" }));
105
+ for (let number = 1; number <= 300; number++) {
106
+ const before = ownerOf("o/r", number, "M", nodes);
107
+ const after = ownerOf("o/r", number, "M", reduced);
108
+ if (before === "b2") assert.notEqual(after, "b2");
109
+ else assert.equal(after, before);
110
+ }
111
+ });
112
+
113
+ test("size filtering respects S < M < L, defaults and case-insensitive labels", () => {
114
+ const small = [{ id: "s", weight: 1, maxSize: "S" }];
115
+ assert.equal(ownerOf("o/r", 1, "S", small), "s");
116
+ assert.equal(ownerOf("o/r", 1, "M", small), null);
117
+ assert.equal(ownerOf("o/r", 1, "L", [{ ...small[0], maxSize: "M" }]), null);
118
+ assert.equal(ownerOf("o/r", 1, "S", [{ ...small[0], active: false }]), null);
119
+ const result = freeIssues("o/r", "/tmp", { gh: fakeGh([issue(1, ["SIZE:s"]), issue(2), issue(3, ["size:l"])]), git: () => "" });
120
+ assert.deepEqual(result.free.map(row => row.size), ["S", "M", "L"]);
121
+ });
122
+
123
+ test("free issues exclude hold labels and taken PR bodies, PR branches and origin branches", () => {
124
+ const issues = Array.from({ length: 12 }, (_, i) => issue(i + 1));
125
+ issues.push(issue(13, ["hold"]), issue(14, ["custom-hold"]), issue(15, ["fleet-skip"]));
126
+ const prs = [{ number: 90, headRefName: "feat/2-work", body: "Fixes #1, #12. Avoid #30 and x#4 and #5suffix and #6_thing." }];
127
+ let branchRead = false;
128
+ const result = freeIssues("o/r", "/tmp", {
129
+ gh: fakeGh(issues, prs), holdLabel: "custom-hold",
130
+ git: (cwd, ...args) => {
131
+ assert.equal(cwd, "/tmp");
132
+ assert.deepEqual(args, ["ls-remote", "--heads", "origin"]);
133
+ branchRead = true;
134
+ return "abc\trefs/heads/fix/3-work\nabc\trefs/heads/fix/40-work\nabc\trefs/heads/fix/7\nabc\trefs/heads/nested/fix/8-work\n";
135
+ },
136
+ });
137
+ assert.ok(branchRead);
138
+ assert.deepEqual(result.free.map(row => row.number), [4, 5, 6, 7, 8, 9, 10, 11]);
139
+ assert.equal(result.taken, 4);
140
+ assert.deepEqual(freeIssues("o/r", "/tmp", {
141
+ gh: fakeGh([issue(1)], [{ number: 90, headRefName: "feat/12-x", body: "Fixes #12" }]),
142
+ git: () => "abc\trefs/heads/feat/12-x\n",
143
+ }).free.map(row => row.number), [1]);
144
+ });
145
+
146
+ test("next prints the oldest five or all, exits 3 when empty, and status stays within 15 lines", t => {
147
+ const remoteFixture = fixture(t);
148
+ const git = (...args) => {
149
+ const result = spawnSync("git", args, { cwd: remoteFixture.cwd, encoding: "utf8" });
150
+ assert.equal(result.status, 0, result.stderr);
151
+ return result.stdout;
152
+ };
153
+ git("init");
154
+ git("init", "--bare", "origin.git");
155
+ git("init", "--bare", "requested.git");
156
+ git("-c", "user.name=Fleet Test", "-c", "user.email=fleet@example.test", "-c", "commit.gpgsign=false", "commit", "--allow-empty", "-m", "fixture");
157
+ git("remote", "add", "origin", path.join(remoteFixture.cwd, "origin.git"));
158
+ git("push", "origin", "HEAD:refs/heads/feat/1-x");
159
+ git("config", `url.${path.join(remoteFixture.cwd, "requested.git")}.insteadOf`, "https://github.com/o/r.git");
160
+ assert.equal(remoteFixture.run(["init", "--self", "a1", "--nodes", "a1:1:L"]).code, 0);
161
+ const remoteReaders = { gh: fakeGh([issue(1)]), origin: () => "local/repo" };
162
+ assert.equal(remoteFixture.run(["next", "--repo", "local/repo"], {
163
+ ...remoteReaders, gh: args => JSON.stringify(args[0] === "issue" ? [issue(1)] : []),
164
+ }).code, 3);
165
+ assert.deepEqual(remoteFixture.run(["next", "--repo", "o/r"], remoteReaders), {
166
+ code: 0, lines: ["1"], errors: [],
167
+ });
168
+ const f = fixture(t);
169
+ assert.equal(f.run(["init", "--self", "a1", "--nodes", "a1:1:L,b2:1:S"]).code, 0);
170
+ const issues = Array.from({ length: 12 }, (_, i) => issue(i + 1, ["size:L"], `2026-01-${String(12 - i).padStart(2, "0")}T00:00:00Z`));
171
+ const extra = { gh: fakeGh(issues), git: () => "", origin: () => "o/r" };
172
+ assert.deepEqual(f.run(["next"], extra), { code: 0, lines: ["12", "11", "10", "9", "8"], errors: [] });
173
+ assert.deepEqual(f.run(["next", "--repo", "o/r", "--all"], extra).lines, issues.map(row => String(row.number)).reverse());
174
+ writeFileSync(path.join(f.cwd, "qc.config.json"), JSON.stringify({ merge: { holdLabel: "custom-hold" } }));
175
+ assert.equal(f.run(["next", "--repo", "o/r"], { ...extra, gh: fakeGh([issue(99, ["custom-hold"])]) }).code, 3);
176
+ const empty = f.run(["next", "--repo", "o/r"], { ...extra, gh: fakeGh([]) });
177
+ assert.deepEqual(empty, { code: 3, lines: [], errors: ["no free issue for a1"] });
178
+ const status = f.run(["status", "--repo", "o/r"], extra);
179
+ assert.equal(status.code, 0);
180
+ assert.equal(status.lines.length, 3);
181
+ assert.match(status.lines[0], /a1.*1.*L.*true.*12.*12,11,10,9,8,7,6,5,4,3$/);
182
+ assert.match(status.lines[1], /b2.*1.*S.*true.*0/);
183
+ assert.match(status.lines[2], /taken.*0.*unassigned.*0/);
184
+ const many = Array.from({ length: 20 }, (_, i) => ({ id: `pc${i}`, weight: 1, maxSize: "L", active: true }));
185
+ writeFileSync(f.env.QC_FLEET_FILE, JSON.stringify({ self: "pc0", nodes: many }));
186
+ const capped = f.run(["status", "--repo", "o/r"], extra);
187
+ assert.equal(capped.lines.length, 15);
188
+ assert.match(capped.lines.at(-1), /6 more nodes/);
189
+ writeFileSync(f.env.QC_FLEET_FILE, JSON.stringify({ self: "a1", nodes: [{ ...nodes[0], active: false }] }));
190
+ assert.match(f.run(["status", "--repo", "o/r"], extra).lines.at(-1), /unassigned.*12/);
191
+ });
192
+
193
+ test("init routes through qc from an empty folder, creates mode 0600 and refuses replacement", t => {
194
+ const guide = readFileSync(new URL("../../../../docs/fleet.md", import.meta.url), "utf8");
195
+ assert.ok(guide.trimEnd().split("\n").length <= 40);
196
+ assert.match(guide, /QC_FLEET_FILE/);
197
+ assert.match(guide, /active.*false/);
198
+ const reference = readFileSync(new URL("../../../../docs/reference.md", import.meta.url), "utf8");
199
+ for (const verb of ["init", "next", "status"]) assert.match(reference, new RegExp(`\\| .*qc fleet ${verb}.*\\|`));
200
+ const f = fixture(t);
201
+ const call = args => spawnSync(process.execPath, [qc, "fleet", ...args], { cwd: f.cwd, env: { ...process.env, ...f.env }, encoding: "utf8" });
202
+ const args = ["init", "--self", "a1", "--nodes", "a1:1:L,b2:2:M,c3:1:S"];
203
+ const first = call(args);
204
+ assert.equal(first.status, 0, first.stderr);
205
+ const saved = readFileSync(f.env.QC_FLEET_FILE, "utf8");
206
+ assert.equal(JSON.parse(saved).nodes.length, 3);
207
+ if (process.platform !== "win32") assert.equal(statSync(f.env.QC_FLEET_FILE).mode & 0o777, 0o600);
208
+ assert.equal(call(args).status, 1);
209
+ assert.equal(readFileSync(f.env.QC_FLEET_FILE, "utf8"), saved);
210
+ assert.equal(call([...args, "--force"]).status, 0);
211
+ for (const nodesArg of ["a1:1:L:extra", "a1:no:L", "a1:1:XL"]) assert.equal(call(["init", "--self", "a1", "--nodes", nodesArg, "--force"]).status, 1);
212
+ assert.equal(call(["init", "--self", "a1"]).status, 1);
213
+ });
@@ -113,11 +113,13 @@ export async function runGateSlot(argv, deps = {}) {
113
113
  let values;
114
114
  let slots;
115
115
  let maxMinutes;
116
+ let line;
116
117
  try {
117
118
  ({ values } = parseArgs({ args: flags, options: { slots: { type: "string" }, "max-minutes": { type: "string" }, status: { type: "boolean" } }, strict: true }));
118
119
  slots = positive(values.slots ?? env.QC_GATE_SLOTS ?? String(DEFAULT_SLOTS), "--slots");
119
120
  maxMinutes = positive(values["max-minutes"] ?? String(DEFAULT_MAX_MINUTES), "--max-minutes");
120
121
  if (!values.status && command.length === 0) throw new Error("name the command after --");
122
+ line = commandLine(command);
121
123
  } catch (error) {
122
124
  say(`qc gate-slot: ${error.message}\n\n${USAGE}`);
123
125
  return 2;
@@ -132,7 +134,6 @@ export async function runGateSlot(argv, deps = {}) {
132
134
  }
133
135
  return 0;
134
136
  }
135
- const line = commandLine(command);
136
137
  let file = null;
137
138
  let waited = false;
138
139
  while (file === null) {
@@ -13,10 +13,10 @@ const GH_SETTINGS = ["GH_CONFIG_DIR", "GH_HOST", "GH_REPO"];
13
13
  const VALUE_FLAGS = new Set(["-b", "--body", "-F", "--body-file", "-t", "--subject", "-A", "--author-email", "--match-head-commit", "--repo"]);
14
14
  const ASSIGNMENT = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s;
15
15
  const POWERSHELL_ENV = /^\$env:([A-Za-z_][A-Za-z0-9_]*)(?:=(.*))?$/is;
16
- const MERGE_ENDPOINT = /^(?:https?:\/\/[^/]+\/(?:api\/v3\/)?)?\/?(?:repos\/[^/]+\/[^/]+\/)?pulls\/\d+\/merge\/?(?:\?.*)?$/;
16
+ const MERGE_ENDPOINT = /^(?:https?:\/\/[^/]+\/(?:api\/v3\/)?)?\/?(?:repos\/[^/]+\/[^/]+\/)?pulls\/\d+\/merge\/?$/;
17
17
  const MERGE_MUTATION = /\bmergePullRequest\b/;
18
- const GRAPHQL_ENDPOINT = /(?:^|\/)graphql\/?(?:\?.*)?$/;
19
- const FIELD_FLAGS = new Set(["--field"]);
18
+ const GRAPHQL_ENDPOINT = /(?:^|\/)graphql\/?$/;
19
+ const FIELD_FLAGS = new Set(["--field", "--raw-field"]);
20
20
  const PR_URL = /^https?:\/\/[^/]+\/([^/]+\/[^/]+)\/pull\/\d+/;
21
21
  const REST_PATH = /^(?:https?:\/\/[^/]+\/(?:api\/v3\/)?)?\/?repos\//;
22
22
  /** The short flags of `gh pr merge` and of `gh api` that take a value, and the long flags of `gh api` that do. */
@@ -25,6 +25,8 @@ const API_VALUE_LETTERS = "FfHXqtp";
25
25
  const API_VALUE_FLAGS = new Set(["--field", "--raw-field", "--header", "--method", "--jq", "--template", "--input", "--hostname", "--cache", "--preview"]);
26
26
  const MAX_QUERY_BYTES = 1024 * 1024;
27
27
 
28
+ const endpointPathFragment = (endpoint) => endpoint.split(/[?#]/, 1)[0];
29
+
28
30
  /** Only the settings that choose gh's account or host; a token is a credential and is never kept. */
29
31
  const kept = (env) => Object.fromEntries(Object.entries(env).filter(([name]) => GH_SETTINGS.includes(name)));
30
32
 
@@ -64,7 +66,7 @@ function leadingFlags(words) {
64
66
  * The words after `gh` as a command: its group, its verb, the words after the verb, and the repository a flag before the verb names.
65
67
  * `gh pr -R o/r merge 60` and `gh -R o/r pr merge 60` are `pr merge 60`. `rest` holds every word after the group, flags kept.
66
68
  */
67
- function ghCommand(words) {
69
+ export function ghCommand(words) {
68
70
  const first = leadingFlags(words);
69
71
  const [group, ...rest] = first.rest;
70
72
  const second = leadingFlags(rest);
@@ -99,7 +101,7 @@ function mergeOf(args) {
99
101
  }
100
102
 
101
103
  /** Every gh call in the command, in order, as `{ words, env }` with the words after `gh`; a nested shell's lines count. */
102
- function ghCalls(command, parse) {
104
+ export function ghCalls(command, parse) {
103
105
  const calls = [];
104
106
  let env = {};
105
107
  for (const segment of parse(command)) {
@@ -125,7 +127,9 @@ export function ghMerges(command, parse) {
125
127
  if (!merge) continue;
126
128
  // The repository comes from a PR URL first, then -R or --repo (the one written last), then GH_REPO. GH_REPO is no setting to keep.
127
129
  const { GH_REPO: fromEnv, ...settings } = env;
128
- merge.repo = PR_URL.exec(merge.selector ?? "")?.[1] ?? merge.repo ?? repo ?? fromEnv ?? null;
130
+ const url = PR_URL.exec(merge.selector ?? "");
131
+ if (url) merge.host = new URL(merge.selector).host;
132
+ merge.repo = url?.[1] ?? merge.repo ?? repo ?? fromEnv ?? null;
129
133
  merges.push({ ...merge, env: settings });
130
134
  }
131
135
  return merges;
@@ -138,32 +142,30 @@ function fileOf(cwd, spelled) {
138
142
  }
139
143
 
140
144
  /**
141
- * The files a `gh api` call reads its body from: each `-F key=@file`, and `--input file`. `-` is standard input.
145
+ * The fragment that reads the fields and input flags of a `gh api` call.
142
146
  * pflag reads a short flag with its value attached (`-Fkey=@file`, `-F=key=@file`) and a cluster of short flags
143
147
  * that ends in `-F` (`-iFkey=@file`, `-iF key=@file`). A letter that takes a value ends a cluster, so it hides an `F` after it.
144
148
  */
145
- function bodyFiles(args) {
146
- const files = [];
147
- const add = (field) => {
148
- if (/^[^=]*=@/.test(field)) files.push(field.slice(field.indexOf("@") + 1));
149
- };
149
+ function bodyValues(args) {
150
+ const values = [];
150
151
  for (let i = 0; i < args.length; i++) {
151
152
  const arg = args[i];
152
- const cluster = /^-([A-Za-z]*)F(.*)$/s.exec(arg);
153
- if (cluster && !/[fFHXqt]/.test(cluster[1])) {
154
- const value = cluster[2] === "" ? args[++i] : cluster[2].replace(/^=/, "");
155
- if (value !== undefined) add(value);
153
+ if (arg.startsWith("-") && !arg.startsWith("--")) {
154
+ const at = [...arg.slice(1)].findIndex((letter) => API_VALUE_LETTERS.includes(letter));
155
+ if (at === -1) continue;
156
+ const flag = arg[at + 1];
157
+ const value = at === arg.length - 2 ? args[++i] : arg.slice(at + 2).replace(/^=/, "");
158
+ if ((flag === "f" || flag === "F") && value !== undefined) values.push({ flag, value });
156
159
  continue;
157
160
  }
158
161
  const at = arg.startsWith("--") ? arg.indexOf("=") : -1;
159
162
  const flag = at === -1 ? arg : arg.slice(0, at);
160
- if (flag !== "--input" && !FIELD_FLAGS.has(flag)) continue;
163
+ if (!API_VALUE_FLAGS.has(flag)) continue;
161
164
  const value = at === -1 ? args[++i] : arg.slice(at + 1);
162
165
  if (value === undefined) continue;
163
- if (flag === "--input") files.push(value);
164
- else add(value);
166
+ if (flag === "--input" || FIELD_FLAGS.has(flag)) values.push({ flag, value });
165
167
  }
166
- return files;
168
+ return values;
167
169
  }
168
170
 
169
171
  /** The text of a query file, or null when it is standard input, too large, or unreadable. */
@@ -178,6 +180,36 @@ function queryText(cwd, spelled) {
178
180
  }
179
181
  }
180
182
 
183
+ /** The fragment that names each mutation's PR node, or null when its input cannot name one. */
184
+ function mutationNodes(query, fields) {
185
+ if (typeof query !== "string") return [null];
186
+ const tokens = (query.match(/#[^\r\n]*|"""[\s\S]*?"""|"(?:\\.|[^"\\])*"|[A-Za-z_][A-Za-z_0-9]*|[^\s,]/g) ?? []).filter((token) => !token.startsWith("#"));
187
+ const nodes = [];
188
+ for (let i = 0; i < tokens.length; i++) {
189
+ if (tokens[i] !== "mergePullRequest") continue;
190
+ let node = null;
191
+ if (tokens[i + 1] === "(" && tokens[i + 2] === "input" && tokens[i + 3] === ":" && tokens[i + 4] === "{") {
192
+ let depth = 1;
193
+ let ids = 0;
194
+ for (let j = i + 5; j < tokens.length && depth > 0; j++) {
195
+ if (tokens[j] === "{") depth++;
196
+ if (tokens[j] === "}") depth--;
197
+ if (depth !== 1 || tokens[j] !== "pullRequestId" || tokens[j + 1] !== ":") continue;
198
+ ids++;
199
+ try {
200
+ const value = tokens[j + 2] === "$" ? fields[tokens[j + 3]] : JSON.parse(tokens[j + 2]);
201
+ node = typeof value === "string" && value.length > 0 ? value : null;
202
+ } catch {
203
+ node = null;
204
+ }
205
+ }
206
+ if (ids !== 1 || depth !== 0) node = null;
207
+ }
208
+ nodes.push(node);
209
+ }
210
+ return nodes.length > 0 ? nodes : [null];
211
+ }
212
+
181
213
  /** True for a `repos/` path that stays inside `repos/`: no `..` segment, spelled or percent-encoded, and no end at `graphql`. */
182
214
  const isRestPath = (endpoint) => REST_PATH.test(endpoint) && !/(?:^|\/)(?:\.|%2e){2}(?:\/|$)/i.test(endpoint) && !GRAPHQL_ENDPOINT.test(endpoint);
183
215
 
@@ -199,30 +231,63 @@ function apiEndpoint(args) {
199
231
  }
200
232
 
201
233
  /**
202
- * Each `gh api` call that merges with no review check, as `{ endpoint, unreadable }`. `endpoint` is the PR merge
203
- * endpoint as written, or the GraphQL URL as written (`graphql` when the call spells none). A call holds a
234
+ * Each `gh api` call that merges with no review check, as `{ endpoint, nodeId, unreadable }`. `endpoint` is the PR merge
235
+ * endpoint or GraphQL URL without its query or fragment (`graphql` when the call spells none). A call holds a
204
236
  * `mergePullRequest` mutation when any argument, or any query file it reads, names it, whatever the URL spelling.
237
+ * `nodeId` names each GraphQL mutation's PR, or null when its input cannot name one.
205
238
  * A GraphQL call whose query file the guard cannot read fails closed, and `unreadable` names that file.
239
+ * `inputField` names the field flag mixed with `--input`, which puts fields in the URL query string.
206
240
  * A call whose endpoint is a `repos/` REST path that stays inside it holds no mutation, so its arguments and files are not searched.
207
241
  * @param options.cwd the folder a relative query file resolves against
208
242
  */
209
243
  export function ghApiMerges(command, parse, { cwd = process.cwd() } = {}) {
210
244
  return ghCalls(command, parse)
211
- .map(({ words }) => ghCommand(words))
245
+ .map(({ words, env }) => ({ ...ghCommand(words), env }))
212
246
  .filter(({ group }) => group === "api")
213
- .flatMap(({ rest: args }) => {
214
- const found = args.filter((word) => MERGE_ENDPOINT.test(word)).map((endpoint) => ({ endpoint }));
215
- if (isRestPath(apiEndpoint(args) ?? "")) return found;
216
- const graphql = args.find((word) => GRAPHQL_ENDPOINT.test(word));
247
+ .flatMap(({ rest: args, env }) => {
248
+ const settings = { ...env };
249
+ for (let i = 0; i < args.length; i++) {
250
+ if (args[i] === "--hostname") settings.GH_HOST = args[++i];
251
+ else if (args[i].startsWith("--hostname=")) settings.GH_HOST = args[i].slice("--hostname=".length);
252
+ }
253
+ const withSettings = (calls) => calls.map((call) => ({ ...call, env: settings }));
254
+ const found = args.map(endpointPathFragment).filter((word) => MERGE_ENDPOINT.test(word)).map((endpoint) => ({ endpoint }));
255
+ const spelled = apiEndpoint(args);
256
+ const endpoint = spelled === null ? null : endpointPathFragment(spelled);
257
+ if (isRestPath(endpoint ?? "")) return withSettings(found);
258
+ const graphql = endpoint !== null && GRAPHQL_ENDPOINT.test(endpoint) ? endpoint : undefined;
217
259
  let mutation = args.some((word) => MERGE_MUTATION.test(word));
218
260
  let unreadable;
219
- for (const file of bodyFiles(args)) {
220
- const text = queryText(cwd, file);
261
+ const fields = {};
262
+ let body = null;
263
+ let input = false;
264
+ let inputField;
265
+ for (const { flag, value } of bodyValues(args)) {
266
+ if (flag === "--input") input = true;
267
+ else inputField ??= flag.startsWith("--") ? flag : `-${flag}`;
268
+ const isInput = flag === "--input";
269
+ const at = value.indexOf("=");
270
+ if (!isInput && at === -1) continue;
271
+ const key = value.slice(0, at);
272
+ const field = value.slice(at + 1);
273
+ const file = isInput ? value : (flag === "F" || flag === "--field") && field.startsWith("@") ? field.slice(1) : null;
274
+ const text = file === null ? field : queryText(cwd, file);
221
275
  if (text === null) unreadable ??= file;
222
276
  else if (MERGE_MUTATION.test(text)) mutation = true;
277
+ if (!isInput) fields[key] = text;
278
+ else {
279
+ try { body = JSON.parse(text); } catch { body = null; }
280
+ }
281
+ }
282
+ if (input && inputField !== undefined && (graphql !== undefined || mutation)) {
283
+ found.push({ endpoint: graphql ?? "graphql", inputField });
284
+ return withSettings(found);
285
+ }
286
+ if (mutation) {
287
+ const nodes = unreadable === undefined ? mutationNodes(fields.query ?? body?.query, { ...body?.variables, ...fields }) : [null];
288
+ found.push(...nodes.map((nodeId) => ({ endpoint: graphql ?? "graphql", nodeId, ...(unreadable === undefined ? {} : { unreadable }) })));
223
289
  }
224
- if (mutation) found.push({ endpoint: graphql ?? "graphql" });
225
290
  else if (graphql !== undefined && unreadable !== undefined) found.push({ endpoint: graphql, unreadable });
226
- return found;
291
+ return withSettings(found);
227
292
  });
228
293
  }
@@ -58,6 +58,21 @@ test("a gh api call to a PR's merge endpoint is found, in each spelling, and no
58
58
 
59
59
  const MUTATION = "mutation { mergePullRequest(input: {pullRequestId: \"X\"}) { clientMutationId } }";
60
60
 
61
+ test("API endpoint matching strips the query and fragment while keeping the host", () => {
62
+ for (const parse of [segmentsOf, powershellSegments]) {
63
+ for (const suffix of ["#x", "?x=1", "?x=1#fragment", "#fragment?x=1"]) {
64
+ for (const endpoint of ["graphql", "https://ghe.example.com/api/graphql"]) {
65
+ assert.deepEqual(ghApiMerges(`gh api '${endpoint}${suffix}' --input -`, parse), [
66
+ { endpoint, unreadable: "-", env: {} },
67
+ ]);
68
+ }
69
+ assert.deepEqual(ghApiMerges(`gh api 'repos/o/r/pulls/1/merge${suffix}' -X PUT`, parse), [
70
+ { endpoint: "repos/o/r/pulls/1/merge", env: {} },
71
+ ]);
72
+ }
73
+ }
74
+ });
75
+
61
76
  test("a mutation word in any argument is found, whatever the spelling of the GraphQL URL", () => {
62
77
  for (const url of ["graphql", "/graphql", "https://api.github.com/graphql", "https://ghe.example.com/api/graphql", "graphql/"]) {
63
78
  assert.deepEqual(ghApiMerges(`gh api ${url} -f query='${MUTATION}'`, segmentsOf).map((call) => call.endpoint), [url], url);
@@ -68,6 +83,61 @@ test("a mutation word in any argument is found, whatever the spelling of the Gra
68
83
  assert.equal(ghApiMerges("gh api https://api.github.com/graphql -f query='query { viewer { login } }'", segmentsOf).length, 0);
69
84
  });
70
85
 
86
+ test("GraphQL merges carry each node id from the mutation or a field", () => {
87
+ const query = 'mutation($id: ID!) { mergePullRequest(input: {pullRequestId: $id}) { clientMutationId } }';
88
+ assert.equal(ghApiMerges(`gh api graphql -f query='${MUTATION}'`, segmentsOf)[0].nodeId, "X");
89
+ for (const flags of ["-f id=PR_123", "-F id=PR_123", "--raw-field=id=PR_123", "--field id=PR_123", "-fid=PR_123", "-iFid=PR_123"]) {
90
+ for (const parse of [segmentsOf, powershellSegments]) {
91
+ assert.equal(ghApiMerges(`gh api graphql -f query='${query}' ${flags}`, parse)[0].nodeId, "PR_123", flags);
92
+ }
93
+ }
94
+ assert.equal(ghApiMerges(`gh api graphql -f query='${query}'`, segmentsOf)[0].nodeId, null);
95
+ const multiple = 'mutation { a: mergePullRequest(input: {pullRequestId: "ON"}) { clientMutationId } b: mergePullRequest(input: {pullRequestId: "OFF"}) { clientMutationId } }';
96
+ assert.deepEqual(ghApiMerges(`gh api graphql -f query='${multiple}'`, segmentsOf).map((call) => call.nodeId), ["ON", "OFF"]);
97
+ });
98
+
99
+ test("GraphQL node identity ignores text inside comments and string values", () => {
100
+ const query = 'mutation { mergePullRequest(input: {clientMutationId: "pullRequestId: $decoy", pullRequestId: "ON"}) { clientMutationId } }';
101
+ assert.equal(ghApiMerges(`gh api graphql -f query='${query}' -f decoy=OFF`, segmentsOf)[0].nodeId, "ON");
102
+ const comment = 'mutation { mergePullRequest(input: { # pullRequestId: $decoy\n pullRequestId: "ON"}) { clientMutationId } }';
103
+ assert.equal(ghApiMerges(`gh api graphql -f query='${comment}' -f decoy=OFF`, segmentsOf)[0].nodeId, "ON");
104
+ });
105
+
106
+ test("GraphQL merges read node ids from query and input files", (t) => {
107
+ const dir = mkdtempSync(path.join(os.tmpdir(), "qc-gh-node-"));
108
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
109
+ const query = 'mutation($id: ID!) { mergePullRequest(input: {pullRequestId: $id}) { clientMutationId } }';
110
+ writeFileSync(path.join(dir, "merge.graphql"), query);
111
+ writeFileSync(path.join(dir, "body.json"), JSON.stringify({ query, variables: { id: "PR_file" } }));
112
+ for (const args of ["-F query=@merge.graphql -F id=PR_file", "--input body.json"]) {
113
+ assert.equal(ghApiMerges(`gh api graphql ${args}`, segmentsOf, { cwd: dir })[0].nodeId, "PR_file");
114
+ }
115
+ });
116
+
117
+ test("a GraphQL endpoint ignores a preceding header value", () => {
118
+ for (const header of ["-H https://github.com/graphql", "--header=https://github.com/graphql", "-iHhttps://github.com/graphql"]) {
119
+ for (const parse of [segmentsOf, powershellSegments]) {
120
+ const [found] = ghApiMerges(`gh api ${header} https://ghe.example.com/api/graphql -f query='${MUTATION}'`, parse);
121
+ assert.equal(found.endpoint, "https://ghe.example.com/api/graphql", header);
122
+ assert.equal(found.nodeId, "X");
123
+ }
124
+ }
125
+ });
126
+
127
+ test("GraphQL input mixed with fields cannot select a node", (t) => {
128
+ const dir = mkdtempSync(path.join(os.tmpdir(), "qc-gh-input-mix-"));
129
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
130
+ const query = 'mutation($id: ID!) { mergePullRequest(input: {pullRequestId: $id}) { clientMutationId } }';
131
+ writeFileSync(path.join(dir, "body.json"), JSON.stringify({ query, variables: { id: "PR_ON" } }));
132
+ for (const field of ["-f id=PR_OFF", `-f query='mutation { mergePullRequest(input: {pullRequestId: "PR_OFF"}) { clientMutationId } }'`]) {
133
+ for (const parse of [segmentsOf, powershellSegments]) {
134
+ const [found] = ghApiMerges(`gh api graphql --input body.json ${field}`, parse, { cwd: dir });
135
+ assert.equal(found.inputField, "-f");
136
+ assert.equal(found.nodeId, undefined);
137
+ }
138
+ }
139
+ });
140
+
71
141
  test("a query file the call reads is searched for the mutation, and a file the guard cannot read fails closed", (t) => {
72
142
  const dir = mkdtempSync(path.join(os.tmpdir(), "qc-gh-api-"));
73
143
  t.after(() => rmSync(dir, { recursive: true, force: true }));
@@ -108,6 +178,10 @@ test("the repository of a merge comes from a PR URL, GH_REPO, an attached -R, or
108
178
  const repoOf = (command, parse = segmentsOf) => ghMerges(command, parse)[0].repo;
109
179
  assert.equal(repoOf("gh pr merge https://github.com/o/r/pull/5 --match-head-commit abc1234"), "o/r");
110
180
  assert.equal(repoOf("gh pr merge https://ghe.example.com/o/r/pull/5/files"), "o/r");
181
+ assert.equal(ghMerges("gh pr merge https://ghe.example.com/o/r/pull/60", segmentsOf)[0].host, "ghe.example.com");
182
+ for (const selector of ["60", "feat/x"]) {
183
+ assert.equal(ghMerges(`gh pr merge ${selector}`, segmentsOf)[0].host, undefined);
184
+ }
111
185
  assert.equal(repoOf("GH_REPO=o/r gh pr merge 5"), "o/r");
112
186
  assert.equal(repoOf("export GH_REPO=o/r && gh pr merge 5"), "o/r");
113
187
  assert.equal(repoOf(String.raw`$env:GH_REPO = "o/r"; gh pr merge 5`, powershellSegments), "o/r");
@@ -1,12 +1,57 @@
1
1
  // A fragment that runs one gh call for a workflow hook. The caller passes the GH_* settings the user's
2
2
  // own command made, so the hook reads with the account that command used.
3
3
 
4
- import { spawnSync } from "node:child_process";
4
+ import { execFile, spawnSync } from "node:child_process";
5
5
  import os from "node:os";
6
6
  import path from "node:path";
7
7
 
8
8
  const GH_TIMEOUT_MS = 20_000;
9
9
 
10
+ /** Reads the consecutive JSON values printed by `gh api --paginate`. */
11
+ export function parsePages(text) {
12
+ if (typeof text !== "string" || !text.trim()) return null;
13
+ const pages = [];
14
+ const scalar = /(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/y;
15
+ let offset = 0;
16
+ try {
17
+ while (offset < text.length) {
18
+ if (/\s/.test(text[offset])) { offset++; continue; }
19
+ const start = offset;
20
+ if ('{["'.includes(text[offset])) {
21
+ let depth = 0;
22
+ let quoted = false;
23
+ let escaped = false;
24
+ do {
25
+ const char = text[offset++];
26
+ if (quoted) {
27
+ if (escaped) escaped = false;
28
+ else if (char === "\\") escaped = true;
29
+ else if (char === '"') quoted = false;
30
+ } else if (char === '"') quoted = true;
31
+ else if (char === "{" || char === "[") depth++;
32
+ else if (char === "}" || char === "]") depth--;
33
+ } while (offset < text.length && (depth > 0 || quoted));
34
+ if (depth !== 0 || quoted) return null;
35
+ } else {
36
+ scalar.lastIndex = offset;
37
+ if (!scalar.exec(text)) return null;
38
+ offset = scalar.lastIndex;
39
+ }
40
+ pages.push(JSON.parse(text.slice(start, offset)));
41
+ }
42
+ return pages;
43
+ } catch {
44
+ return null;
45
+ }
46
+ }
47
+
48
+ /** Flattens API object pages, or returns null for an unreadable list. */
49
+ export function parseApiList(text, key) {
50
+ const pages = parsePages(text);
51
+ if (!pages || !pages.every((page) => Array.isArray(page?.[key]))) return null;
52
+ return pages.flatMap((page) => page[key]);
53
+ }
54
+
10
55
  /** Expands a leading `~`, `~/`, or `~\` in each value, as a shell does for an assignment. */
11
56
  export function expandHome(env) {
12
57
  return Object.fromEntries(
@@ -19,12 +64,28 @@ export function expandHome(env) {
19
64
 
20
65
  /** @returns gh's stdout on exit 0, or null when gh fails, times out, or is not installed. */
21
66
  export function runGh(args, { cwd = process.cwd(), env = {}, timeoutMs = GH_TIMEOUT_MS } = {}) {
22
- const result = spawnSync("gh", args, {
67
+ const result = runGhResult(args, { cwd, env, timeoutMs });
68
+ return result.status === 0 ? (result.stdout ?? "") : null;
69
+ }
70
+
71
+ /** Resource: run a gh request without blocking other requests under the caller's deadline. */
72
+ export function runGhAsync(args, { cwd = process.cwd(), env = {}, timeoutMs = GH_TIMEOUT_MS } = {}) {
73
+ return new Promise((resolve) => {
74
+ execFile("gh", args, {
75
+ cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024, windowsHide: true,
76
+ timeout: timeoutMs, env: { ...process.env, ...expandHome(env) },
77
+ }, (error, stdout) => resolve(error ? null : stdout));
78
+ });
79
+ }
80
+
81
+ /** Returns the process result, including stderr and any spawn error. */
82
+ export function runGhResult(args, { cwd = process.cwd(), env = {}, timeoutMs = GH_TIMEOUT_MS } = {}) {
83
+ return spawnSync("gh", args, {
23
84
  cwd,
24
85
  encoding: "utf8",
86
+ maxBuffer: 64 * 1024 * 1024,
25
87
  windowsHide: true,
26
88
  timeout: timeoutMs,
27
89
  env: { ...process.env, ...expandHome(env) },
28
90
  });
29
- return result.status === 0 ? (result.stdout ?? "") : null;
30
91
  }