rungate 0.5.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 (142) 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 +209 -0
  5. package/lib/behavioral-cache.ts +150 -2
  6. package/lib/branch-diff.ts +139 -0
  7. package/lib/branch-protection.ts +790 -0
  8. package/lib/brief-ac-alignment.ts +104 -0
  9. package/lib/brief-references.ts +205 -0
  10. package/lib/bun-version.ts +347 -0
  11. package/lib/check-remedy.ts +140 -0
  12. package/lib/ci-checkout.ts +18 -1
  13. package/lib/ci-history-depth.ts +159 -0
  14. package/lib/ci-setup-step.ts +96 -0
  15. package/lib/claude-code-action.ts +85 -0
  16. package/lib/claude-tool-vocabulary.ts +188 -0
  17. package/lib/cli-commands.ts +15 -0
  18. package/lib/commit-sha.ts +42 -0
  19. package/lib/commit-subject.ts +90 -0
  20. package/lib/compliance-report.ts +377 -45
  21. package/lib/compliance.ts +196 -20
  22. package/lib/config-loader.ts +51 -1
  23. package/lib/config-trackable.ts +391 -0
  24. package/lib/conformity.ts +1272 -189
  25. package/lib/containment.ts +238 -0
  26. package/lib/content-hash.ts +24 -0
  27. package/lib/context-docs.ts +143 -28
  28. package/lib/create-brief.ts +2 -1
  29. package/lib/create-sc.ts +323 -4
  30. package/lib/dev-liveness.ts +180 -0
  31. package/lib/discovery-branch-points.ts +432 -0
  32. package/lib/discovery-stability.ts +481 -0
  33. package/lib/distribution-currency.ts +186 -0
  34. package/lib/doc-routing.ts +157 -0
  35. package/lib/doc-scan-targets.ts +9 -0
  36. package/lib/evidence-command-transport.ts +160 -0
  37. package/lib/evidence-prevalidator.ts +246 -2
  38. package/lib/evidence-satisfiability.ts +534 -12
  39. package/lib/failure-intake.ts +317 -0
  40. package/lib/fallow-availability.ts +286 -0
  41. package/lib/fs-write-capabilities.ts +232 -0
  42. package/lib/gate-refusal-currency.ts +112 -0
  43. package/lib/gate-run-split.ts +147 -0
  44. package/lib/gate-timeouts.ts +82 -0
  45. package/lib/generators/agent-briefs.ts +4 -1
  46. package/lib/generators/agents-md.ts +204 -48
  47. package/lib/generators/code-map.ts +2 -1
  48. package/lib/generators/types.ts +8 -0
  49. package/lib/git-dates.ts +55 -0
  50. package/lib/git-isolation.ts +140 -0
  51. package/lib/github.ts +15 -0
  52. package/lib/google-auth-action.ts +93 -0
  53. package/lib/harness-project.ts +48 -0
  54. package/lib/harness-provenance.ts +255 -0
  55. package/lib/hook-evidence.ts +235 -0
  56. package/lib/hook-scopes.ts +386 -0
  57. package/lib/hook-target-tree.ts +398 -0
  58. package/lib/hook-trees.ts +447 -0
  59. package/lib/js-top-level-code.ts +78 -10
  60. package/lib/junit-checks.ts +536 -0
  61. package/lib/launch-base.ts +253 -0
  62. package/lib/line-citation.ts +372 -0
  63. package/lib/local-calendar-day.ts +78 -0
  64. package/lib/orphan-reaper.ts +468 -0
  65. package/lib/parity-binding.ts +205 -0
  66. package/lib/per-test-timeouts.ts +219 -0
  67. package/lib/plan-coverage.ts +151 -0
  68. package/lib/prior-branch.ts +201 -8
  69. package/lib/process-table.ts +146 -0
  70. package/lib/project-state-derivation.ts +219 -0
  71. package/lib/project-state-root.ts +258 -0
  72. package/lib/project-state-shape.ts +59 -0
  73. package/lib/promote-outputs.ts +6 -2
  74. package/lib/published-artifact.ts +525 -0
  75. package/lib/readdir-sorted.ts +45 -0
  76. package/lib/report-provenance.ts +156 -0
  77. package/lib/review-execution-reading.ts +206 -0
  78. package/lib/review-tool-agreement.ts +433 -0
  79. package/lib/rule-promotion.ts +234 -0
  80. package/lib/rule-retirement.ts +525 -0
  81. package/lib/run-branch.ts +612 -0
  82. package/lib/rungate-schema.ts +19 -0
  83. package/lib/runner-home.ts +274 -0
  84. package/lib/sc-claim-forms.ts +75 -0
  85. package/lib/sc-id-cross-tree.ts +323 -0
  86. package/lib/sc-ids.ts +121 -13
  87. package/lib/sc-reservations.ts +289 -0
  88. package/lib/scaffold/ai-review-findings.ts +403 -0
  89. package/lib/scaffold/ai-review-step.ts +4777 -0
  90. package/lib/scaffold/managed-workflow.ts +587 -192
  91. package/lib/scaffold/owned-files.ts +186 -39
  92. package/lib/scaffold/pre-push-hook.ts +49 -5
  93. package/lib/scaffold/rehearsal.ts +205 -71
  94. package/lib/scaffold/steps.ts +1517 -293
  95. package/lib/scaffold/workflow-census.ts +217 -0
  96. package/lib/scaffold/workflow-drift.ts +217 -0
  97. package/lib/scaffold/write-steps.ts +10 -4
  98. package/lib/scan-budget.ts +247 -0
  99. package/lib/scanner.ts +80 -62
  100. package/lib/scratch-roots.ts +50 -5
  101. package/lib/screenshot-discovery.ts +121 -0
  102. package/lib/screenshot-upload.ts +41 -1
  103. package/lib/secret-patterns.ts +511 -8
  104. package/lib/ship-mode.ts +219 -0
  105. package/lib/source-slice.ts +294 -0
  106. package/lib/spec-listing.ts +148 -0
  107. package/lib/spec-requirements.ts +209 -0
  108. package/lib/stale-cleanup.ts +37 -3
  109. package/lib/suite-flake.ts +278 -0
  110. package/lib/suite-measurement.ts +23 -4
  111. package/lib/suite-run-reading.ts +411 -1
  112. package/lib/suite-timeout-margin.ts +193 -0
  113. package/lib/test-case-bodies.ts +883 -0
  114. package/lib/test-case-deletion.ts +653 -0
  115. package/lib/test-census.ts +97 -29
  116. package/lib/test-command-positions.ts +274 -0
  117. package/lib/test-command.ts +133 -0
  118. package/lib/test-suite-lock.ts +325 -26
  119. package/lib/tool-probe.ts +142 -0
  120. package/lib/top-level-cd.ts +393 -0
  121. package/lib/tracked-vs-ignored.ts +234 -0
  122. package/lib/tree-entries.ts +89 -0
  123. package/lib/ts-ast.ts +200 -0
  124. package/lib/validators/spec-validators.ts +3 -2
  125. package/lib/walk-test-files.ts +97 -0
  126. package/lib/workflow-actions.ts +263 -0
  127. package/lib/worktree-collect.ts +177 -5
  128. package/lib/worktree-repo.ts +36 -1
  129. package/package.json +2 -1
  130. package/scripts/ai-review-findings.ts +45 -0
  131. package/scripts/audit-specs.ts +247 -12
  132. package/scripts/audit-transcript.ts +2 -1
  133. package/scripts/convert-spec.ts +2 -1
  134. package/scripts/create-sc.ts +37 -7
  135. package/scripts/create-spec.ts +2 -1
  136. package/scripts/create-success.ts +2 -1
  137. package/scripts/extract-constraints.ts +197 -26
  138. package/scripts/generate-code-map.ts +62 -28
  139. package/scripts/scaffold-project.ts +12 -2
  140. package/scripts/split-spec.ts +2 -1
  141. package/scripts/sync-sc-status.ts +127 -14
  142. package/scripts/sync-spec-tests.ts +2 -1
