rungate 0.8.2 → 0.8.4

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 (74) hide show
  1. package/bin/rungate.ts +11 -6
  2. package/config/prove-evidence.schema.json +21 -3
  3. package/gates/.gate-salt +1 -1
  4. package/gates/gate-executor.ts +153 -1
  5. package/gates/prove.test.ts +12 -6
  6. package/gates/schema.ts +69 -6
  7. package/gates/workflow.test.ts +12 -5
  8. package/hooks/BunTestPathGuard.hook.ts +106 -0
  9. package/hooks/DocHygiene.hook.ts +2 -1
  10. package/hooks/GateResultProtection.hook.ts +28 -7
  11. package/hooks/HookCurrency.hook.ts +48 -1
  12. package/hooks/TopLevelCdGuard.hook.ts +38 -6
  13. package/hooks/VerifyPhaseLock.hook.ts +25 -8
  14. package/hooks/WorkflowStateGuard.hook.ts +24 -7
  15. package/lib/ai-review-jury.ts +725 -0
  16. package/lib/ai-review-rounds.ts +791 -4
  17. package/lib/ai-review-unmeasured.ts +361 -0
  18. package/lib/bash-write-guard.ts +1235 -102
  19. package/lib/bun-test-paths.ts +253 -0
  20. package/lib/cli-commands.ts +252 -11
  21. package/lib/closing-reference-audit.ts +163 -0
  22. package/lib/conformity.ts +17 -1
  23. package/lib/create-sc.ts +45 -12
  24. package/lib/derived-spec.ts +206 -0
  25. package/lib/file-claims.ts +335 -0
  26. package/lib/finding-arbiter.ts +502 -28
  27. package/lib/finding-jury.ts +61 -5
  28. package/lib/finding-pr-routing.ts +333 -0
  29. package/lib/frontmatter.ts +16 -0
  30. package/lib/gate-check-audit.ts +646 -0
  31. package/lib/generators/agents-md.ts +29 -0
  32. package/lib/github.ts +112 -7
  33. package/lib/hook-tree-currency.ts +494 -0
  34. package/lib/issue-closure-audit.ts +161 -14
  35. package/lib/issue-create-override.ts +53 -3
  36. package/lib/issue-filing-gate.ts +1073 -76
  37. package/lib/local-review-rounds.ts +523 -0
  38. package/lib/organize.ts +21 -1
  39. package/lib/project-state-shape.ts +56 -5
  40. package/lib/release-preflight.ts +90 -1
  41. package/lib/repo-path.ts +94 -0
  42. package/lib/report-provenance.ts +218 -3
  43. package/lib/risk-tier.ts +302 -0
  44. package/lib/rounds-to-pass.ts +274 -0
  45. package/lib/rule-row-drift.ts +199 -0
  46. package/lib/sc-claim-forms.ts +33 -5
  47. package/lib/sc-guard.ts +11 -1
  48. package/lib/sc-id-cross-tree.ts +17 -2
  49. package/lib/sc-ids.ts +71 -6
  50. package/lib/sc-reservations.ts +158 -14
  51. package/lib/scaffold/ai-review-findings.ts +1369 -27
  52. package/lib/scaffold/ai-review-step.ts +4095 -119
  53. package/lib/scaffold/ai-review-unmeasured-workflow.ts +243 -0
  54. package/lib/scaffold/owned-files.ts +14 -0
  55. package/lib/scaffold/steps.ts +100 -9
  56. package/lib/scratch-roots.ts +93 -3
  57. package/lib/spec-updater.ts +22 -2
  58. package/lib/spec-write-ast.ts +728 -0
  59. package/lib/spec-write-sweep.ts +470 -0
  60. package/lib/test-suite-lock.ts +127 -13
  61. package/lib/ts-ast.ts +26 -0
  62. package/lib/validators/spec-validators.ts +36 -7
  63. package/lib/write-spec.ts +138 -0
  64. package/package.json +2 -1
  65. package/scripts/ai-review-findings.ts +41 -1
  66. package/scripts/arbitrate-finding.ts +330 -12
  67. package/scripts/audit-specs.ts +225 -24
  68. package/scripts/convert-spec.ts +7 -2
  69. package/scripts/create-sc.ts +14 -2
  70. package/scripts/create-spec.ts +5 -2
  71. package/scripts/detect-sc-drift.ts +10 -2
  72. package/scripts/record-ai-review-unmeasured.ts +370 -0
  73. package/scripts/split-spec.ts +17 -4
  74. package/scripts/sync-sc-status.ts +14 -2
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Which ROWS of a preserved rule file no longer match the generator (#1287).
3
+ *
4
+ * ## The defect this reports
5
+ *
6
+ * `.claude/rules/*.md` is preserved whole when a human has edited it (#370),
7
+ * and that is correct — the alternative truncated
8
+ * `checks-must-be-able-to-fail.md` from 262 lines to 65 and exited 0. But
9
+ * **preservation is per-file and staleness is per-row.** One hand-edited row
10
+ * freezes every other row in the file at whatever the generator emitted when
11
+ * it was first written, so a consumer who upgrades specifically to receive a
12
+ * correction does not receive it, and nothing says so.
13
+ *
14
+ * Measured on `pov-plugin`, 0.5.0 → 0.8.1, 2026-10-22. #781 replaced a
15
+ * hardcoded falsehood in `key-files.md` — the `PROJECT-STATE.md` row asserting
16
+ * *"generated from project-state.json — don't edit directly"* — with a real
17
+ * reading of the consumer's tree (`projectStateDerivation`). That consumer's
18
+ * reading is `NO_GENERATOR`: there is no generator, and `PROJECT-STATE.md` is
19
+ * the only copy of the session handoff. The upgrade shipped, the file was
20
+ * preserved, the false sentence survived, and a session that reads the row
21
+ * believes the file regenerates and leaves the handoff stale — the exact harm
22
+ * #781 existed to remove. The run said `PRESERVED (hand-edited since the
23
+ * harness wrote it)` and named no row.
24
+ *
25
+ * ## Why #1148's discriminator does not extend
26
+ *
27
+ * #1148 fixed this class for workflows: a `generated-sha` that VERIFIES proves
28
+ * the bytes on disk are the harness's own output, so preserving them against a
29
+ * newer generator protects no consumer intent, and the harness may overwrite.
30
+ *
31
+ * That discriminator answers the right question about the wrong unit, and it
32
+ * gets this case wrong in both halves:
33
+ *
34
+ * 1. **It is per-file and binary.** On the consumer above the file IS
35
+ * genuinely hand-edited — two rows were removed deliberately, with the
36
+ * reasons written into the file — so the sha does not verify, preservation
37
+ * is the *correct* per-file answer, and the stale row still ships. There is
38
+ * no setting of a whole-file bit that both keeps the hand edit and refreshes
39
+ * the row beside it.
40
+ * 2. **Workflows had a container; markdown does not.** #1148 could preserve
41
+ * per-unit because YAML hands it named, parseable, addressable blocks —
42
+ * `jobs:` keys. Markdown prose has no such container, which is exactly why
43
+ * rule files took the whole-file path in the first place.
44
+ *
45
+ * ## The unit, and what it is allowed to do
46
+ *
47
+ * A **markdown table row, addressed by its first cell.** That is the one
48
+ * construct in these files with a stable identity: every generated rule table
49
+ * leads with a file path, a command name, a spec filename or a strategy name,
50
+ * and rows can be reordered without changing it. It is checkable, and it is
51
+ * the granularity the harm actually has.
52
+ *
53
+ * It is used to REPORT and never to REWRITE, and the reason is a byte cost.
54
+ * Rewriting one row requires knowing whether the consumer authored its current
55
+ * text, and the whole-file sha cannot answer that — a row's provenance has to
56
+ * be *emitted into the file*. Measured on this repo at a 24-byte marker per
57
+ * row (`<!--g:0123456789abcdef-->`): 42 rows across the three un-scoped table
58
+ * rules is **1,008 bytes at launch**, and `harness-managed.md`'s 23 more take
59
+ * it to **1,560 at peak** — against 4,644 bytes of headroom at 93% of
60
+ * `SURFACE_BUDGET_BYTES`. A third of the remaining budget, paid by every agent
61
+ * on every run, to carry data only the scaffold reads. Reporting needs no
62
+ * provenance and costs **zero** bytes, because the address is the first cell,
63
+ * which is already in the file.
64
+ *
65
+ * So this reports a row that does not match current generator output. It does
66
+ * **not** claim to know which side changed it — it cannot, and saying so is
67
+ * the point. A row the consumer edited and a row the consumer never received
68
+ * are the same bytes from here, and a report that pretended otherwise would be
69
+ * a detector narrower than what it detects
70
+ * (`.claude/rules/checks-must-be-able-to-fail.md`).
71
+ *
72
+ * ## The asymmetry is deliberate
73
+ *
74
+ * Rows the generator emits are compared. Rows only the file has are **not**
75
+ * reported: the generator has no opinion about content a consumer added, and
76
+ * reporting it would make every hand-edited file noisy on every run — which is
77
+ * "report everything", and a fix that scores by reporting everything is not a
78
+ * fix.
79
+ */
80
+
81
+ /** One generated row the preserved file does not reproduce. */
82
+ export interface RowDriftReading {
83
+ /** Keys present on both sides whose remaining cells differ. */
84
+ changed: string[];
85
+ /** Keys the generator emits that the preserved file has no row for. */
86
+ missing: string[];
87
+ /**
88
+ * How many addressable rows the generator's output has.
89
+ *
90
+ * Zero is not "clean" — it is UNMEASURED at this granularity, and the report
91
+ * says so rather than implying a prose rule file was checked row by row. A
92
+ * reading that could not be taken is not one that passed
93
+ * (`.claude/rules/config-access.md`).
94
+ */
95
+ generatedRows: number;
96
+ }
97
+
98
+ const ROW = /^\s*\|(.*)\|\s*$/;
99
+ const SEPARATOR_CELL = /^:?-{3,}:?$/;
100
+
101
+ function cells(line: string): string[] | null {
102
+ const m = ROW.exec(line);
103
+ if (!m) return null;
104
+ const parts = m[1].split("|").map(c => c.trim());
105
+ if (parts.length < 2) return null;
106
+ // `|---|---|` is punctuation, not a row. Its first cell would otherwise
107
+ // become a key that every table in every file shares.
108
+ if (parts.every(c => SEPARATOR_CELL.test(c))) return null;
109
+ return parts;
110
+ }
111
+
112
+ /**
113
+ * The address of a row.
114
+ *
115
+ * Emphasis is stripped because a hand-edit that only backticks or bolds the
116
+ * key must not read as the generator's row vanishing and an unrelated one
117
+ * appearing — that would report two findings for zero changes in meaning, and
118
+ * both would be wrong.
119
+ */
120
+ export function rowKey(cell: string): string {
121
+ return cell.replace(/[`*_]/g, "").trim();
122
+ }
123
+
124
+ /** Rows keyed by first cell. A key may repeat, so the value is a list. */
125
+ export function tableRows(text: string): Map<string, string[]> {
126
+ const rows = new Map<string, string[]>();
127
+ for (const line of text.split("\n")) {
128
+ const c = cells(line);
129
+ if (c === null) continue;
130
+ const key = rowKey(c[0]);
131
+ if (key === "") continue;
132
+ const value = c.slice(1).join(" | ");
133
+ const bucket = rows.get(key);
134
+ if (bucket) bucket.push(value);
135
+ else rows.set(key, [value]);
136
+ }
137
+ return rows;
138
+ }
139
+
140
+ /**
141
+ * The single binding that decides which rows drifted.
142
+ *
143
+ * One exported predicate, for the reason `lib/rule-provenance.ts` gives about
144
+ * `decideRuleWrite`: a second site answering the same question would survive
145
+ * any mutation of this one and hold the case up for a reason unrelated to the
146
+ * mechanism working.
147
+ */
148
+ export function ruleRowDrift(existing: string, generated: string): RowDriftReading {
149
+ const have = tableRows(existing);
150
+ const want = tableRows(generated);
151
+
152
+ const changed: string[] = [];
153
+ const missing: string[] = [];
154
+ let generatedRows = 0;
155
+
156
+ for (const [key, wantValues] of want) {
157
+ generatedRows += wantValues.length;
158
+ const haveValues = have.get(key);
159
+ if (haveValues === undefined) {
160
+ missing.push(key);
161
+ continue;
162
+ }
163
+ // Multiset comparison rather than a single value: a duplicated key
164
+ // collapsing into one entry would silently drop a row from the reading.
165
+ const a = [...wantValues].sort();
166
+ const b = [...haveValues].sort();
167
+ if (a.length !== b.length || a.some((v, i) => v !== b[i])) changed.push(key);
168
+ }
169
+
170
+ return { changed, missing, generatedRows };
171
+ }
172
+
173
+ /**
174
+ * The clause the scaffold report appends to a `PRESERVED:` line.
175
+ *
176
+ * Separate from the reading so the wording can be asserted without the parser,
177
+ * and so there is one place that turns a reading into prose.
178
+ */
179
+ export function rowDriftClause(reading: RowDriftReading): string {
180
+ const { changed, missing, generatedRows } = reading;
181
+ if (generatedRows === 0) {
182
+ return "no table rows to compare, so no row-level reading was taken";
183
+ }
184
+ if (changed.length === 0 && missing.length === 0) {
185
+ return `all ${generatedRows} generated rows match`;
186
+ }
187
+ const parts: string[] = [];
188
+ if (changed.length > 0) {
189
+ parts.push(
190
+ `${changed.length} of ${generatedRows} generated rows do not match: ${changed.join(", ")}`,
191
+ );
192
+ }
193
+ if (missing.length > 0) {
194
+ parts.push(`${missing.length} generated rows are not in the file: ${missing.join(", ")}`);
195
+ }
196
+ // Which side changed a row is not knowable from here, and the clause says so
197
+ // rather than letting the reader assume the harness decided.
198
+ return `${parts.join("; ")} (your edit, or a correction this file never received)`;
199
+ }
@@ -46,6 +46,29 @@
46
46
  * `.claude/rules/checks-must-be-able-to-fail.md` says never to fail that way.
