rungate 0.4.1 → 0.6.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 (87) hide show
  1. package/config/behavioral-sc-map.json +170 -0
  2. package/config/brief-policies.json +28 -0
  3. package/config/ceremony-profiles.json +207 -0
  4. package/config/check-registry.json +114 -0
  5. package/config/matcher-registry.json +142 -0
  6. package/config/prove-evidence.schema.json +65 -0
  7. package/config/spec-policies.json +36 -0
  8. package/config/universal-rules.yaml +15 -0
  9. package/config/workflow-schema.json +279 -0
  10. package/lib/agents-md-sections.ts +144 -0
  11. package/lib/branch-diff.ts +139 -0
  12. package/lib/bun-version.ts +268 -0
  13. package/lib/ci-checkout.ts +1 -1
  14. package/lib/cli-commands.ts +7 -1
  15. package/lib/compliance.ts +13 -11
  16. package/lib/config-loader.ts +12 -0
  17. package/lib/conformity.ts +1147 -116
  18. package/lib/context-docs.ts +143 -28
  19. package/lib/create-brief.ts +2 -1
  20. package/lib/create-sc.ts +90 -4
  21. package/lib/doc-scan-targets.ts +9 -0
  22. package/lib/evidence-command-transport.ts +160 -0
  23. package/lib/evidence-prevalidator.ts +22 -0
  24. package/lib/fallow-availability.ts +129 -0
  25. package/lib/gate-refusal-currency.ts +112 -0
  26. package/lib/gate-timeouts.ts +82 -0
  27. package/lib/generators/agent-briefs.ts +4 -1
  28. package/lib/generators/agents-md.ts +71 -23
  29. package/lib/generators/code-map.ts +2 -1
  30. package/lib/generators/types.ts +8 -0
  31. package/lib/git-dates.ts +55 -0
  32. package/lib/github.ts +195 -0
  33. package/lib/js-top-level-code.ts +27 -2
  34. package/lib/junit-checks.ts +484 -0
  35. package/lib/local-calendar-day.ts +78 -0
  36. package/lib/package-closure.ts +278 -2
  37. package/lib/project-state-shape.ts +59 -0
  38. package/lib/promote-outputs.ts +6 -2
  39. package/lib/release-preflight.ts +196 -0
  40. package/lib/report-provenance.ts +156 -0
  41. package/lib/sc-claim-forms.ts +75 -0
  42. package/lib/sc-id-cross-tree.ts +311 -0
  43. package/lib/scaffold/ai-review-step.ts +180 -0
  44. package/lib/scaffold/defaults.ts +40 -0
  45. package/lib/scaffold/managed-workflow.ts +125 -27
  46. package/lib/scaffold/owned-files.ts +48 -2
  47. package/lib/scaffold/profiles.ts +94 -0
  48. package/lib/scaffold/rehearsal.ts +232 -73
  49. package/lib/scaffold/steps.ts +777 -152
  50. package/lib/scaffold/write-steps.ts +56 -13
  51. package/lib/scanner.ts +38 -12
  52. package/lib/source-anchor.ts +144 -0
  53. package/lib/spec-listing.ts +148 -0
  54. package/lib/spec-requirements.ts +209 -0
  55. package/lib/success-doc.ts +779 -0
  56. package/lib/suite-run-reading.ts +364 -0
  57. package/lib/test-census.ts +199 -0
  58. package/lib/test-command.ts +133 -0
  59. package/lib/test-suite-lock.ts +166 -10
  60. package/lib/tool-probe.ts +120 -0
  61. package/lib/tracked-vs-ignored.ts +234 -0
  62. package/lib/trajectory.ts +377 -0
  63. package/lib/validators/spec-validators.ts +35 -6
  64. package/lib/workflow-security.ts +101 -0
  65. package/lib/workflow-test-harness.ts +349 -0
  66. package/package.json +6 -1
  67. package/scripts/audit-specs.ts +247 -12
  68. package/scripts/audit-transcript.ts +2 -1
  69. package/scripts/convert-spec.ts +2 -1
  70. package/scripts/create-sc.ts +17 -7
  71. package/scripts/create-spec.ts +2 -1
  72. package/scripts/create-success.ts +163 -0
  73. package/scripts/extract-constraints.ts +90 -19
  74. package/scripts/generate-code-map.ts +53 -12
  75. package/scripts/scaffold-project.ts +31 -4
  76. package/scripts/split-spec.ts +2 -1
  77. package/scripts/sync-sc-status.ts +57 -5
  78. package/scripts/sync-spec-tests.ts +2 -1
  79. package/specs/SPEC-TEMPLATE.md +200 -0
  80. package/templates/SUCCESS-TEMPLATE.md +72 -0
  81. package/templates/agent-briefs/_shared.md +9 -0
  82. package/templates/agent-briefs/aditi.md +46 -0
  83. package/templates/agent-briefs/discovery.md +37 -0
  84. package/templates/agent-briefs/marcus.md +39 -0
  85. package/templates/agent-briefs/quinn.md +67 -0
  86. package/templates/agent-briefs/rook.md +40 -0
  87. package/templates/agent-briefs/serena.md +39 -0
