@feigi/fleet-ctl 0.0.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 (245) hide show
  1. package/.claude-plugin/plugin.json +9 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +18 -0
  4. package/agents/fleet-finisher.agent.md +7 -0
  5. package/agents/fleet-implementer-alt.agent.md +210 -0
  6. package/agents/fleet-implementer.agent.md +210 -0
  7. package/agents/fleet-merge-bot.agent.md +7 -0
  8. package/agents/fleet-review-comments.agent.md +40 -0
  9. package/agents/fleet-review-correctness.agent.md +43 -0
  10. package/agents/fleet-review-runner.agent.md +73 -0
  11. package/agents/fleet-review-silent-failure.agent.md +49 -0
  12. package/agents/fleet-review-simplify.agent.md +46 -0
  13. package/agents/fleet-review-snapshot.agent.md +24 -0
  14. package/agents/fleet-review-tests.agent.md +46 -0
  15. package/agents/fleet-review-types.agent.md +41 -0
  16. package/agents/fleet-review-verifier.agent.md +29 -0
  17. package/commands/review-and-fix.md +98 -0
  18. package/commands/run-merge-bot.md +357 -0
  19. package/commands/run-team-help.md +17 -0
  20. package/package.json +23 -0
  21. package/scripts/agent-test-dir-prose.test.mjs +59 -0
  22. package/scripts/agent-test.test.mjs +1636 -0
  23. package/scripts/ambient-git-vars-mjs-prose.test.mjs +354 -0
  24. package/scripts/ambient-git-vars-prose.test.mjs +192 -0
  25. package/scripts/ancestry-check-position-prose.test.mjs +175 -0
  26. package/scripts/apply-ruleset.test.mjs +420 -0
  27. package/scripts/arg-header-probes-prose.test.mjs +393 -0
  28. package/scripts/arg.mjs +600 -0
  29. package/scripts/arg.test.mjs +1354 -0
  30. package/scripts/board-cli.test.mjs +694 -0
  31. package/scripts/board-identity.test.mjs +429 -0
  32. package/scripts/board-liveness-banner.test.mjs +119 -0
  33. package/scripts/board-prev-shape.test.mjs +229 -0
  34. package/scripts/board-tryparse-null.test.mjs +119 -0
  35. package/scripts/board.html +471 -0
  36. package/scripts/board.mjs +2037 -0
  37. package/scripts/board.test.mjs +3086 -0
  38. package/scripts/brief-after-cut-prose.test.mjs +53 -0
  39. package/scripts/candidates-exit3-prose.test.mjs +302 -0
  40. package/scripts/candidates.mjs +674 -0
  41. package/scripts/candidates.test.mjs +2101 -0
  42. package/scripts/caveat-unification-prose.test.mjs +98 -0
  43. package/scripts/ci-comment-rot-prose.test.mjs +2025 -0
  44. package/scripts/ci-completes-premise-prose.test.mjs +257 -0
  45. package/scripts/ci-state-prose.test.mjs +113 -0
  46. package/scripts/ci-state.mjs +761 -0
  47. package/scripts/ci-state.test.mjs +1640 -0
  48. package/scripts/ci-vacuous-green.test.mjs +368 -0
  49. package/scripts/citation-sweep-prose.test.mjs +1572 -0
  50. package/scripts/claim-lifecycle.test.mjs +185 -0
  51. package/scripts/claim-ticket.sh +417 -0
  52. package/scripts/claim-ticket.test.mjs +1121 -0
  53. package/scripts/closing-keyword-prose.test.mjs +193 -0
  54. package/scripts/cockpit-launch-idempotent-prose.test.mjs +165 -0
  55. package/scripts/cockpit-tick-nonblocking.test.mjs +210 -0
  56. package/scripts/compute-board.mjs +579 -0
  57. package/scripts/compute-board.test.mjs +1060 -0
  58. package/scripts/compute-spend.mjs +329 -0
  59. package/scripts/compute-spend.test.mjs +451 -0
  60. package/scripts/cross-repo-citation-prose.test.mjs +156 -0
  61. package/scripts/cwd-isolation-pins.mjs +83 -0
  62. package/scripts/dedupe-guard-prose.test.mjs +243 -0
  63. package/scripts/derive-testcmd.sh +239 -0
  64. package/scripts/derive-testcmd.test.mjs +380 -0
  65. package/scripts/diff-stats.mjs +231 -0
  66. package/scripts/diff-stats.test.mjs +408 -0
  67. package/scripts/dispatch-block-golden-prose.test.mjs +1024 -0
  68. package/scripts/dispatch-block-pins-prose.test.mjs +615 -0
  69. package/scripts/drop-merged-label.sh +173 -0
  70. package/scripts/drop-merged-label.test.mjs +480 -0
  71. package/scripts/expected-jobs-prose.test.mjs +80 -0
  72. package/scripts/filing-bar-seat-prose.test.mjs +242 -0
  73. package/scripts/filing-claim-bar-prose.test.mjs +166 -0
  74. package/scripts/finisher-dispatch-premise-prose.test.mjs +312 -0
  75. package/scripts/finisher-halt-prose.test.mjs +106 -0
  76. package/scripts/finisher-name-prose.test.mjs +134 -0
  77. package/scripts/finisher-own-tree-prose.test.mjs +285 -0
  78. package/scripts/finisher-pin-race-prose.test.mjs +339 -0
  79. package/scripts/fix-applier-correction-rules-prose.test.mjs +201 -0
  80. package/scripts/fix-applier-result-file-prose.test.mjs +100 -0
  81. package/scripts/fleet-bootstrap +155 -0
  82. package/scripts/fleet-heartbeat.mjs +272 -0
  83. package/scripts/fleet-heartbeat.test.mjs +450 -0
  84. package/scripts/fleet-provenance +207 -0
  85. package/scripts/fleet-provenance.test.mjs +64 -0
  86. package/scripts/fleet-run +148 -0
  87. package/scripts/fleet-run.test.mjs +90 -0
  88. package/scripts/fleet-state.mjs +400 -0
  89. package/scripts/fleet-state.test.mjs +373 -0
  90. package/scripts/fleet-tick-prose.test.mjs +299 -0
  91. package/scripts/fleet-tick.mjs +832 -0
  92. package/scripts/fleet-tick.test.mjs +1332 -0
  93. package/scripts/force-with-lease-reason-prose.test.mjs +184 -0
  94. package/scripts/frontmatter-allowlist.json +64 -0
  95. package/scripts/frontmatter-check.mjs +256 -0
  96. package/scripts/frontmatter-check.test.mjs +436 -0
  97. package/scripts/git-env.mjs +124 -0
  98. package/scripts/git-env.test.mjs +149 -0
  99. package/scripts/git-status-untracked-mode-sweep.test.mjs +216 -0
  100. package/scripts/gone-walk.test.mjs +213 -0
  101. package/scripts/gp-sep-invariant-prose.test.mjs +188 -0
  102. package/scripts/head-moved-after-label-prose.test.mjs +233 -0
  103. package/scripts/immutable-body-claim-prose.test.mjs +413 -0
  104. package/scripts/implementer-model-tier.test.mjs +643 -0
  105. package/scripts/inflight-citation-prose.test.mjs +144 -0
  106. package/scripts/inflight-exit2-prose.test.mjs +81 -0
  107. package/scripts/inflight-probe-guard-prose.test.mjs +109 -0
  108. package/scripts/inflight-scan-scope-prose.test.mjs +57 -0
  109. package/scripts/inflight.sh +1106 -0
  110. package/scripts/inflight.test.mjs +2984 -0
  111. package/scripts/injection-control-prose.test.mjs +404 -0
  112. package/scripts/install-root-audit.test.mjs +464 -0
  113. package/scripts/instrument-check-prose.test.mjs +235 -0
  114. package/scripts/instruments.sh +394 -0
  115. package/scripts/instruments.test.mjs +787 -0
  116. package/scripts/issue-tracker-prose.test.mjs +71 -0
  117. package/scripts/json.sh +248 -0
  118. package/scripts/json.test.mjs +364 -0
  119. package/scripts/ledger-dispatch.test.mjs +516 -0
  120. package/scripts/ledger-grammar.mjs +85 -0
  121. package/scripts/ledger-grammar.test.mjs +142 -0
  122. package/scripts/ledger-read-require-file.test.mjs +197 -0
  123. package/scripts/ledger.mjs +1753 -0
  124. package/scripts/ledger.test.mjs +3554 -0
  125. package/scripts/line-distance-prose.test.mjs +245 -0
  126. package/scripts/liveness-rationale-prose.test.mjs +83 -0
  127. package/scripts/locale-pin-prose.test.mjs +189 -0
  128. package/scripts/member-outcome-prose.test.mjs +167 -0
  129. package/scripts/member-outcomes-header.test.mjs +148 -0
  130. package/scripts/member-outcomes-prose.test.mjs +63 -0
  131. package/scripts/member-outcomes.mjs +231 -0
  132. package/scripts/member-outcomes.test.mjs +507 -0
  133. package/scripts/member-prompt-prose.test.mjs +161 -0
  134. package/scripts/member-record.mjs +605 -0
  135. package/scripts/member-record.test.mjs +516 -0
  136. package/scripts/member-write-guard.mjs +279 -0
  137. package/scripts/member-write-guard.test.mjs +211 -0
  138. package/scripts/merge-commit-probe-prose.test.mjs +122 -0
  139. package/scripts/merge-gate.mjs +262 -0
  140. package/scripts/merge-gate.test.mjs +613 -0
  141. package/scripts/muted-git-guard-sweep.test.mjs +493 -0
  142. package/scripts/net-ssh-precedence-prose.test.mjs +91 -0
  143. package/scripts/net-watchdog-prose.test.mjs +79 -0
  144. package/scripts/net.sh +409 -0
  145. package/scripts/net.test.mjs +211 -0
  146. package/scripts/no-ci-gate-prose.test.mjs +108 -0
  147. package/scripts/no-undo-audit.sh +1134 -0
  148. package/scripts/no-undo-audit.test.mjs +3965 -0
  149. package/scripts/no-wave.test.mjs +138 -0
  150. package/scripts/node-floor-sweep.test.mjs +611 -0
  151. package/scripts/pointer-target-prose.test.mjs +186 -0
  152. package/scripts/pr-overlap.mjs +417 -0
  153. package/scripts/pr-overlap.test.mjs +695 -0
  154. package/scripts/printf-die-sweep.test.mjs +384 -0
  155. package/scripts/prompt-renderer.mjs +39 -0
  156. package/scripts/prompt-renderer.test.mjs +68 -0
  157. package/scripts/prose-pin.mjs +808 -0
  158. package/scripts/prose-pin.test.mjs +1034 -0
  159. package/scripts/prove-merge.sh +228 -0
  160. package/scripts/prove-merge.test.mjs +995 -0
  161. package/scripts/pull-table-relabel-prose.test.mjs +60 -0
  162. package/scripts/quiet-payload-prose.test.mjs +222 -0
  163. package/scripts/reap.sh +1768 -0
  164. package/scripts/reap.test.mjs +4395 -0
  165. package/scripts/reaping-prose.test.mjs +159 -0
  166. package/scripts/refuter-scratch-prose.test.mjs +135 -0
  167. package/scripts/release-label-required-prose.test.mjs +71 -0
  168. package/scripts/release-label-split-prose.test.mjs +169 -0
  169. package/scripts/release-ticket.sh +1716 -0
  170. package/scripts/release-ticket.test.mjs +5106 -0
  171. package/scripts/renovate-release-contract.test.mjs +379 -0
  172. package/scripts/repo-root.mjs +544 -0
  173. package/scripts/repo-root.test.mjs +873 -0
  174. package/scripts/reporter-output-rule-prose.test.mjs +208 -0
  175. package/scripts/review-agent-report-only.test.mjs +49 -0
  176. package/scripts/review-core-cwd-isolation.test.mjs +374 -0
  177. package/scripts/review-core-reads.test.mjs +478 -0
  178. package/scripts/review-core-refuter-scratch.test.mjs +148 -0
  179. package/scripts/review-core-snapshot-path.test.mjs +777 -0
  180. package/scripts/review-core-specialist-scratch.test.mjs +189 -0
  181. package/scripts/review-core-testcmd.test.mjs +288 -0
  182. package/scripts/review-core-unrun.test.mjs +530 -0
  183. package/scripts/review-core-unverified-discriminant.test.mjs +208 -0
  184. package/scripts/review-core.mjs +1028 -0
  185. package/scripts/review-eval-resolver-path.test.mjs +55 -0
  186. package/scripts/review-eval.mjs +197 -0
  187. package/scripts/review-host-fixture.mjs +73 -0
  188. package/scripts/review-in-run-retry.test.mjs +187 -0
  189. package/scripts/review-no-vendor-dispatch.test.mjs +45 -0
  190. package/scripts/review-path-default.test.mjs +796 -0
  191. package/scripts/review-runner-spawns.test.mjs +93 -0
  192. package/scripts/review-runner.test.mjs +155 -0
  193. package/scripts/review-tier-audit.test.mjs +140 -0
  194. package/scripts/run-artifact-pr-prose.test.mjs +341 -0
  195. package/scripts/run-merge-bot-prose.test.mjs +1391 -0
  196. package/scripts/scratch-partition-invariant-prose.test.mjs +74 -0
  197. package/scripts/scripts-path-citation-sweep.test.mjs +73 -0
  198. package/scripts/section-between-guard-prose.test.mjs +378 -0
  199. package/scripts/select-dimensions.test.mjs +674 -0
  200. package/scripts/shared-refusal.test.mjs +388 -0
  201. package/scripts/shell-traps-prose.test.mjs +507 -0
  202. package/scripts/shortlist.mjs +355 -0
  203. package/scripts/shortlist.test.mjs +366 -0
  204. package/scripts/slow-transport.mjs +72 -0
  205. package/scripts/snapshot-repo.test.mjs +772 -0
  206. package/scripts/snapshot-runner-audience-prose.test.mjs +129 -0
  207. package/scripts/spend-view.test.mjs +312 -0
  208. package/scripts/staleness-qualifier-prose.test.mjs +251 -0
  209. package/scripts/staleness-verdict-prose.test.mjs +142 -0
  210. package/scripts/staleness.mjs +414 -0
  211. package/scripts/staleness.test.mjs +893 -0
  212. package/scripts/stalled-member-liveness-prose.test.mjs +219 -0
  213. package/scripts/stash-prohibition-prose.test.mjs +313 -0
  214. package/scripts/strip-comments.mjs +44 -0
  215. package/scripts/tier-check.mjs +468 -0
  216. package/scripts/tier-check.test.mjs +726 -0
  217. package/scripts/tier-guard-gate-prose.test.mjs +216 -0
  218. package/scripts/tier-outcomes-header.test.mjs +586 -0
  219. package/scripts/tier-outcomes.mjs +441 -0
  220. package/scripts/tier-outcomes.test.mjs +342 -0
  221. package/scripts/tier-roles.mjs +250 -0
  222. package/scripts/tier-roles.test.mjs +316 -0
  223. package/scripts/tracker-block-copy-prose.test.mjs +288 -0
  224. package/scripts/triage-labels-gloss-prose.test.mjs +97 -0
  225. package/scripts/unattended-git-sweep.test.mjs +142 -0
  226. package/scripts/verify-sha-exit2-prose.test.mjs +269 -0
  227. package/scripts/verify-sha.sh +117 -0
  228. package/scripts/verify-sha.test.mjs +693 -0
  229. package/scripts/watcher-degraded-block.test.mjs +372 -0
  230. package/scripts/watcher-key-prose.test.mjs +106 -0
  231. package/scripts/within-run-pair-prose.test.mjs +208 -0
  232. package/scripts/worktree-audit.sh +482 -0
  233. package/scripts/worktree-audit.test.mjs +1407 -0
  234. package/scripts/worktree-head-prose.test.mjs +276 -0
  235. package/scripts/worktree-listing-sweep.test.mjs +217 -0
  236. package/scripts/worktree-model-prose.test.mjs +216 -0
  237. package/scripts/worktree.sh +470 -0
  238. package/skills/next-ticket/SKILL.md +138 -0
  239. package/skills/run-team/SKILL.md +3603 -0
  240. package/skills/run-team/references/ci-and-staleness.md +75 -0
  241. package/skills/run-team/references/correction-tickets.md +37 -0
  242. package/skills/run-team/references/isolation.md +23 -0
  243. package/skills/run-team/references/member-lifecycle.md +73 -0
  244. package/skills/run-team/references/reaping.md +73 -0
  245. package/skills/sizing-a-ticket/SKILL.md +39 -0