47
47
  */
48
48
 
49
+ import { TRACKED_ID_PREFIXES } from "./sc-ids";
50
+
51
+ /**
52
+ * The id shapes a claim form may name: every TRACKED criterion prefix, plus
53
+ * `AC` for an issue's own acceptance criteria (#1298).
54
+ *
55
+ * `AC` is here and is not in `TRACKED_ID_PREFIXES`, which is the distinction
56
+ * worth keeping: an `AC-` id is never a criterion anything ticks, but it does
57
+ * appear in the id runs these forms recognise — `// AC-2 / SC-516 / SC-517:`
58
+ * is one label, and dropping `AC` would stop the run parsing and lose the two
59
+ * credits after it.
60
+ *
61
+ * Built from the list rather than respelled, because respelling it is what
62
+ * made `CRC-` claimable in two forms of five: `covers` and `spec-ref` look
63
+ * for a VERB and credit whatever id follows, while `label`, `line` and
64
+ * `attribution` recognise the id itself and so carried their own copy of
65
+ * `(?:SC|AC)`. A prefix whose credit depends on how the author happened to
66
+ * phrase the comment is not tracked, it is lucky.
67
+ */
68
+ const CLAIM_ID = `(?:${[...TRACKED_ID_PREFIXES, "AC"]
69
+ .sort((a, b) => b.length - a.length)
70
+ .join("|")})-[A-Z]?\\d+`;
71
+
49
72
  /** A structural position that could only have been written to declare coverage. */
