rungate 0.8.2 → 0.8.3

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 (63) 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/DocHygiene.hook.ts +2 -1
  9. package/hooks/GateResultProtection.hook.ts +28 -7
  10. package/hooks/HookCurrency.hook.ts +48 -1
  11. package/hooks/VerifyPhaseLock.hook.ts +25 -8
  12. package/hooks/WorkflowStateGuard.hook.ts +24 -7
  13. package/lib/ai-review-jury.ts +725 -0
  14. package/lib/ai-review-rounds.ts +791 -4
  15. package/lib/ai-review-unmeasured.ts +361 -0
  16. package/lib/bash-write-guard.ts +1235 -102
  17. package/lib/cli-commands.ts +252 -11
  18. package/lib/closing-reference-audit.ts +163 -0
  19. package/lib/conformity.ts +12 -0
  20. package/lib/create-sc.ts +45 -12
  21. package/lib/derived-spec.ts +206 -0
  22. package/lib/file-claims.ts +335 -0
  23. package/lib/finding-arbiter.ts +502 -28
  24. package/lib/finding-jury.ts +48 -1
  25. package/lib/finding-pr-routing.ts +333 -0
  26. package/lib/frontmatter.ts +16 -0
  27. package/lib/gate-check-audit.ts +259 -0
  28. package/lib/generators/agents-md.ts +29 -0
  29. package/lib/github.ts +112 -7
  30. package/lib/hook-tree-currency.ts +494 -0
  31. package/lib/issue-closure-audit.ts +161 -14
  32. package/lib/issue-create-override.ts +53 -3
  33. package/lib/issue-filing-gate.ts +1073 -76
  34. package/lib/local-review-rounds.ts +523 -0
  35. package/lib/organize.ts +10 -0
  36. package/lib/project-state-shape.ts +56 -5
  37. package/lib/repo-path.ts +94 -0
  38. package/lib/report-provenance.ts +65 -3
  39. package/lib/risk-tier.ts +302 -0
  40. package/lib/rounds-to-pass.ts +274 -0
  41. package/lib/rule-row-drift.ts +199 -0
  42. package/lib/sc-claim-forms.ts +33 -5
  43. package/lib/sc-guard.ts +11 -1
  44. package/lib/sc-id-cross-tree.ts +17 -2
  45. package/lib/sc-ids.ts +71 -6
  46. package/lib/sc-reservations.ts +158 -14
  47. package/lib/scaffold/ai-review-findings.ts +1157 -18
  48. package/lib/scaffold/ai-review-step.ts +3798 -76
  49. package/lib/scaffold/ai-review-unmeasured-workflow.ts +243 -0
  50. package/lib/scaffold/owned-files.ts +14 -0
  51. package/lib/scaffold/steps.ts +83 -9
  52. package/lib/scratch-roots.ts +93 -3
  53. package/lib/spec-updater.ts +16 -0
  54. package/lib/validators/spec-validators.ts +28 -2
  55. package/package.json +2 -1
  56. package/scripts/ai-review-findings.ts +41 -1
  57. package/scripts/arbitrate-finding.ts +330 -12
  58. package/scripts/audit-specs.ts +225 -23
  59. package/scripts/create-sc.ts +11 -0
  60. package/scripts/detect-sc-drift.ts +10 -2
  61. package/scripts/record-ai-review-unmeasured.ts +370 -0
  62. package/scripts/split-spec.ts +12 -0
  63. package/scripts/sync-sc-status.ts +11 -0