@@ -0,0 +1,380 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { execFileSync, spawnSync } from "node:child_process";
4
+ import { mkdtempSync, mkdirSync, writeFileSync, symlinkSync, chmodSync, readFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+
8
+ // derive-testcmd.sh is the ONE reader of a repository's Recipe cache (ADR
9
+ // 0015) — reused by claim-ticket.sh and review-core.mjs's snapshot agent. It
10
+ // infers nothing: no fixture here carries a package.json, a lockfile or a
11
+ // test-file naming convention, because none of them can change its answer.
12
+ const SCRIPT = join(import.meta.dirname, "derive-testcmd.sh");
13
+
14
+ // The frame markers, read from the script itself rather than copied here: a
15
+ // behavior-preserving rename of derive-testcmd.sh's `open`/`close` values
16
+ // must not break a test whose only job is to prove the guard around them.
17
+ const FRAME_MATCH = readFileSync(SCRIPT, "utf8").match(/^open='([^']*)' close='([^']*)'/m);
18
+ if (!FRAME_MATCH) throw new Error("could not find the open/close frame markers in derive-testcmd.sh");
19
+ const [, FRAME_OPEN, FRAME_CLOSE] = FRAME_MATCH;
20
+
21
+ // Fixture construction must not inherit an ambient GIT_DIR (the #1020 case
22
+ // below sets one deliberately, for the SCRIPT only): under one, `git init`
23
+ // re-inits whatever it names and the fixture is built nowhere.
24
+ const FIXTURE_ENV = { ...process.env, GIT_DIR: undefined, GIT_WORK_TREE: undefined };
25
+
26
+ function repo(files = {}) {
27
+ const dir = mkdtempSync(join(tmpdir(), "derive-testcmd-"));
28
+ const git = (...a) => execFileSync("git", a, { cwd: dir, stdio: "pipe", env: FIXTURE_ENV, encoding: "utf8" });
29
+ git("init", "-q");
30
+ git("config", "user.email", "t@t");
31
+ git("config", "user.name", "t");
32
+ for (const [name, body] of Object.entries(files)) writeFileSync(join(dir, name), body);
33
+ git("commit", "-q", "--allow-empty", "-m", "x");
34
+ git("add", "-A");
35
+ git("commit", "-q", "--allow-empty", "-m", "files");
36
+ return { dir, head: git("rev-parse", "HEAD").trim() };
37
+ }
38
+
39
+ // A proven Recipe: every field the reader requires, the proof included.
40
+ const recipe = (head, over = {}) => ({
41
+ install: "true",
42
+ test: "sh ./run-tests.sh",
43
+ derivedAt: head,
44
+ installClean: true,
45
+ testCount: 3,
46
+ ...over,
47
+ });
48
+
49
+ function cache(dir, body) {
50
+ mkdirSync(join(dir, ".fleet"), { recursive: true });
51
+ writeFileSync(join(dir, ".fleet", "recipe.json"), typeof body === "string" ? body : JSON.stringify(body));
52
+ }
53
+
54
+ function derive(dir, field = "test", env = process.env, cwd = tmpdir()) {
55
+ const r = spawnSync("sh", [SCRIPT, dir, field], { encoding: "utf8", env, cwd, timeout: 30_000 });
56
+ return { status: r.status, out: r.stdout.replace(/\n$/, ""), err: r.stderr };
57
+ }
58
+
59
+ // Every refusal that sends its reader to re-derive must say WHICH step does
60
+ // that — the controller or reviewer reading it has no other pointer.
61
+ const NAMES_STEP = /run the Recipe derivation step \(run-team phase 0, before the first claim — ADR 0015\)/;
62
+
63
+ test("a proven cache yields the requested command, verbatim, and nothing on stderr", () => {
64
+ const { dir, head } = repo();
65
+ cache(dir, recipe(head, { install: "true", test: `sh -c 'echo "a b"'` }));
66
+ const t = derive(dir, "test");
67
+ assert.equal(t.status, 0, t.err);
68
+ assert.equal(t.out, `sh -c 'echo "a b"'`, "quotes and spaces reach the caller untouched");
69
+ assert.equal(t.err, "");
70
+ const i = derive(dir, "install");
71
+ assert.equal(i.status, 0, i.err);
72
+ assert.equal(i.out, "true");
73
+ });
74
+
75
+ test("an absent cache refuses, naming the derivation step — never an inference", () => {
76
+ // A tree that the pre-ADR-0015 inference would have ACCEPTED (a Node test
77
+ // file) is refused all the same: nothing about the tree is consulted.
78
+ const { dir } = repo({ "t.test.mjs": "" });
79
+ const r = derive(dir);
80
+ assert.equal(r.status, 1);
81
+ assert.equal(r.out, "", "no command it could not read");
82
+ assert.match(r.err, /^derive-testcmd: no Recipe cache at .*\/\.fleet\/recipe\.json — refusing to infer/);
83
+ assert.match(r.err, NAMES_STEP);
84
+ });
85
+
86
+ test("a linked worktree reads the main checkout's cache, not a private one", () => {
87
+ // The two consumers both hand a WORKTREE in: review-core's snapshot agent
88
+ // passes the PR's worktree, and a claim's tree is one. The cache lives
89
+ // once, beside the common git dir, like the ledger.
90
+ const { dir, head } = repo();
91
+ cache(dir, recipe(head, { test: "true" }));
92
+ const wt = join(mkdtempSync(join(tmpdir(), "derive-wt-")), "wt");
93
+ execFileSync("git", ["worktree", "add", "-q", "--detach", wt], { cwd: dir, stdio: "pipe", env: FIXTURE_ENV });
94
+ const r = derive(wt);
95
+ assert.equal(r.status, 0, r.err);
96
+ assert.equal(r.out, "true");
97
+ });
98
+
99
+ test("wrong argument count and an unknown field refuse with a usage message", () => {
100
+ const { dir, head } = repo();
101
+ cache(dir, recipe(head));
102
+ for (const argv of [[], [dir], [dir, "test", "extra"]]) {
103
+ const r = spawnSync("sh", [SCRIPT, ...argv], { encoding: "utf8" });
104
+ assert.equal(r.status, 1, JSON.stringify(argv));
105
+ assert.match(r.stderr, /usage: derive-testcmd\.sh <repo> <install\|test>/);
106
+ }
107
+ const r = derive(dir, "derivedAt");
108
+ assert.equal(r.status, 1);
109
+ assert.match(r.err, /unknown Recipe field 'derivedAt' — expected install or test/);
110
+ });
111
+
112
+ test("a non-repository directory refuses cleanly", () => {
113
+ const dir = mkdtempSync(join(tmpdir(), "derive-testcmd-not-a-repo-"));
114
+ const r = derive(dir);
115
+ assert.equal(r.status, 1);
116
+ assert.match(r.err, /is not a git repository/);
117
+ });
118
+
119
+ // Each row breaks exactly one requirement of a PROVEN Recipe; each must be
120
+ // refused with its own reason and the derivation step, and none may leak a
121
+ // command out of a cache the checks did not pass.
122
+ test("an unparseable or unproven cache refuses, naming what is missing", (t) => {
123
+ const { dir, head } = repo();
124
+ const rows = [
125
+ ["{not json", /it does not parse/],
126
+ ["[]", /it is not a JSON object/],
127
+ [recipe(head, { install: undefined }), /`install` is not a non-empty command string/],
128
+ [recipe(head, { test: " " }), /`test` is not a non-empty command string/],
129
+ [recipe(head, { test: 7 }), /`test` is not a non-empty command string/],
130
+ [recipe(head, { derivedAt: "main" }), /`derivedAt` is not a full commit id/],
131
+ [recipe(head, { derivedAt: head.slice(0, 12) }), /`derivedAt` is not a full commit id/],
132
+ [recipe(head, { installClean: undefined }), /`installClean` is not true/],
133
+ [recipe(head, { installClean: "true" }), /`installClean` is not true/],
134
+ [recipe(head, { testCount: 0 }), /no proof of real tests/],
135
+ [recipe(head, { testCount: 2.5 }), /no proof of real tests/],
136
+ [recipe(head, { testCount: undefined, mutation: "" }), /no proof of real tests/],
137
+ ];
138
+ for (const [body, why] of rows) {
139
+ cache(dir, body);
140
+ for (const field of ["test", "install"]) {
141
+ const r = derive(dir, field);
142
+ const label = `${field} from ${typeof body === "string" ? body : JSON.stringify(body)}`;
143
+ assert.equal(r.status, 1, label);
144
+ assert.equal(r.out, "", label);
145
+ assert.match(r.err, /the Recipe cache at .* is unusable: /, label);
146
+ assert.match(r.err, why, label);
147
+ assert.match(r.err, NAMES_STEP, label);
148
+ }
149
+ }
150
+ });
151
+
152
+ // The must-ACCEPT half of the proof rules: either proof alone is enough, and
153
+ // a sha256 repository's 64-hex commit id is a full id too.
154
+ test("either proof alone is accepted, and so is a 64-hex commit id", () => {
155
+ const { dir, head } = repo();
156
+ for (const over of [
157
+ { testCount: undefined, mutation: "flipped assert in t/a.test.js; suite went red" },
158
+ { testCount: 1 },
159
+ { derivedAt: head.padEnd(64, "0") },
160
+ ]) {
161
+ cache(dir, recipe(head, { ...over, test: "true" }));
162
+ const r = derive(dir);
163
+ assert.equal(r.status, 0, `${JSON.stringify(over)}: ${r.err}`);
164
+ assert.equal(r.out, "true");
165
+ }
166
+ });
167
+
168
+ // Invalid on failure to RUN (ADR 0015): a leading word that does not resolve
169
+ // from the repo is a stale Recipe, refused with the invalidation message.
170
+ test("a command whose binary is missing or not executable refuses as an invalid cache", () => {
171
+ const { dir, head } = repo({ "run.sh": "#!/bin/sh\n" });
172
+ chmodSync(join(dir, "run.sh"), 0o644);
173
+ for (const [field, over, word] of [
174
+ ["test", { test: "no-such-binary-2117 --all" }, "no-such-binary-2117"],
175
+ ["install", { install: "no-such-installer-2117 ci" }, "no-such-installer-2117"],
176
+ ["test", { test: "./run.sh" }, "./run.sh"],
177
+ ["test", { test: "./missing.sh" }, "./missing.sh"],
178
+ ["test", { test: "CI=1 LANG=C no-such-binary-2117" }, "no-such-binary-2117"],
179
+ ]) {
180
+ cache(dir, recipe(head, over));
181
+ const r = derive(dir, field);
182
+ assert.equal(r.status, 1, `${JSON.stringify(over)} must refuse`);
183
+ assert.equal(r.out, "");
184
+ assert.match(r.err, new RegExp(`is invalid: its ${field} command '${word.replace(/[.*]/g, "\\$&")}' is not found or not executable`));
185
+ assert.match(r.err, NAMES_STEP);
186
+ }
187
+ });
188
+
189
+ // The must-ACCEPT half of the run probe, which is where a guard like this
190
+ // goes wrong: every one of these RUNS, so refusing any would strand a repo on
191
+ // a Recipe that is fine. A failing suite (`false`) is a finding, not a stale
192
+ // Recipe — this script never runs the command, so it cannot tell and must
193
+ // not try. A relative script resolves from <repo>, not from the caller's cwd.
194
+ test("a runnable command is accepted, however it is spelled — and a failing suite is not a stale Recipe", () => {
195
+ const { dir, head } = repo({ "run.sh": "#!/bin/sh\nexit 0\n" });
196
+ chmodSync(join(dir, "run.sh"), 0o755);
197
+ for (const cmd of [
198
+ "./run.sh",
199
+ "sh ./run-tests.sh",
200
+ "false",
201
+ "FOO=1 BAR=x ./run.sh --flag",
202
+ "cd sub && make test",
203
+ `"./my tests.sh"`,
204
+ "$HOME/bin/runner",
205
+ "node --test plugin/scripts/*.test.mjs",
206
+ ]) {
207
+ cache(dir, recipe(head, { test: cmd }));
208
+ const r = derive(dir, "test", process.env, tmpdir());
209
+ assert.equal(r.status, 0, `${cmd}: ${r.err}`);
210
+ assert.equal(r.out, cmd);
211
+ }
212
+ });
213
+
214
+ // Both consumers append the runner's own arguments after this string
215
+ // textually (`exec sh -c '<cmd> "$@"' agent-test "$@"`), so a command ending
216
+ // in `;` or `&` lets a real shell read those arguments as an unrelated
217
+ // top-level command, and a `#`-led word swallows everything after it,
218
+ // arguments included, as a comment — neither failure is about whether the
219
+ // command runs, so it is refused here rather than left to fail at claim time.
220
+ test("a command ending in ';' or '&', or carrying a '#' word, refuses — a runner-appended argument would never reach it", () => {
221
+ const { dir, head } = repo({ "run.sh": "#!/bin/sh\nexit 0\n" });
222
+ chmodSync(join(dir, "run.sh"), 0o755);
223
+ for (const cmd of ["sh ./run-tests.sh;", "sh ./run-tests.sh &", "sh ./run-tests.sh # all suites"]) {
224
+ cache(dir, recipe(head, { test: cmd }));
225
+ const r = derive(dir, "test", process.env, tmpdir());
226
+ assert.equal(r.status, 1, `${cmd} must refuse: ${r.out}`);
227
+ assert.match(r.err, /a runner-appended argument/, `${cmd}: ${r.err}`);
228
+ }
229
+ });
230
+
231
+ // --- #2217: the frame above lets a value keep a trailing newline that an
232
+ // unframed `$(…)` capture always stripped silently, so a command that used
233
+ // to read as `true;` (caught above) now reads as `true;\n` inside the
234
+ // frame and must still be caught the same way.
235
+ test("a command ending in ';' or '&' followed by a newline still refuses (#2217)", () => {
236
+ const { dir, head } = repo();
237
+ for (const cmd of ["true;\n", "true &\n"]) {
238
+ cache(dir, recipe(head, { test: cmd }));
239
+ const r = derive(dir, "test", process.env, tmpdir());
240
+ assert.equal(r.status, 1, `${JSON.stringify(cmd)} must refuse: ${r.out}`);
241
+ assert.match(r.err, /a runner-appended argument/, `${JSON.stringify(cmd)}: ${r.err}`);
242
+ }
243
+ });
244
+
245
+ test("a command of assignments alone names nothing to run and refuses", () => {
246
+ const { dir, head } = repo();
247
+ cache(dir, recipe(head, { test: "CI=1 FOO=2" }));
248
+ const r = derive(dir);
249
+ assert.equal(r.status, 1);
250
+ assert.match(r.err, /its test command names no command, only assignments/);
251
+ });
252
+
253
+ // The assignment-skip loop above only accepts `NAME=value` prefixes whose
254
+ // name is a valid shell identifier (`[A-Za-z0-9_]` only) — a hyphen breaks
255
+ // the inner guard, so `a-b=c` is never skipped as an assignment and is read
256
+ // as the leading command word itself instead.
257
+ test("an assignment-shaped word with an invalid variable name is read as the command, not skipped", () => {
258
+ const { dir, head } = repo();
259
+ cache(dir, recipe(head, { test: "a-b=c ./run.sh" }));
260
+ const r = derive(dir);
261
+ assert.equal(r.status, 1);
262
+ assert.match(r.err, /its test command 'a-b=c' is not found or not executable/);
263
+ });
264
+
265
+ // --- #1020: the ambient GIT_DIR that outranks `-C "$repo"`. Under it,
266
+ // `--git-common-dir` answers for the OTHER repository, and the cache read is
267
+ // that repository's Recipe reported as this one's.
268
+ test("an ambient GIT_DIR does not read another repository's Recipe (#1020)", () => {
269
+ const here = repo();
270
+ cache(here.dir, recipe(here.head, { test: "true" }));
271
+ const elsewhere = repo();
272
+ cache(elsewhere.dir, recipe(elsewhere.head, { test: "false" }));
273
+ assert.equal(derive(elsewhere.dir).out, "false", "fixture: the other repo must answer differently");
274
+
275
+ const r = derive(here.dir, "test", { ...process.env, GIT_DIR: join(elsewhere.dir, ".git") });
276
+ assert.equal(r.status, 0, r.err);
277
+ assert.equal(r.out, "true", "an ambient GIT_DIR must not answer for another repository");
278
+ });
279
+
280
+ // --- #1175: the cross-file invariant claim-ticket.sh's captures rest on. It
281
+ // captures THIS script with stderr merged and runs the result on its success
282
+ // path, so any byte this script writes to stderr on success becomes part of
283
+ // the Install step it runs and the Test entrypoint it bakes into the runner.
284
+ // NODE_DEBUG makes the validator's own interpreter chatty; the positive
285
+ // control proves the env is not inert.
286
+ test("the success path writes nothing to stderr, even when node is chatty (#1175)", () => {
287
+ const CHATTY = { ...process.env, NODE_DEBUG: "module" };
288
+ const control = spawnSync("node", ["-e", "0"], { encoding: "utf8", env: CHATTY });
289
+ assert.ok(control.stderr.length > 0, "fixture: NODE_DEBUG=module must make node write to stderr");
290
+
291
+ const { dir, head } = repo();
292
+ cache(dir, recipe(head, { install: "true", test: "true" }));
293
+ for (const field of ["install", "test"]) {
294
+ const r = derive(dir, field, CHATTY);
295
+ assert.equal(r.status, 0, r.err);
296
+ assert.equal(r.out, "true");
297
+ assert.equal(r.err, "", `the ${field} success path must write nothing to stderr`);
298
+ }
299
+ });
300
+
301
+ // --- #1141: an unusable interpreter is named as itself, never as a corrupt
302
+ // cache. PATH is REPLACED with links to exactly what the script runs, so the
303
+ // interpreter is really unreachable rather than shadowed.
304
+ const SHIMMED = ["sh", "git", "mktemp", "cat", "rm"];
305
+ function shimPath({ node }) {
306
+ const bin = mkdtempSync(join(tmpdir(), "derive-path-"));
307
+ for (const name of SHIMMED) {
308
+ const real = execFileSync("sh", ["-c", `command -v ${name}`], { encoding: "utf8" }).trim();
309
+ symlinkSync(real, join(bin, name));
310
+ }
311
+ if (node) symlinkSync(process.execPath, join(bin, "node"));
312
+ return bin;
313
+ }
314
+
315
+ test("an unusable interpreter refuses in this script's own voice, never the cache's", () => {
316
+ const { dir, head } = repo();
317
+ cache(dir, recipe(head, { test: "true" }));
318
+ const absent = derive(dir, "test", { ...process.env, PATH: shimPath({ node: false }) });
319
+ assert.equal(absent.status, 1);
320
+ assert.equal(absent.out, "");
321
+ assert.match(absent.err, /^derive-testcmd: node is unusable/);
322
+ assert.doesNotMatch(absent.err, /is unusable: it does not parse/);
323
+
324
+ // The false-positive control: the same stripped PATH with the interpreter
325
+ // present reads the cache to completion, so the refusal above is about node
326
+ // and not about a PATH too thin for the script to run at all.
327
+ const present = derive(dir, "test", { ...process.env, PATH: shimPath({ node: true }) });
328
+ assert.equal(present.status, 0, present.err);
329
+ assert.equal(present.out, "true");
330
+ });
331
+
332
+ // --- #2217: node's STDOUT is the capture itself, so the stream split above
333
+ // does nothing for it. A version-manager or proxy shim prints before exec'ing
334
+ // the real node, or — not exec'ing — after it exits, and unframed that chatter
335
+ // became part of the command: refused as a stale cache when its first word
336
+ // did not resolve, handed on when it did. Every stub runs the real interpreter
337
+ // by ABSOLUTE path: re-running `node` through PATH would find the stub again.
338
+ function nodeStub(body) {
339
+ const bin = mkdtempSync(join(tmpdir(), "derive-stub-"));
340
+ writeFileSync(join(bin, "node"), `#!/bin/sh\n${body.replaceAll("NODE", `'${process.execPath}'`)}\n`);
341
+ chmodSync(join(bin, "node"), 0o755);
342
+ return { ...process.env, PATH: `${bin}:${process.env.PATH}` };
343
+ }
344
+
345
+ test("stdout chatter around the Recipe value refuses, blaming node's output and never the cache (#2217)", (t) => {
346
+ const { dir, head } = repo();
347
+ cache(dir, recipe(head));
348
+ const stubs = {
349
+ "a banner before exec": ['echo "Now using node v22.0.0"; exec NODE "$@"', "Now using node v22.0.0"],
350
+ "a digit prefix with no newline": ['printf 1; exec NODE "$@"', `1${FRAME_OPEN}`],
351
+ "trailing output from a shim that does not exec": ['NODE "$@"; st=$?; printf done; exit $st', `${FRAME_CLOSE}done`],
352
+ "a shim whose own chatter spells out the sentinel": [`printf "${FRAME_OPEN}SNEAKY-INJECTED"; exec NODE "$@"`, `${FRAME_OPEN}SNEAKY-INJECTED${FRAME_OPEN}`],
353
+ };
354
+ for (const [name, [body, shown]] of Object.entries(stubs)) {
355
+ const env = nodeStub(body);
356
+ for (const field of ["install", "test"]) {
357
+ t.diagnostic(`${name}, ${field}`);
358
+ const r = derive(dir, field, env);
359
+ assert.equal(r.status, 1, `${name}/${field}: ${r.err}`);
360
+ assert.equal(r.out, "", `${name}/${field}: nothing may reach the caller`);
361
+ assert.match(r.err, /^derive-testcmd: node's stdout carried more than the framed Recipe value/);
362
+ assert.ok(r.err.includes(shown), `${name}/${field}: the refusal shows the capture: ${r.err}`);
363
+ assert.doesNotMatch(r.err, /Recipe cache .* is invalid/);
364
+ assert.doesNotMatch(r.err, /Recipe derivation step/);
365
+ }
366
+ }
367
+ });
368
+
369
+ // The must-ACCEPT half: with no stub the frame is invisible, and a value with
370
+ // an embedded newline crosses it byte for byte.
371
+ test("the framed read hands on the exact value, an embedded newline included (#2217)", () => {
372
+ const { dir, head } = repo();
373
+ cache(dir, recipe(head, { install: "true\ntrue", test: "sh ./run-tests.sh\n: second line" }));
374
+ const i = derive(dir, "install");
375
+ assert.equal(i.status, 0, i.err);
376
+ assert.equal(i.out, "true\ntrue");
377
+ const t = derive(dir, "test");
378
+ assert.equal(t.status, 0, t.err);
379
+ assert.equal(t.out, "sh ./run-tests.sh\n: second line");
380
+ });
@@ -0,0 +1,231 @@
1
+ #!/usr/bin/env node
2
+ // Size a PR's diff and classify its files, so a review can scale its fan-out to
3
+ // the change instead of running the full specialist set on an 8-line docs edit.
4
+ //
5
+ // The fleet docs already SAY "two or three specialists for annotation-only or
6
+ // single-file, the full set for production code" — in two places — but nothing
7
+ // computes the diff, so the default is the full set every time. This turns that
8
+ // judgement into one deterministic call. `review-core.mjs` reads the booleans;
9
+ // a human reads `profile`.
10
+ //
11
+ // Facts only. It does NOT decide which dimensions to run — that policy lives in
12
+ // the caller, next to the dimension list it owns. `docsOnly`/`hasTests`/`hasSrc`
13
+ // are chosen so the caller's selection is a clean expression over them.
14
+ //
15
+ // `classify` and `computeStats` are pure and exported so the classifier is
16
+ // unit-tested (diff-stats.test.mjs) without a live `gh`; the CLI runs only when
17
+ // this file is executed directly.
18
+
19
+ import { execFileSync } from "node:child_process";
20
+ import { pathToFileURL } from "node:url";
21
+ import { makeDie, defineFlags } from "./arg.mjs";
22
+
23
+ const NAME = "diff-stats";
24
+
25
+ // Classification is by path — the cheapest signal that separates "prose" from
26
+ // "code" — and priority-ordered because a test file is also a .ts file: test
27
+ // wins over src, docs and config are named explicitly, src is the residue.
28
+ export const isTest = (p) => /(\.|_)(test|spec)\.[cm]?[jt]sx?$/i.test(p) || /(^|\/)(__tests__|tests?|e2e|__mocks__)\//i.test(p);
29
+ export const isDocs = (p) => /\.(md|mdx|markdown|txt|rst|adoc)$/i.test(p) || /(^|\/)docs?\//i.test(p) || /(^|\/)(README|CHANGELOG|LICENSE|CONTRIBUTING)(\.|$)/i.test(p);
30
+ export const isConfig = (p) =>
31
+ /\.(ya?ml|toml|ini|cfg|conf|json|json5|lock|env)$/i.test(p) ||
32
+ /(^|\/)\.github\//i.test(p) ||
33
+ /\.config\.[cm]?[jt]s$/i.test(p) ||
34
+ /(^|\/)(package-lock\.json|pnpm-lock\.yaml|yarn\.lock|\.[a-z]+rc)$/i.test(p);
35
+
36
+ // A runnable-code extension (.js/.cjs/.mjs/.ts/.tsx/.jsx/…), and the naming
37
+ // convention that marks a code file as config regardless of where it sits.
38
+ const isCodeExt = (p) => /\.[cm]?[jt]sx?$/i.test(p);
39
+ const isConfigName = (p) => /\.config\.[cm]?[jt]sx?$/i.test(p);
40
+
41
+ export function classify(p) {
42
+ if (isTest(p)) return "test";
43
+ // A code file is `src` even under docs/ or .github/. Path-based docs/config
44
+ // rules must not swallow executable code — a docs-site generator or a
45
+ // composite-action script — or the src-gated dimensions (types, silent-failure,
46
+ // simplify) silently never run on real code. Exception: `*.config.{js,ts,…}` is
47
+ // config by naming convention.
48
+ if (isCodeExt(p) && !isConfigName(p)) return "src";
49
+ if (isDocs(p)) return "docs";
50
+ if (isConfig(p)) return "config";
51
+ return "src";
52
+ }
53
+
54
+ // Turn the `gh --json files` array (per-file additions/deletions) into the facts
55
+ // the caller selects dimensions from. Pure: no I/O, so it is directly testable.
56
+ // `docsOnly` is deliberately strict — purely docs, no src/test/config — so a docs
57
+ // PR that also nudges a CI workflow keeps its fuller review. `hasSrc`/`hasTests`
58
+ // let the caller drop the `tests`/`types`/`silent-failure`/`simplify` dimensions
59
+ // when there is nothing for them.
60
+ //
61
+ // `changedFiles` is the PR's UNCAPPED file count, and it is a second argument
62
+ // because `files` is capped: `gh pr view --json files` pages at 100 and exits 0
63
+ // with no warning (measured on microsoft/vscode#329568 — `files` 100 against
64
+ // `changedFiles` 124). Every fact below is then computed off a short list with
65
+ // nothing in the blob contradicting it: `loc` under-counts, `docsOnly` can flip
66
+ // because the src files fell off the end, and `paths` is what `review-core.mjs`
67
+ // puts in front of a specialist under "and no others". `truncated` is set ONLY
68
+ // when the two counts disagree, so it is absent on every normal PR and the
69
+ // caller can treat its presence as "this list is short by construction".
70
+ export function computeStats(files, changedFiles) {
71
+ const kinds = { docs: 0, test: 0, config: 0, src: 0 };
72
+ let loc = 0;
73
+ const paths = [];
74
+ for (const f of files) {
75
+ const kind = classify(f.path);
76
+ kinds[kind] += 1;
77
+ const fileLoc = (f.additions || 0) + (f.deletions || 0);
78
+ loc += fileLoc;
79
+ paths.push({ path: f.path, kind, loc: fileLoc });
80
+ }
81
+
82
+ const hasSrc = kinds.src > 0;
83
+ const hasTests = kinds.test > 0;
84
+ const hasConfig = kinds.config > 0;
85
+ const docsOnly = files.length > 0 && !hasSrc && !hasTests && !hasConfig;
86
+
87
+ let profile;
88
+ if (files.length === 0) profile = "empty";
89
+ else if (docsOnly) profile = "docs";
90
+ else if (!hasSrc && hasTests) profile = "tests-only";
91
+ else if (files.length === 1) profile = "single-file";
92
+ else if (loc < 30) profile = "small";
93
+ else profile = "production";
94
+
95
+ const stats = { files: files.length, loc, kinds, docsOnly, hasSrc, hasTests, hasConfig, profile, paths };
96
+ if (Number.isInteger(changedFiles) && changedFiles > files.length) stats.truncated = changedFiles;
97
+ return stats;
98
+ }
99
+
100
+ // --- CLI (runs only when executed directly, never on import) ---------------
101
+
102
+ // die()/numArg() shared with the other fleet scripts — see arg.mjs for the
103
+ // fail-open (#61/#169/#878) and pipe-safety (#176/#328) rationale. `--pr` is
104
+ // the only flag read here, and numArg() rather than arg() because this file
105
+ // was the live half of #840's defect: the `if (!pr)` below caught a trailing
106
+ // `--pr` — `undefined` is falsy — but never a non-numeric one, so `--pr abc`
107
+ // reached `gh pr view abc` and printed `{"pr":null,…}` at exit 0. Measured
108
+ // against a stub gh that answers, which is what a real one does for `abc`:
109
+ // it resolves as a BRANCH, so the stats underneath were genuine and about
110
+ // whatever PR that branch heads, reported under a null id.
111
+ const die = makeDie(NAME);
112
+ const { numArg, sweep, stray } = defineFlags(die, { flags: { pr: "value" } });
113
+
114
+ // #932. The one truncation rule for the raw gh value this script quotes into a
115
+ // refusal: clip behind a visible marker, and only when the value was really
116
+ // clipped. Unmarked — `raw.trim().slice(0, 120)`, what the die below used to do
117
+ // — the length quoted is gh's, not this script's, so a 269 KB portal page and a
118
+ // 90-character one render identically and a reader cannot tell a whole
119
+ // diagnostic from a cut one.
120
+ //
121
+ // HEAD, not tail, measured on this site's own payload rather than imported from
122
+ // #638/PR #931's fix for the same unmarked clip in ledger.mjs. Those sites clip
123
+ // STDERR, where warnings lead and the cause lands last; `run()` above passes no
124
+ // `stdio`, so execFileSync forwards the child's stderr and returns stdout ALONE
125
+ // — this clips stdout. Real gh (2.100.0) never puts non-JSON there: a missing
126
+ // PR, bad credentials and an intercepting proxy all report on stderr at exit 1,
127
+ // which run()'s catch takes; a forced TTY, a pager and `GH_DEBUG=api` each left
128
+ // stdout pure JSON; and a payload past execFileSync's 1 MiB maxBuffer throws
129
+ // ENOBUFS rather than returning a mid-JSON cut, so the one shape whose cause
130
+ // would sit at the tail cannot reach `raw`. What remains is an interposer on
131
+ // that stdout — a wrapper, shim or captive portal — and every one of those
132
+ // leads with its own message. Measured on real bytes: github.com's 404 body
133
+ // ends `</div></body></html>`, which every HTML error page on earth shares and
134
+ // which names no cause, while its head carries `<!DOCTYPE html>`; a wrapper
135
+ // that prints a notice and delegates ends in `"changeType":"MODIFIED"}]}`,
136
+ // reading as if gh had answered perfectly and the parser were at fault. Tail
137
+ // here would keep the noise and discard the answer.
138
+ //
139
+ // The marker counts against `n`, so `cut(s).length <= n` for every `n >=
140
+ // MARKER.length` — the only regime the one call site below exercises, since
141
+ // `cut` is module-private and always called with the default `n = 120`. This
142
+ // is the one place it differs from ci-state.mjs's `cut` (#1479), whose marker
143
+ // sits past its `n`: `s.slice(0, n)` there appends the marker unconditionally,
144
+ // measuring 133 characters against ci-state.mjs's own 120-char cap — and this
145
+ // script's stderr is read by review-core.mjs's snapshot agent, markdown fed to a
146
+ // model, the context budget run()'s comment above measures in bytes. A cap
147
+ // that the marker can push past is not a cap. `Math.max` because a caller
148
+ // passing an `n` under the marker's own width would otherwise hand `slice` a
149
+ // negative end, which counts from the END of the string — silently inverting
150
+ // the direction this comment just measured, the one failure mode worth a
151
+ // guard on a single-call-site helper.
152
+ const MARKER = "… (truncated)";
153
+ const cut = (s, n = 120) => (s.length > n ? `${s.slice(0, Math.max(0, n - MARKER.length))}${MARKER}` : s);
154
+
155
+ function run(cmd, args) {
156
+ console.error(`$ ${cmd} ${args.join(" ")}`);
157
+ try {
158
+ return execFileSync(cmd, args, { encoding: "utf8" });
159
+ } catch (e) {
160
+ // Fail closed. A broken query must not read as "empty diff". The harm is not
161
+ // a trim — computeStats([]) yields profile "empty", which review-core.mjs
162
+ // WIDENS to the full set. It is that a real production PR would be sized
163
+ // from a lie, and the widen only looks safe until the next caller reads
164
+ // these facts for something else.
165
+ // Names the cause, never the child's stderr — execFileSync forwarded it
166
+ // already (no `stdio` above), so interpolating it emits every byte twice:
167
+ // measured 7,700 B becoming 15,454 B, into review-core.mjs's snapshot agent,
168
+ // which is markdown read by a model. `e.message` is the same string, not a
169
+ // fallback — Node builds it as `Command failed: <cmd>\n<stderr>`. Three
170
+ // disjoint shapes: Node-aborted (ENOENT/ENOBUFS), signal, exit (#176).
171
+ die(
172
+ `${cmd} failed: ${e.code ?? (e.signal ? `killed by ${e.signal}` : `exit ${e.status}`)}`,
173
+ );
174
+ }
175
+ }
176
+
177
+ function main() {
178
+ // `=== null`, not `!pr`: numArg() returns a NUMBER, so `--pr 0` — a value
179
+ // the caller did give — would otherwise draw a usage line claiming `--pr` is
180
+ // required, where gh answers it truthfully as no such PR. Absent is this
181
+ // file's own refusal and malformed is numArg()'s, per arg.mjs.
182
+ const pr = numArg("pr");
183
+ if (pr === null) die("usage: diff-stats.mjs --pr <number>");
184
+ // #365, weaker here for the same reason as pr-overlap.mjs: `--pr` is
185
+ // required, so a misspelled `--prr 5` already fell through to the usage die
186
+ // above. What was silently ignored at exit 0 is a stray riding along with a
187
+ // good `--pr` (`--pr 5 --base main`), and that is what this closes.
188
+ //
189
+ // Inside main(), never at module scope: computeStats() is imported by
190
+ // diff-stats.test.mjs and select-dimensions.test.mjs, and a module-scope
191
+ // sweep would read the IMPORTER's argv. (review-pr runs this script as a
192
+ // CLI subprocess with its own argv, so it is not one of those importers.)
193
+ // Below the guard above, so `--pr --json` keeps #169's "--pr needs a value".
194
+ sweep();
195
+ // #463: sweep() only refuses a `--`-prefixed token; a bare or single-dash
196
+ // one (`--pr 42 basee`) rode along in silence the same way. This file
197
+ // takes no positional, so any leftover token is a stray.
198
+ stray();
199
+
200
+ // Parsed through a guard, not bare. gh can exit 0 with a non-JSON body — a
201
+ // proxy's HTML error page is the measured case — and an uncaught SyntaxError
202
+ // exits 1, a code this script does not define (die is 2, success 0). Same
203
+ // fail-closed rule as run() above: a broken response is not an empty diff.
204
+ // `changedFiles` rides the same query for free and is the only thing that
205
+ // reveals the 100-file cap on `files` — see computeStats.
206
+ const raw = run("gh", ["pr", "view", String(pr), "--json", "files,changedFiles"]);
207
+ let info;
208
+ try {
209
+ info = JSON.parse(raw);
210
+ } catch {
211
+ die(`gh pr view ${pr} returned no JSON — ${cut(raw.trim())}`);
212
+ }
213
+ // Same fail-closed rule as run() above, and the one place it was missing: `||
214
+ // []` turned a malformed response into a fully-formed `profile: "empty"`
215
+ // measurement, exit 0, indistinguishable on stdout from a real empty PR. That
216
+ // is the lie the comment in run() warns about, manufactured at the
217
+ // `computeStats` call this guard protects.
218
+ if (!info) die("gh returned no body");
219
+ if (!Array.isArray(info.files)) die("gh returned no files array");
220
+ const stats = computeStats(info.files, info.changedFiles);
221
+
222
+ console.error(
223
+ ` ${NAME}: pr=${pr} files=${stats.files} loc=${stats.loc} ` +
224
+ `docs=${stats.kinds.docs} test=${stats.kinds.test} config=${stats.kinds.config} src=${stats.kinds.src} → ${stats.profile}` +
225
+ (stats.truncated ? ` (TRUNCATED: gh listed ${stats.files} of ${stats.truncated} files)` : ""),
226
+ );
227
+
228
+ console.log(JSON.stringify({ pr, ...stats }));
229
+ }
230
+
231
+ if (import.meta.url === pathToFileURL(process.argv[1] || "").href) main();