rungate 0.6.0 → 0.7.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 (113) hide show
  1. package/lib/affected-tests.ts +398 -0
  2. package/lib/agent-audit.ts +2 -3
  3. package/lib/agent-worktree.ts +287 -0
  4. package/lib/agents-md-sections.ts +81 -16
  5. package/lib/behavioral-cache.ts +150 -2
  6. package/lib/branch-protection.ts +790 -0
  7. package/lib/brief-ac-alignment.ts +104 -0
  8. package/lib/brief-references.ts +205 -0
  9. package/lib/bun-version.ts +93 -14
  10. package/lib/check-remedy.ts +140 -0
  11. package/lib/ci-checkout.ts +17 -0
  12. package/lib/ci-history-depth.ts +159 -0
  13. package/lib/ci-setup-step.ts +96 -0
  14. package/lib/claude-code-action.ts +85 -0
  15. package/lib/claude-tool-vocabulary.ts +188 -0
  16. package/lib/cli-commands.ts +15 -0
  17. package/lib/commit-sha.ts +42 -0
  18. package/lib/commit-subject.ts +90 -0
  19. package/lib/compliance-report.ts +377 -45
  20. package/lib/compliance.ts +191 -17
  21. package/lib/config-loader.ts +39 -1
  22. package/lib/config-trackable.ts +391 -0
  23. package/lib/conformity.ts +1087 -100
  24. package/lib/containment.ts +238 -0
  25. package/lib/content-hash.ts +24 -0
  26. package/lib/create-sc.ts +249 -16
  27. package/lib/dev-liveness.ts +180 -0
  28. package/lib/discovery-branch-points.ts +432 -0
  29. package/lib/discovery-stability.ts +481 -0
  30. package/lib/distribution-currency.ts +186 -0
  31. package/lib/doc-routing.ts +157 -0
  32. package/lib/evidence-prevalidator.ts +224 -2
  33. package/lib/evidence-satisfiability.ts +534 -12
  34. package/lib/failure-intake.ts +317 -0
  35. package/lib/fallow-availability.ts +157 -0
  36. package/lib/fs-write-capabilities.ts +232 -0
  37. package/lib/gate-run-split.ts +147 -0
  38. package/lib/generators/agents-md.ts +140 -32
  39. package/lib/git-isolation.ts +140 -0
  40. package/lib/github.ts +15 -0
  41. package/lib/google-auth-action.ts +93 -0
  42. package/lib/harness-project.ts +48 -0
  43. package/lib/harness-provenance.ts +255 -0
  44. package/lib/hook-evidence.ts +235 -0
  45. package/lib/hook-scopes.ts +386 -0
  46. package/lib/hook-target-tree.ts +398 -0
  47. package/lib/hook-trees.ts +447 -0
  48. package/lib/js-top-level-code.ts +78 -10
  49. package/lib/junit-checks.ts +52 -0
  50. package/lib/launch-base.ts +253 -0
  51. package/lib/line-citation.ts +372 -0
  52. package/lib/orphan-reaper.ts +468 -0
  53. package/lib/parity-binding.ts +205 -0
  54. package/lib/per-test-timeouts.ts +219 -0
  55. package/lib/plan-coverage.ts +151 -0
  56. package/lib/prior-branch.ts +201 -8
  57. package/lib/process-table.ts +146 -0
  58. package/lib/project-state-derivation.ts +219 -0
  59. package/lib/project-state-root.ts +258 -0
  60. package/lib/published-artifact.ts +525 -0
  61. package/lib/readdir-sorted.ts +45 -0
  62. package/lib/review-execution-reading.ts +206 -0
  63. package/lib/review-tool-agreement.ts +433 -0
  64. package/lib/rule-promotion.ts +234 -0
  65. package/lib/rule-retirement.ts +525 -0
  66. package/lib/run-branch.ts +612 -0
  67. package/lib/rungate-schema.ts +19 -0
  68. package/lib/runner-home.ts +274 -0
  69. package/lib/sc-id-cross-tree.ts +19 -7
  70. package/lib/sc-ids.ts +121 -13
  71. package/lib/sc-reservations.ts +289 -0
  72. package/lib/scaffold/ai-review-findings.ts +403 -0
  73. package/lib/scaffold/ai-review-step.ts +4661 -64
  74. package/lib/scaffold/managed-workflow.ts +587 -192
  75. package/lib/scaffold/owned-files.ts +152 -45
  76. package/lib/scaffold/pre-push-hook.ts +49 -5
  77. package/lib/scaffold/steps.ts +1413 -244
  78. package/lib/scaffold/workflow-census.ts +217 -0
  79. package/lib/scaffold/workflow-drift.ts +217 -0
  80. package/lib/scaffold/write-steps.ts +4 -0
  81. package/lib/scan-budget.ts +247 -0
  82. package/lib/scanner.ts +43 -51
  83. package/lib/scratch-roots.ts +50 -5
  84. package/lib/screenshot-discovery.ts +121 -0
  85. package/lib/screenshot-upload.ts +41 -1
  86. package/lib/secret-patterns.ts +511 -8
  87. package/lib/ship-mode.ts +219 -0
  88. package/lib/source-slice.ts +294 -0
  89. package/lib/stale-cleanup.ts +37 -3
  90. package/lib/suite-flake.ts +278 -0
  91. package/lib/suite-measurement.ts +23 -4
  92. package/lib/suite-run-reading.ts +241 -1
  93. package/lib/suite-timeout-margin.ts +193 -0
  94. package/lib/test-case-bodies.ts +883 -0
  95. package/lib/test-case-deletion.ts +653 -0
  96. package/lib/test-census.ts +97 -29
  97. package/lib/test-command-positions.ts +274 -0
  98. package/lib/test-suite-lock.ts +159 -16
  99. package/lib/tool-probe.ts +31 -9
  100. package/lib/top-level-cd.ts +393 -0
  101. package/lib/tree-entries.ts +89 -0
  102. package/lib/ts-ast.ts +200 -0
  103. package/lib/walk-test-files.ts +97 -0
  104. package/lib/workflow-actions.ts +263 -0
  105. package/lib/worktree-collect.ts +177 -5
  106. package/lib/worktree-repo.ts +36 -1
  107. package/package.json +2 -1
  108. package/scripts/ai-review-findings.ts +45 -0
  109. package/scripts/create-sc.ts +21 -1
  110. package/scripts/extract-constraints.ts +107 -7
  111. package/scripts/generate-code-map.ts +23 -30
  112. package/scripts/scaffold-project.ts +8 -1
  113. package/scripts/sync-sc-status.ts +77 -16