@@ -0,0 +1,274 @@
1
+ /**
2
+ * Rounds-to-pass, reported beside recall (CRC-M11).
3
+ *
4
+ * Covers CRC-M11 (specs/CODE-REVIEW-CONVERGENCE-SPEC.md). The audit entry it
5
+ * answers reads: *"The round number is computed per run and retained nowhere.
6
+ * Nothing tracks rounds-to-pass beside recall."* The first half stopped being
7
+ * true when the ledger landed — `readLedger` returns a `LedgerRound[]` and
8
+ * #1405 taught it to state how many rounds it evicted. This module is the
9
+ * second half: turning those per-pull-request histories into the three
10
+ * numbers the spec's target is written in.
11
+ *
12
+ * Those numbers, from the source the spec is drawn from:
13
+ *
14
+ * | | before | after |
15
+ * |---|---|---|
16
+ * | passed after one round | 65% | 78% |
17
+ * | five or more rounds | 8.9% | 1.5% |
18
+ * | **mean rounds to pass** | **2.08** | **1.32** |
19
+ *
20
+ * ## The reason this is not a one-line average
21
+ *
22
+ * **Averaging over pull requests that passed is survivorship, and it biases
23
+ * the number in the flattering direction.** Every pull request still open at
24
+ * round 6 is precisely the kind this metric exists to find, and it is exactly
25
+ * the kind an average over merged pull requests drops. A review process that
26
+ * got worse — more rounds, more abandonment — can therefore show a FALLING
27
+ * mean rounds-to-pass, because the slow ones leave the population instead of
28
+ * raising the number.
29
+ *
30
+ * So the mean is reported over the ones that passed, because that is what
31
+ * "rounds to pass" means, and it is reported **beside the count that did not
32
+ * pass and the rounds they have spent**. A mean with no `stillOpen` beside it
33
+ * is not this metric, and `summariseRoundsToPass` has no way to emit one.
34
+ *
35
+ * `fiveOrMoreRate` is deliberately computed over the WHOLE measured
36
+ * population, passed or not. It is the tail statistic, and a tail measured
37
+ * only on survivors has had its tail cut off.
38
+ *
39
+ * ## What is UNMEASURED here, and why truncation is the sharp one
40
+ *
41
+ * A ledger that cannot say how many rounds it dropped gives a round count
42
+ * that is a **lower bound, not a number**. Counting it at its visible length
43
+ * silently understates every long history — the same direction as the
44
+ * survivorship bias above, which is why it is refused rather than estimated.
45
+ * `AI_REVIEW_TRUNCATION_STATED` with a `dropped` count IS measurable:
46
+ * `rounds.length + dropped` is the total, and that is what #1405 was for.
47
+ *
48
+ * An absent ledger and an unreadable one are different facts and neither is
49
+ * "one round" — `.claude/rules/config-access.md`'s *Silent Default
50
+ * Substitution*, in a metric where the default is the most common value.
51
+ *
52
+ * A round whose entry recorded `findings: null` (`measured: false`) still
53
+ * COUNTS as a round. The reviewer ran; what is unreadable is what it found,
54
+ * which is a question about recall and not about how many times round the
55
+ * loop went.
56
+ */
57
+
58
+ import {
59
+ AI_REVIEW_LEDGER_ABSENT,
60
+ AI_REVIEW_LEDGER_READ,
61
+ AI_REVIEW_LEDGER_UNREADABLE,
62
+ AI_REVIEW_TRUNCATION_STATED,
63
+ type LedgerReading,
64
+ } from "./ai-review-rounds";
65
+
66
+ /** The tail bucket the spec's target names. */
67
+ export const LONG_REVIEW_ROUNDS = 5;
68
+
69
+ export type RoundsRefusal =
70
+ /** No ledger comment on the pull request at all. */
71
+ | "LEDGER_ABSENT"
72
+ /** A ledger was found and could not be parsed. */
73
+ | "LEDGER_UNREADABLE"
74
+ /** The ledger cannot say how many rounds it evicted, so its length is a floor. */
75
+ | "ROUNDS_TRUNCATION_UNKNOWN"
76
+ /** The ledger parsed and holds no rounds, which is not a pull request reviewed once. */
77
+ | "ROUNDS_EMPTY"
78
+ /** A stated eviction count that is not a count. */
79
+ | "ROUNDS_DROPPED_UNREADABLE";
80
+
81
+ /** One pull request's history, as the caller read it. */
82
+ export interface PullRequestRounds {
83
+ readonly number: number;
84
+ readonly ledger: LedgerReading;
85
+ /**
86
+ * Did this pull request PASS — merge, or otherwise reach the state the
87
+ * rounds were spent getting to?
88
+ *
89
+ * Deliberately not `merged`: a consumer whose definition of passing is not
90
+ * "merged" should be able to say so without this module having an opinion
91
+ * about its workflow.
92
+ */
93
+ readonly passed: boolean;
94
+ }
95
+
96
+ export interface UnmeasuredPullRequest {
97
+ readonly number: number;
98
+ readonly refusal: RoundsRefusal;
99
+ readonly detail: string;
100
+ }
101
+
102
+ export interface RoundsToPassReading {
103
+ /**
104
+ * Mean rounds taken by the pull requests that PASSED. `null` when none did,
105
+ * or none was measurable — never 0, which is a real and different value.
106
+ */
107
+ readonly meanRoundsToPass: number | null;
108
+ /** Share of PASSED pull requests that took exactly one round. `null` if none. */
109
+ readonly passedAfterOneRoundRate: number | null;
110
+ /**
111
+ * Share of ALL measured pull requests at or over `LONG_REVIEW_ROUNDS`,
112
+ * passed or not. Over the whole population on purpose — see the docblock.
113
+ */
114
+ readonly fiveOrMoreRate: number | null;
115
+ /** How many measured pull requests passed, and how many have not. */
116
+ readonly passedCount: number;
117
+ readonly stillOpenCount: number;
118
+ /** Rounds spent so far by the measured pull requests that have NOT passed. */
119
+ readonly stillOpenRounds: readonly number[];
120
+ /** Round count -> how many measured pull requests took it, passed or not. */
121
+ readonly distribution: ReadonlyMap<number, number>;
122
+ /** Every pull request that could not be counted, and why. */
123
+ readonly unmeasured: readonly UnmeasuredPullRequest[];
124
+ }
125
+
126
+ /**
127
+ * How many rounds this pull request has had, or a refusal.
128
+ *
129
+ * Exported because it is the single decision site this module's battery
130
+ * mutates: every count in the summary comes through here, so a mutation of it
131
+ * is a mutation of the whole metric. A later caller that counts
132
+ * `rounds.length` itself bypasses the truncation refusal and the measurement
133
+ * goes quietly optimistic — `.claude/rules/checks-must-be-able-to-fail.md`.
134
+ */
135
+ export function roundsTaken(
136
+ pr: PullRequestRounds,
137
+ ): { rounds: number } | { refusal: RoundsRefusal; detail: string } {
138
+ const { ledger } = pr;
139
+
140
+ if (ledger.status === AI_REVIEW_LEDGER_ABSENT) {
141
+ return {
142
+ refusal: "LEDGER_ABSENT",
143
+ detail:
144
+ "No ledger comment on this pull request. That is not a pull request " +
145
+ "reviewed once — it is one nothing recorded, and the two differ by " +
146
+ "exactly the value this metric is most often wrong by.",
147
+ };
148
+ }
149
+ if (ledger.status === AI_REVIEW_LEDGER_UNREADABLE) {
150
+ return {
151
+ refusal: "LEDGER_UNREADABLE",
152
+ detail: `The ledger was found and could not be read: ${ledger.reason}`,
153
+ };
154
+ }
155
+
156
+ if (ledger.truncation.status !== AI_REVIEW_TRUNCATION_STATED) {
157
+ return {
158
+ refusal: "ROUNDS_TRUNCATION_UNKNOWN",
159
+ detail:
160
+ `The ledger holds ${ledger.rounds.length} round(s) and cannot say how ` +
161
+ `many it evicted (${ledger.truncation.reason}), so that figure is a ` +
162
+ `LOWER BOUND and not a count. Counting it would understate exactly ` +
163
+ `the long histories this metric exists to surface.`,
164
+ };
165
+ }
166
+
167
+ const { dropped } = ledger.truncation;
168
+ if (!Number.isInteger(dropped) || dropped < 0) {
169
+ return {
170
+ refusal: "ROUNDS_DROPPED_UNREADABLE",
171
+ detail:
172
+ `The ledger states an eviction count of ${JSON.stringify(dropped)}, ` +
173
+ `which is not a number of rounds.`,
174
+ };
175
+ }
176
+
177
+ const total = ledger.rounds.length + dropped;
178
+ if (total === 0) {
179
+ return {
180
+ refusal: "ROUNDS_EMPTY",
181
+ detail:
182
+ "The ledger parsed, states nothing was evicted, and holds no rounds. " +
183
+ "A pull request with no rounds has not passed review in one; it has " +
184
+ "not had one.",
185
+ };
186
+ }
187
+ return { rounds: total };
188
+ }
189
+
190
+ /**
191
+ * The three numbers the spec's target is written in, plus what it took to
192
+ * refuse the rest.
193
+ *
194
+ * An empty or wholly-unmeasurable population returns nulls, not zeros. A mean
195
+ * of nothing is not 0, and a rate over nothing is not 0% — both of those read
196
+ * as "perfect" on the dashboard this feeds.
197
+ */
198
+ export function summariseRoundsToPass(
199
+ prs: readonly PullRequestRounds[],
200
+ ): RoundsToPassReading {
201
+ const unmeasured: UnmeasuredPullRequest[] = [];
202
+ const distribution = new Map<number, number>();
203
+ const passedRounds: number[] = [];
204
+ const stillOpenRounds: number[] = [];
205
+
206
+ for (const pr of prs) {
207
+ const taken = roundsTaken(pr);
208
+ if ("refusal" in taken) {
209
+ unmeasured.push({ number: pr.number, refusal: taken.refusal, detail: taken.detail });
210
+ continue;
211
+ }
212
+ distribution.set(taken.rounds, (distribution.get(taken.rounds) ?? 0) + 1);
213
+ (pr.passed ? passedRounds : stillOpenRounds).push(taken.rounds);
214
+ }
215
+
216
+ const measured = passedRounds.length + stillOpenRounds.length;
217
+ const mean =
218
+ passedRounds.length === 0
219
+ ? null
220
+ : passedRounds.reduce((a, b) => a + b, 0) / passedRounds.length;
221
+
222
+ return {
223
+ meanRoundsToPass: mean,
224
+ passedAfterOneRoundRate:
225
+ passedRounds.length === 0
226
+ ? null
227
+ : passedRounds.filter(r => r === 1).length / passedRounds.length,
228
+ // Whole population, passed or not. A tail measured on survivors only has
229
+ // had its tail cut off — the one line of this module worth re-reading.
230
+ fiveOrMoreRate:
231
+ measured === 0
232
+ ? null
233
+ : [...passedRounds, ...stillOpenRounds].filter(r => r >= LONG_REVIEW_ROUNDS)
234
+ .length / measured,
235
+ passedCount: passedRounds.length,
236
+ stillOpenCount: stillOpenRounds.length,
237
+ stillOpenRounds,
238
+ distribution,
239
+ unmeasured,
240
+ };
241
+ }
242
+
243
+ /**
244
+ * The reading as lines, for the eval runner to print beside recall.
245
+ *
246
+ * The unmeasured count is on the FIRST line, not a footnote. A rounds-to-pass
247
+ * of 1.32 over four pull requests out of sixty is a different claim from the
248
+ * same number over sixty, and a reader who has to scroll to learn which will
249
+ * quote the one they saw first.
250
+ */
251
+ export function formatRoundsToPass(reading: RoundsToPassReading): string[] {
252
+ const pct = (v: number | null) => (v === null ? "UNMEASURED" : `${(v * 100).toFixed(1)}%`);
253
+ const num = (v: number | null) => (v === null ? "UNMEASURED" : v.toFixed(2));
254
+ const measured = reading.passedCount + reading.stillOpenCount;
255
+
256
+ const lines = [
257
+ `rounds-to-pass: measured ${measured}, unmeasured ${reading.unmeasured.length}` +
258
+ ` (passed ${reading.passedCount}, still open ${reading.stillOpenCount})`,
259
+ ` mean rounds to pass ${num(reading.meanRoundsToPass)} (target 1.32, from 2.08)`,
260
+ ` passed after 1 round ${pct(reading.passedAfterOneRoundRate)} (target 78%, from 65%)`,
261
+ ` ${LONG_REVIEW_ROUNDS}+ rounds ${pct(reading.fiveOrMoreRate)} ` +
262
+ `(target 1.5%, from 8.9%; over ALL measured, not only those that passed)`,
263
+ ];
264
+ if (reading.stillOpenCount > 0) {
265
+ lines.push(
266
+ ` still open at rounds: ${[...reading.stillOpenRounds].sort((a, b) => b - a).join(", ")}` +
267
+ ` — these are excluded from the mean BY DEFINITION and are why it flatters`,
268
+ );
269
+ }
270
+ for (const u of reading.unmeasured) {
271
+ lines.push(` #${u.number} UNMEASURED ${u.refusal}: ${u.detail}`);
272
+ }
273
+ return lines;
274
+ }
@@ -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",