package/lib/sc-ids.ts CHANGED
@@ -193,9 +193,49 @@ export function isFixtureScId(id: string): boolean {
193
193
  * declaredById EVERY form. The namespace as it actually is, which is what
194
194
  * ambiguity and allocation have to be computed over.
195
195
  */
196
+ /**
197
+ * Whether the `specs/` this registry was built from was actually enumerated
198
+ * (#606).
199
+ *
200
+ * `buildScRegistry([])` is a registry with no declarations, and it means "this
201
+ * tree declares nothing" — a reading. A caller that could not list `specs/` at
202
+ * all produces the same empty maps and means the opposite, and before this
203
+ * field existed nothing downstream could tell them apart:
204
+ * `allocateScNumber`'s registry leg reported `found: reg.declaredById.size`
205
+ * with `status: "read"` for both. `0` from a width that was consulted and `0`
206
+ * from a width that was skipped are the same number and opposite facts
207
+ * (`.claude/rules/config-access.md`).
208
+ *
209
+ * The reason travels with the status because "install something" fixes a
210
+ * missing directory and nothing else does — a skip with no reason is a skip
211
+ * nobody can act on.
212
+ */
213
+ export interface ScRegistryEnumeration {
214
+ status: "enumerated" | "unenumerated";
215
+ /** Why `specs/` could not be enumerated. Absent when it was. */
216
+ reason?: string;
217
+ }
218
+
196
219
  export interface ScRegistry {
197
220
  byId: Map<string, string[]>;
198
221
  declaredById: Map<string, string[]>;
222
+ /** Where the declarations came from, or why they could not be collected. */
223
+ enumeration: ScRegistryEnumeration;
224
+ }
225
+
226
+ /**
227
+ * A registry whose `specs/` could NOT be listed (#606).
228
+ *
229
+ * Empty maps, like `buildScRegistry([])` — and the only thing separating the
230
+ * two is this flag, which is the point. A consumer handed one of these must
231
+ * not report the registry width as consulted.
232
+ */
233
+ export function unenumeratedScRegistry(reason: string): ScRegistry {
234
+ return {
235
+ byId: new Map(),
236
+ declaredById: new Map(),
237
+ enumeration: { status: "unenumerated", reason },
238
+ };
199
239
  }
200
240
 
201
241
  /** The template's ids are placeholders — `isTemplateSpec` already skips it. */
@@ -276,7 +316,9 @@ export function buildScRegistry(specs: Array<{ file: string; content: string }>)
276
316
  record(declaredById, d.id, file);
277
317
  }