@@ -0,0 +1,238 @@
1
+ /**
2
+ * The containment reading: are there harness-pattern files left in the
3
+ * locations this harness was moved OUT of (#921).
4
+ *
5
+ * ## Why this is a module and not three lines in a test
6
+ *
7
+ * `test/structure.test.ts` ST-2b used to compose the old harness root from
8
+ * `process.env.HOME` and `readdirSync` it, then assert the listing was empty.
9
+ * Two separate defects, and the second is the worse one:
10
+ *
11
+ * - `if (!existsSync(dir)) return` made ABSENCE a pass. A machine with no
12
+ * old `gates/` directory ran the case to completion having measured
13
+ * nothing, which is indistinguishable from a clean directory —
14
+ * `.claude/rules/checks-must-be-able-to-fail.md`, first shape.
15
+ * - The verdict of the suite that gates THIS repository was set by whatever
16
+ * the developer happened to have installed in their home directory. Two
17
+ * unrelated scripts belonging to another running process made every full
18
+ * local suite 1-fail, while CI — where the home directory is empty — was
19
+ * green on the same commit. **The CI green was the vacuous case and the
20
+ * local red was the only real measurement**, which is the exact shape that
21
+ * gets read as flake and suppressed.
22
+ *
23
+ * Containment is still a property worth watching: harness code moved out of
24
+ * the old locations, and a copy left behind is a second source of truth. What
25
+ * is wrong is reading it off a directory this repository does not own, inside
26
+ * the suite that gates this repository's changes.
27
+ *
28
+ * So the reading is separated from where it is pointed. The suite points it
29
+ * at fixture trees it builds itself and asserts the three states it can
30
+ * return. `scripts/check-containment.ts` points it at the real old root for
31
+ * whoever can actually act on a stray — and that script's exit code, not the
32
+ * repo suite's verdict, is where a machine-local stray shows up.
33
+ *
34
+ * ## Three states, not two
35
+ *
36
+ * `0 strays`, `directory absent` and `could not read the directory` are three
37
+ * different facts and only the first is a pass. Same vocabulary as
38
+ * `scripts/check-unit-suite.sh` (exit 2 = nothing was measured) and the secret
39
+ * scan in `gates.yml` (capture first, so a git failure fails closed).
40
+ */
41
+
42
+ import { existsSync, readdirSync, statSync } from "fs";
43
+ import { join } from "path";
44
+
45
+ import { remedyMessage } from "./check-remedy";
46
+
47
+ /** What a reading of one watched location can say. */
48
+ export type ContainmentState = "CLEAN" | "STRAY" | "UNMEASURED";
49
+
50
+ /**
51
+ * What a location that could not be looked at reports.
52
+ *
53
+ * One declaration, so there is exactly one site to flip in a mutation
54
+ * battery and no second decider can hold a case up while this one is dead.
55
+ * Flipping it to `"CLEAN"` is the pre-#921 behaviour — `if (!existsSync(dir))
56
+ * return` — and is the mutation `test/containment-home-independence.test.ts`
57
+ * applies.
58
+ */
59
+ export const ABSENT_STATE: ContainmentState = "UNMEASURED";
60
+
61
+ /** A directory that must hold no file with the given extension. */
62
+ export interface WatchedDir {
63
+ /** Relative to the old harness root. */
64
+ dir: string;
65
+ /** The extension that makes a file there a harness-pattern file. */
66
+ ext: string;
67
+ }
68
+
69
+ /**
70
+ * The directories the harness was moved out of, and the extension that marks
71
+ * a harness file in each.
72
+ *
73
+ * Spelled here rather than derived from `reference/migration-manifest.json`,
74
+ * and the reason is a correctness one rather than convenience: the manifest
75
+ * also lists `skills/`, `PAI/` and `scripts/*.sh` sources, which were NOT
76
+ * migrated away from the old root and still legitimately live there. A watch
77
+ * list derived from every manifest source would report that legitimate tree
78
+ * as strays, and a report that is wrong by construction gets ignored, which
79
+ * costs more than the hand-maintained list of three.
80
+ */
81
+ export const WATCHED_DIRS: readonly WatchedDir[] = [
82
+ { dir: "workflows", ext: ".js" },
83
+ { dir: "gates", ext: ".ts" },
84
+ { dir: "lib", ext: ".ts" },
85
+ ];
86
+
87
+ /**
88
+ * Individual files whose old directory still holds unrelated files, so the
89
+ * whole directory cannot be scanned by extension.
90
+ *
91
+ * `scripts/` in the old root is shared with scripts that never moved, so only
92
+ * the named two are strays there. This is a narrowing of what counts as a
93
+ * stray in a shared directory, not an exemption for a stray that was found.
94
+ */
95
+ export const WATCHED_FILES: readonly string[] = [
96
+ "scripts/sync-spec-tests.ts",
97
+ "scripts/scaffold-rungate-config.ts",
98
+ ];
99
+
100
+ /** What one watched location says, and why. */
101
+ export interface ContainmentReading {
102
+ /** Human-readable subject, e.g. `workflows/*.js`. */
103
+ subject: string;
104
+ /** The absolute path that was examined. */
105
+ path: string;
106
+ state: ContainmentState;
107
+ /** Absolute paths of the harness-pattern files found. Empty unless STRAY. */
108
+ strays: string[];
109
+ /** Why the state is what it is — the sentence a reader needs. */
110
+ note: string;
111
+ }
112
+
113
+ function dirReading(oldRoot: string, { dir, ext }: WatchedDir): ContainmentReading {
114
+ const path = join(oldRoot, dir);
115
+ const subject = `${dir}/*${ext}`;
116
+ if (!existsSync(path)) {
117
+ return {
118
+ subject,
119
+ path,
120
+ state: ABSENT_STATE,
121
+ strays: [],
122
+ note: `${path} does not exist, so nothing was looked at. Absent is not clean.`,
123
+ };
124
+ }
125
+ let entries: string[];
126
+ try {
127
+ entries = readdirSync(path).map(String);
128
+ } catch (err) {
129
+ // Fails CLOSED. A catch that returned an empty listing here would turn
130
+ // an unreadable directory into a pass, which is the fail-open shape this
131
+ // whole module exists to refuse.
132
+ return {
133
+ subject,
134
+ path,
135
+ state: ABSENT_STATE,
136
+ strays: [],
137
+ note: `${path} could not be read (${(err as Error).message}), so nothing was looked at.`,
138
+ };
139
+ }
140
+ const strays = entries.filter(f => f.endsWith(ext)).map(f => join(path, f));
141
+ return {
142
+ subject,
143
+ path,
144
+ state: strays.length > 0 ? "STRAY" : "CLEAN",
145
+ strays,
146
+ note:
147
+ strays.length > 0
148
+ ? `${strays.length} harness-pattern file(s) in ${path}`
149
+ : `${entries.length} entr(ies) read in ${path}, none ending ${ext}`,
150
+ };
151
+ }
152
+
153
+ function fileReading(oldRoot: string, rel: string): ContainmentReading {
154
+ const path = join(oldRoot, rel);
155
+ const parent = join(oldRoot, rel.split("/").slice(0, -1).join("/"));
156
+ if (!existsSync(parent)) {
157
+ return {
158
+ subject: rel,
159
+ path,
160
+ state: ABSENT_STATE,
161
+ strays: [],
162
+ note: `${parent} does not exist, so ${rel} was never looked for. Absent is not clean.`,
163
+ };
164
+ }
165
+ let present = false;
166
+ try {
167
+ present = statSync(path).isFile();
168
+ } catch {
169
+ present = false;
170
+ }
171
+ return {
172
+ subject: rel,
173
+ path,
174
+ state: present ? "STRAY" : "CLEAN",
175
+ strays: present ? [path] : [],
176
+ note: present ? `${path} is still in the old location` : `${path} is not present`,
177
+ };
178
+ }
179
+
180
+ /**
181
+ * Read every watched location under `oldRoot`.
182
+ *
183
+ * `oldRoot` is a parameter and has no default on purpose: a default would put
184
+ * the home directory back inside every caller that forgot to think about it,
185
+ * and the whole point of #921 is that the repo suite must name a root it owns.
186
+ */
187
+ export function readContainment(oldRoot: string): ContainmentReading[] {
188
+ return [
189
+ ...WATCHED_DIRS.map(w => dirReading(oldRoot, w)),
190
+ ...WATCHED_FILES.map(f => fileReading(oldRoot, f)),
191
+ ];
192
+ }
193
+
194
+ /**
195
+ * The verdict over a set of readings.
196
+ *
197
+ * STRAY outranks UNMEASURED because a found file is actionable now; both are
198
+ * non-zero, so neither can be mistaken for clean. A reading set that is empty
199
+ * is UNMEASURED — zero locations examined is not zero strays found.
200
+ */
201
+ export function containmentVerdict(readings: ContainmentReading[]): ContainmentState {
202
+ if (readings.length === 0) return "UNMEASURED";
203
+ if (readings.some(r => r.state === "STRAY")) return "STRAY";
204
+ if (readings.some(r => r.state === "UNMEASURED")) return "UNMEASURED";
205
+ return "CLEAN";
206
+ }
207
+
208
+ /** 0 clean, 1 a stray was found, 2 nothing was measured. */
209
+ export function containmentExitCode(state: ContainmentState): 0 | 1 | 2 {
210
+ if (state === "CLEAN") return 0;
211
+ return state === "STRAY" ? 1 : 2;
212
+ }
213
+
214
+ /**
215
+ * The message a refusal carries: every file, the directory it is in, and the
216
+ * action — routed through `remedyMessage` so it also names the family of
217
+ * repository-level checks when the project carries that document.
218
+ */
219
+ export function containmentRemedy(root: string, readings: ContainmentReading[]): string {
220
+ const strays = readings.filter(r => r.state === "STRAY").flatMap(r => r.strays);
221
+ const unmeasured = readings.filter(r => r.state === "UNMEASURED");
222
+ const unmeasuredNote = unmeasured.length
223
+ ? ` ${unmeasured.length} location(s) reported UNMEASURED and are NOT clean: ` +
224
+ `${unmeasured.map(r => r.note).join("; ")}.`
225
+ : "";
226
+ return remedyMessage({
227
+ root,
228
+ check: "ST-2b containment",
229
+ violations: strays,
230
+ fix:
231
+ `each file above is a second copy of the harness in a directory it was moved out of. ` +
232
+ `Read it, find who owns it, and move or delete it there — do NOT delete a file you ` +
233
+ `did not put there, and do NOT add its name to a list of accepted ones, which only ` +
234
+ `dates the problem. The repo suite asserts this reading against a fixture tree it ` +
235
+ `owns and never a home directory; \`bun scripts/check-containment.ts\` is what takes ` +
236
+ `it against the real old root.${unmeasuredNote}`,
237
+ });
238
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The content hash a constraint candidate is identified by — ONE binding.
3
+ *
4
+ * A LEAF module, moved here from `scripts/extract-constraints.ts` and
5
+ * re-exported from it under the name every existing caller knows. That is the
6
+ * arrangement `lib/git-dates.ts` has with `lib/conformity.ts` (#508) and
7
+ * `lib/harness-identity.ts` has with `isHarnessItself` (#380): one binding,
8
+ * two names.
9
+ *
10
+ * It moved for a reason worth stating rather than for tidiness. The permanent
11
+ * veto in `reference/rejected-constraints.md` (SC-137) is a table of these
12
+ * hashes, and `loadRejectedHashes` matches a candidate against it by string
13
+ * equality. A second implementation of "the hash of a candidate" — even a
14
+ * correct one — would make the veto silently stop applying to whichever
15
+ * producer used the other copy, and no behavioural test could tell the two
16
+ * apart while they agreed. `lib/failure-intake.ts` is that second producer,
17
+ * so this is the collapse done before the pair exists rather than after
18
+ * (`.claude/rules/checks-must-be-able-to-fail.md`, fourth shape).
19
+ */
20
+ import { createHash } from "crypto";
21
+
22
+ export function contentHash(text: string): string {
23
+ return createHash("sha256").update(text.trim().toLowerCase()).digest("hex").slice(0, 12);
24
+ }
package/lib/create-sc.ts CHANGED
@@ -9,9 +9,19 @@ import { join, dirname } from "path";
9
9
  import { fileURLToPath } from "url";
10
10
 
11
11
  import type { ScRegistry } from "./sc-ids";
12
- import { isFixtureScId, scIdsSpelledInSource, SC_SOURCE_DIRS } from "./sc-ids";
12
+ import { isFixtureScId, scIdsSpelledInSourceReading, SC_SOURCE_DIRS } from "./sc-ids";
13
13
  import type { ScNamespaceReading, SourceReading } from "./sc-id-cross-tree";
14
14
  import { readScNamespace } from "./sc-id-cross-tree";
15
+ import type { ScReservation, ScReservationReading } from "./sc-reservations";
16
+ import {
17
+ lowestFreeInBlock,
18
+ readScReservations,
19
+ RESERVATION_REFUSAL,
20
+ reservationFor,
21
+ reservedCeiling,
22
+ reservedIdCount,
23
+ SC_RESERVATIONS_PATH,
24
+ } from "./sc-reservations";
15
25
  import { tryLoadRungateConfig } from "./config-loader";
16
26
 
17
27
  // ── Types ─────────────────────────────────────────────────────
@@ -298,6 +308,102 @@ export function nextSCNumber(
298
308
  return Math.max(...ids) + 1;
299
309
  }
300
310
 
311
+ /**
312
+ * The same three widths `nextSCNumber` reads, as a SET rather than a maximum.
313
+ *
314
+ * It exists because a reserved block is allocated from the bottom, not from
315
+ * the top: `max + 1` cannot answer "is 2174 free" when the block runs
316
+ * 2170..2189 and the tree's maximum is 2400. Both derive from one list
317
+ * comprehension so the two cannot come to disagree about which ids count — a
318
+ * second scan with a different fixture rule would be two deciders for one
319
+ * question (`.claude/rules/checks-must-be-able-to-fail.md`, fourth shape).
320
+ */
321
+ export function takenScNumbers(
322
+ specContent: string,
323
+ reg?: ScRegistry,
324
+ spelledInSource?: Iterable<string>,
325
+ ): Set<number> {
326
+ const taken = new Set<number>();
327
+ const take = (raw: string): void => {
328
+ const n = Number(raw.replace(/^SC-[A-Z]?/, ""));
329
+ if (Number.isFinite(n)) taken.add(n);
330
+ };
331
+ for (const raw of idsInSpecContent(specContent)) take(raw);
332
+ for (const id of reg?.declaredById.keys() ?? []) take(id);
333
+ for (const id of spelledInSource ?? []) if (!isFixtureScId(id)) take(id);
334
+ return taken;
335
+ }
336
+
337
+ /**
338
+ * The reservation store as a `SourceReading`, in one place.
339
+ *
340
+ * One binding for all three states, so a mutation has one site and a caller
341
+ * cannot assemble a leg that says `read` over a store it never opened. `found`
342
+ * is the number of ids the store declares OCCUPIED — the size of the space it
343
+ * removes from the allocator — and it is `0` under `absent` and `unreadable`
344
+ * for the same reason every other leg reports `0` when it did not run:
345
+ * `status` is what tells those apart, never the count.
346
+ */
347
+ export function scReservationLeg(reading: ScReservationReading): SourceReading {
348
+ const label = `SC reservation store (${SC_RESERVATIONS_PATH})`;
349
+ if (reading.status === "read") {
350
+ return {
351
+ label: `${label}: ${reading.blocks.length} block(s)`,
352
+ kind: "reservations",
353
+ status: "read",
354
+ found: reservedIdCount(reading.blocks),
355
+ };
356
+ }
357
+ return {
358
+ label,
359
+ kind: "reservations",
360
+ status: "skipped",
361
+ reason: reading.reason ?? `the store is ${reading.status}`,
362
+ found: 0,
363
+ };
364
+ }
365
+
366
+ /**
367
+ * Thrown when the caller's own reserved block has no id left in it.
368
+ *
369
+ * A distinct error rather than a fall-through to "allocate above the block",
370
+ * because that fall-through is the cheapest wrong fix and it silently undoes
371
+ * the separation the block was handed out to provide, on the one day it
372
+ * matters. Widening the block is a decision a person makes in the store.
373
+ */
374
+ export class ScReservationExhaustedError extends Error {}
375
+
376
+ /**
377
+ * The number, given the floor, the store and who is asking.
378
+ *
379
+ * Exported because it is the single binding a mutation battery points at:
380
+ * every reservation-aware decision this module makes happens here and nowhere
381
+ * else, so there is no second copy to hold a case up when this one is broken.
382
+ */
383
+ export function allocateAgainstReservations(
384
+ floor: number,
385
+ blocks: ScReservation[],
386
+ owner: string | null,
387
+ taken: ReadonlySet<number>,
388
+ ): number {
389
+ const mine = reservationFor(blocks, owner);
390
+ if (mine !== null) {
391
+ const free = lowestFreeInBlock(mine, taken);
392
+ if (free === null) {
393
+ throw new ScReservationExhaustedError(
394
+ `the SC block reserved to ${mine.owner} (${mine.from}-${mine.to}) is spent — ` +
395
+ `widen it in ${SC_RESERVATIONS_PATH} rather than allocating outside it`,
396
+ );
397
+ }
398
+ return free;
399
+ }
400
+ // No block of your own. The floor is still correct about what is WRITTEN;
401
+ // it knows nothing about what is DECLARED, so it is raised past every block
402
+ // in the store. This is the row that covers the renumber case — the one
403
+ // where nobody thought of themselves as allocating.
404
+ return Math.max(floor, reservedCeiling(blocks) + 1);
405
+ }
406
+
301
407
  /**
302
408
  * The next free SC number for a project, over every namespace this machine
303
409
  * can see (#503).
@@ -338,38 +444,165 @@ export function nextSCNumber(
338
444
  * own, with the count each contributed — `0` from a leg that was consulted
339
445
  * and `0` from a leg that was skipped are the same number and opposite
340
446
  * facts (`.claude/rules/config-access.md`).
447
+ *
448
+ * ## …and for two issues all three said `read` without asking (#606)
449
+ *
450
+ * The sentence above was the docstring of a function that hardcoded
451
+ * `status: "read"` on every one of the three. Measured on a tree holding one
452
+ * spec and none of the four source directories: `source-mentions` reported
453
+ * `read, found 0` — which is also the output for a tree whose four
454
+ * directories were walked and held no ids. A consumer whose tests live in
455
+ * `tests/` or `src/` was in the second case on every single run.
456
+ *
457
+ * Two of the three are now derived, and one is not:
458
+ *
459
+ * | Leg | Source of `found` | Can it have failed to read? |
460
+ * |---|---|---|
461
+ * | `spec-content` | `idsInSpecContent(specContent)` | **No.** `specContent` is a string parameter, already in memory. `0` here is a reading |
462
+ * | `registry` | `reg.declaredById.size` | Yes — `reg` may have been built from a `specs/` the caller could not enumerate, which `ScRegistry.enumeration` now states |
463
+ * | `source-mentions` | the source walk | Yes — four directories, any of which the walk returns silently from |
464
+ *
465
+ * `spec-content` stays `read` deliberately. Rewriting all three uniformly is
466
+ * the cheap-looking repair and it adds an unreachable branch to the one leg
467
+ * that was right, which no case can go red over.
468
+ *
469
+ * A leg that could not be fully read also appends to `namespace.unmeasured`,
470
+ * because `status` is a per-leg fact and `unmeasured` is the list a caller
471
+ * prints. A gap in only one of them is a gap a reader can miss.
472
+ *
473
+ * ## …and all six legs read ids that have already been WRITTEN (#725)
474
+ *
475
+ * Every width above answers "which ids can this machine find typed somewhere
476
+ * right now". None of them can see an id another session has decided to take
477
+ * and not yet typed, which is the window `.claude/rules/parallel-sessions.md`
478
+ * says people sit in for an hour. Four collisions on 2026-10-19 came out of
479
+ * it, and in three of them the allocator was never run at all — a renumber
480
+ * during a repair, two individually-correct branch allocations, and ids
481
+ * hand-written into a test file.
482
+ *
483
+ * `lib/sc-reservations.ts` is the seventh leg and the only one that is a
484
+ * reading of a DECLARATION rather than of the tree. `opts.owner` — a branch
485
+ * name or issue ref — selects the caller's own block:
486
+ *
487
+ * | The caller | What it gets |
488
+ * |---|---|
489
+ * | owns a block with room in it | the lowest free id INSIDE that block |
490
+ * | owns a block that is spent | a refusal naming the block |
491
+ * | owns no block | an id above every block in the store, so it cannot land in someone else's |
492
+ *
493
+ * The no-owner row is the one that makes the store work for the renumber
494
+ * case: a session that never declared anything still cannot be handed an id
495
+ * out of a block somebody else declared.
496
+ *
497
+ * A store that is present and could not be read is a REFUSAL, not an empty
498
+ * reading — see `lib/sc-reservations.ts`. A store that is genuinely absent is
499
+ * a skipped leg with a named `unmeasured` entry, because every scaffolded
500
+ * consumer project is in that state and a refusal they cannot act on is a
501
+ * gate everyone learns to click past.
341
502
  */
342
503
  export function allocateScNumber(
343
504
  root: string,
344
505
  specContent: string,
345
506
  reg: ScRegistry,
507
+ opts?: { owner?: string | null },
346
508
  ): { number: number; namespace: ScNamespaceReading } {
347
509
  const namespace = readScNamespace(root);
348
- const spelled = [...scIdsSpelledInSource(root).keys()];
349
- const number = nextSCNumber(specContent, reg, [...spelled, ...namespace.ids.keys()]);
510
+ const source = scIdsSpelledInSourceReading(root);
511
+ const spelled = [...source.ids.keys()];
512
+ const floor = nextSCNumber(specContent, reg, [...spelled, ...namespace.ids.keys()]);
513
+
514
+ const unmeasured: string[] = [];
515
+
516
+ const reservations = readScReservations(root);
517
+ // The refusal, before the number exists. Returning a floor computed without
518
+ // a store that is sitting right there, unreadable, is the pre-#725
519
+ // behaviour: `0`, `{}` and silence are indistinguishable from success
520
+ // (`.claude/rules/config-access.md`).
521
+ if (reservations.status === "unreadable") {
522
+ throw new Error(`${RESERVATION_REFUSAL} (${reservations.path}): ${reservations.reason}`);
523
+ }
524
+ const reservationLeg = scReservationLeg(reservations);
525
+ if (reservations.status !== "read") {
526
+ unmeasured.push(
527
+ `the SC reservation store could not be consulted: ${reservations.reason ?? "no reason given"}`,
528
+ );
529
+ }
530
+ const taken = takenScNumbers(specContent, reg, [...spelled, ...namespace.ids.keys()]);
531
+ const number = allocateAgainstReservations(floor, reservations.blocks, opts?.owner ?? null, taken);
532
+
533
+ const registryLabel = "spec registry (every declared id, checkbox and heading)";
534
+ const registryLeg: SourceReading = reg.enumeration.status === "enumerated"
535
+ ? { label: registryLabel, kind: "registry", status: "read", found: reg.declaredById.size }
536
+ : {
537
+ label: registryLabel,
538
+ kind: "registry",
539
+ status: "skipped",
540
+ reason: reg.enumeration.reason ?? "the spec registry was not enumerated",
541
+ found: 0,
542
+ };
543
+ if (reg.enumeration.status === "unenumerated") {
544
+ unmeasured.push(
545
+ `the spec registry was not enumerated: ${reg.enumeration.reason ?? "no reason given"}`,
546
+ );
547
+ }
548
+
549
+ const sourceLabel = `SC ids spelled under ${SC_SOURCE_DIRS.join(", ")}`;
550
+ const unreached = source.unwalkable.map(u => `${u.dir} (${u.reason})`).join("; ");
551
+ let sourceLeg: SourceReading;
552
+ if (source.walked.length === 0) {
553
+ // None of them opened. There is no reading here at all, and the count is
554
+ // the count of a walk that never happened.
555
+ sourceLeg = {
556
+ label: sourceLabel,
557
+ kind: "source-mentions",
558
+ status: "skipped",
559
+ reason: `none of ${SC_SOURCE_DIRS.join(", ")} could be walked: ${unreached}`,
560
+ found: 0,
561
+ };
562
+ } else if (source.unwalkable.length > 0) {
563
+ // Partially read, and the count is real for the part that was. Saying
564
+ // `skipped` here would swap the two cases rather than separate them.
565
+ sourceLeg = {
566
+ label: `${sourceLabel} (walked ${source.walked.join(", ")})`,
567
+ kind: "source-mentions",
568
+ status: "read",
569
+ reason: `could not walk ${unreached}`,
570
+ found: new Set(spelled).size,
571
+ };
572
+ } else {
573
+ sourceLeg = {
574
+ label: sourceLabel,
575
+ kind: "source-mentions",
576
+ status: "read",
577
+ found: new Set(spelled).size,
578
+ };
579
+ }
580
+ for (const u of source.unwalkable) {
581
+ unmeasured.push(`source directory ${u.dir} could not be walked: ${u.reason}`);
582
+ }
350
583
 
351
584
  const legs: SourceReading[] = [
352
585
  {
586
+ // Not derived, and the table above says why: there is no state in which
587
+ // this one could have failed to read a string it was handed.
353
588
  label: "the spec's own content",
354
589
  kind: "spec-content",
355
590
  status: "read",
356
591
  found: new Set(idsInSpecContent(specContent)).size,
357
592
  },
358
- {
359
- label: "spec registry (every declared id, checkbox and heading)",
360
- kind: "registry",
361
- status: "read",
362
- found: reg.declaredById.size,
363
- },
364
- {
365
- label: `SC ids spelled under ${SC_SOURCE_DIRS.join(", ")}`,
366
- kind: "source-mentions",
367
- status: "read",
368
- found: new Set(spelled).size,
369
- },
593
+ registryLeg,
594
+ sourceLeg,
595
+ reservationLeg,
370
596
  ];
371
597
 
372
- return { number, namespace: { ...namespace, sources: [...legs, ...namespace.sources] } };
598
+ return {
599
+ number,
600
+ namespace: {
601
+ ...namespace,
602
+ sources: [...legs, ...namespace.sources],
603
+ unmeasured: [...unmeasured, ...namespace.unmeasured],
604
+ },
605
+ };
373
606
  }
374
607
 
375
608
  /**