@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,600 @@
1
+ // Shared CLI-boundary helpers for the fleet scripts: die(), arg(), numArg(),
2
+ // has(), sweep(), stray(), the three refusal rules
3
+ // isFlagLike()/hasEqualsForm()/isDigits(), and writeAll() — the short-write
4
+ // and EAGAIN retry loop every script's own stdout/stderr write routes
5
+ // through (#1549).
6
+ // #367: was five drifting copies of arg(), three of has(), seven of die() in
7
+ // two incompatible shapes — one paste behind on any guard fix. One copy now;
8
+ // a fix to the contract lands here once and reaches every caller that routes
9
+ // through the helper it fixes.
10
+ //
11
+ // For die() that is every script that has one: `grep -ln '^function die(' \
12
+ // scripts/*.mjs` reports none, so no script carries a private
13
+ // module-scope die() any more. The `^` is the whole command: unanchored, it
14
+ // matches this very comment and makeDie()'s own indented `return function
15
+ // die(msg)`, so it reported arg.mjs — a settling command that answers with
16
+ // the file asserting it settles nothing. For the guards it is not, and the gap
17
+ // is where this file's own defect used to live: a script that hand-rolls its
18
+ // argv reader cannot call arg()/has() at all, because those refuse under a
19
+ // GENERATED message ("--<name> needs a value") and such a reader exists
20
+ // precisely to refuse under its own ("--file needs a path"). ledger.mjs
21
+ // splices --file/--require-file out of argv itself (#362) and
22
+ // member-outcomes.mjs reads its own --file, so both were out of arg()'s
23
+ // reach — and both answered that by copying the expression, which is a
24
+ // requirement recorded where nothing executes it.
25
+ //
26
+ // #567 closed that: the rules are stated once, as isFlagLike() and
27
+ // hasEqualsForm() below, and BOTH readers import and call them while keeping
28
+ // their own wording. No script now restates one of these rules as a value
29
+ // guard instead of calling it. That is executed, not documented —
30
+ // shared-refusal.test.mjs reds when a copy is re-inlined, including one
31
+ // re-inlined behaviour-identically, which no behavioural test can see. Read
32
+ // the current division with `grep -n 'from "./arg.mjs"'
33
+ // scripts/*.mjs | grep -v test` rather than trusting a list
34
+ // here to have aged well.
35
+ //
36
+ // The scripts that hold a flag refusal of their OWN are the second edit sites
37
+ // for this contract: change a rule here and each of them needs the same change
38
+ // made again at its own site. Holding that refusal is what makes a script one
39
+ // — not whether arg()'s refusals reach it. Being out of arg()'s reach is one
40
+ // way to end up holding one; running a second parser alongside arg() is
41
+ // another, and each way has a script that qualifies only under it.
42
+ //
43
+ // Which scripts those are is readable off the `from "./arg.mjs"` grep this
44
+ // header already recommends, provided you read the imported SYMBOL list and
45
+ // not the filenames: a row binding defineFlags has delegated the unknown-flag
46
+ // refusal, so `grep -n '^import .*makeDie.* from "./arg.mjs"'
47
+ // scripts/*.mjs | grep -v test | grep -v defineFlags` leaves the
48
+ // rows that hold their own. Anchoring on `^import` is load-bearing for the
49
+ // same reason it is on the die() grep: unanchored, this very comment matches
50
+ // itself. Requiring makeDie is what keeps the rows to SCRIPTS: every script
51
+ // importing this file refuses its command line through a die() bound from
52
+ // here, and a module that binds none has no command line to refuse a flag on
53
+ // — review-core.mjs, which imports isDigits alone and is itself imported by
54
+ // review-eval.mjs, joined the `scripts/*.mjs` glob when #1763 renamed it from
55
+ // `.js`. A future script that refuses WITHOUT makeDie falls out of this grep;
56
+ // that is the price of the filter, named here rather than hidden. Read that output
57
+ // for the roster — the scripts this header names exemplify a way of
58
+ // qualifying, and were never the whole of it.
59
+ //
60
+ // fleet-tick.mjs is the one script still outside arg()/has(), and
61
+ // deliberately: it parses its flags with node:util's parseArgs, so its
62
+ // unknown-flag, required-flag and range refusals are a separate edit site on
63
+ // its own terms. Its integer guard is no longer one of them — #878 gave the
64
+ // digits grammar its own predicate (isDigits() below) precisely because
65
+ // isFlagLike() cannot express it, and int() now calls that instead of
66
+ // hand-writing the third spelling. What stays fleet-tick's own there is the
67
+ // `String(raw).trim()` its input needs and the wording of its refusal, not
68
+ // the rule.
69
+ //
70
+ // candidates.mjs qualifies the other way, which the reach test cannot express:
71
+ // it binds makeArg/makeHas, so arg()'s refusals DO reach it — `node
72
+ // scripts/candidates.mjs --limit` refuses under the generated
73
+ // wording from here — and it parses with node:util's parseArgs as well, whose
74
+ // unknown-flag refusal is its own edit site: `node
75
+ // scripts/candidates.mjs --bogus`. Why that refusal is not
76
+ // sweep()'s is argued at refuseUnknown(), which owns the trade-off; this names the
77
+ // edit site rather than restating it.
78
+ //
79
+ // Each factory takes (or returns something bound to) the caller's own die(),
80
+ // because every script's die() speaks under its own NAME — that stays
81
+ // site-specific, nothing here hardcodes a script name.
82
+
83
+ import { writeSync } from "node:fs";
84
+
85
+ // #1549: ONE write-retry loop, not three. Resuming a short write and waiting
86
+ // out an EAGAIN are properties of the FD, not of any one caller, so die()
87
+ // below, ci-state.mjs's verdict writes and staleness.mjs's verdict() all
88
+ // route through writeAll() instead of each hand-rolling the same
89
+ // while/try/subarray. They were three independent copies held in step by a
90
+ // comment reading "mirrors emit()" and by nothing executable — which is
91
+ // exactly how one of them (ci-state.mjs's emit()) stayed the only one with no
92
+ // retry cap at all. board.mjs's fault() is the fourth site and is #1547's to
93
+ // move, not this file's.
94
+ const MAX_EAGAIN_RETRIES = 200;
95
+
96
+ // Shared across every retry: Atomics.wait never writes or notifies it, so one
97
+ // instance times out exactly as a fresh one would, without allocating a
98
+ // SharedArrayBuffer on every EAGAIN.
99
+ const IDLE = new Int32Array(new SharedArrayBuffer(4));
100
+
101
+ // Writes every byte of `text` to `fd`, or reports that it could not.
102
+ //
103
+ // A single writeSync fails two ways against a pipe whose reader has left it
104
+ // full — the state an fd reaches once a stream has been initialised on it
105
+ // (console.error does that to fd 2) and enough output is queued behind it. It
106
+ // either SHORT-WRITES, returning the count it managed and throwing nothing at
107
+ // all, silently truncating with no diagnostic for a catch to see (#885/#889);
108
+ // or it throws EAGAIN. So this resumes from writeSync's own return value
109
+ // until the buffer is empty, and reads EAGAIN as "momentarily full", waiting
110
+ // 1ms for the reader rather than treating it as failure. The wait is what
111
+ // keeps that retry from spinning: against a reader asleep three seconds, a
112
+ // bare `continue` burned a full core for the whole stall where the 1ms wait
113
+ // burned almost none, both delivering the same bytes.
114
+ //
115
+ // The EAGAIN retry is CAPPED (#889). Uncapped, a reader that stays open but
116
+ // never drains — not merely a slow one — spins here forever, and every caller
117
+ // is one whose whole job is to finish and report an exit code, so an
118
+ // indefinite hang trades that guarantee away. Past the cap this gives up on
119
+ // the BYTES rather than on the process.
120
+ //
121
+ // Returns true when the whole of `text` landed, false when bytes were lost —
122
+ // to a non-EAGAIN errno, or to the cap. What that costs is the caller's to
123
+ // decide, and the callers genuinely differ: die() exits 2 either way,
124
+ // staleness.mjs's verdict() downgrades to could-not-check, ci-state.mjs
125
+ // carries on to its own exit code. The one thing none of them may do is
126
+ // mistake a short write for a complete one, which is what a bare writeSync
127
+ // leaves every one of them doing.
128
+ export function writeAll(fd, text) {
129
+ let buf = Buffer.from(text);
130
+ let retries = 0;
131
+ while (buf.length) {
132
+ try {
133
+ const written = writeSync(fd, buf);
134
+ if (written > 0) retries = 0;
135
+ buf = buf.subarray(written);
136
+ } catch (e) {
137
+ if (e.code !== "EAGAIN" || ++retries > MAX_EAGAIN_RETRIES) return false;
138
+ Atomics.wait(IDLE, 0, 0, 1);
139
+ }
140
+ }
141
+ return true;
142
+ }
143
+
144
+ // die() is writeSync, not console.error (#176/#328/#363). On a pipe,
145
+ // process.stderr.write is ASYNC and process.exit() discards whatever is
146
+ // still queued — a large forwarded child stderr (gh's own) eats the refusal
147
+ // line that follows it, because the refusal is queued last and dropped
148
+ // first. writeSync goes straight to the fd instead, so it survives.
149
+ //
150
+ // The leading newline is load-bearing, not formatting: writeSync lands while
151
+ // the forwarded child stderr may still be draining through the (async)
152
+ // stream, so without it this text can land mid-line with no separator.
153
+ // Every reader of these refusals, tests included, matches them
154
+ // line-anchored; without the leading newline they silently stop matching
155
+ // under exactly the large-stderr failure writeSync exists to survive.
156
+ export function makeDie(name) {
157
+ return function die(msg) {
158
+ // The try covers the TEMPLATE as well as the write, and that is the whole
159
+ // of its job: uncaught, a throwing msg — or anything escaping writeAll —
160
+ // skips process.exit(2) and drops the process to Node's default exit 1,
161
+ // inverting the caller's own exit-code contract (#299/#328). Hoisting the
162
+ // string out to writeAll's argument list reintroduces precisely that,
163
+ // which is why the pin in candidates.test.mjs requires it to sit inside.
164
+ // writeAll's false return is ignored on purpose, and says no more than
165
+ // this function always promised: the message may be lost, the exit code
166
+ // may not.
167
+ try {
168
+ writeAll(2, `\n${name}: ${msg}\n`);
169
+ } catch {
170
+ // Message (or its own construction) may be lost; the exit code below must not be.
171
+ }
172
+ process.exit(2);
173
+ };
174
+ }
175
+
176
+ // #61/#169: a flag given with no value must never read as the flag being
177
+ // absent. Every arg()-reading call site falls back with `||`/`??`, so a
178
+ // trailing flag used to silently substitute a default — the malformed
179
+ // invocation reading as a successful one.
180
+ //
181
+ // Four spellings reach that one harm, so all four are refused: no value, an
182
+ // empty or blank value, a value that is itself a `--flag`, and the
183
+ // `--flag=value` form `indexOf` cannot see (`arg()` would otherwise report
184
+ // the flag absent and the caller would fall back exactly as if it were).
185
+ // Rejecting a `--`-prefixed value does forfeit a real capability — a value
186
+ // that legitimately starts with `--` — and staleness.mjs (#238) is a caller
187
+ // that can want one: its `--gone`/`--present` value is a string quoted out of
188
+ // a ticket, and #240's is `--label ready-for-agent`. Refusing loudly here
189
+ // still beats silently taking the next flag as this one's value, so this
190
+ // guard itself does not bend for it. staleness.mjs (#818) instead opts a
191
+ // caller in per flag with its own end-of-options separator, `--gone --
192
+ // '<value>'`, read before arg() ever sees the value — bare, with no `--`
193
+ // immediately before it, this refusal still stands unchanged.
194
+ // #567: the two predicates immediately below ARE those rules, exported so a
195
+ // caller that cannot route through arg()/has() consumes them instead of
196
+ // copying the expression — the header above says which callers and why.
197
+ // isDigits(), further down, is a third export on the same terms for a
198
+ // different rule (#878); these two are the ones this paragraph is about.
199
+ //
200
+ // What travels is the RULE, never the refusal text: each caller keeps its own
201
+ // die() wording, which is the constraint that made copying look necessary in
202
+ // the first place. ledger.mjs says "--file needs a path" where arg() below
203
+ // says "--<name> needs a value", because a reader who typed --file is owed the
204
+ // flag they typed and not the grammar behind it.
205
+ //
206
+ // Plain exports, not factories, because neither takes a script NAME — one is a
207
+ // predicate over a value, the other over an argv. That is also why #467's
208
+ // proposed makeCli(NAME) collapse of makeDie/makeArg/makeHas cannot absorb
209
+ // them whichever way it lands: those three exist to BIND a name, and these
210
+ // have no name to bind.
211
+ export function isFlagLike(value) {
212
+ return value === undefined || value.trim() === "" || value.startsWith("--");
213
+ }
214
+
215
+ // Prefix-matched on `--name=`, so a longer flag name sharing the prefix
216
+ // (`--filename=x` asked about `file`) is NOT caught here — that one is a name
217
+ // no script reads, which is sweep()'s to refuse in its own wording.
218
+ //
219
+ // argv is a parameter because the two kinds of caller hold different arrays:
220
+ // arg()/has() read the live process.argv, where argv[0] and argv[1] are the
221
+ // node and script paths and are scanned harmlessly; ledger.mjs holds its own
222
+ // process.argv.slice(2) and passes it.
223
+ export function hasEqualsForm(name, argv = process.argv) {
224
+ return argv.some((a) => a.startsWith(`--${name}=`));
225
+ }
226
+
227
+ export function makeArg(die) {
228
+ return function arg(name) {
229
+ const i = process.argv.indexOf(`--${name}`);
230
+ if (i === -1) {
231
+ if (hasEqualsForm(name)) die(`--${name} needs a space-separated value, not --${name}=`);
232
+ return null;
233
+ }
234
+ const value = process.argv[i + 1];
235
+ if (isFlagLike(value)) die(`--${name} needs a value`);
236
+ return value;
237
+ };
238
+ }
239
+
240
+ // #364: a boolean flag written --name=value must refuse, not read as
241
+ // absent — same fail-open class as arg()'s `=` guard above, but
242
+ // boolean-specific wording: there is no value to take, so "needs a
243
+ // space-separated value" would lie.
244
+ export function makeHas(die) {
245
+ return function has(name) {
246
+ if (hasEqualsForm(name)) die(`--${name} is a boolean flag, not --${name}=`);
247
+ return process.argv.includes(`--${name}`);
248
+ };
249
+ }
250
+
251
+ // #878: the digits rule, stated once. #840 closed a non-numeric `--pr` in
252
+ // ci-state.mjs alone, and the identical shape stayed live in its siblings.
253
+ // Measured on the pre-fix tree against a stub `gh` that ANSWERS, the way a
254
+ // real one does for a branch ref: `diff-stats.mjs --pr abc` reached
255
+ // `gh pr view abc` and printed `{"pr":null,…}` at exit 0, and
256
+ // `pr-overlap.mjs --a abc --b def` printed `{"a":null,"b":null,…}` at exit 0
257
+ // under a real `signal: "files"` verdict. Each payload's only identifying
258
+ // field was built with `Number()`, and `JSON.stringify(NaN)` is `null` — a
259
+ // report that cannot be attributed to the PR it answered for, at the exit code
260
+ // the fleet gates on. `gh pr view` resolves a non-numeric ref as a BRANCH, so
261
+ // the answer underneath was genuine and about a different PR.
262
+ //
263
+ // The class is NOT bounded by the `arg("pr")` spelling — pr-overlap.mjs reads
264
+ // `--a`/`--b` — so it is enumerated by SHAPE: an argument checked for
265
+ // truthiness alone, then handed to `gh` as a ref AND to `Number()` in a
266
+ // payload field. Its members are ci-state.mjs, diff-stats.mjs and
267
+ // pr-overlap.mjs, and all three now route through numArg() below. A sweep for
268
+ // the flag NAME finds two of the three, which is how the third stayed open
269
+ // through #840's review.
270
+ //
271
+ // Stated here rather than a third time at the call sites, because the
272
+ // invariant had no single expression: ci-state.mjs spelled it `/^[0-9]+$/`
273
+ // while fleet-tick.mjs's int() spells it `/^\d+$/` over a parseArgs value,
274
+ // each with its own wording. #367 overturned #169's "no shared module" ruling
275
+ // to stop exactly this drift, and a fourth spelling IS the drift.
276
+
277
+ // `+`, so the empty string is not a number. arg() already refuses that value
278
+ // through isFlagLike, but this predicate's other consumers do not read argv
279
+ // through arg(): fleet-tick.mjs's int() reads parseArgs values, where
280
+ // `Number("")` is 0 and `Number.isInteger(0)` is true, so `--pool ""` — the
281
+ // shape an unset shell variable produces — would read as a genuine, empty
282
+ // pool.
283
+ //
284
+ // Digits, not a `Number()` coercion, and the difference is the whole guard:
285
+ // `Number` accepts `1e3`, ` 42 `, `0x2a` and `Infinity`, and each of those
286
+ // reaches `gh` as a ref that is not the PR the caller meant. It forfeits the
287
+ // branch and URL spellings `gh pr view` itself takes — the same trade the
288
+ // `--`-prefixed value rule above makes — and nothing in this repo passes one:
289
+ // board.mjs's runCiState() sends `String(pr)` off a numeric record, and every
290
+ // documented invocation is `--pr <N>`.
291
+ //
292
+ // RegExp.test coerces, which is load-bearing in both directions. It is what
293
+ // lets review-core.mjs ask this about a workflow argument that arrives as the
294
+ // number 42 rather than the string "42"; it is also why this can never be an
295
+ // ABSENCE check, since `null` coerces to the string "null" and answers false.
296
+ // Every caller reads absence first, on its own terms.
297
+ //
298
+ // Leading zeros are accepted: `Number("007")` is 7 and `gh pr view 007`
299
+ // resolves PR 7, so there is nothing ambiguous to refuse. The shell half of
300
+ // this same invariant (claim-ticket.sh, inflight.sh, release-ticket.sh,
301
+ // drop-merged-label.sh) carries an extra `0?*` clause that refuses them, and
302
+ // this rule deliberately does not adopt it — tightening here would refuse a
303
+ // `--pr 007` that #840's shipped guard accepts, which is a behaviour change
304
+ // dressed as a de-duplication.
305
+ //
306
+ // A plain export rather than a factory, for the reason isFlagLike and
307
+ // hasEqualsForm are: it is a question about a value and binds no script name.
308
+ export function isDigits(value) {
309
+ return /^[0-9]+$/.test(value);
310
+ }
311
+
312
+ // numArg() is built ON arg(), not beside it, so the digits test runs AFTER arg()'s own
313
+ // value guards: `--pr` given trailing still reports "--pr needs a value" and
314
+ // `--pr=5` still reports the `=` form. Where both would refuse, the more
315
+ // specific wording wins — the same ordering rule sweep() states below.
316
+ //
317
+ // Absent returns null and is never refused here. That half does not decompose:
318
+ // pr-overlap.mjs's usage line names `--a` and `--b` at once, so its absent
319
+ // case has no per-flag wording to give. So only the MALFORMED refusal travels,
320
+ // and it is flag-named because all three callers mean one thing by it, while
321
+ // each caller keeps its own absent refusal above its own usage text — the
322
+ // header's "what travels is the RULE, never the refusal text", applied to a
323
+ // product whose two refusals genuinely differ in that respect.
324
+ //
325
+ // This also discharges #840's placement rule structurally instead of
326
+ // positionally. That guard had to sit BELOW ci-state.mjs's usage die because
327
+ // RegExp.test coerces `null` to "null": hoisted above it, an omitted `--pr`
328
+ // was answered with a complaint about a number and the usage line never
329
+ // printed. numArg() only ever tests a value it actually read, so the refusal
330
+ // is free to land at the read and no call site has to remember an order.
331
+ //
332
+ // Returns a NUMBER, which is what deletes the defect rather than guarding
333
+ // upstream of it: the payload sites each built `pr: Number(pr)`, and that
334
+ // expression is where `NaN` became `null`. Converted here, it cannot be
335
+ // reached with anything but digits and no call site restates it. Callers test
336
+ // absence as `=== null`, never `!pr` — `--pr 0` is a value the caller GAVE,
337
+ // and answering it with a usage line claiming `--pr` is required would be a
338
+ // lie, where `gh` answers it truthfully as no such PR.
339
+ function readNum(die, arg, name) {
340
+ const raw = arg(name);
341
+ if (raw === null) return null;
342
+ if (!isDigits(raw)) die(`--${name} needs a number, got ${raw}`);
343
+ return Number(raw);
344
+ }
345
+
346
+ // #365: the guards above all answer "was this flag given well?", and none of
347
+ // them can answer "was a flag given that nothing reads?". A MISSPELLED name is
348
+ // simply never looked for, so `ci-state.mjs --pr 5 --basee main` computed a
349
+ // real verdict against the DEFAULT base and exited 0/1 with no refusal — the
350
+ // same fail-open harm as #61/#169, reached from the other side: not an absent
351
+ // value, an unread flag. It bites hardest where the caller is markdown re-read
352
+ // by a model each run (ci-state.mjs, candidates.mjs), and #173 already recorded
353
+ // one landing: a doc naming `--label` where the flag is `--require-label`.
354
+ //
355
+ // Only `--`-prefixed tokens are its business. Everything else is positional and
356
+ // is not — board.mjs's `build`/`serve` subcommands, and every valued flag's
357
+ // value. A value can never legitimately BE a `--` token either, because arg()
358
+ // above refuses `--base --other` outright, so there is nothing to skip over and
359
+ // no need to know here which names take a value.
360
+ //
361
+ // #463: that leftover class — a bare or single-dash token nothing reads,
362
+ // `ci-state.mjs --pr 42 basee main` or `-basee` — is not this function's fix,
363
+ // and stays out of scope here for the same reason board.mjs's subcommands are:
364
+ // this sweep still refuses ONLY a `--`-prefixed token, unchanged.
365
+ // refuseStrays() below covers it instead, because unlike this sweep it DOES
366
+ // need to know which names take a value, to skip over one instead of refusing
367
+ // it.
368
+ //
369
+ // The `=` form is looked up by NAME alone: `--base=main` stays arg()/has()'s to
370
+ // refuse in their own wording, while `--basee=main` is caught here. The token
371
+ // is then echoed verbatim rather than the parsed name, so the refusal quotes
372
+ // what the caller actually typed.
373
+ //
374
+ // Callers put the call BELOW their own value guards, the way candidates.mjs
375
+ // places its parseArgs, so where both would refuse the more specific wording
376
+ // wins — `diff-stats.mjs --pr --json` still reports "--pr needs a value" and
377
+ // not the stray behind it. Nothing above those guards runs a query, so it is
378
+ // still a refusal before gh.
379
+ //
380
+ // One deliberate exception: board.mjs sweeps ABOVE its `cmd`, for the reason
381
+ // its own comment gives — so `board.mjs --prot 9000` names the stray rather
382
+ // than printing the usage line for a missing subcommand. The cost is that
383
+ // `build --ledger --bogus` gets this generic wording instead of "--ledger
384
+ // needs a value"; both exit 2, both name a real error, both refuse before gh.
385
+ //
386
+ // candidates.mjs deliberately does NOT route through this. It accepts no
387
+ // positionals, so its parseArgs (#173) additionally refuses a bare
388
+ // `candidates.mjs ready-for-agent` — which this cannot, board.mjs's
389
+ // subcommands being exactly that shape. Strictly stronger there; leave it.
390
+ //
391
+ // ledger.mjs is left out for the opposite reason: its `check`, `filed`, `row`
392
+ // and `ruled` all take a FREE-TEXT tail, where a `--` token is legitimately
393
+ // DATA — `check
394
+ // "--require-file silently absent when value missing"` works today and is the
395
+ // shape of issue titles in this repo — so this sweep would refuse working
396
+ // invocations, which #365's own AC calls worse than the bug. #584 NARROWED
397
+ // that gap without routing through this sweep, rather than closing it, and
398
+ // #1161 narrowed it again: ledger.mjs's own refuseStrayInCheckTail() is read on
399
+ // `check`'s tail ALONE, and refuses a `--`-prefixed token there only when it
400
+ // shares that tail with something else — the shape an unquoted stray flag
401
+ // makes, never the shape a one-argument subject makes — so a subject that
402
+ // legitimately opens with `--`, given as that one argument, is accepted and
403
+ // emitted in the payload's `subject` field unchanged. Unchanged there, not
404
+ // everywhere: `check` normalises and reorders the subject before it becomes a
405
+ // tracker query, so `the --basee flag is unread` is queried as `unread basee
406
+ // flag`.
407
+ //
408
+ // #1744 widened refuseStrayInCheckTail() again, past `--`-prefixed tokens: it
409
+ // also refuses a bare ONE-dash spelling of ledger.mjs's own flag names
410
+ // (`-require-file` for `--require-file`), matched by name rather than
411
+ // prefix, still only when the tail carries something besides it. ledger.mjs
412
+ // states that reasoning and its narrowed scope once, on
413
+ // refuseStrayInCheckTail() itself; not restated here.
414
+ //
415
+ // `check` alone, on a documented-convention test that ledger.mjs states once
416
+ // on refuseStrayInCheckTail() itself, with the docs and the measurement behind
417
+ // it (#1161) — not restated here, and not restated at its call site either.
418
+ // What guards the other three instead is ledger.mjs's refuseStrayInId(), a
419
+ // bare prefix test on the id slot ahead of the tail, where a `--` token is
420
+ // never data.
421
+ //
422
+ // It is the LENGTH gate that spares the legitimate case, not the prefix test
423
+ // — refuseStrayInId()'s id-slot prefix test is now `startsWith("-")` (#1678),
424
+ // no longer the same one this sweep uses (`startsWith("--")`). The id slot
425
+ // can take the stricter single-dash test because no free text ever lives
426
+ // there — a legitimate id is bare digits, optionally `#`-prefixed. This
427
+ // sweep can't: it scans invocations whose free-text positionals can
428
+ // legitimately open with a single dash, the same reason `check`'s tail
429
+ // above can't either. A prefix test with no length gate was measured
430
+ // refusing the legitimate subject.
431
+ //
432
+ // #584 does not make this file's cost disappear; it buys a smaller version of
433
+ // the same cost. An unquoted subject carrying a `--` word is a working
434
+ // invocation ledger.mjs's `check` now refuses too: `check the --basee flag is
435
+ // unread` answered at exit 0 before #584 and exits 2 after it. The residual
436
+ // that stays open and owned is a lone stray with no subject beside it, still
437
+ // taken as the subject, which ledger.mjs's own comment prices.
438
+ function refuseUnknown(die, known) {
439
+ for (const a of process.argv.slice(2)) {
440
+ if (a.startsWith("--") && !known.includes(a.slice(2).split("=")[0])) {
441
+ die(`unknown flag ${a} — accepted: ${known.map((k) => `--${k}`).join(", ")}`);
442
+ }
443
+ }
444
+ }
445
+
446
+ // #463: sweep() above only ever refuses a `--`-prefixed token — deliberately,
447
+ // per its own comment, because staying ignorant of which names take a value
448
+ // is what keeps it from having to refuse board.mjs's `build`/`serve` or any
449
+ // flag's own value. That leaves the OTHER half of "was a flag given that
450
+ // nothing reads?" open: a bare word or a single dash, which sweep's
451
+ // `startsWith("--")` check was never going to catch — `ci-state.mjs --pr 42
452
+ // basee main` runs the compare against the DEFAULT base and reports a real,
453
+ // wrong verdict at exit 0/1, the same fail-open harm as #365 reached from the
454
+ // positional side rather than the misspelled-flag side. `-basee` is the
455
+ // likelier typo of the two, since the caller plainly meant a flag.
456
+ //
457
+ // Widening sweep's own bound past `--` cannot fix this — #365's triage ruling
458
+ // is explicit that the sweep must never refuse tokens outside it, and
459
+ // board.mjs's subcommands are exactly the shape a widened sweep would catch
460
+ // by mistake. Nor can `startsWith("-")`: it refuses a legitimate negative
461
+ // value such as `--spend-since -1`, which arg() accepts today. The only way
462
+ // to tell a stray from a value is to know, by NAME, which flags take one —
463
+ // so unlike every guard above, this one takes that set from the script's flag
464
+ // table (defineFlags() below) instead of discovering it from argv.
465
+ //
466
+ // `positionals` is the script's own declared grammar for the one slot ahead
467
+ // of its flags — board.mjs's `build`/`serve`; every other caller passes
468
+ // none. Only the FIRST non-flag token can fill that slot; a second one, or
469
+ // any positional at all on a script that declares none, is refused by name.
470
+ //
471
+ // Every `--`-prefixed token here is assumed to have already survived sweep()
472
+ // — callers run this after it, same ordering — so a name whose declared kind
473
+ // is not "value" is a known boolean flag and consumes nothing, and a name
474
+ // declared "value" takes the next token as its value unconditionally,
475
+ // whatever that token looks like (that unconditional skip is what lets
476
+ // `--spend-since -1` through instead of reading `-1` as a stray positional).
477
+ // An `=`-joined form (`--pr=5`) is never treated as carrying a value to skip
478
+ // over: has()/arg() already refuse that form, by name, for every flag
479
+ // declared "value", wherever the script reads it — before or after this
480
+ // call.
481
+ function refuseStrays(die, flags, positionals) {
482
+ const argv = process.argv.slice(2);
483
+ let usedPositional = false;
484
+ for (let i = 0; i < argv.length; i++) {
485
+ const a = argv[i];
486
+ if (a.startsWith("--")) {
487
+ if (!a.includes("=") && flags[a.slice(2)] === "value") i++;
488
+ continue;
489
+ }
490
+ if (!usedPositional && positionals.includes(a)) {
491
+ usedPositional = true;
492
+ continue;
493
+ }
494
+ die(`unexpected argument '${a}'`);
495
+ }
496
+ }
497
+
498
+ // #1077: ONE declaration of a script's flags, and every reader bound to it.
499
+ // `flags` maps each name to "value" or "bool"; `positionals` is the grammar
500
+ // refuseStrays() above accepts ahead of the flags (board.mjs's
501
+ // `build`/`serve`). One key per flag, so a name cannot be declared both ways.
502
+ //
503
+ // The invariant this carries used to be prose at each call site: the set of
504
+ // flags stray() skips a value for had to name exactly, and only, the flags
505
+ // the script reads with arg(). A name wrongly present buys the token after
506
+ // it an unconditional skip, so the very stray the guard exists to catch
507
+ // becomes invisible; a name wrongly absent turns a legitimate value into a
508
+ // refused stray. Five scripts typed that list twice, once for sweep() and
509
+ // once for stray(), and nothing checked either copy against which reader the
510
+ // script actually called. A bare table would only have moved that risk — a
511
+ // boolean marked "value" is the same typo in new syntax — so the table and
512
+ // the reads are bound instead: sweep() and stray() both read this same
513
+ // `flags` object rather than a copy each, so the two halves cannot drift
514
+ // from each other the way the two lists did; sweep() accepts every declared
515
+ // name, stray() skips after the "value" ones, and a read of the wrong KIND
516
+ // refuses the first time it runs. arg()/numArg() accept only a "value" name
517
+ // and has() only a "bool" one, so a presence test on a value flag is refused
518
+ // too: test arg()'s result against null instead.
519
+ //
520
+ // A declared kind that is itself neither "value" nor "bool" — a typo in the
521
+ // table, not a caller's mistake — is the one drift the read-time guards
522
+ // above cannot catch on their own: a name never read on a given run would
523
+ // carry a bad kind through unnoticed. Refused here, at construction, instead
524
+ // of only at whichever read happens to reach it.
525
+ //
526
+ // That refusal goes through die() at exit 2, never a thrown Error: exit 1 is
527
+ // a verdict in ci-state.mjs (not green), merge-gate.mjs (blocked) and
528
+ // tier-roles.mjs (check failed), which is the inversion makeDie() exists to
529
+ // prevent (#299/#328). It is worded `bug:` because only the script's own
530
+ // source can reach it — no command line can make a correct table disagree
531
+ // with a correct read.
532
+ //
533
+ // Construction runs nothing but the kind check above and the table copy
534
+ // below. sweep() and stray() stay explicit calls the script places, below its
535
+ // own per-flag guards, so the more specific wording still wins where both
536
+ // would refuse (diff-stats.mjs's `--pr --json`, tier-check.mjs's roster
537
+ // flags). And every reader looks at process.argv when CALLED, never at a copy
538
+ // taken here: staleness.mjs splices its `--gone -- <needle>` triple out of
539
+ // process.argv before its sweep()/stray() run, and a snapshot would refuse
540
+ // the needle.
541
+ //
542
+ // The TABLE, by contrast, is copied once here, before anything derives from
543
+ // it (#2114): sweep() takes its names at construction while the other readers
544
+ // look a name up per call, so a caller mutating its own `flags` object
545
+ // afterwards would leave arg() accepting a name sweep() refuses. With the
546
+ // copy, no reader sees a later mutation, and no kind the construction check
547
+ // never saw can reach a reader. A copy, not Object.freeze(): the caller's
548
+ // object stays its own, unchanged — the line gitEnv() in git-env.mjs holds
549
+ // for its caller's `base` too.
550
+ //
551
+ // #2172 review: `flags` not being a plain object at all — `null`, or absent
552
+ // because a caller typed `{ flag: {...} }` instead of `{ flags: {...} }` and
553
+ // this destructures it to `undefined` — used to throw a TypeError straight
554
+ // out of `Object.keys(undefined)`, before #2114 introduced the copy below.
555
+ // `{ ...undefined }` and `{ ...null }` both spread to `{}` without
556
+ // complaint, so the copy would otherwise turn a loud construction-time crash
557
+ // into a silently empty flag table whose every read fails later, elsewhere,
558
+ // with no mention of the missing table. Checked here, before the copy, for
559
+ // the same reason the kind loop below runs at construction rather than at
560
+ // whichever read first notices: a table this broken is the script's own
561
+ // mistake, not its caller's.
562
+ export function defineFlags(die, { flags: table, positionals = [] }) {
563
+ if (table === null || typeof table !== "object") {
564
+ die(`bug: defineFlags() needs a flags table, got ${table === null ? "null" : typeof table}`);
565
+ }
566
+ const flags = { ...table };
567
+ const names = Object.keys(flags);
568
+ for (const name of names) {
569
+ if (flags[name] !== "value" && flags[name] !== "bool") {
570
+ die(`bug: --${name} declared ${flags[name]}, not "value" or "bool"`);
571
+ }
572
+ }
573
+ const rawArg = makeArg(die);
574
+ const rawHas = makeHas(die);
575
+ const expect = (name, kind) => {
576
+ const declared = Object.hasOwn(flags, name) ? flags[name] : undefined;
577
+ if (declared === kind) return;
578
+ die(`bug: --${name} read as ${kind} but ${declared === undefined ? "not declared" : `declared ${declared}`}`);
579
+ };
580
+ return {
581
+ arg(name) {
582
+ expect(name, "value");
583
+ return rawArg(name);
584
+ },
585
+ numArg(name) {
586
+ expect(name, "value");
587
+ return readNum(die, rawArg, name);
588
+ },
589
+ has(name) {
590
+ expect(name, "bool");
591
+ return rawHas(name);
592
+ },
593
+ sweep() {
594
+ refuseUnknown(die, names);
595
+ },
596
+ stray() {
597
+ refuseStrays(die, flags, positionals);
598
+ },
599
+ };
600
+ }