278
318
  }
279
- return { byId, declaredById };
319
+ // Enumerated by construction: the caller handed over the list of specs it
320
+ // read. An empty list is a tree that declares nothing, which is a reading.
321
+ return { byId, declaredById, enumeration: { status: "enumerated" } };
280
322
  }
281
323
 
282
324
  /**
@@ -396,8 +438,42 @@ export interface ScMentionInSource {
396
438
  inComment: boolean;
397
439
  }
398
440
 
441
+ /** A directory the walk met and could not open, with the reason it gave. */
442
+ export interface ScSourceDirUnwalkable {
443
+ /** Relative to `root` where that is possible, absolute otherwise. */
444
+ dir: string;
445
+ reason: string;
446
+ }
447
+
399
448
  /**
400
- * Every numeric SC id spelled anywhere under `SC_SOURCE_DIRS`.
449
+ * What the source walk found AND where it could not look (#606).
450
+ *
451
+ * The walk returns silently from a directory it cannot open, which is right
452
+ * for the walk — a consumer whose tests live in `tests/` has no `test/` and
453
+ * that is not an error. It is wrong for a CALLER that then reports the result
454
+ * as a completed read: a tree with four readable, present, genuinely empty
455
+ * source directories and a tree with none of them both produce zero ids, and
456
+ * only one of them has been measured.
457
+ *
458
+ * So the count and the coverage travel together. A scan that reports a
459
+ * verdict reports its own coverage
460
+ * (`.claude/rules/checks-must-be-able-to-fail.md`).
461
+ */
462
+ export interface ScSourceMentionsReading {
463
+ mentions: ScMentionInSource[];
464
+ /** Which of `SC_SOURCE_DIRS` were opened. Never contains an unwalkable dir. */
465
+ walked: string[];
466
+ /**
467
+ * Every directory `readdirSync` refused — a top-level `SC_SOURCE_DIRS`
468
+ * entry or anything nested beneath one, because the fail-open is the same
469
+ * `catch` in both positions.
470
+ */
471
+ unwalkable: ScSourceDirUnwalkable[];
472
+ }
473
+
474
+ /**
475
+ * Every numeric SC id spelled anywhere under `SC_SOURCE_DIRS`, with an
476
+ * account of which of those directories were actually walked (#606).
401
477
  *
402
478
  * Deliberately NOT restricted to declaring forms. The allocator's question is
403
479
  * "could handing out this number break something", and a fixture spelled in
@@ -407,18 +483,28 @@ export interface ScMentionInSource {
407
483
  * (`.claude/rules/claiming-sc-coverage.md`); this is a different question
408
484
  * asked for a different purpose, and widening it here cannot credit anything.
409
485
  */