50
73
  export type ClaimForm =
51
74
  /** `covers`/`covering`/`coverage` within 60 chars before the id. */
@@ -99,10 +122,14 @@ const SPEC_REF_LINE = /^[\s*\/|─—-]*SPEC-REF\b/i;
99
122
  * `#173 — SC-587, SC-588, SC-589, SC-590.`, `#323 SC-6 —`, `#190 / SC-624:`.
100
123
  * An issue number before the ids does not make the line less of a heading.
101
124
  */
102
- const LEADING_ID_RUN = /^[\s*\/|─—-]*(?:#\d+\s*[\/|—–:-]*\s*)?(?:(?:SC|AC)-[A-Z]?\d+(?:\s*(?:\.\.+|,|\/|\||and|&|–|—|-)\s*)?)+/;
125
+ const LEADING_ID_RUN = new RegExp(
126
+ `^[\\s*/|─—-]*(?:#\\d+\\s*[/|—–:-]*\\s*)?(?:${CLAIM_ID}(?:\\s*(?:\\.\\.+|,|/|\\||and|&|–|—|-)\\s*)?)+`,
127
+ );
103
128
 
104
129
  /** The same run, but required to terminate in a colon — a label, not a list. */
105
- const LEADING_ID_LABEL = /^[\s*\/|─—-]*(?:#\d+\s*[\/|—–-]*\s*)?(?:(?:SC|AC)-[A-Z]?\d+[\s,\/|]*)+:/;
130
+ const LEADING_ID_LABEL = new RegExp(
131
+ `^[\\s*/|─—-]*(?:#\\d+\\s*[/|—–-]*\\s*)?(?:${CLAIM_ID}[\\s,/|]*)+:`,
132
+ );
106
133
 
107
134
  const LINE_START = /(?:^|\n)[\s*\/|─—-]*$/;
108
135
 
@@ -154,8 +181,9 @@ export function commentClaimForm(comment: string, at: number, id: string): Claim
154
181
  * is the self-reference this whole area keeps producing, and it was caught by
155
182
  * reading the diff of lost credits rather than by the rule itself.
156
183
  */
157
- const IDS_ONLY =
158
- /^[\s,\/|&+-]*(?:(?:#\d+|(?:SC|AC)-[A-Z]?\d+)(?:\s*(?:\.\.+|,|\/|\||&|and|–|—|-)\s*)?)+[\s.]*$/;
184
+ const IDS_ONLY = new RegExp(
185
+ `^[\\s,/|&+-]*(?:(?:#\\d+|${CLAIM_ID})(?:\\s*(?:\\.\\.+|,|/|\\||&|and|–|—|-)\\s*)?)+[\\s.]*$`,
186
+ );
159
187
 
160
188
  /**
161
189
  * A parenthetical that LABELS: opens with an id and a colon, then prose.
@@ -167,7 +195,7 @@ const IDS_ONLY =
167
195
  * `// The SC statement in a spec file: "SC-318: Something (behavioral)"`,
168
196
  * which is a QUOTED EXAMPLE of a spec line, not a claim about one.
169
197
  */
170
- const PAREN_LABEL = /^\s*(?:SC|AC)-[A-Z]?\d+\s*:/;
198
+ const PAREN_LABEL = new RegExp(`^\\s*${CLAIM_ID}\\s*:`);
171
199
 
172
200
  /**
173
201
  * A RANGE inside a parenthetical — `(SC-1930..SC-1948)`.
package/lib/sc-guard.ts CHANGED
@@ -15,6 +15,7 @@ import { join, dirname } from "path";
15
15
  import { fileURLToPath } from "url";
16
16
  import { spawnSync } from "child_process";
17
17
  import { parseFrontmatter, isMatchablePattern, isBehavioralSC } from "./conformity";
18
+ import { SC_ID_SOURCE } from "./sc-ids";
18
19
  import type { ParsedSC } from "./conformity";
19
20
 
20
21
  // ── Types ──────────────────────────────────────────────────
@@ -34,7 +35,16 @@ export interface SCValidationResult {
34
35
 
35
36
  // ── SC Detection ───────────────────────────────────────────
36
37
 
37
- const SC_LINE_PATTERN = /^- \[ \] (SC-\w+):\s*(.+)$/gm;
38
+ /**
39
+ * An unchecked declaration, built from `SC_ID_SOURCE` (#1298).
40
+ *
41
+ * Was `SC-\w+`, which is wrong in both directions at once: wider than the
42
+ * notation, so `SC-guard` and `SC-TEST` in prose read as new criteria, and
43
+ * narrower than the namespace, so a `CRC-` criterion arriving in a spec edit
44
+ * was never validated against the matcher registry at all. The shared source
45
+ * is the only spelling that is neither.
46
+ */
47
+ const SC_LINE_PATTERN = new RegExp(`^- \\[ \\] (${SC_ID_SOURCE}):\\s*(.+)$`, "gm");
38
48
 
39
49
  /**
40
50
  * Extract all unchecked SC lines from content.
@@ -55,7 +55,12 @@ import { execFileSync, spawnSync } from "child_process";
55
55
  import { existsSync, readdirSync, readFileSync, statSync } from "fs";
56
56
  import { join } from "path";
57
57
 
58
- import { isFixtureScId, scDeclarationPattern, scHeadingDeclarationPattern } from "./sc-ids";
58
+ import {
59
+ isFixtureScId,
60
+ scDeclarationPattern,
61
+ scHeadingDeclarationPattern,
62
+ TRACKED_ID_PREFIXES,
63
+ } from "./sc-ids";
59
64
 
60
65
  /**
61
66
  * One place ids were looked for, and whether the look succeeded.
@@ -274,7 +279,17 @@ export function idsInRefs(root: string): { ids: string[]; refs: number; grepped:
274
279
  // Declaration-shaped lines only — a checkbox or a heading. Every
275
280
  // mention would be correct and is ~30x the output, which is how the
276
281
  // first version hit the buffer limit.
277
- "^(- \\[.\\] |#+ )SC-[A-Z]?[0-9]+",
282
+ //
283
+ // The PREFIX comes from `TRACKED_ID_PREFIXES`, and the id's shape is
284
+ // deliberately NOT restated here (#1298). This is a prefilter for the
285
+ // two declaration patterns applied to its output below, so the only
286
+ // error that costs anything is being NARROWER than they are — a
287
+ // dropped line never reaches `matchAll` and reads as an id nobody
288
+ // declared (`.claude/rules/checks-must-be-able-to-fail.md`, second
289
+ // shape). Wider is free: `- [ ] SC-foo:` survives the grep and the
290
+ // parsers reject it. Spelled as a POSIX ERE, which `git grep -E`
291
+ // takes and which has neither `(?:` nor `\d`.
292
+ `^(- \\[.\\] |#+ )(${TRACKED_ID_PREFIXES.join("|")})-`,
278
293
  ...refs.slice(i, i + 100),
279
294
  "--",
280
295
  "specs/*.md",
package/lib/sc-ids.ts CHANGED
@@ -77,14 +77,60 @@ export interface ScDeclaration {
77
77
  }
78
78
 
79
79
  /**
80
- * The id itself: `SC-`, an optional uppercase class letter, digits.
80
+ * The prefixes whose ids are TRACKED CRITERIA (#1298).
81
+ *
82
+ * `SC` was the only one for as long as there was only one namespace. The
83
+ * second arrived with `specs/CODE-REVIEW-CONVERGENCE-SPEC.md`, whose 56
84
+ * criteria are `CRC-A1`..`CRC-N5`, and the reason it is a second PREFIX
85
+ * rather than 56 more `SC-` ids is the class letter: in this namespace a
86
+ * letter means ANTI-criterion (`isAntiCriterion`, and SPEC-TEMPLATE.md's
87
+ * `- [ ] SC-A1: [anti-criterion — must NOT happen]`), so all 56 would have
88
+ * read as things that must not happen. In the convergence spec the letter is
89
+ * a SECTION. Same character, different fact, so: different prefix.
90
+ *
91
+ * ## This list is the only thing that decides
92
+ *
93
+ * Adding a prefix here is the whole of adding a namespace, because every
94
+ * pattern below is built from `SC_ID_SOURCE` and `SC_ID_SOURCE` is built from
95
+ * this. That is #330's property — four files parsing ids four ways is what
96
+ * made an anti-criterion a declaration to one reader and invisible to three —
97
+ * extended one axis further.
98
+ *
99
+ * ## What it deliberately does NOT reach
100
+ *
101
+ * `isAntiCriterion` and `isIssueShaped` stay spelled `SC-` by hand, and each
102
+ * says why at its own definition. They are not readers of the namespace; they
103
+ * are statements about what a character MEANS inside one. Building them from
104
+ * this list is the cheapest wrong fix here: it parses all 56 criteria — so a
105
+ * parse-only test goes green — and makes every one of them an anti-criterion,
106
+ * which is the exact bug the rename was done to avoid. `crossSpecCollisions`
107
+ * and `crossFormCollisions` both filter anti-criteria OUT, so the 56 would
108
+ * also have become the only ids in the tree two specs could silently share.
109
+ * `test/tracked-id-prefixes.test.ts` holds that pair apart.
110
+ */
111
+ export const TRACKED_ID_PREFIXES: readonly string[] = ["SC", "CRC"];
112
+
113
+ /**
114
+ * The prefixes as a regex alternation, longest first.
81
115
  *
82
- * Not `\w+`. A class letter is part of the notation (`A` for anti-criterion);
83
- * an arbitrary word is a prose fragment. Kept as a source string so the
84
- * declaration and mention patterns are built from one definition and cannot
85
- * drift — the drift is what #330 is about.
116
+ * Alternation is first-match, not longest-match, so `(?:S|SC)-1` can never
117
+ * reach its second branch. Nothing in the list today is a prefix of anything
118
+ * else in it; sorting is what keeps that from mattering when one is.
86
119
  */
87
- export const SC_ID_SOURCE = "SC-[A-Z]?\\d+";
120
+ export const TRACKED_ID_PREFIX_SOURCE = `(?:${[...TRACKED_ID_PREFIXES]
121
+ .sort((a, b) => b.length - a.length)
122
+ .join("|")})`;
123
+
124
+ /**
125
+ * The id itself: a tracked prefix, an optional uppercase class letter, digits.
126
+ *
127
+ * Not `\w+`. A class letter is part of the notation (`A` for anti-criterion in
128
+ * the `SC-` namespace, a section in `CRC-`); an arbitrary word is a prose
129
+ * fragment. Kept as a source string so the declaration and mention patterns
130
+ * are built from one definition and cannot drift — the drift is what #330 is
131
+ * about.
132
+ */
133
+ export const SC_ID_SOURCE = `${TRACKED_ID_PREFIX_SOURCE}-[A-Z]?\\d+`;
88
134
 
89
135
  /** A declared id: a checklist line opening with one. Not a mention. */
90
136
  export function scDeclarationPattern(): RegExp {
@@ -123,6 +169,16 @@ export function oneScMentionPattern(id: string): RegExp {
123
169
  * Anti-criteria are numbered per spec, so the id alone does not identify one.
124
170
  * `specs/SPEC-TEMPLATE.md` ships `- [ ] SC-A1: [anti-criterion — must NOT
125
171
  * happen]`, which is where every spec's A1 comes from.
172
+ *
173
+ * **`SC-` by hand, and it must not be built from `TRACKED_ID_PREFIXES`**
174
+ * (#1298). This is not a reader of the id pattern — it is a statement about
175
+ * what a class letter means in ONE namespace, and the two namespaces disagree
176
+ * about exactly that. `CRC-B3`'s letter is the convergence spec's section B;
177
+ * reading it as "must NOT happen" inverts the criterion, and the three
178
+ * consumers make that expensive rather than merely wrong: `ambiguityOf`
179
+ * returns `"per-spec"`, and `crossSpecCollisions` and `crossFormCollisions`
180
+ * filter the id out before looking for duplicates, so two specs could declare
181
+ * the same `CRC-` id with nothing to notice.
126
182
  */
127
183
  export function isAntiCriterion(id: string): boolean {
128
184
  return /^SC-[A-Z]\d+$/.test(id);
@@ -135,6 +191,11 @@ export function isAntiCriterion(id: string): boolean {
135
191
  * produces is `SC-1`..`SC-9` — and all nine are declared by
136
192
  * `specs/bootstrap-data-flow/success-criteria.md`. The overlap is exactly the
137
193
  * single-digit numerics; `SC-640` cannot be an issue's 640th criterion.
194
+ *
195
+ * `SC-` by hand for the same reason as `isAntiCriterion`: the collision is
196
+ * with how the HARNESS numbers an issue's own criteria, and it numbers them
197
+ * `SC-1`..`SC-9`. Nothing produces a bare `CRC-1` by accident, so a tracked
198
+ * prefix added here would qualify criteria that are not ambiguous.
138
199
  */
139
200
  export function isIssueShaped(id: string): boolean {
140
201
  return /^SC-\d$/.test(id);
@@ -179,6 +240,10 @@ export function isFixtureScId(id: string): boolean {
179
240
  const n = Number(id.replace(/^SC-/, ""));
180
241
  return Number.isInteger(n) && n >= FIXTURE_SC_FLOOR;
181
242
  }
243
+ // `SC-` only, and so is `scMentionsInSource` below. Both serve the ALLOCATOR,
244
+ // and `scripts/create-sc.ts` allocates in the `SC-` namespace alone — a `CRC-`
245
+ // id is hand-numbered inside one spec's section. Widening either without an
246
+ // allocator to protect would add a reading nothing consumes (#1298).
182
247
 
183
248
  /**
184
249
  * The registry: which spec files declare each id.
@@ -91,6 +91,43 @@ export const RESERVATIONS_CONTROL_KEY = "reservations";
91
91
  /** The message prefix every refusal out of this module and its allocator uses. */
92
92
  export const RESERVATION_REFUSAL = "SC reservation store is present and unreadable";
93
93
 
94
+ /**
95
+ * The namespace an untagged block's integers belong to.
96
+ *
97
+ * Every entry written before #1363 is an SC claim, so this is the value an
98
+ * absent field resolves to and the reason the field is optional at all.
99
+ * Absent is the one case with a declared default; a field that is PRESENT
100
+ * and unusable is refused (`blockFault`), because only absence was ever
101
+ * given a meaning (`.claude/rules/config-access.md`, Silent Default
102
+ * Substitution).
103
+ */
104
+ export const SC_NAMESPACE = "SC";
105
+
106
+ /**
107
+ * Every namespace this store can hold, and the only strings `namespace` may
108
+ * take.
109
+ *
110
+ * A closed set, and an unknown value is a refusal rather than a block the
111
+ * reader passes through: the whole defect in #1363 is a claim the store
112
+ * accepted and the allocator read as a claim about something else, so a
113
+ * namespace nobody has taught the allocator about must not be storable
114
+ * either. Adding one is an edit here plus a line in
115
+ * `.claude/rules/parallel-sessions.md`, which is the point — the set of
116
+ * namespaces is a thing sessions agree on, not a thing an entry invents.
117
+ *
118
+ * | Namespace | Ids | Allocated by |
119
+ * |---|---|---|
120
+ * | `SC` | `SC-<n>` success criteria | `lib/create-sc.ts` |
121
+ * | `FG` | `FG-<n>` blocks in `test/issue-filing-gate.test.ts` | by hand |
122
+ * | `AR` | `AR-<n>` blocks in `test/finding-arbiter.test.ts` | by hand |
123
+ *
124
+ * `FG` and `AR` have no allocator. That is exactly why they need the
125
+ * registry: they are chosen by eyeballing headroom above the highest id in
126
+ * the file, by every agent that adds a block, which is the third method
127
+ * `.claude/rules/parallel-sessions.md` names as an allocation.
128
+ */
129
+ export const RESERVATION_NAMESPACES: readonly string[] = [SC_NAMESPACE, "FG", "AR"];
130
+
94
131
  /** One declared block. `from` and `to` are inclusive. */
95
132
  export interface ScReservation {
96
133
  /** Branch name or issue ref. The thing another session can look you up by. */
@@ -98,6 +135,43 @@ export interface ScReservation {
98
135
  from: number;
99
136
  to: number;
100
137
  note?: string;
138
+ /**
139
+ * Which ids these integers claim. Absent means {@link SC_NAMESPACE}.
140
+ *
141
+ * Optional on the interface so a caller can build an SC block without
142
+ * saying so, and ALWAYS populated on a block that came out of
143
+ * {@link readScReservations} — see {@link ResolvedScReservation}.
144
+ */
145
+ namespace?: string;
146
+ }
147
+
148
+ /**
149
+ * A block as the reader hands it back: the namespace is resolved, never absent.
150
+ *
151
+ * The distinction is load-bearing rather than cosmetic. `namespace?: string`
152
+ * invites a call site to read `b.namespace` and compare it against `"SC"`,
153
+ * which is `false` for every entry written before #1363 — the fail-open this
154
+ * issue is about, arriving in the code that fixes it.
155
+ */
156
+ export type ResolvedScReservation = ScReservation & { namespace: string };
157
+
158
+ /**
159
+ * The namespace a block claims, resolving the documented default.
160
+ *
161
+ * One binding. A second site that spelled `b.namespace ?? "SC"` would
162
+ * survive any mutation of this one (`.claude/rules/checks-must-be-able-to-fail.md`,
163
+ * fourth shape).
164
+ */
165
+ export function namespaceOf(block: { namespace?: string }): string {
166
+ return block.namespace ?? SC_NAMESPACE;
167
+ }
168
+
169
+ /** The blocks claiming ids in one namespace, with the default resolved. */
170
+ export function blocksInNamespace(
171
+ blocks: readonly ScReservation[],
172
+ namespace: string,
173
+ ): ScReservation[] {
174
+ return blocks.filter(b => namespaceOf(b) === namespace);
101
175
  }
102
176
 
103
177
  export type ScReservationStatus = "read" | "absent" | "unreadable";
@@ -107,7 +181,7 @@ export interface ScReservationReading {
107
181
  /** Absolute path the reading was taken from, whether or not it existed. */
108
182
  path: string;
109
183
  /** Empty under every status except a `read` of a store that declares blocks. */
110
- blocks: ScReservation[];
184
+ blocks: ResolvedScReservation[];
111
185
  /** Why it could not be read, or why the store is absent. Absent on a clean read. */
112
186
  reason?: string;
113
187
  }
@@ -134,7 +208,29 @@ function blockFault(raw: unknown, index: number): string | null {
134
208
  if (!isCount(b.from)) return `${at} (${String(b.owner)}) has no usable "from"`;
135
209
  if (!isCount(b.to)) return `${at} (${String(b.owner)}) has no usable "to"`;
136
210
  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) {
211
+ // PRESENT and unusable is refused; absent resolves to SC. Only absence was
212
+ // ever given a meaning, so defaulting a `7` or a `"QQ"` would be the store
213
+ // accepting a claim and the allocator reading it as a claim about something
214
+ // else — the defect this field exists to end (#1363).
215
+ let namespace: string | undefined;
216
+ if (b.namespace !== undefined) {
217
+ if (typeof b.namespace !== "string") {
218
+ return `${at} (${String(b.owner)}) has a non-string "namespace"`;
219
+ }
220
+ if (!RESERVATION_NAMESPACES.includes(b.namespace)) {
221
+ return (
222
+ `${at} (${String(b.owner)}) declares the unknown namespace "${b.namespace}" — ` +
223
+ `this store holds ${RESERVATION_NAMESPACES.join(", ")}`
224
+ );
225
+ }
226
+ namespace = b.namespace;
227
+ }
228
+ // The fixture floor is an SC rule and is applied only to SC blocks. The
229
+ // 9000s exist because `nextSCNumber` drops fixture ids on purpose; no other
230
+ // namespace has an allocator, a fixture range, or anything that would make
231
+ // a high integer unhonourable. Applying an SC-specific bound to an FG block
232
+ // is the same category error as reading its integers as SC ids.
233
+ if (namespaceOf({ namespace }) === SC_NAMESPACE && (b.to as number) >= FIXTURE_SC_FLOOR) {
138
234
  return `${at} (${String(b.owner)}) reaches into the fixture range, which the allocator cannot honour`;
139
235
  }
140
236
  if (b.note !== undefined && typeof b.note !== "string") return `${at} (${String(b.owner)}) has a non-string note`;
@@ -149,13 +245,24 @@ function blockFault(raw: unknown, index: number): string | null {
149
245
  * two owners is strictly worse than no store, because the sessions reading it
150
246
  * both believe they are separated.
151
247
  */
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`;
248
+ function overlapFault(blocks: readonly ResolvedScReservation[]): string | null {
249
+ // WITHIN a namespace, never across one. `FG-45..60` and `SC-45..60` share
250
+ // their integers and claim nothing in common, so comparing them would make
251
+ // the first correctly-declared FG block refuse the whole store — and a
252
+ // refused store refuses every allocation in the repository. Grouping first
253
+ // is what lets the check keep its teeth while the store holds more than one
254
+ // kind of id (#1363).
255
+ for (const namespace of new Set(blocks.map(namespaceOf))) {
256
+ const sorted = blocksInNamespace(blocks, namespace).sort((a, b) => a.from - b.from);
257
+ for (let i = 1; i < sorted.length; i++) {
258
+ const prev = sorted[i - 1];
259
+ const cur = sorted[i];
260
+ if (cur.from <= prev.to) {
261
+ return (
262
+ `${namespace}: ${prev.owner} (${prev.from}-${prev.to}) and ` +
263
+ `${cur.owner} (${cur.from}-${cur.to}) overlap`
264
+ );
265
+ }
159
266
  }
160
267
  }
161
268
  return null;
@@ -214,9 +321,20 @@ export function readScReservations(root: string): ScReservationReading {
214
321
  return { status: "unreadable", path, blocks: [], reason: faults.join("; ") };
215
322
  }
216
323
 
324
+ // The namespace is RESOLVED here, once, so no downstream reader has to
325
+ // remember that an absent field means SC. Every block that leaves this
326
+ // function carries a concrete namespace.
217
327
  const blocks = declared.map(b => {
218
328
  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 };
329
+ // `blockFault` has already refused anything that is neither absent nor a
330
+ // known string, so the narrowing here cannot silently widen the set.
331
+ const declaredNs = typeof r.namespace === "string" ? r.namespace : undefined;
332
+ const block: ResolvedScReservation = {
333
+ owner: r.owner as string,
334
+ from: r.from as number,
335
+ to: r.to as number,
336
+ namespace: namespaceOf({ namespace: declaredNs }),
337
+ };
220
338
  if (typeof r.note === "string") block.note = r.note;
221
339
  return block;
222
340
  });
@@ -240,15 +358,41 @@ export function reservedCeiling(blocks: ScReservation[]): number {
240
358
  }
241
359
 
242
360
  /**
243
- * The block reserved to `owner`, or `null`.
361
+ * EVERY block `owner` holds in `blocks`, in declaration order. Possibly none.
244
362
  *
245
363
  * Exact match on the owner string. A prefix or substring match is the tempting
246
364
  * widening and it is the wrong one: `fix/725` matching `fix/725-followup`
247
365
  * hands one block to two branches, which is the defect this file exists over.
366
+ *
367
+ * **Plural because an owner genuinely holds more than one block** (#1541), and
368
+ * this function selects nothing on the caller's behalf. It was singular until
369
+ * 2026-10-24 and returned `blocks.find(...)` — the FIRST match — which made it
370
+ * a function that reads as broken on its own and is saved by its caller:
371
+ * nothing in it says which of an owner's blocks you are getting, or that there
372
+ * might be more. Three readers reached three different wrong conclusions about
373
+ * it in one day, including that a store with two entries under one owner was
374
+ * malformed. It is not: a branch needing ids in two namespaces declares two
375
+ * entries, which is the arrangement `.claude/rules/parallel-sessions.md` shows,
376
+ * and two DISJOINT blocks in ONE namespace are not refused either.
377
+ *
378
+ * So the narrowing belongs to the caller, visibly, and both do it differently
379
+ * on purpose:
380
+ *
381
+ * - `allocateAgainstReservations` filters to `SC` first and then walks what
382
+ * this returns in order, so an owner whose first block is spent is handed
383
+ * its second instead of a refusal.
384
+ * - `test/sc-fixture-namespace.test.ts` passes the whole store, because its
385
+ * question is whether the probe owner holds a block in ANY namespace.
386
+ *
387
+ * Neither is expressible against a singular lookup without the caller knowing
388
+ * something this signature does not tell it. Do not re-add a `namespace`
389
+ * parameter to recover the old shape: the filter would then exist here AND in
390
+ * the allocator, which is two deciders answering one question — a mutation of
391
+ * either leaves the other holding every case up.
248
392
  */
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;
393
+ export function reservationsFor(blocks: ScReservation[], owner: string | null): ScReservation[] {
394
+ if (owner === null || owner.trim() === "") return [];
395
+ return blocks.filter(b => b.owner === owner);
252
396
  }
253
397
 
254
398
  /**