@@ -0,0 +1,156 @@
1
+ /**
2
+ * The tree a report was measured against, stated by the reporter (#553).
3
+ *
4
+ * Two security reviews arrived from peer sessions on 2026-10-17. Both
5
+ * reported CONFIRMED findings, both were measured against a tree the branch
6
+ * had already moved past, and in both cases the report gave no way to tell.
7
+ * sec-492's three findings were measured at `7fdfa72a` (20:32); two commits
8
+ * landed about 75 minutes later and closed all three, and two of the
9
+ * "0 red" mutation rows are 3 and 1 on main.
10
+ *
11
+ * ## What is missing is the SENDING side
12
+ *
13
+ * `.claude/rules/parallel-sessions.md` already covers the receiving side —
14
+ * *"peer reports are evidence, not fact"* — and that rule worked both times:
15
+ * the reports were checked before anything was acted on, which is the only
16
+ * reason neither cost anything. But verifying every finding from scratch is
17
+ * the expensive path to a cheap fact that **the reviewer already holds**.
18
+ *
19
+ * The ship pipeline solves this inside itself: `reviewIsCurrent` pins a
20
+ * review to a commit and blocks when the branch has moved, which is #129,
21
+ * #169, #171 and #244 of accumulated work. A review conducted OUTSIDE
22
+ * `workflows/ship.js` inherits none of it.
23
+ *
24
+ * So this is that same binding, reachable from a terminal. It does not
25
+ * reimplement the comparison — `reviewIsCurrent` is imported, because a
26
+ * second decider answering the same question is behaviourally one decider
27
+ * and no test can tell them apart
28
+ * (`.claude/rules/checks-must-be-able-to-fail.md`).
29
+ *
30
+ * ## It fails closed, and an unanswerable question is not a pass
31
+ *
32
+ * A branch that cannot be resolved, a SHA that is not a SHA, a directory
33
+ * that is not a repository: all `current: false`, each with a reason naming
34
+ * what could not be read. A reviewer who cannot establish currency has
35
+ * learned something worth putting in the report, and a provenance block that
36
+ * went quiet on an error would be worse than none — it would be a claim.
37
+ */
38
+ import { execFileSync } from "child_process";
39
+
40
+ import { reviewIsCurrent } from "./security-verdict";
41
+
42
+ /** The exit code of a stale or unmeasurable reading. One site, so it can be mutated. */
43
+ export const STALE_EXIT = 1;
44
+
45
+ export interface ProvenanceReading {
46
+ /** The commit the report describes. */
47
+ measured: string | null;
48
+ /** The commit the branch ends at now, or null when it could not be read. */
49
+ tip: string | null;
50
+ /** The ref the tip was read from, e.g. `origin/fix/553`. */
51
+ ref: string | null;
52
+ current: boolean;
53
+ /** Always present. Names both operands when there are two to name. */
54
+ reason: string;
55
+ }
56
+
57
+ function git(root: string, args: string[]): string | null {
58
+ try {
59
+ return execFileSync("git", args, {
60
+ cwd: root,
61
+ encoding: "utf-8",
62
+ timeout: 60_000,
63
+ stdio: ["ignore", "pipe", "pipe"],
64
+ }).trim();
65
+ } catch {
66
+ return null;
67
+ }
68
+ }
69
+
70
+ /**
71
+ * The ref whose tip a report should be aged against.
72
+ *
73
+ * `origin/<branch>` when it exists, because that is what another session can
74
+ * see; the local branch otherwise, which is the honest answer for work that
75
+ * has not been pushed. Detached HEAD has no branch and says so.
76
+ */
77
+ export function defaultRef(root: string): string | null {
78
+ const branch = git(root, ["rev-parse", "--abbrev-ref", "HEAD"]);
79
+ if (branch === null || branch === "" || branch === "HEAD") return null;
80
+ if (git(root, ["rev-parse", "--verify", "--quiet", `refs/remotes/origin/${branch}`]) !== null) {
81
+ return `origin/${branch}`;
82
+ }
83
+ return branch;
84
+ }
85
+
86
+ /**
87
+ * Compare the tree a report describes against the tree the branch ends at.
88
+ *
89
+ * `measured` defaults to this working tree's HEAD, which is what a reviewer
90
+ * who just finished reading has in front of them.
91
+ */
92
+ export function provenanceReading(
93
+ root: string,
94
+ measured?: string,
95
+ ref?: string,
96
+ ): ProvenanceReading {
97
+ const measuredSha = measured ?? git(root, ["rev-parse", "HEAD"]);
98
+ const resolvedRef = ref ?? defaultRef(root);
99
+
100
+ if (resolvedRef === null) {
101
+ return {
102
+ measured: measuredSha,
103
+ tip: null,
104
+ ref: null,
105
+ current: false,
106
+ reason:
107
+ `UNMEASURED: no branch to age this report against — ${root} is not a repository, ` +
108
+ `or HEAD is detached. State the commit you measured and say that the branch could ` +
109
+ `not be resolved.`,
110
+ };
111
+ }
112
+
113
+ // Fetch nothing. A reviewer who has not fetched is comparing against a
114
+ // stale remote-tracking ref, which is a different failure from a moved
115
+ // branch and must not be hidden by a network call this function made on
116
+ // its own.
117
+ const tip = git(root, ["rev-parse", "--verify", `${resolvedRef}^{commit}`]);
118
+ if (tip === null) {
119
+ return {
120
+ measured: measuredSha,
121
+ tip: null,
122
+ ref: resolvedRef,
123
+ current: false,
124
+ reason:
125
+ `UNMEASURED: ${resolvedRef} could not be resolved, so there is nothing to compare ` +
126
+ `${measuredSha ?? "an unreadable HEAD"} against.`,
127
+ };
128
+ }
129
+
130
+ // The one binding. `workflows/ship.js` inlines a copy of this function for
131
+ // the sandbox (#69) and `test/security-verdict-blocks.test.ts` holds the
132
+ // two to parity; this is the library side, imported rather than repeated.
133
+ const currency = reviewIsCurrent(measuredSha, tip);
134
+ return {
135
+ measured: measuredSha,
136
+ tip,
137
+ ref: resolvedRef,
138
+ current: currency.current,
139
+ reason: currency.current
140
+ ? `the report describes ${measuredSha}, which is the tip of ${resolvedRef}`
141
+ : (currency.reason ??
142
+ `the report describes ${measuredSha}, which is not the tip of ${resolvedRef} (${tip})`),
143
+ };
144
+ }
145
+
146
+ /** The block to paste at the top of a report. Always states both commits. */
147
+ export function provenanceBlock(reading: ProvenanceReading): string {
148
+ const lines = [
149
+ `Measured against: ${reading.measured ?? "UNKNOWN"}`,
150
+ `Branch tip (${reading.ref ?? "unresolved"}): ${reading.tip ?? "UNKNOWN"}`,
151
+ reading.current
152
+ ? `Currency: CURRENT — ${reading.reason}`
153
+ : `Currency: NOT CURRENT — ${reading.reason}`,
154
+ ];
155
+ return lines.join("\n");
156
+ }
@@ -169,11 +169,86 @@ const IDS_ONLY =
169
169
  */