410
- export function scMentionsInSource(root: string): ScMentionInSource[] {
486
+ export function scMentionsInSource(root: string): ScSourceMentionsReading {
411
487
  const { readdirSync, readFileSync } = require("fs") as typeof import("fs");
412
- const { join } = require("path") as typeof import("path");
488
+ const { join, relative } = require("path") as typeof import("path");
413
489
  const { commentMask } = require("./strip-js-comments") as typeof import("./strip-js-comments");
414
490
  const out: ScMentionInSource[] = [];
491
+ const unwalkable: ScSourceDirUnwalkable[] = [];
415
492
 
416
- const walk = (dir: string): void => {
493
+ /** True when the directory was opened. The return value is the whole fix. */
494
+ const walk = (dir: string): boolean => {
417
495
  let entries;
418
496
  try {
419
497
  entries = readdirSync(dir, { withFileTypes: true });
420
- } catch {
421
- return; // a source dir this consumer does not have
498
+ } catch (err) {
499
+ // A source dir this consumer does not have. Still not an error — but
500
+ // the caller hears about it, because "walked and found nothing" and
501
+ // "never opened" were the same answer until #606.
502
+ const rel = relative(root, dir);
503
+ unwalkable.push({
504
+ dir: rel === "" || rel.startsWith("..") ? dir : rel,
505
+ reason: (err as Error).message,
506
+ });
507
+ return false;
422
508
  }
423
509
  for (const e of entries) {
424
510
  if (e.name === "node_modules" || e.name === ".git") continue;
@@ -432,20 +518,42 @@ export function scMentionsInSource(root: string): ScMentionInSource[] {
432
518
  out.push({ id: m[0], file: p.slice(root.length + 1), inComment: mask[m.index!] === true });
433
519
  }
434
520
  }
521
+ return true;
435
522
  };
436
- for (const d of SC_SOURCE_DIRS) walk(join(root, d));
437
- return out;
523
+
524
+ const walked: string[] = [];
525
+ for (const d of SC_SOURCE_DIRS) if (walk(join(root, d))) walked.push(d);
526
+ return { mentions: out, walked, unwalkable };
438
527
  }
439
528
 
440
- /** Ids spelled in source, with the files that spell them. */
441
- export function scIdsSpelledInSource(root: string): Map<string, string[]> {
529
+ /** Ids spelled in source, with the files that spell them, and the coverage. */
530
+ export interface ScIdsSpelledReading {
531
+ ids: Map<string, string[]>;
532
+ walked: string[];
533
+ unwalkable: ScSourceDirUnwalkable[];
534
+ }
535
+
536
+ /**
537
+ * Ids spelled in source, keeping the walk's own account of where it looked.
538
+ *
539
+ * ONE place builds the id map, so `scIdsSpelledInSource` and the allocator's
540
+ * source-mentions leg cannot be two deciders that agree
541
+ * (`.claude/rules/checks-must-be-able-to-fail.md`, fourth shape).
542
+ */
543
+ export function scIdsSpelledInSourceReading(root: string): ScIdsSpelledReading {
544
+ const reading = scMentionsInSource(root);
442
545
  const found = new Map<string, string[]>();
443
- for (const m of scMentionsInSource(root)) {
546
+ for (const m of reading.mentions) {
444
547
  const files = found.get(m.id) ?? [];
445
548
  if (!files.includes(m.file)) files.push(m.file);
446
549
  found.set(m.id, files);
447
550
  }
448
- return found;
551
+ return { ids: found, walked: reading.walked, unwalkable: reading.unwalkable };
552
+ }
553
+
554
+ /** Ids spelled in source, with the files that spell them. */
555
+ export function scIdsSpelledInSource(root: string): Map<string, string[]> {
556
+ return scIdsSpelledInSourceReading(root).ids;
449
557
  }
450
558
 
451
559
  /**
@@ -0,0 +1,289 @@
1
+ /**
2
+ * SC id reservations, as a file in the repository rather than in a prompt (#725).
3
+ *
4
+ * ## Why a file, when the allocator already reads every worktree and every ref
5
+ *
6
+ * `readScNamespace` (#503) reads sibling worktrees' `specs/` and every local
7
+ * and remote-tracking ref. That is a reading of ids that have already been
8
+ * **written down somewhere this machine can see**. It cannot see an id a
9
+ * session has decided to use and not yet typed, and it cannot see anything on
10
+ * another clone at all.
11
+ *
12
+ * On 2026-10-19 that produced four collisions in one day. The first was eight
13
+ * PRs merging in sequence, two of which both claimed SC-2161 and SC-2162. The
14
+ * other three are the ones that matter for this module, because **in none of
15
+ * them was the allocator ever run**:
16
+ *
17
+ * | Instance | How the id was consumed |
18
+ * |---|---|
19
+ * | two | a renumber during the repair of instance one, picked by reading the highest id in the tree by hand |
20
+ * | three | two branches each allocating correctly against a view that excluded the other, found only by sweeping branch diffs |
21
+ * | four | ids hand-written into a new test file, caught by `sc-fixture-namespace` |
22
+ *
23
+ * So no change to what the allocator *returns* could have prevented three of
24
+ * the four: nothing consulted it. The class is "an id consumed without going
25
+ * through the allocator", and the only thing that covers that class is a
26
+ * declaration someone makes **before** consuming the ids, in a place every
27
+ * other session reads. That is this file.
28
+ *
29
+ * The convention already existed — five sessions were handed disjoint blocks
30
+ * in their briefs — and it worked. It lived entirely in prompts, so nothing in
31
+ * the tree recorded which blocks were reserved or by whom, and it survived
32
+ * exactly as long as everyone remembered. Instance two was made by the person
33
+ * handing the blocks out, outside any block, because a repair did not feel
34
+ * like an allocation. A renumber is an allocation.
35
+ *
36
+ * ## `{}` and `{"reservations": []}` are not the same state
37
+ *
38
+ * This is `.claude/rules/config-access.md`'s *Silent Default Substitution* in
39
+ * the place it does the most damage: **zero known reservations is not "no
40
+ * conflict", it is very often an unread store.** A `JSON.parse` that succeeds
41
+ * and yields an object with no `reservations` key gives an empty block list,
42
+ * which is byte-identical to a store that genuinely reserves nothing — and the
43
+ * allocator then allocates as if nothing were reserved, which is the pre-#725
44
+ * behaviour wearing a fix.
45
+ *
46
+ * So `RESERVATIONS_CONTROL_KEY` is the control string
47
+ * `.claude/rules/checks-must-be-able-to-fail.md` asks for: a string that MUST
48
+ * be present if the store holds anything at all. Absent, the reading is
49
+ * `unreadable`, not empty, and `allocateScNumber` refuses rather than
50
+ * returning a number.
51
+ *
52
+ * Three states, three different facts:
53
+ *
54
+ * | State | Means | Allocator |
55
+ * |---|---|---|
56
+ * | `absent` | no store in this tree — the normal state for a scaffolded consumer | allocates, with a `skipped` leg and a named `unmeasured` entry |
57
+ * | `unreadable` | a store is there and this process could not read it | **refuses** |
58
+ * | `read` | the store parsed and declared its control key | allocates, treating every block as occupied |
59
+ *
60
+ * `absent` does not refuse on purpose. Every consumer project this harness
61
+ * scaffolds has no store, and a refusal they cannot act on is the fastest way
62
+ * to build a gate everyone learns to click past.
63
+ */
64
+ import { execFileSync } from "child_process";
65
+ import { existsSync, readFileSync } from "fs";
66
+ import { join } from "path";
67
+
68
+ import { FIXTURE_SC_FLOOR } from "./sc-ids";
69
+
70
+ /**
71
+ * Where the store lives, relative to the project root.
72
+ *
73
+ * `specs/` because SC ids are a property of the spec namespace, and because
74
+ * the cross-tree reader already points every session at that directory. It is
75
+ * JSON rather than Markdown so that a reserved block is a pair of integers
76
+ * and never the string `SC-<N>` — a store spelling ids literally would be
77
+ * picked up by `scIdsSpelledInSource` and by `spec-sc-ids-unique`, and a
78
+ * reservation would then read as a declaration.
79
+ */
80
+ export const SC_RESERVATIONS_PATH = "specs/sc-reservations.json";
81
+
82
+ /**
83
+ * The key that must be present if the store holds anything.
84
+ *
85
+ * One binding, because a second place that decides what a readable store looks
86
+ * like would survive any mutation of the first
87
+ * (`.claude/rules/checks-must-be-able-to-fail.md`, fourth shape).
88
+ */
89
+ export const RESERVATIONS_CONTROL_KEY = "reservations";
90
+
91
+ /** The message prefix every refusal out of this module and its allocator uses. */
92
+ export const RESERVATION_REFUSAL = "SC reservation store is present and unreadable";
93
+
94
+ /** One declared block. `from` and `to` are inclusive. */
95
+ export interface ScReservation {
96
+ /** Branch name or issue ref. The thing another session can look you up by. */
97
+ owner: string;
98
+ from: number;
99
+ to: number;
100
+ note?: string;
101
+ }
102
+
103
+ export type ScReservationStatus = "read" | "absent" | "unreadable";
104
+
105
+ export interface ScReservationReading {
106
+ status: ScReservationStatus;
107
+ /** Absolute path the reading was taken from, whether or not it existed. */
108
+ path: string;
109
+ /** Empty under every status except a `read` of a store that declares blocks. */
110
+ blocks: ScReservation[];
111
+ /** Why it could not be read, or why the store is absent. Absent on a clean read. */
112
+ reason?: string;
113
+ }
114
+
115
+ /** A positive integer and nothing else — `1.5`, `NaN` and `"7"` are all refused. */
116
+ function isCount(v: unknown): v is number {
117
+ return typeof v === "number" && Number.isSafeInteger(v) && v >= 1;
118
+ }
119
+
120
+ /**
121
+ * Validate one entry, returning the reason it is unusable or `null`.
122
+ *
123
+ * A block at or above the fixture floor is refused rather than clamped: the
124
+ * 9000s exist so a fixture can spell an id that no criterion will ever take,
125
+ * and a reservation up there is a declaration the allocator structurally
126
+ * cannot honour (`nextSCNumber` drops fixture ids on purpose). Silently
127
+ * ignoring it would make the store say one thing and the allocator do another.
128
+ */
129
+ function blockFault(raw: unknown, index: number): string | null {
130
+ const at = `${RESERVATIONS_CONTROL_KEY}[${index}]`;
131
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return `${at} is not an object`;
132
+ const b = raw as Record<string, unknown>;
133
+ if (typeof b.owner !== "string" || b.owner.trim() === "") return `${at} has no owner`;
134
+ if (!isCount(b.from)) return `${at} (${String(b.owner)}) has no usable "from"`;
135
+ if (!isCount(b.to)) return `${at} (${String(b.owner)}) has no usable "to"`;
136
+ if ((b.to as number) < (b.from as number)) return `${at} (${String(b.owner)}) runs backwards`;
137
+ if ((b.to as number) >= FIXTURE_SC_FLOOR) {
138
+ return `${at} (${String(b.owner)}) reaches into the fixture range, which the allocator cannot honour`;
139
+ }
140
+ if (b.note !== undefined && typeof b.note !== "string") return `${at} (${String(b.owner)}) has a non-string note`;
141
+ return null;
142
+ }
143
+
144
+ /**
145
+ * Two blocks that overlap are a collision the store itself declares.
146
+ *
147
+ * This is the one failure mode a reservation file adds that a prompt did not
148
+ * have, so it is refused rather than merged: a store that hands the same id to
149
+ * two owners is strictly worse than no store, because the sessions reading it
150
+ * both believe they are separated.
151
+ */
152
+ function overlapFault(blocks: ScReservation[]): string | null {
153
+ const sorted = [...blocks].sort((a, b) => a.from - b.from);
154
+ for (let i = 1; i < sorted.length; i++) {
155
+ const prev = sorted[i - 1];
156
+ const cur = sorted[i];
157
+ if (cur.from <= prev.to) {
158
+ return `${prev.owner} (${prev.from}-${prev.to}) and ${cur.owner} (${cur.from}-${cur.to}) overlap`;
159
+ }
160
+ }
161
+ return null;
162
+ }
163
+
164
+ /**
165
+ * Read the store, naming which of the three states it is in.
166
+ *
167
+ * Never throws. The refusal belongs to the allocator, which is the thing with
168
+ * a number to withhold; a reader that threw would make `absent` and
169
+ * `unreadable` reach the caller the same way.
170
+ */
171
+ export function readScReservations(root: string): ScReservationReading {
172
+ const path = join(root, SC_RESERVATIONS_PATH);
173
+ if (!existsSync(path)) {
174
+ return { status: "absent", path, blocks: [], reason: `no reservation store at ${SC_RESERVATIONS_PATH}` };
175
+ }
176
+
177
+ let raw: string;
178
+ try {
179
+ raw = readFileSync(path, "utf-8");
180
+ } catch (err) {
181
+ return { status: "unreadable", path, blocks: [], reason: (err as Error).message };
182
+ }
183
+
184
+ let parsed: unknown;
185
+ try {
186
+ parsed = JSON.parse(raw);
187
+ } catch (err) {
188
+ return { status: "unreadable", path, blocks: [], reason: `invalid JSON: ${(err as Error).message}` };
189
+ }
190
+
191
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
192
+ return { status: "unreadable", path, blocks: [], reason: "the store is not a JSON object" };
193
+ }
194
+
195
+ // The control string. An object with no `reservations` key yields an empty
196
+ // block list through every other path in this function, and that empty list
197
+ // is indistinguishable from a store that reserves nothing — so it is checked
198
+ // before any empty result is believed.
199
+ const declared = (parsed as Record<string, unknown>)[RESERVATIONS_CONTROL_KEY];
200
+ if (declared === undefined) {
201
+ return {
202
+ status: "unreadable",
203
+ path,
204
+ blocks: [],
205
+ reason: `the store declares no "${RESERVATIONS_CONTROL_KEY}" key, so an empty reading would be a reading of nothing`,
206
+ };
207
+ }
208
+ if (!Array.isArray(declared)) {
209
+ return { status: "unreadable", path, blocks: [], reason: `"${RESERVATIONS_CONTROL_KEY}" is not an array` };
210
+ }
211
+
212
+ const faults = declared.map((b, i) => blockFault(b, i)).filter((f): f is string => f !== null);
213
+ if (faults.length > 0) {
214
+ return { status: "unreadable", path, blocks: [], reason: faults.join("; ") };
215
+ }
216
+
217
+ const blocks = declared.map(b => {
218
+ const r = b as Record<string, unknown>;
219
+ const block: ScReservation = { owner: r.owner as string, from: r.from as number, to: r.to as number };
220
+ if (typeof r.note === "string") block.note = r.note;
221
+ return block;
222
+ });
223
+
224
+ const overlap = overlapFault(blocks);
225
+ if (overlap !== null) {
226
+ return { status: "unreadable", path, blocks: [], reason: `the store declares an overlap: ${overlap}` };
227
+ }
228
+
229
+ return { status: "read", path, blocks };
230
+ }
231
+
232
+ /** How many ids the store declares occupied. `0` under every non-`read` status. */
233
+ export function reservedIdCount(blocks: ScReservation[]): number {
234
+ return blocks.reduce((n, b) => n + (b.to - b.from + 1), 0);
235
+ }
236
+
237
+ /** The highest id any block reaches, or `0` when nothing is reserved. */
238
+ export function reservedCeiling(blocks: ScReservation[]): number {
239
+ return blocks.reduce((n, b) => Math.max(n, b.to), 0);
240
+ }
241
+
242
+ /**
243
+ * The block reserved to `owner`, or `null`.
244
+ *
245
+ * Exact match on the owner string. A prefix or substring match is the tempting
246
+ * widening and it is the wrong one: `fix/725` matching `fix/725-followup`
247
+ * hands one block to two branches, which is the defect this file exists over.
248
+ */
249
+ export function reservationFor(blocks: ScReservation[], owner: string | null): ScReservation | null {
250
+ if (owner === null || owner.trim() === "") return null;
251
+ return blocks.find(b => b.owner === owner) ?? null;
252
+ }
253
+
254
+ /**
255
+ * The lowest id in `block` that nothing in `taken` already holds, or `null`
256
+ * when the block is spent.
257
+ *
258
+ * `null` is a refusal the caller has to say something about. Falling back to
259
+ * "allocate above the block" would quietly undo the separation the block was
260
+ * handed out to provide, on the one day it matters.
261
+ */
262
+ export function lowestFreeInBlock(block: ScReservation, taken: ReadonlySet<number>): number | null {
263
+ for (let n = block.from; n <= block.to; n++) if (!taken.has(n)) return n;
264
+ return null;
265
+ }
266
+
267
+ /**
268
+ * The branch name a CLI should look itself up by, or `null`.
269
+ *
270
+ * `null` on a detached HEAD or on anything that is not a git checkout, and
271
+ * never a guess: an owner this function invented would match no block, which
272
+ * routes the caller to the no-block path — above every reservation — rather
273
+ * than into somebody else's.
274
+ */
275
+ export function currentScOwner(root: string): string | null {
276
+ try {
277
+ const branch = execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
278
+ cwd: root,
279
+ encoding: "utf-8",
280
+ timeout: 30_000,
281
+ // Captured, not inherited — a `fatal: not a git repository` in the
282
+ // middle of a suite's output breaks every downstream reader of it (#60).
283
+ stdio: ["ignore", "pipe", "pipe"],
284
+ }).trim();
285
+ return branch === "" || branch === "HEAD" ? null : branch;
286
+ } catch {
287
+ return null;
288
+ }
289
+ }