@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,674 @@
1
+ #!/usr/bin/env node
2
+ // Open issues that are candidates for work, reduced to the fields a shortlist
3
+ // needs.
4
+ //
5
+ // Never fetches raw bodies for the whole list — they are ~97% of the payload.
6
+ // The body is reduced to dependency references by `gh`, which applies `--jq`
7
+ // in its own process — so this file checks the rows it gets back rather than
8
+ // assuming the reduction applied.
9
+ //
10
+ // The label policy is a FLAG, not prose. `next-ticket` may drop a required
11
+ // label and retry when the result is empty; the fleet must not, because an
12
+ // empty ready-for-agent queue means there is no work, not that the net should
13
+ // widen — ready-for-human tickets need a human to brainstorm first, and an
14
+ // unattended fleet has no channel to one.
15
+ //
16
+ // Exit-code contract — the whole interface for a caller that reads no
17
+ // stderr: 0 = survivors, JSON array on stdout. 1 = the query succeeded and
18
+ // returned no rows at all. 2 = the query broke (bad args, gh failure, a
19
+ // reduction that did not apply, a capped result). 3 = the query succeeded,
20
+ // returned at least one row, and every row was removed by the to-spec
21
+ // filter — distinct from 1 so a caller such as run-team's phase 0 can say
22
+ // "the only labeled items are specs, run to-tickets" instead of "no work"
23
+ // (#64). Exit 3 describes the FINAL query attempt only — with
24
+ // `--allow-fallback`, a labeled all-specs pass that falls back to a
25
+ // genuinely empty unfiltered pass is exit 1, not 3; the drop count is never
26
+ // carried across the two attempts.
27
+
28
+ import { execFileSync } from "node:child_process";
29
+ import { parseArgs } from "node:util";
30
+ import { makeDie, makeArg, makeHas } from "./arg.mjs";
31
+
32
+ const NAME = "candidates";
33
+
34
+ // die()/arg()/has() shared with the other fleet scripts — see arg.mjs for
35
+ // the fail-open (#61/#169/#364) and pipe-safety (#176/#328/#363) rationale.
36
+ // No caller of THIS file is a hand-typed CLI. Two are markdown re-read by a
37
+ // model each run (next-ticket/SKILL.md, run-team/SKILL.md), which is why a
38
+ // malformed invocation is more plausible here than the shared guard's shape
39
+ // alone suggests — a model retypes the flags every time. The third,
40
+ // shortlist.mjs's scan(), spawns it with hardcoded args that cannot drift.
41
+ const die = makeDie(NAME);
42
+ const arg = makeArg(die);
43
+ const has = makeHas(die);
44
+
45
+ const requireLabel = arg("require-label");
46
+ const allowFallback = has("allow-fallback");
47
+
48
+ // Default well above the proving ground's real volume. Measured 2026-07-23:
49
+ // 106 issues survive the exclusions, so the previous hardcoded 100 dropped six
50
+ // of them — silently, because a truncated list is indistinguishable from a
51
+ // complete one. A high-priority ticket sitting at position 101 was invisible to
52
+ // the fleet and nothing said so.
53
+ const limit = Number(arg("limit") ?? 500);
54
+ if (!Number.isInteger(limit) || limit < 1) die(`--limit must be a positive integer, got '${arg("limit")}'`);
55
+
56
+ // The accepted flag set, declared once, and the only check on flag NAMES.
57
+ // Nothing checked them until #173: an unrecognised flag was ignored, so
58
+ // `--label ready-for-agent` — the spelling run-team's own phase 0 rule carried
59
+ // — ran the UNFILTERED query at exit 0, the widening `--require-label` exists
60
+ // to prevent.
61
+ //
62
+ // Runs BELOW the value guards, deliberately: where both would refuse — notably
63
+ // `--require-label` and `--limit` given with no value — arriving second leaves
64
+ // the refusal to #169's wording above rather than Node's. Nothing above emits
65
+ // output or runs a query, so refusing this late is still refusing before gh.
66
+ //
67
+ // The catch is unconditional, and THAT is the guard. Testing `e.code` for
68
+ // `ERR_PARSE_ARGS_UNKNOWN_OPTION` is what shipped first and it did not hold.
69
+ // `parseArgs` throws on the FIRST offending argument, so dropping any other
70
+ // code does not narrow the guard, it disables it for every argv where such an
71
+ // argument comes earlier — the unknown flag behind it is never reached. Two
72
+ // other codes were measured on node v26.5.0: ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL
73
+ // for a bare positional, ERR_PARSE_ARGS_INVALID_OPTION_VALUE both for
74
+ // `--boolflag=value` and for a string flag left without its value.
75
+ //
76
+ // Measured on that version: `ready-for-agent`, `junk --label ready-for-agent`
77
+ // and `--allow-fallback=true --label ready-for-agent` each ran the UNFILTERED
78
+ // query at exit 0, while `--label ready-for-agent` and
79
+ // `--require-label x --bogus` both refused. Position is not what decided it —
80
+ // a bad flag last still refused — only whether something earlier threw a code
81
+ // the catch dropped.
82
+ const OPTIONS = {
83
+ "require-label": { type: "string" },
84
+ "allow-fallback": { type: "boolean" },
85
+ "limit": { type: "string" },
86
+ };
87
+ // No `strict: true`: strict IS parseArgs' default, and stays the default when
88
+ // `allowPositionals`, `tokens` or `allowNegative` are added alongside it —
89
+ // measured across 48 argv shapes with and without, zero differences in error
90
+ // code, message or `{values, positionals}`.
91
+ try {
92
+ parseArgs({ options: OPTIONS });
93
+ } catch (e) {
94
+ die(`${e.message} — accepted: ${Object.keys(OPTIONS).map((f) => `--${f}`).join(", ")}`);
95
+ }
96
+
97
+ if (allowFallback && !requireLabel) die("--allow-fallback is meaningless without --require-label");
98
+
99
+ // #175's other half, and the half the fix below newly makes possible: the
100
+ // label is QUOTED into the search term, so a `"` inside it closes that quote
101
+ // early and the remainder becomes free text — the same misparse, with the fix
102
+ // applied. A `\` breaks the same term from the other side, because GitHub
103
+ // DOES honour `\"` as an escaped quote inside a qualifier: measured against
104
+ // feigi/claude-config 2026-08-17, negating a label no issue carries is a
105
+ // no-op, so `-label:"zzz" label:"ready-for-agent"` returns the same count as
106
+ // `label:"ready-for-agent"` alone — while `-label:"zzz\" label:"ready-for-agent"`
107
+ // returns the count for `ready-for-agent` as FREE TEXT instead, the backslash
108
+ // having eaten the closing quote and swallowed the whole following qualifier.
109
+ // Doubling does not escape it. Here the label term is LAST, so a trailing
110
+ // backslash leaves its value unterminated and the query answers zero rows at
111
+ // HTTP 200, no error — #175's silent empty, with the fix applied. Neither
112
+ // character can be represented, so refuse both at exit 2 ("the query broke")
113
+ // rather than send a query whose empty answer would read as exit 1.
114
+ if (requireLabel && /["\\]/.test(requireLabel)) die(`--require-label cannot contain a double quote or a backslash, got '${requireLabel}'`);
115
+
116
+ // The five `wayfinder:*` terms are separate `-label:` clauses, not a wildcard —
117
+ // GitHub's search has no `-label:"wayfinder:*"` — and none is quoted despite
118
+ // the colon each value carries. Measured 2026-09-08 against feigi/fleet-plugin:
119
+ // negating `wayfinder:map` alone excludes exactly one more issue than the
120
+ // unfiltered open count, and that issue is #1292 — a colon inside a label
121
+ // value is parsed as part of the label, not as a delimiter that ends it early
122
+ // and spills the remainder into free text, the failure mode `label:"…"`
123
+ // quoting exists for a SPACE (see `query()`'s comment below). Stated as a
124
+ // relationship rather than a pinned count for the same reason `query()`'s own
125
+ // comment gives it below: the queue churns hourly, so a digit is wrong within
126
+ // a day and reads as a regression. Quoting every value anyway would cost
127
+ // nothing (`-label:"wayfinder:map"` measured identical: same one-issue
128
+ // exclusion, same issue) — left unquoted here because an unconditional
129
+ // quote-everything rule belongs at the one call site building every label
130
+ // term (`query()` below), and EXCLUDE is a static literal no caller
131
+ // assembles.
132
+ const EXCLUDE =
133
+ "-label:in-progress -label:onhold -label:wontfix -label:needs-triage -label:needs-info -label:wayfinder:map -label:wayfinder:research -label:wayfinder:prototype -label:wayfinder:grilling -label:wayfinder:task";
134
+ // `d` walks the body line by line rather than one regex over the whole
135
+ // string, because RE2 (gojq's engine — gh applies `--jq` with gojq, not the
136
+ // system jq this file's own tests stub; see #63) has no lookahead, so
137
+ // "capture every ref up to the next heading" cannot be expressed as a single
138
+ // pattern. A heading line (`^#{1,6}[ \t]`) toggles a running "inside a
139
+ // blocking section" flag on when its text DECLARES one: any of the verb
140
+ // phrases, which end at a non-word character and tolerate trailing text
141
+ // because a heading opening with one is declaring a blocker whatever follows
142
+ // it; or the noun form
143
+ // `Dependencies`/`Dependency`, which must be the WHOLE heading, a trailing
144
+ // `:` aside. The noun form cannot be given the verb forms' tolerance:
145
+ // `## Dependency injection` is an ordinary section title in a code repo, and
146
+ // arming on it would turn every `#N` in its bullets into a blocker the body
147
+ // never declared (#439 — the noun form is the heading #208's brief used, and
148
+ // the gate named the verbs alone, so that section opened nothing).
149
+ //
150
+ // Either form may carry EMPHASIS, which markdown puts outside the words:
151
+ // `## **Dependencies**` names a dependency exactly as `## Dependencies` does,
152
+ // and read without the `\*` runs it armed no section at all, so every ref its
153
+ // bullets declared was dropped — exit 0, nothing on stderr, #439's silent
154
+ // wrong admission reached through this gate rather than through the inline
155
+ // label separator #439 widened (#1031). The runs are
156
+ // `\**` rather than `\*{0,2}` because `*`, `**` and `***` are all emphasis a
157
+ // heading is written with, and the noun form needs one on EACH side of its
158
+ // optional colon: markdown closes the bold before it (`**Dependencies**:`)
159
+ // or after it (`**Dependencies:**`) depending on where the author put the
160
+ // punctuation, the same both-sides tolerance the inline label separator
161
+ // below carries for the same reason. The end-of-line anchor is untouched —
162
+ // the runs go AROUND it, and they match asterisks ONLY, so
163
+ // `## **Dependency injection**` still arms nothing. Widen either run to a
164
+ // general wildcard and that heading arms, which is the whole distinction the
165
+ // anchor exists to hold; candidates.test.mjs pins both directions, on both
166
+ // engines.
167
+ //
168
+ // `after` is an inline label only, because `## After the migration` is
169
+ // ordinary narrative and arming on it invents a blocker, while a heading that
170
+ // really does declare one (`## After #12 lands`) still resolves through the
171
+ // inline pass below. The flag clears at ANY following heading (blocking or
172
+ // not); inside such a section only LIST-ITEM lines are read — that is the
173
+ // `## Blocked by` + list form to-tickets publishes, and the restriction is
174
+ // what keeps an unclosed section (nothing
175
+ // headed after it, the common shape) from sweeping every later `#N` in the
176
+ // body, inventing a blocker that silently starves the ticket out of the
177
+ // queue. Independently, any line — inside a section or not — carrying the
178
+ // phrase, then any run of whitespace and asterisks around an optional `:`,
179
+ // then one or more `#N` refs on that same line is read too — to-tickets'
180
+ // local-file `**Blocked by:** #12`, the markdown `Blocked by **#179**` that
181
+ // bolds the REF, and the bare `depends on #5` are all instances of that one
182
+ // match. The separator is a combined `[\s*]*` run rather than asterisk groups
183
+ // flanking the colon: those groups sat ahead of the separating whitespace, so
184
+ // they matched only asterisks flush against the phrase, and a space before the
185
+ // bold — where markdown actually puts it — dropped the ref (#439). Both passes
186
+ // are strictly line-local, which the removed `(?:depends on|…)\s+#\d+` regex
187
+ // was not: its `\s+` crossed newlines, so a
188
+ // phrase ending one line with its ref opening the next was collected and now
189
+ // is not. That narrowing is deliberate — neither to-tickets template writes
190
+ // that shape, and the alternative (carrying a "label seen, ref pending" flag
191
+ // into the following line) re-opens the same over-fire the list-item
192
+ // restriction above closes. A ref elsewhere in the body — not under a
193
+ // heading section, not after a label — is not collected: neither pass reaches
194
+ // it. Verified against real gojq (`go install
195
+ // github.com/itchyny/gojq/cmd/gojq@v0.12.19`) on every form in
196
+ // candidates.test.mjs's dependency-forms fixtures, not only the system jq the
197
+ // STUB there execs. The engines now agree on every one of those forms,
198
+ // including the ones that used to split. The separator is `[\t \p{Zs}*]*`
199
+ // and not `[\s*]*`, so `Blocked by:<U+00A0>#12` collects `[12]` under BOTH
200
+ // engines where it used to collect `[12]` under Oniguruma and `[]` under RE2
201
+ // — #383 ruled the ref a real blocker, because GFM renders that line as
202
+ // `Blocked by: #12` and autolinks the ref, so a reader sees a dependency and
203
+ // an admission gate must not miss one. Since no fixture splits any more, the
204
+ // gated tests can no longer identify their engine by disagreement: the STUB
205
+ // records which binary it executed and they assert that recording is gojq.
206
+ // The per-position rulings are set out above the JQ declaration below.
207
+ //
208
+ // `depmiss` is the diagnostic half (#1032), and it is deliberately LOOSER
209
+ // than the gate: any heading MENTIONING the concept that the gate did not
210
+ // arm. The gate's own pattern is named `armed` and both halves call it, so
211
+ // "did not arm" is the exact complement of what opened the section rather
212
+ // than a second approximation of it that could drift out of step. An empty
213
+ // `d` has two causes stderr could not tell apart — a ticket that declared no
214
+ // blocker, and a heading that declared one the gate refused — and the second
215
+ // is reachable BY DESIGN, since the noun form arms only as a whole heading:
216
+ // `## Dependencies (blocking)` collects nothing and printed the same row as a
217
+ // ticket with no dependencies at all. Matching the gate here would report
218
+ // nothing, because the headings worth naming are exactly the ones it
219
+ // rejected.
220
+ //
221
+ // So it over-fires by construction, `## Dependency injection` included, and
222
+ // THAT is why the stderr line it feeds is worded "not parsed, check the
223
+ // heading" and never as a fault: a DI section is not a mistake, and a
224
+ // diagnostic that calls it one false-alarms on every code-repo ticket
225
+ // carrying one — a line people learn to ignore is worse than no line.
226
+ // `after` stays out of the pattern for the same reason it arms no section
227
+ // above: `## After the migration` is narrative, so naming it would be noise
228
+ // with no near-miss behind it.
229
+ //
230
+ // A separate pass over the body rather than a third field on `depnums`'
231
+ // reducer, which is the pinned one and not worth reshaping for a diagnostic;
232
+ // the body is already walked twice and a third walk is nothing against the
233
+ // query it rides on. The trim is `rtrimstr("\r")` — literal, not `\s+$` —
234
+ // because the only whitespace that would disturb the line this prints is the
235
+ // CR of a CRLF body (what GitHub's web textarea writes), and a regex there
236
+ // would buy cosmetics at the price of one more regex position to rule on and
237
+ // keep portable (#383). `dh` never reaches stdout: the payload is stripped of it
238
+ // at the `JSON.stringify` below, because this is a stderr signal and #1032
239
+ // rules a payload field out of scope.
240
+ // ENGINE-PORTABLE CLASSES (#383). The program below contains no `\\s`, `\\d` or
241
+ // `\\b`: every position spells an explicit class. It has to, because the suite
242
+ // applies this expression with system jq (Oniguruma, all three Unicode-aware)
243
+ // while gh applies it with its embedded gojq (Go RE2, where `\\s` is
244
+ // `[\\t\\n\\f\\r ]`, `\\d` is `[0-9]` and `\\b` is ASCII). The same body reduced
245
+ // differently depending on who ran it, and gojq's answer is the one that
246
+ // reaches production. No library upgrade closes it: gh 2.100.0 embeds gojq
247
+ // v0.12.19, which is the latest release, Go's `\\s` is ASCII by design, jq
248
+ // 1.8.x still uses Oniguruma, and no inline flag (`(?S)`, `(?a)`, `(?u)`,
249
+ // `(?D)`) is accepted by both engines.
250
+ //
251
+ // The class is chosen PER POSITION, not once for the file. The governing rule
252
+ // is that each position follows GitHub's GFM rendering (measured with
253
+ // `gh api /markdown`); where no markdown rule applies, it follows what a
254
+ // reader sees. So two positions on the same line legitimately differ:
255
+ //
256
+ // after a heading's `#` marker — `[ \t]`
257
+ // `armed` and `depmiss`, both of which only ever match a heading that
258
+ // HAS title text after the marker (a keyword like "blocked by" or
259
+ // "dependencies"), so a marker with nothing after it already fails on
260
+ // content grounds and never needs a wider class here. GFM opens a
261
+ // heading on a space or a tab ONLY: `##<U+00A0>x` and `##<FF>x` both
262
+ // render as paragraphs. This narrows ASCII too — `\f` used to open a
263
+ // heading here and deliberately no longer does.
264
+ // after a heading's `#` marker, any-heading toggle — `([ \t]|\r?$)`
265
+ // `depnums`' per-line toggle, which decides whether a line STARTS a new
266
+ // heading at all (armed or not) so an open blocking section resets.
267
+ // Unlike `armed`/`depmiss` above, this one also has to recognize a
268
+ // BARE marker-only heading — no title text follows, so `[ \t]` alone
269
+ // never matches it, and the old open section wrongly kept collecting
270
+ // refs past it (#383 over-collection). GFM still renders a bare `##`
271
+ // as a real (empty) `<h2>`, so it must still close the section: `$`
272
+ // admits end-of-line, `\r?` admits the same position just before a
273
+ // CRLF line's trailing `\r` (the one `split("\n")` leaves behind).
274
+ // list-item indent and marker gap — `[ \t]*` … `[ \t]`
275
+ // Same GFM rule one level down: `-<U+00A0>#12` and `-<FF>#12` render as
276
+ // paragraphs, so neither is a bullet and neither declares a blocker.
277
+ // end of a heading line — `[\t\f\r \p{Zs}]*` before the anchor
278
+ // `armed`'s `dependenc(?:y|ies)` arm and the `spec` predicate. Padding a
279
+ // real heading with U+00A0, EM SPACE or IDEOGRAPHIC SPACE still renders
280
+ // an `<h2>`, so it is still that heading. `\f` is stripped by GFM; `\r`
281
+ // keeps CRLF bodies working; VERTICAL TAB stays EXCLUDED, because GFM
282
+ // renders it as U+FFFD and a replacement character is not blank.
283
+ // inline label/ref separators — `[\t\f\r \p{Zs}*]*`
284
+ // `Blocked by:<U+00A0>#12` renders as `Blocked by: #12` and GitHub
285
+ // autolinks the ref, so a reader sees a blocker — and an admission gate
286
+ // must not be the one thing that misses it. Matches the end-of-heading
287
+ // -line class above for the same reasons and the same characters:
288
+ // `\f` is stripped by GFM, `\r` keeps CRLF bodies working. Missing
289
+ // either one here silently drops a chained ref (`Blocked by
290
+ // #12,\f#13` losing `#13`) — the opposite, worse direction from the
291
+ // over-collection above: an admission gate must never MISS a blocker.
292
+ // every digit run — `[0-9]`
293
+ // Arabic-Indic digits are not refs anyone is trying to support, and this
294
+ // is the position where divergence could take the whole run down rather
295
+ // than change one row: under Oniguruma `\d` collected `#` + U+0661 U+0662,
296
+ // `tonumber` rejected it, and the program exited 5 — so a single ticket
297
+ // body took down the entire candidate listing.
298
+ // word boundary after a blocking phrase — `(?:[^\p{L}\p{M}\p{N}_]|` + anchor
299
+ // Unicode-aware, unlike RE2's ASCII `\b`: a letter, combining mark or
300
+ // digit that CONTINUES the word means a different word, so a heading
301
+ // reading `## Blocked by` + U+00E9 does not arm. Consuming one character
302
+ // rather than matching zero-width is safe — nothing follows this arm.
303
+ //
304
+ // Wherever any non-ASCII whitespace counts at all, it is `\p{Zs}` and nothing
305
+ // wider: every Unicode space separator renders as a blank, so the rule is
306
+ // "looks like a space", and both engines agree on `\p{Zs}`. Mind the double
307
+ // escaping below — jq's `\\p{Zs}` is `\\\\p{Zs}` in this JS source string.
308
+ //
309
+ // Measured over 24 fixtures on jq-1.7.1-apple and gojq 0.12.19: zero splits.
310
+ // candidates.test.mjs pins the rows that used to split, on both engines, and
311
+ // proves which engine each gated test actually reached.
312
+ //
313
+ // NATIVE EDGES (#1741). `d` is the UNION of the body scan above and the
314
+ // numbers on the issue's native "blocked by" edges, which ride the same
315
+ // query as gh's `blockedBy` field — no extra round trip, the cost #58
316
+ // deferred them on — merged and sorted by the final `unique`. Union, not
317
+ // replacement: to-tickets still writes blockers only as body text, and a
318
+ // hand-written body can name a blocker nobody wired as an edge, so dropping
319
+ // the scan would silently un-block both. The edges close the opposite miss:
320
+ // #593's body chains `**#531**` behind a parenthetical the scan cannot
321
+ // cross, and only its native edge carries #531. `d` stays RAW — a closed
322
+ // blocker's number is kept although the edge carries its state, exactly as
323
+ // the scan keeps one, because the consumers (run-team / next-ticket step 2)
324
+ // judge openness and a `d` whose two halves meant different things would
325
+ // be worse than either. Only `blockedBy` counts: `parent`/`subIssues` are
326
+ // hierarchy, not blocking, and are not fetched. A missing or null
327
+ // `blockedBy` contributes nothing, so an issue with no edges reduces to
328
+ // exactly the body scan's `d`. `d` is bare numbers, so an edge to ANOTHER
329
+ // repository's issue would read as this repo's #N — measured 2026-09-25:
330
+ // none exists here (0 of 65 edges).
331
+ //
332
+ // `blockers` refuses rather than truncating. gh fetches the edges as
333
+ // `blockedBy(first:50)` (read off `GH_DEBUG=api` on gh 2.100.0) and GitHub
334
+ // caps each relationship type at 50 per issue, so `nodes` arrives whole
335
+ // today — measured 2026-09-25 across every issue in this repo, open and
336
+ // closed: `totalCount` equals `nodes | length` on all 37 issues with edges,
337
+ // the most on one being 7. If either constant moves, a longer list arrives
338
+ // cut short and `d` drops blockers with nothing said: the silent cap
339
+ // refuseIfCapped() refuses for the list as a whole, here for one row. So
340
+ // `error()` fails the whole query instead — gh exits non-zero with the
341
+ // message and query() dies at exit 2, "the query broke" — because a blocker
342
+ // list is the one input an admission gate must never read short.
343
+ // `blockedBy` is a gh 2.94.0 field. gh refuses a `--json` field it does not
344
+ // know (`Unknown JSON field`, exit 1 — measured on 2.100.0 with a made-up
345
+ // one), so an older gh dies at exit 2 here rather than running without edges.
346
+ const JQ =
347
+ 'def armed: test("(?i)^#{1,6}[ \\\\t]+\\\\**((?:depends on|blocked by|requires)(?:[^\\\\p{L}\\\\p{M}\\\\p{N}_]|$)|dependenc(?:y|ies)\\\\**:?\\\\**[\\\\t\\\\f\\\\r \\\\p{Zs}]*$)");\n' +
348
+ '\n' +
349
+ 'def depmiss:\n' +
350
+ ' [ split("\\n")[]\n' +
351
+ ' | select(test("(?i)^#{1,6}[ \\\\t].*(dependenc|blocked by|depends on|requires)") and (armed | not))\n' +
352
+ ' | rtrimstr("\\r")\n' +
353
+ ' ];\n' +
354
+ '\n' +
355
+ 'def depnums:\n' +
356
+ ' (reduce (split("\\n"))[] as $line (\n' +
357
+ ' {insec: false, nums: []};\n' +
358
+ ' ($line | armed) as $bh\n' +
359
+ ' | ($line | test("^#{1,6}([ \\\\t]|\\\\r?$)")) as $any\n' +
360
+ ' | (if $any then $bh else .insec end) as $nextsec\n' +
361
+ ' | ($line | test("^[ \\\\t]*([-*+]|[0-9]+[.)])[ \\\\t]")) as $item\n' +
362
+ ' | {\n' +
363
+ ' insec: $nextsec,\n' +
364
+ ' nums: (\n' +
365
+ ' .nums\n' +
366
+ ' + (if $nextsec and $item then [$line | scan("#[0-9]+")] else [] end)\n' +
367
+ ' + [ $line\n' +
368
+ ' | scan("(?i)(?:depends on|blocked by|requires|after)[\\\\t\\\\f\\\\r \\\\p{Zs}*]*:?[\\\\t\\\\f\\\\r \\\\p{Zs}*]*(#[0-9]+(?:[\\\\t\\\\f\\\\r \\\\p{Zs}*]*(?:,|and)?[\\\\t\\\\f\\\\r \\\\p{Zs}*]*#[0-9]+)*)")\n' +
369
+ ' | .[0]\n' +
370
+ ' | scan("#[0-9]+")\n' +
371
+ ' ]\n' +
372
+ ' )\n' +
373
+ ' }\n' +
374
+ ' )).nums\n' +
375
+ ' | map(ltrimstr("#") | tonumber)\n' +
376
+ ' | unique;\n' +
377
+ '\n' +
378
+ 'def blockers:\n' +
379
+ ' (.blockedBy.nodes // []) as $nodes\n' +
380
+ ' | if (.blockedBy.totalCount // 0) > ($nodes | length)\n' +
381
+ ' then error("#\\(.number): blockedBy lists \\($nodes | length) of \\(.blockedBy.totalCount) blockers, so d would miss the rest")\n' +
382
+ ' else [$nodes[].number]\n' +
383
+ ' end;\n' +
384
+ '\n' +
385
+ '[.[] | {n:.number,t:.title,l:[.labels[].name],\n' +
386
+ ' spec:((.body//"")|test("(?m)^#{2,6}[ \\\\t]+User Stories[\\\\t\\\\f\\\\r \\\\p{Zs}]*$")),\n' +
387
+ ' d:(((.body//"")|depnums) + blockers | unique),\n' +
388
+ ' dh:((.body//"")|depmiss)}]\n';
389
+
390
+ function query(label) {
391
+ // The label is a VALUE in GitHub's query language, not part of its syntax,
392
+ // so it is quoted rather than interpolated raw (#175). Unquoted, a value
393
+ // ends at the FIRST SPACE and every word after it becomes a free-text term
394
+ // instead — measured 2026-08-17, `label:ready-for-agent candidates` returns
395
+ // strictly fewer issues here than `label:ready-for-agent`, and on
396
+ // microsoft/vscode `label:help wanted` returns nothing at all where
397
+ // `label:"help wanted"` returns that label's real backlog. A caller reads
398
+ // the narrowed result as the label's own answer, and an empty one as exit 1,
399
+ // "the query worked and there is no work" — against a queue that is not
400
+ // empty. Reachable wherever a repo remapped its triage labels, which
401
+ // docs/agents/triage-labels.md exists to invite. Stated as relationships
402
+ // rather than counts on purpose: the queue churns hourly, so a pinned digit
403
+ // is wrong within a day and reads as the fix having regressed.
404
+ //
405
+ // Quoted unconditionally, not only when the label contains whitespace —
406
+ // though NOT because a second character is dangerous. Space is the one
407
+ // character GitHub splits an unquoted value on; a `:` is inert there,
408
+ // measured the same day: `label:auto:logs` and `label:"auto:logs"` agree on
409
+ // renovatebot/renovate, as do `label:Team:Core` and `label:"Team:Core"` on
410
+ // elastic/kibana. The reason to quote every label is that quoting a value
411
+ // needing none is a measured no-op (`label:ready-for-agent` and
412
+ // `label:"ready-for-agent"` agree here), so one unconditional form beats a
413
+ // predicate that has to stay in step with GitHub's parser to stay correct.
414
+ const search = label ? `${EXCLUDE} label:"${label}"` : EXCLUDE;
415
+ const args = [
416
+ "issue", "list",
417
+ "--state", "open",
418
+ "--limit", String(limit),
419
+ "--search", search,
420
+ "--json", "number,title,labels,body,blockedBy",
421
+ "--jq", JQ,
422
+ ];
423
+ console.error(`$ gh ${args.join(" ")}`);
424
+ let out;
425
+ try {
426
+ out = execFileSync("gh", args, { encoding: "utf8" });
427
+ } catch (e) {
428
+ // Fail closed. A failed query and an empty queue are different facts, and
429
+ // only one of them means "there is no work".
430
+ //
431
+ // Names the cause, never gh's stderr — same discipline as the row-shape
432
+ // refusal below. execFileSync forwards the child's stderr to ours already
433
+ // (it does so precisely because `stdio` is absent from the options above —
434
+ // Node gates the forward on `!options.stdio`, so adding one silently makes
435
+ // this message the only report). Interpolating `e.stderr` therefore emitted
436
+ // every byte twice: measured 7,700 B of gh stderr → 15,454 B, into a caller
437
+ // that is markdown read by a model. `e.message` is the same string, not a
438
+ // safer fallback — Node builds it as `Command failed: <cmd>\n<stderr>`.
439
+ //
440
+ // Three disjoint shapes, so three branches. `e.code` is set when Node
441
+ // itself aborted the call: ENOENT (nothing spawned, nothing printed),
442
+ // ENOBUFS/ETIMEDOUT (the child ran and printed, then Node killed it).
443
+ // `e.signal` is the only field a signal death sets — without it this reads
444
+ // `exit null`, naming nothing, for the OOM kill and the SIGPIPE. `e.status`
445
+ // carries a real exit code, whose stderr the caller has already seen.
446
+ die(
447
+ `gh issue list failed: ${
448
+ e.code ?? (e.signal ? `killed by ${e.signal}` : `exit ${e.status}`)
449
+ }`,
450
+ );
451
+ }
452
+ const trimmed = out.trim();
453
+ // Not `return []`. The reduction is `[…]`-wrapped, so it emits an array for
454
+ // every input including none — empty output means it did not run, which is
455
+ // the same fact as the shape check below, not an empty queue.
456
+ if (trimmed === "") die("gh returned no output — the --jq reduction did not apply");
457
+ let rows;
458
+ try {
459
+ rows = JSON.parse(trimmed);
460
+ } catch (e) {
461
+ die(`could not parse gh output as JSON: ${e.message}`);
462
+ }
463
+ // The reduction runs inside gh, not here, so nothing at this end guarantees
464
+ // it applied — an older gh, an expression it rejects, an error object from a
465
+ // proxy. Unchecked, the wrong shape flows on until the first use of it
466
+ // throws, and an uncaught throw exits 1: the code reserved for "successful
467
+ // query, no survivors". Fail closed, same as the failed-query path above.
468
+ if (!Array.isArray(rows)) die("gh output is not an array — the --jq reduction did not apply");
469
+ const bad = rows.findIndex(
470
+ (r) =>
471
+ !r ||
472
+ typeof r.n !== "number" ||
473
+ typeof r.t !== "string" ||
474
+ !Array.isArray(r.l) ||
475
+ !Array.isArray(r.d) ||
476
+ !Array.isArray(r.dh) ||
477
+ typeof r.spec !== "boolean",
478
+ );
479
+ // The row is named, never dumped: an unreduced payload carries every issue
480
+ // body, ~97% of what this file refuses to fetch in the first place.
481
+ // Says what is wrong, not why: this also fires when the reduction ran fine
482
+ // and the upstream field types were not what it assumed, so it cannot claim
483
+ // the reduction did not apply the way the two checks above can.
484
+ if (bad !== -1) die(`gh output row ${bad} is not {n,t,l,d,dh,spec} — not the shape the --jq reduction produces`);
485
+ return rows;
486
+ }
487
+
488
+ // Hitting the limit exactly means the answer may be incomplete, and there is
489
+ // no way to tell from the result itself. Refuse rather than hand back a
490
+ // shortlist that silently omits work — "no silent caps" is the rule this
491
+ // enforces. Applied verbatim to BOTH the labeled query and the fallback
492
+ // query below — the fallback result was previously never re-checked, so
493
+ // --require-label <nonexistent> --allow-fallback could ship a silently
494
+ // truncated unfiltered list.
495
+ function refuseIfCapped(rows, description) {
496
+ if (rows.length === limit) {
497
+ die(
498
+ `exactly ${limit} results${description} — the list is capped and may be truncated. ` +
499
+ `Re-run with a higher --limit; a shortlist that silently drops tickets is not an answer.`,
500
+ );
501
+ }
502
+ }
503
+
504
+ // `## User Stories` is to-spec's signature — mandatory in its template, absent
505
+ // from every ticket template. to-spec stamps a whole spec `ready-for-agent`
506
+ // with "no need for additional triage", so it arrives looking admissible; it is
507
+ // to-tickets' INPUT, not a ticket, however well decided it is.
508
+ //
509
+ // ponytail: shape-match on to-spec's template, and no markdown awareness — a
510
+ // ticket quoting `## User Stories` inside a fenced block is dropped too. Not
511
+ // worth a fence parser: every drop is logged by number, so a false positive is
512
+ // loud rather than silent.
513
+ //
514
+ // #65: two shapes the predicate leaves undecided by accident, now decided.
515
+ // Depth is `#{2,6}`, not `##` — two or more `#`, not exactly two, and capped
516
+ // where CommonMark caps an ATX heading, same as `depnums`' own `#{1,6}` above:
517
+ // a line of seven `#` is not a heading and must not read as the signature.
518
+ // to-spec's own `<spec-template>` is flat (`## Problem Statement`, `##
519
+ // Solution`, `## User Stories`, `## Implementation Decisions` — nothing
520
+ // nests), so widening costs nothing against real to-spec output. It closes a
521
+ // leak: a spec hand-nested or reformatted under a parent heading (`###
522
+ // User Stories`) used to read as an ordinary ticket. The asymmetry decides
523
+ // it even where a real to-spec body would never trigger it — a leaked spec
524
+ // is silent and expensive (a member implements a whole spec as one ticket),
525
+ // a false drop is loud (logged by number, `[unfiltered]`/`[label:…]`
526
+ // tagged). The separator between marker and text is `[ \t]+` — horizontal
527
+ // whitespace only, not `\s+` — so a heading can never span a line break: a
528
+ // body whose line is exactly `##` with `User Stories` starting the next
529
+ // line no longer reads as the same heading. That is also #383's ruling for
530
+ // this position, on GFM's own rule: only a space or a tab opens a heading, so
531
+ // `##<U+00A0>User Stories` renders as a PARAGRAPH and is not a spec at all.
532
+ //
533
+ // The TRAILING class is `[\t\f\r \p{Zs}]*`, and it is a DIFFERENT class from
534
+ // the one after the marker — ruling the two positions separately is the whole
535
+ // point. The `$` under `(?m)` already anchors the line end, so the run there
536
+ // can only ever eat whitespace before an anchor and can never make a line that
537
+ // is NOT the signature read as one, while narrowing it to `[ \t]*` would drop
538
+ // the `\r` of a CRLF body — what GitHub's web textarea writes — and leak that
539
+ // spec silently. It is spelled out rather than left as `\s*` because `\s` is
540
+ // the one construct here whose meaning changes with the engine (Oniguruma
541
+ // reads it Unicode-aware, RE2 as `[\t\n\f\r ]`), and #383 ruled the position
542
+ // by what GFM renders: `## User Stories` padded with U+00A0, EM SPACE or
543
+ // IDEOGRAPHIC SPACE are all real `<h2>`s, so all three are still to-spec specs
544
+ // and all three are dropped. `\p{Zs}` is exactly "renders as a blank" and both
545
+ // engines agree on it; `\f` is in the class because GFM strips it; `\r` is
546
+ // what keeps CRLF working. ASCII VERTICAL TAB is deliberately OUT: GFM renders
547
+ // it as U+FFFD, so `## User Stories<VT>` is not blank-padded to a reader and
548
+ // is not dropped. Before the ruling this position diverged — a U+00A0-padded
549
+ // heading was a spec under the system jq the suite execs and NOT one under the
550
+ // gojq gh applies, so in production dropSpecs never fired and the spec shipped
551
+ // as a claimable ticket. Pinned against real gojq in candidates.test.mjs,
552
+ // which now also pins which engine it reached.
553
+ //
554
+ // This is the ONLY line of defence — nothing downstream catches a spec. A
555
+ // leaked one is decided and needs no human hands, so it passes both of phase
556
+ // 2's bail tests, and heavy is explicitly never a bail reason (run-team:180).
557
+ // Change to-spec's template and this predicate goes with it, or a member
558
+ // implements an entire spec as one ticket.
559
+ // `pass` names which query the drop came from — required, not defaulted: the
560
+ // fallback runs only when the labeled query emptied out, so in production the
561
+ // unfiltered query is a SUPERSET of the labeled one, and every spec dropped in
562
+ // pass 1 is dropped again in pass 2. Unattributed, that reads as the same spec
563
+ // counted twice; named, a reader can tell "2 drops, 1 spec, seen both passes"
564
+ // from "2 drops, 2 specs" at a glance. Deliberately not deduplicated — #133.
565
+ function dropSpecs(rows, pass) {
566
+ const kept = [];
567
+ for (const { spec, ...rest } of rows) {
568
+ if (spec) {
569
+ // "no silent caps" covers drops too — a filtered list that does not say
570
+ // what it filtered is indistinguishable from a complete one.
571
+ console.error(` dropped #${rest.n} — to-spec spec, not a ticket (User Stories heading) [${pass}]`);
572
+ } else {
573
+ kept.push(rest);
574
+ }
575
+ }
576
+ return kept;
577
+ }
578
+
579
+ let rows = query(requireLabel);
580
+ console.error(` ${rows.length} candidate(s)${requireLabel ? ` with label:${requireLabel}` : ""}`);
581
+ refuseIfCapped(rows, requireLabel ? ` with label:${requireLabel}` : "");
582
+ // After refuseIfCapped, never before: filtering first can shrink the array below
583
+ // `limit` and the cap check would stop seeing a truncated list. Before the
584
+ // emptiness test below, never after: a queue whose every row was filtered out
585
+ // IS an empty queue — see #60. Telling that case apart from a genuinely empty
586
+ // one, for a caller reading only the exit code, is #64 — closed by exit 3 at
587
+ // the foot of this file, which is what the raw count below is captured for.
588
+ // Raw count captured just before the filter that can empty `rows` out, so
589
+ // `allFilteredOut` below can tell "nothing came back" from "rows came back
590
+ // and the filter ate them all". Reassigned wholesale in the fallback branch,
591
+ // never OR'd/summed with pass 1's value — #64's edge case is exactly a pass 1
592
+ // all-filtered (raw>0) whose fallback pass is genuinely empty (raw=0), which
593
+ // must read as the fallback's own facts (exit 1), not a merge of the two.
594
+ const rawCount1 = rows.length;
595
+ rows = dropSpecs(rows, requireLabel ? `label:${requireLabel}` : "unfiltered");
596
+ let allFilteredOut = rawCount1 > 0 && rows.length === 0;
597
+
598
+ if (rows.length === 0 && allowFallback && requireLabel) {
599
+ console.error(`${NAME}: empty with label:${requireLabel}; --allow-fallback given, retrying unfiltered`);
600
+ rows = query(null);
601
+ console.error(` ${rows.length} candidate(s) unfiltered`);
602
+ refuseIfCapped(rows, " unfiltered (fallback)");
603
+ // After refuseIfCapped for the same reason as above; the emptiness half does
604
+ // not transfer, as no gate follows this one. The call must exist because the
605
+ // fallback's rows arrive raw and nothing downstream drops a spec.
606
+ const rawCount2 = rows.length;
607
+ rows = dropSpecs(rows, "unfiltered (fallback)");
608
+ allFilteredOut = rawCount2 > 0 && rows.length === 0;
609
+ }
610
+
611
+ // FIFO among survivors. Issue number is monotonic in creation order, so this
612
+ // needs no extra field and no query semantics. Dependencies do not rank —
613
+ // blocked tickets are dropped by the CONSUMER reading `d` (run-team step 2 /
614
+ // next-ticket step 2), not here, and to-tickets publishes chains blockers-first
615
+ // so lower numbers are the blockers anyway. `d` covers every body form
616
+ // to-tickets publishes — heading + list, bold/inline label, the original bare
617
+ // phrasings — see #58, and GitHub's native blocked-by edges too (#1741), so
618
+ // a chain wired only as edges reaches this sort with its blockers in `d`.
619
+ // Native sub-issue links are still not read: parent/child is hierarchy, not
620
+ // blocking, so a blocker recorded only as one reaches it with none.
621
+ rows.sort((a, b) => a.n - b.n);
622
+
623
+ for (const r of rows) {
624
+ console.error(` #${r.n} [${r.l.join(",")}] ${r.t}${r.d.length ? ` deps:${r.d.join(";")}` : ""}`);
625
+ // #1032. A SECOND line, never a field on the row above: that row's format is
626
+ // what phase 0 reads and it stays byte-identical, `deps:` suppressed on an
627
+ // empty list and all. Indented under the row it belongs to, and repeating
628
+ // `#N` so a reader who greps the wording still gets the candidate with it.
629
+ //
630
+ // Says what was seen and what was not done with it, and points at the
631
+ // heading. No "error", no "invalid", no imperative to fix anything: the
632
+ // shape that most often reaches here — a noun-form heading carrying
633
+ // qualifying text — is legitimate usage the gate refuses on purpose (see
634
+ // `depmiss` above), so a fault-worded line would false-alarm every ticket
635
+ // that writes one. What the caller does with it is a judgement call this
636
+ // has no standing to make: `d` may be empty because the heading was prose
637
+ // all along, or because a real blocker was declared under a heading the
638
+ // scan does not read, and only the body says which.
639
+ if (r.dh.length) {
640
+ console.error(
641
+ ` #${r.n} heading mentions dependencies, not parsed as a dependency section` +
642
+ ` — refs under it are not in deps, check the heading: ${r.dh.map((h) => `'${h}'`).join(", ")}`,
643
+ );
644
+ }
645
+ }
646
+
647
+ // Compact: the pretty per-candidate view already went to stderr above; this
648
+ // payload is parsed by a machine, and indenting up to `--limit` issues is pure
649
+ // token cost in the controller's context.
650
+ //
651
+ // `dh` is dropped here rather than never collected: the heading text exists
652
+ // only inside gh's process, where the reduction runs, so the only way to it is
653
+ // a field on the row — and #1032 rules a payload field out of scope, the
654
+ // stderr signal being the whole of what it asks for. Here, and not in
655
+ // `dropSpecs`' destructure where the row's other stderr-only field (`spec`)
656
+ // leaves the payload: that runs BEFORE the per-candidate lines above, which
657
+ // are what `dh` is for. A replacer, not a rebuilt array: it drops the key
658
+ // without copying up to `--limit` rows to do it. Add a field to the
659
+ // reduction that stdout SHOULD carry and it needs naming here, or it
660
+ // silently never ships.
661
+ console.log(JSON.stringify(rows, (k, v) => (k === "dh" ? undefined : v)));
662
+
663
+ // Exit 1 for a successful query with no survivors, exit 3 when those zero
664
+ // survivors are the filter's doing rather than the query's — see the
665
+ // exit-code contract in the file header (#64). `allFilteredOut` already
666
+ // describes only the final attempt (see above), so no further branching on
667
+ // requireLabel/allowFallback is needed here.
668
+ //
669
+ // exitCode, not exit(): stdout on a pipe is async too, and process.exit() drops
670
+ // the queued payload at the 64 KiB buffer while still reporting 0. Measured,
671
+ // 499 rows — one under the DEFAULT --limit — arrived truncated mid-JSON at exit
672
+ // 0, the corrupt-payload-typed-as-success this file's exit codes exist to make
673
+ // impossible. refuseIfCapped cannot see it: that fires at exactly `limit`.
674
+ process.exitCode = rows.length === 0 ? (allFilteredOut ? 3 : 1) : 0;