170
170
  const PAREN_LABEL = /^\s*(?:SC|AC)-[A-Z]?\d+\s*:/;
171
171
 
172
+ /**
173
+ * A RANGE inside a parenthetical — `(SC-1930..SC-1948)`.
174
+ *
175
+ * An attribution names THE criterion a statement is about. A range names a
176
+ * group, which is how prose refers to a set it is discussing rather than
177
+ * claiming, and the scanner can only see the two ids that are literally
178
+ * written: a range of nineteen credits its two endpoints and silently not
179
+ * the seventeen between them. A form that credits 2 of the 19 ids it names
180
+ * is not measuring anything.
181
+ *
182
+ * Found in #574, on this sentence:
183
+ *
184
+ * * The spec's 19 behavioural criteria (SC-1930..SC-1948) are NOT
185
+ * * covered here.
186
+ *
187
+ * — which credited SC-1930 and SC-1948 and ticked both boxes. The
188
+ * self-reference this area keeps producing, now in its sharpest form: a
189
+ * comment saying the criteria are not covered was the evidence that they
190
+ * were.
191
+ *
192
+ * Measured before narrowing, because narrowing a detector is the change
193
+ * most likely to buy green with blindness: of 32 attribution credits in the
194
+ * tree, 30 are plain and 2 are ranges — and the 2 are these. A range at the
195
+ * START of a line is still a claim, by the `line` form, which is where
196
+ * `* SC-561..SC-564 (SPEC.md)` is credited and is unaffected.
197
+ */
198
+ const PAREN_RANGE = /\.\.+/;
199
+
172
200
  function inIdOnlyParenthetical(line: string, at: number): boolean {
173
201
  const open = line.lastIndexOf("(", at);
174
202
  if (open < 0) return false;
175
203
  const close = line.indexOf(")", open);
176
204
  if (close < 0 || close < at) return false;
177
205
  const inner = line.slice(open + 1, close);
206
+ if (PAREN_RANGE.test(inner)) return false;
178
207
  return IDS_ONLY.test(inner) || PAREN_LABEL.test(inner);
179
208
  }
209
+
210
+ /**
211
+ * A `describe`/`test`/`it` call that opens a title literal, and whether it
212
+ * will ever run (#574).
213
+ *
214
+ * A test title is the project's oldest coverage convention and the one
215
+ * position that needed no rule — until `test.todo("SC-1930: …")` turned out
216
+ * to be a title too. A todo is the one test guaranteed never to fail, so
217
+ * crediting it produces a tick indistinguishable from a tick earned by a
218
+ * test that can go red. Measured when this was found: 64 ids named only
219
+ * inside a `.todo`, 37 of them ticked `[x]` in a spec, and 19 more about to
220
+ * flip on the next run of the sync — one of them from a file whose own
221
+ * comment says, four lines from the top, that none of its criteria are
222
+ * covered here.
223
+ *
224
+ * `.skip` is the same fact with a different word, and there are five of
225
+ * those. `.skipIf` and `.todoIf` take a condition, so whether they ran is
226
+ * not answerable from the source at all; there are none today and they are
227
+ * named anyway, because a predicate narrower than what it detects is this
228
+ * repo's third defect shape and the cost of naming them is one word each.
229
+ *
230
+ * `.only`, `.each`, `.failing` and `.concurrent` all RUN, so they still
231
+ * credit — `.failing` included, because a test expected to fail is still a
232
+ * test that goes red when the expectation stops holding.
233
+ *
234
+ * Returns `null` when the text does not open a title call at all. The three
235
+ * answers are distinct on purpose: a non-running title must be reported as
236
+ * UNMEASURED rather than dropped, and dropping it would make "nobody has
237
+ * written this test" look exactly like "nobody has mentioned this id".
238
+ */
239
+ export type TitleCall = "runs" | "never-runs";
240
+
241
+ const NON_RUNNING = /\.(?:todo|skip|skipIf|todoIf)\b/;
242
+
243
+ /** Opens a `describe`/`test`/`it` title, allowing `.each(...)`, `.only`, `.skip`, `.todo`. */
244
+ const TITLE_CALL = /\b(?:describe|test|it)\s*((?:\.\w+\s*(?:\([^)]*\))?\s*)*)\(\s*$/;
245
+
246
+ /**
247
+ * THE single exported predicate for whether a title call declares coverage,
248
+ * for the same reason `commentClaimForm` is: one binding to mutate.
249
+ */
250
+ export function titleCall(before: string): TitleCall | null {
251
+ const m = TITLE_CALL.exec(before);
252
+ if (m === null) return null;
253
+ return NON_RUNNING.test(m[1] ?? "") ? "never-runs" : "runs";
254
+ }
@@ -0,0 +1,311 @@
1
+ /**
2
+ * The SC id namespace as it exists on this machine, not in this checkout (#503).
3
+ *
4
+ * `nextSCNumber` allocates "highest + 1", and #392 taught it to read the whole
5
+ * registry rather than one spec's content. Both fixes are about the same
6
+ * mistake at different widths, and the width was still wrong: the registry is
7
+ * `specs/` **in the working tree the command happens to run in**.
8
+ *
9
+ * On 2026-10-16 two sessions allocated `SC-1706..1710` within minutes of each
10
+ * other — one in `specs/HARNESS-STANDARD.md`, one in
11
+ * `specs/CONFIG-DIRECTORY-STRUCTURE-SPEC.md`, in two worktrees of the same
12
+ * repository. Both read the highest id they could see. Both were right about
13
+ * their own tree. `test/spec-sc-ids-unique.test.ts` was green in each,
14
+ * independently, until a rebase put them in one place.
15
+ *
16
+ * That is the second shape in `.claude/rules/checks-must-be-able-to-fail.md`
17
+ * — a detector narrower than what it detects. The question is "is this number
18
+ * free in the project"; the detector answered "is this number free in this
19
+ * checkout". The two differ exactly when more than one session is working,
20
+ * which here is the normal case: this repository has 110 worktrees on disk.
21
+ *
22
+ * ## Two sources, because the collision lives in the gap between them
23
+ *
24
+ * | Source | Catches | Misses |
25
+ * |---|---|---|
26
+ * | sibling worktrees' `specs/` | **uncommitted** ids in another session's tree | a branch whose worktree was removed |
27
+ * | every local and remote-tracking ref | committed ids on any branch, pushed or not | work that exists only on another machine |
28
+ *
29
+ * Neither alone is enough. The #503 collision was an unpushed branch in
30
+ * another worktree, which the ref scan sees only once it is committed —
31
+ * and `.claude/rules/parallel-sessions.md` exists because that window is
32
+ * real and people sit in it for an hour.
33
+ *
34
+ * ## This errs toward "taken", deliberately
35
+ *
36
+ * A stale worktree holding an abandoned branch contributes ids that nothing
37
+ * will ever claim, and the allocator will skip them. That costs a gap in the
38
+ * numbering, which costs nothing: SC ids are opaque join keys, not an
39
+ * ordering anyone reads. The other direction costs a collision, which is two
40
+ * spec lines a test can bind to and no way to see which one it bound to.
41
+ *
42
+ * ## What this is NOT
43
+ *
44
+ * It is not a guard that refuses on a cross-tree duplicate, and that is a
45
+ * measurement rather than a shrug. Across the 110 worktrees on this machine,
46
+ * 30 ids are declared in more than one spec FILE: `SC-A1`/`SC-A2`, which are
47
+ * anti-criteria that several specs legitimately carry, and `SC-694..703`,
48
+ * which is a REAL collision from months ago, resolved on main by renumbering
49
+ * and preserved forever in the stale trees that still hold the losing side.
50
+ * A guard over that population is permanently red for reasons nobody can act
51
+ * on, which is the fastest way to build a refusal everyone learns to click
52
+ * past. Fix the allocator that mints collisions; do not alarm on the fossils.
53
+ */
54
+ import { execFileSync } from "child_process";
55
+ import { existsSync, readdirSync, readFileSync, statSync } from "fs";
56
+ import { join } from "path";
57
+
58
+ import { isFixtureScId, scDeclarationPattern, scHeadingDeclarationPattern } from "./sc-ids";
59
+
60
+ /**
61
+ * One place ids were looked for, and whether the look succeeded.
62
+ *
63
+ * `worktree` and `refs` are this module's own two sources. The other three
64
+ * are the legs `allocateScNumber` composes on top of them (#593) — the
65
+ * spec's own content, the spec registry, and the ids spelled in source. They
66
+ * live in the same shape because the question a reader asks is one question:
67
+ * which widths produced this number, and did any of them fail to run.
68
+ */
69
+ export interface SourceReading {
70
+ label: string;
71
+ kind: "worktree" | "refs" | "spec-content" | "registry" | "source-mentions";
72
+ /** `read` means the ids below came from here; `skipped` means they did not. */
73
+ status: "read" | "skipped";
74
+ /** Why it was skipped. Absent on a successful read. */
75
+ reason?: string;
76
+ /** How many distinct ids this source contributed. */
77
+ found: number;
78
+ }
79
+
80
+ export interface ScNamespaceReading {
81
+ /** id → the labels that declared it. */
82
+ ids: Map<string, string[]>;
83
+ sources: SourceReading[];
84
+ /**
85
+ * Why this reading is a floor rather than a fact. Never empty: a clone on
86
+ * another machine is outside anything this process can see, and saying so
87
+ * is the difference between an unmeasured half and a silent pass
88
+ * (`.claude/rules/config-access.md`).
89
+ */
90
+ unmeasured: string[];
91
+ }
92
+
93
+ function git(root: string, args: string[]): string {
94
+ // 64 MB, because the default is 1 MB and a grep over a thousand refs blows
95
+ // through it. Measured: the first run of this module reported
96
+ // `ENOBUFS (stdout or stderr buffer reached maxBuffer size limit)` as a
97
+ // skipped source, which is the reading behaving correctly over a bug.
98
+ return execFileSync("git", args, {
99
+ cwd: root,
100
+ encoding: "utf-8",
101
+ timeout: 120_000,
102
+ maxBuffer: 64 * 1024 * 1024,
103
+ // Captured, not inherited. A failed `git` here is a source this reading
104
+ // records as skipped, and letting its stderr through would put
105
+ // "fatal: not a git repository" in the middle of a suite's output for a
106
+ // case that is handling exactly that (#60: a test must not corrupt the
107
+ // output stream of the suite containing it).
108
+ stdio: ["ignore", "pipe", "pipe"],
109
+ });
110
+ }
111
+
112
+ /**
113
+ * Every worktree of this repository except `root` itself.
114
+ *
115
+ * `failure` is non-null when git could not be asked at all — which is a
116
+ * different fact from "there are no siblings", and conflating the two is how
117
+ * a reading of nothing reads as a reading of everything.
118
+ */
119
+ export function siblingWorktrees(root: string): { paths: string[]; failure: string | null } {
120
+ let out: string;
121
+ try {
122
+ out = git(root, ["worktree", "list", "--porcelain"]);
123
+ } catch (err) {
124
+ return { paths: [], failure: (err as Error).message.split("\n")[0] };
125
+ }
126
+ const paths: string[] = [];
127
+ let current: string | null = null;
128
+ let prunable = false;
129
+ const flush = (): void => {
130
+ if (current && !prunable && current !== root) paths.push(current);
131
+ current = null;
132
+ prunable = false;
133
+ };
134
+ for (const line of out.split("\n")) {
135
+ if (line.startsWith("worktree ")) {
136
+ flush();
137
+ current = line.slice("worktree ".length);
138
+ } else if (line.startsWith("prunable")) {
139
+ prunable = true;
140
+ }
141
+ }
142
+ flush();
143
+ return { paths, failure: null };
144
+ }
145
+
146
+ /** The ids a single `specs/` directory declares, by checkbox or by heading. */
147
+ function idsInSpecsDir(specsDir: string): string[] {
148
+ const ids: string[] = [];
149
+ for (const name of readdirSync(specsDir)) {
150
+ if (!name.endsWith(".md")) continue;
151
+ let content: string;
152
+ try {
153
+ content = readFileSync(join(specsDir, name), "utf-8");
154
+ } catch {
155
+ // A spec we cannot read contributes nothing, and the caller records the
156
+ // tree as read regardless: one unreadable file is not an unmeasured
157
+ // tree, and pretending otherwise would make every reading unmeasured.
158
+ continue;
159
+ }
160
+ for (const m of content.matchAll(scDeclarationPattern())) ids.push(m[2]);
161
+ for (const m of content.matchAll(scHeadingDeclarationPattern())) ids.push(m[1]);
162
+ }
163
+ return ids;
164
+ }
165
+
166
+ /**
167
+ * Ids declared in `specs/` on any ref this repository holds — local branches
168
+ * and remote-tracking branches both.
169
+ *
170
+ * One `git grep` over every ref at once rather than a checkout each: measured
171
+ * at 0.17s over 1087 refs, against minutes for the obvious implementation.
172
+ */
173
+ function idsInRefs(root: string): { ids: string[]; refs: number; failure: string | null } {
174
+ let refList: string;
175
+ try {
176
+ refList = git(root, ["for-each-ref", "--format=%(refname)", "refs/heads", "refs/remotes"]);
177
+ } catch (err) {
178
+ return { ids: [], refs: 0, failure: (err as Error).message.split("\n")[0] };
179
+ }
180
+ const refs = refList.split("\n").filter(r => r.trim() !== "");
181
+ if (refs.length === 0) return { ids: [], refs: 0, failure: null };
182
+
183
+ const ids: string[] = [];
184
+ // Batched: a ref list this long overruns the argument limit in one call.
185
+ for (let i = 0; i < refs.length; i += 100) {
186
+ let out: string;
187
+ try {
188
+ out = git(root, [
189
+ "grep",
190
+ "-h",
191
+ "-E",
192
+ // Declaration-shaped lines only — a checkbox or a heading. Every
193
+ // mention would be correct and is ~30x the output, which is how the
194
+ // first version hit the buffer limit.
195
+ "^(- \\[.\\] |#+ )SC-[A-Z]?[0-9]+",
196
+ ...refs.slice(i, i + 100),
197
+ "--",
198
+ "specs/*.md",
199
+ ]);
200
+ } catch (err) {
201
+ // git grep exits 1 when nothing matched, which is a real answer and not
202
+ // a failure. Anything else is a failure, and the caller must hear it.
203
+ const status = (err as { status?: number }).status;
204
+ if (status === 1) continue;
205
+ return { ids, refs: refs.length, failure: (err as Error).message.split("\n")[0] };
206
+ }
207
+ for (const m of out.matchAll(scDeclarationPattern())) ids.push(m[2]);
208
+ for (const m of out.matchAll(scHeadingDeclarationPattern())) ids.push(m[1]);
209
+ }
210
+ return { ids, refs: refs.length, failure: null };
211
+ }
212
+
213
+ /**
214
+ * Every SC id this machine can see, with an account of where it looked.
215
+ *
216
+ * Fixture ids — the reserved 9000s — are dropped. The reservation exists so a
217
+ * fixture can spell an id without claiming it, and counting one as taken
218
+ * would push every future criterion past 9000 and destroy the reservation it
219
+ * was built on. That is `nextSCNumber`'s rule for `spelledInSource`, applied
220
+ * at the same width.
221
+ */
222
+ export function readScNamespace(root: string): ScNamespaceReading {
223
+ const ids = new Map<string, string[]>();
224
+ const sources: SourceReading[] = [];
225
+ const unmeasured: string[] = [];
226
+
227
+ const record = (id: string, label: string): void => {
228
+ if (isFixtureScId(id)) return;
229
+ const seen = ids.get(id) ?? [];
230
+ if (!seen.includes(label)) seen.push(label);
231
+ ids.set(id, seen);
232
+ };
233
+
234
+ const { paths, failure } = siblingWorktrees(root);
235
+ if (failure !== null) {
236
+ sources.push({ label: "git worktree list", kind: "worktree", status: "skipped", reason: failure, found: 0 });
237
+ unmeasured.push(`sibling worktrees could not be enumerated: ${failure}`);
238
+ }
239
+ for (const path of paths) {
240
+ const specsDir = join(path, "specs");
241
+ let usable = false;
242
+ try {
243
+ usable = existsSync(specsDir) && statSync(specsDir).isDirectory();
244
+ } catch {
245
+ usable = false;
246
+ }
247
+ if (!usable) {
248
+ // A worktree git lists but whose tree is gone, or which predates
249
+ // specs/. Recorded rather than dropped: a skipped source is the thing
250
+ // that makes the count below a floor.
251
+ sources.push({ label: path, kind: "worktree", status: "skipped", reason: "no readable specs/ directory", found: 0 });
252
+ unmeasured.push(`${path}: no readable specs/ directory`);
253
+ continue;
254
+ }
255
+ let found: string[];
256
+ try {
257
+ found = idsInSpecsDir(specsDir);
258
+ } catch (err) {
259
+ sources.push({ label: path, kind: "worktree", status: "skipped", reason: (err as Error).message, found: 0 });
260
+ unmeasured.push(`${path}: ${(err as Error).message}`);
261
+ continue;
262
+ }
263
+ for (const id of found) record(id, path);
264
+ sources.push({ label: path, kind: "worktree", status: "read", found: new Set(found).size });
265
+ }
266
+
267
+ const refs = idsInRefs(root);
268
+ if (refs.failure !== null) {
269
+ sources.push({ label: "refs", kind: "refs", status: "skipped", reason: refs.failure, found: 0 });
270
+ unmeasured.push(`branch refs could not be read: ${refs.failure}`);
271
+ } else {
272
+ for (const id of refs.ids) record(id, "refs");
273
+ sources.push({
274
+ label: `refs (${refs.refs} local and remote-tracking)`,
275
+ kind: "refs",
276
+ status: "read",
277
+ found: new Set(refs.ids).size,
278
+ });
279
+ }
280
+
281
+ // Always present, and not boilerplate: it is the one half of the namespace
282
+ // no process on this machine can reach, and an allocator that did not say
283
+ // so would be claiming a guarantee it cannot give.
284
+ unmeasured.push(
285
+ "ids allocated in a clone on another machine, and not yet pushed or fetched here, are not visible to any of the above",
286
+ );
287
+
288
+ return { ids, sources, unmeasured };
289
+ }
290
+
291
+ /**
292
+ * A one-line account of what a reading covered, for a CLI to print.
293
+ *
294
+ * It NAMES the legs rather than counting them (#593). A count says how many
295
+ * sources answered; it cannot say which width went unasked, and a number
296
+ * allocated without consulting the spec registry printed the same
297
+ * "2 source(s)" as one that had. This is the single binding every caller
298
+ * prints through, so there is no second renderer to drift from it.
299
+ */
300
+ export function describeReading(reading: ScNamespaceReading): string {
301
+ const read = reading.sources.filter(s => s.status === "read");
302
+ const skipped = reading.sources.filter(s => s.status === "skipped");
303
+ const legs = [...new Set(reading.sources.map(s => s.kind))];
304
+ const parts = [
305
+ `${reading.ids.size} ids across ${read.length} source(s)`,
306
+ `legs: ${legs.join(", ")}`,
307
+ skipped.length > 0 ? `${skipped.length} skipped` : null,
308
+ `${reading.unmeasured.length} unmeasured`,
309
+ ].filter(Boolean);
310
+ return parts.join(", ");
311
+ }