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
@@ -8,21 +8,43 @@
8
8
  *
9
9
  * Thin CLI consumer — core logic exported for testing.
10
10
  */
11
- import { readFileSync, writeFileSync, readdirSync, existsSync } from "fs";
11
+ import { readFileSync, writeFileSync, existsSync } from "fs";
12
12
  import { join, dirname } from "path";
13
13
  import { fileURLToPath } from "url";
14
14
  import {
15
15
  parseFrontmatter,
16
16
  matchPattern,
17
17
  isBehavioralSC,
18
- type ParsedSC,
18
+ type ExtractedSC,
19
19
  } from "../lib/conformity";
20
+ import { parseScDeclarations } from "../lib/sc-ids";
21
+ import { collectSpecFiles } from "../lib/spec-files";
22
+ import { skipLine, type DerivedReading } from "../lib/derived-spec";
23
+ import { maySpecBeWritten, writeSpec } from "../lib/write-spec";
20
24
 
21
25
  // ── Types ─────────────────────────────────────────────────────
22
26
 
27
+ /**
28
+ * `total` is EVERY criterion the spec declares. `ticked` is how many of those
29
+ * are already done, and `matched`/`unmatched`/`behavioral` partition the
30
+ * UNTICKED ones only, so:
31
+ *
32
+ * total === ticked + matched + unmatched + behavioral
33
+ *
34
+ * The split is deliberate rather than incidental. Those three answer "what
35
+ * open work can the conformity engine bind?", which is a question about
36
+ * criteria nobody has satisfied yet. `unmatched` feeds `strictUnmatched`, the
37
+ * exit code and the `--fix` candidate set, so folding 1,443 ticked criteria
38
+ * into it would turn a number that means "open work the engine cannot bind"
39
+ * into one that means nothing. Whether a TICKED criterion is covered is a
40
+ * different question with a different owner — `uncoveredTickedScs` in
41
+ * `lib/sc-cover.ts`.
42
+ */
23
43
  export interface SpecAuditResult {
24
44
  specFile: string;
25
45
  total: number;
46
+ /** Declared `- [x]`. Reported, and never a rewrite candidate. */
47
+ ticked: number;
26
48
  matched: number;
27
49
  unmatched: number;
28
50
  behavioral: number;
@@ -54,14 +76,37 @@ export interface RewriteEntry {
54
76
  kept?: string;
55
77
  }
56
78
 
79
+ /**
80
+ * A spec `--fix` declined to write because a generator owns it (#1286).
81
+ *
82
+ * Separate from `RewriteEntry.kept`, which records a CRITERION left alone
83
+ * inside a file that was still written. This records a FILE that was not
84
+ * opened for writing at all, so a caller cannot report it as `UPDATED:`.
85
+ */
86
+ export interface SkippedSpec {
87
+ specFile: string;
88
+ reading: DerivedReading;
89
+ /** The one-line refusal, naming the file and why. */
90
+ message: string;
91
+ /** How many criteria would have been edited had the file been writable. */
92
+ wouldHaveEdited: number;
93
+ }
94
+
57
95
  export interface AuditResult {
58
96
  specs: SpecAuditResult[];
59
97
  totalSCs: number;
98
+ totalTicked: number;
60
99
  totalMatched: number;
61
100
  totalUnmatched: number;
62
101
  totalBehavioral: number;
63
102
  strictUnmatched: number;
64
103
  rewrites?: RewriteEntry[];
104
+ /**
105
+ * Always present in fix mode, and empty is a reading rather than an
106
+ * absence — a `--fix` that skipped a file silently is the same defect as
107
+ * one that wrote it silently.
108
+ */
109
+ skipped: SkippedSpec[];
65
110
  }
66
111
 
67
112
  // ── Registry loading ──────────────────────────────────────────
@@ -90,14 +135,67 @@ function loadRegistry(): RegistryEntry[] {
90
135
 
91
136
  // ── SC extraction ─────────────────────────────────────────────
92
137
 
93
- function extractSCs(content: string, specFile: string): ParsedSC[] {
94
- const scs: ParsedSC[] = [];
95
- const pattern = /^- \[ \] (SC-\w+):\s*(.+)$/gm;
96
- let match;
97
- while ((match = pattern.exec(content)) !== null) {
98
- scs.push({ id: match[1], statement: match[2].trim(), specFile });
99
- }
100
- return scs;
138
+ /**
139
+ * Every criterion a spec declares, from the SHARED binding.
140
+ *
141
+ * This was `/^- \[ \] (SC-\w+):\s*(.+)$/gm` — a reporter carrying its own,
142
+ * narrower spelling of a thing `lib/sc-ids.ts` already decides. That is the
143
+ * fourth shape in `.claude/rules/checks-must-be-able-to-fail.md` pointing the
144
+ * wrong way: two deciders, disagreeing, with the reporter the one people read.
145
+ * It was narrow in two directions at once.
146
+ *
147
+ * - **`SC-\w+` cannot see a `CRC-` id.** `TRACKED_ID_PREFIXES` has held two
148
+ * namespaces since #1313. `specs/CODE-REVIEW-CONVERGENCE-SPEC.md` declares
149
+ * 56 criteria and is marked `compliance: strict`, and this reported
150
+ * `total 0` for it. That is worse than crashing: silence is visibly broken,
151
+ * `0` reads as "nothing to do" and stops anyone looking.
152
+ * - **The `- [ ] ` literal cannot see a TICKED criterion**, in any namespace.
153
+ * So the `SC-` side had been under-reporting for its whole life and nobody
154
+ * noticed, because the number it printed was plausible. Measured on this
155
+ * tree: **66 reported against 1,669 declared.** It was showing 4% of the
156
+ * corpus.
157
+ *
158
+ * `parseScDeclarations` is the one owner, so this reporter, the status
159
+ * flipper, the drift gate and the collision detectors now agree about what a
160
+ * criterion is by construction rather than by four regexes happening to match.
161
+ */
162
+ function extractSCs(content: string, specFile: string): ExtractedSC[] {
163
+ return parseScDeclarations(content, specFile).map((d) => ({
164
+ id: d.id,
165
+ statement: d.statement,
166
+ specFile,
167
+ checked: d.checked,
168
+ }));
169
+ }
170
+
171
+ /**
172
+ * The population `--fix` may rewrite — and it is NOT the population this
173
+ * reporter reads.
174
+ *
175
+ * Reporting a criterion costs a row in a table. Rewriting one edits a spec,
176
+ * and #1286 is open about `--fix` damaging a file it should not have touched.
177
+ * Different decisions, different risk, so the reporter widened and the writer
178
+ * did not. Each clause subtracts a population this change would otherwise
179
+ * have handed the rewriter as a side effect:
180
+ *
181
+ * | clause | what it holds back, measured on this tree |
182
+ * |---|---|
183
+ * | `!checked` | 1,443 ticked criteria — finished work |
184
+ * | `SC-` prefix | 55 unmatched `CRC-` criteria, in a spec being bound concurrently |
185
+ * | top-level | 91 unmatched criteria in a split spec under `specs/` |
186
+ *
187
+ * All three live here rather than being enforced upstream, because a clause
188
+ * split across two sites is two deciders for one question: mutate either and
189
+ * the other holds the case up.
190
+ *
191
+ * This is a SCOPE, not a second opinion about what a criterion is —
192
+ * `extractSCs` remains the only thing that decides that. Deleting a clause is
193
+ * a deliberate one-line widening whenever somebody wants it, and
194
+ * `test/audit-specs-blindness.test.ts` AB-4 measures that the set it selects
195
+ * is the pre-change population exactly.
196
+ */
197
+ export function isRewriteCandidate(sc: ExtractedSC): boolean {
198
+ return !sc.checked && sc.id.startsWith("SC-") && !sc.specFile.includes("/");
101
199
  }
102
200
 
103
201
  // ── Closest pattern matching for rewrites ─────────────────────
@@ -596,12 +694,34 @@ export function auditSpecs(
596
694
  const specsDir = join(root, "specs");
597
695
  const specs: SpecAuditResult[] = [];
598
696
  const rewrites: RewriteEntry[] = [];
697
+ const skipped: SkippedSpec[] = [];
599
698
 
600
699
  if (!existsSync(specsDir)) {
601
- return { specs, totalSCs: 0, totalMatched: 0, totalUnmatched: 0, totalBehavioral: 0, strictUnmatched: 0, rewrites };
700
+ return {
701
+ specs,
702
+ totalSCs: 0,
703
+ totalTicked: 0,
704
+ totalMatched: 0,
705
+ totalUnmatched: 0,
706
+ totalBehavioral: 0,
707
+ strictUnmatched: 0,
708
+ rewrites,
709
+ skipped,
710
+ };
602
711
  }
603
712
 
604
- const specFiles = readdirSync(specsDir).filter((f) => f.endsWith(".md"));
713
+ // The SHARED enumeration (#225), not a second walk. This was
714
+ // `readdirSync(specsDir).filter(f => f.endsWith(".md"))`, which reports
715
+ // `bootstrap-data-flow` as a directory entry and then drops it for not
716
+ // ending in `.md` — so its six specs and 260 criteria were not merely
717
+ // unread, they were unreachable. `scripts/detect-sc-drift.ts` already
718
+ // carries a docblock about having fixed exactly this for itself, so the
719
+ // reporter and the drift gate disagreed about what a spec is, and the gate
720
+ // was the one that was right.
721
+ //
722
+ // Entries come back relative to `specsDir`, so a nested spec names itself
723
+ // `bootstrap-data-flow/success-criteria.md` in the table and in a finding.
724
+ const specFiles = collectSpecFiles(specsDir);
605
725
 
606
726
  for (const specFile of specFiles) {
607
727
  const filePath = join(specsDir, specFile);
@@ -618,20 +738,27 @@ export function auditSpecs(
618
738
  const matchedSCs: SCClassification[] = [];
619
739
  const unmatchedSCs: SCClassification[] = [];
620
740
  const behavioralSCs: SCClassification[] = [];
741
+ /** The unmatched criteria as declared, so the writer can scope itself. */
742
+ const unmatchedDecls: ExtractedSC[] = [];
621
743
 
622
- for (const sc of scs) {
744
+ // Over the UNTICKED criteria only — see `SpecAuditResult`. Widening
745
+ // `total` to the whole corpus must not widen `unmatched`.
746
+ const open = scs.filter((sc) => !sc.checked);
747
+ for (const sc of open) {
623
748
  if (isBehavioralSC(sc)) {
624
749
  behavioralSCs.push({ id: sc.id, statement: sc.statement, category: "behavioral" });
625
750
  } else if (matchPattern(sc) !== null) {
626
751
  matchedSCs.push({ id: sc.id, statement: sc.statement, category: "matched" });
627
752
  } else {
628
753
  unmatchedSCs.push({ id: sc.id, statement: sc.statement, category: "unmatched" });
754
+ unmatchedDecls.push(sc);
629
755
  }
630
756
  }
631
757
 
632
758
  specs.push({
633
759
  specFile,
634
760
  total: scs.length,
761
+ ticked: scs.length - open.length,
635
762
  matched: matchedSCs.length,
636
763
  unmatched: unmatchedSCs.length,
637
764
  behavioral: behavioralSCs.length,
@@ -642,11 +769,32 @@ export function auditSpecs(
642
769
  });
643
770
 
644
771
  // ── Fix mode: rewrite unmatched SCs in-place ──────────────
645
- if (opts?.fix && unmatchedSCs.length > 0) {
772
+ const rewritable = unmatchedDecls.filter(isRewriteCandidate);
773
+
774
+ // #1286: asked BEFORE the rewrite loop, not beside the `writeFileSync`.
775
+ // A derived file must not contribute `RewriteEntry`s either — the
776
+ // scaffold turns those into `UPDATED: specs/<file>` and stages the path,
777
+ // so recording rewrites for a file nobody wrote reports an edit that did
778
+ // not happen and dirties a tree that is clean.
779
+ // #1552: this early consult is NOT a second decider — `maySpecBeWritten`
780
+ // and `writeSpec` both land on `mayWrite`. It exists because the refusal
781
+ // has to happen before the rewrite loop, not at the write.
782
+ const { allowed, reading } = maySpecBeWritten(content);
783
+ if (opts?.fix && rewritable.length > 0 && !allowed) {
784
+ skipped.push({
785
+ specFile,
786
+ reading,
787
+ message: skipLine(specFile, reading),
788
+ wouldHaveEdited: rewritable.length,
789
+ });
790
+ continue;
791
+ }
792
+
793
+ if (opts?.fix && rewritable.length > 0) {
646
794
  let modified = content;
647
795
  let hasChanges = false;
648
796
 
649
- for (const usc of unmatchedSCs) {
797
+ for (const usc of rewritable) {
650
798
  const closest = findClosestPattern(usc.statement);
651
799
  const decision = decideRewrite(usc.statement, closest);
652
800
 
@@ -700,12 +848,13 @@ export function auditSpecs(
700
848
  }
701
849
 
702
850
  if (hasChanges) {
703
- writeFileSync(filePath, modified);
851
+ writeSpec(filePath, modified, { label: specFile });
704
852
  }
705
853
  }
706
854
  }
707
855
 
708
856
  const totalSCs = specs.reduce((sum, s) => sum + s.total, 0);
857
+ const totalTicked = specs.reduce((sum, s) => sum + s.ticked, 0);
709
858
  const totalMatched = specs.reduce((sum, s) => sum + s.matched, 0);
710
859
  const totalUnmatched = specs.reduce((sum, s) => sum + s.unmatched, 0);
711
860
  const totalBehavioral = specs.reduce((sum, s) => sum + s.behavioral, 0);
@@ -713,7 +862,17 @@ export function auditSpecs(
713
862
  .filter((s) => s.compliance === "strict")
714
863
  .reduce((sum, s) => sum + s.unmatched, 0);
715
864
 
716
- return { specs, totalSCs, totalMatched, totalUnmatched, totalBehavioral, strictUnmatched, rewrites };
865
+ return {
866
+ specs,
867
+ totalSCs,
868
+ totalTicked,
869
+ totalMatched,
870
+ totalUnmatched,
871
+ totalBehavioral,
872
+ strictUnmatched,
873
+ rewrites,
874
+ skipped,
875
+ };
717
876
  }
718
877
 
719
878
  // ── Report formatting ─────────────────────────────────────────
@@ -724,24 +883,66 @@ export function formatReport(result: AuditResult): string {
724
883
  lines.push("=".repeat(60));
725
884
  lines.push("");
726
885
 
727
- // Per-spec table
728
- lines.push(
729
- `${"Spec".padEnd(45)} ${"total".padEnd(6)} ${"matched".padEnd(8)} ${"unmatched".padEnd(10)} ${"behavioral".padEnd(10)}`
886
+ // The name column is sized to the longest name present. A nested spec is
887
+ // named by its path, so a fixed 45 would silently push every other column
888
+ // out of alignment on exactly the rows this change made visible.
889
+ const nameWidth = Math.max(
890
+ "Spec".length,
891
+ ...result.specs.map((s) => s.specFile.length),
730
892
  );
731
- lines.push("-".repeat(80));
893
+ const row = (
894
+ name: string,
895
+ total: string | number,
896
+ ticked: string | number,
897
+ matched: string | number,
898
+ unmatched: string | number,
899
+ behavioral: string | number,
900
+ ) =>
901
+ `${name.padEnd(nameWidth)} ${String(total).padEnd(6)} ${String(ticked).padEnd(7)} ` +
902
+ `${String(matched).padEnd(8)} ${String(unmatched).padEnd(10)} ${String(behavioral).padEnd(10)}`;
903
+
904
+ lines.push(row("Spec", "total", "ticked", "matched", "unmatched", "behavioral"));
905
+ lines.push("-".repeat(nameWidth + 46));
732
906
 
733
907
  for (const spec of result.specs) {
734
908
  lines.push(
735
- `${spec.specFile.padEnd(45)} ${String(spec.total).padEnd(6)} ${String(spec.matched).padEnd(8)} ${String(spec.unmatched).padEnd(10)} ${String(spec.behavioral).padEnd(10)}`
909
+ row(spec.specFile, spec.total, spec.ticked, spec.matched, spec.unmatched, spec.behavioral),
736
910
  );
737
911
  }
738
912
 
739
- lines.push("-".repeat(80));
913
+ lines.push("-".repeat(nameWidth + 46));
914
+ lines.push(
915
+ row(
916
+ "TOTAL",
917
+ result.totalSCs,
918
+ result.totalTicked,
919
+ result.totalMatched,
920
+ result.totalUnmatched,
921
+ result.totalBehavioral,
922
+ ),
923
+ );
924
+ lines.push("");
925
+ // `matched`/`unmatched`/`behavioral` are the UNTICKED split, and a reader
926
+ // who adds the columns and gets `total` only by accident will read them as
927
+ // a partition of the whole. Say which population they describe.
740
928
  lines.push(
741
- `${"TOTAL".padEnd(45)} ${String(result.totalSCs).padEnd(6)} ${String(result.totalMatched).padEnd(8)} ${String(result.totalUnmatched).padEnd(10)} ${String(result.totalBehavioral).padEnd(10)}`
929
+ `total = ticked + matched + unmatched + behavioral. ` +
930
+ `matched/unmatched/behavioral classify the ${result.totalSCs - result.totalTicked} UNTICKED criteria only.`,
742
931
  );
743
932
  lines.push("");
744
933
 
934
+ // #1286: named individually, never summarised. "1 spec skipped" is not
935
+ // something a reader can act on, and a skip nobody can see is the same
936
+ // defect as the write it replaced.
937
+ if (result.skipped.length > 0) {
938
+ lines.push(`Not written — a generator owns these (${result.skipped.length}):`);
939
+ for (const s of result.skipped) {
940
+ lines.push(` ${s.message}`);
941
+ lines.push(` ${s.wouldHaveEdited} criteria would have been edited.`);
942
+ }
943
+ lines.push("");
944
+ }
945
+
745
946
  return lines.join("\n");
746
947
  }
747
948
 
@@ -13,7 +13,8 @@
13
13
  * bun scripts/convert-spec.ts rules.md --governs "input validation" # custom governs
14
14
  */
15
15
 
16
- import { existsSync, readFileSync, writeFileSync, mkdirSync } from "fs";
16
+ import { existsSync, readFileSync, mkdirSync } from "fs";
17
+ import { writeSpec } from "../lib/write-spec";
17
18
  import { join, basename, dirname } from "path";
18
19
  import { SIGNAL_PHRASE_PATTERNS } from "../lib/signal-phrases";
19
20
  import { localCalendarDay } from "../lib/local-calendar-day";
@@ -289,6 +290,10 @@ if (existsSync(outputPath)) {
289
290
  process.exit(1);
290
291
  }
291
292
 
292
- writeFileSync(outputPath, specContent);
293
+ // #1552: create-only — the `existsSync` refusal above means this never meets
294
+ // bytes a generator owns. It routes through the chokepoint anyway, because
295
+ // "this writer is safe for a second reason" is how two unguarded writers got
296
+ // classified out of the population in the first place.
297
+ writeSpec(outputPath, specContent, { label: `specs/${filename}` });
293
298
  console.log(`Created specs/${filename}`);
294
299
  console.log(` ${rules.length} rules extracted (${rules.filter((r) => !r.testable).length} non-testable)`);
@@ -14,7 +14,7 @@
14
14
  *
15
15
  * Thin CLI consumer — all logic lives in lib/create-sc.ts.
16
16
  */
17
- import { readFileSync, writeFileSync, existsSync } from "fs";
17
+ import { readFileSync, existsSync } from "fs";
18
18
  import {
19
19
  allocateScNumber,
20
20
  generateSCText,
@@ -24,6 +24,8 @@ import {
24
24
  import { readScRegistry } from "./sync-sc-status";
25
25
  import { describeReading } from "../lib/sc-id-cross-tree";
26
26
  import { currentScOwner } from "../lib/sc-reservations";
27
+ import { skipLine } from "../lib/derived-spec";
28
+ import { maySpecBeWritten, writeSpec } from "../lib/write-spec";
27
29
  import { join } from "path";
28
30
 
29
31
  /** Same resolution sync-sc-status uses, so both halves read one tree. */
@@ -113,9 +115,19 @@ try {
113
115
  const { number: scNumber, namespace } = allocateScNumber(ROOT, content, readScRegistry(), { owner });
114
116
  const scLine = formatSCLine(scNumber, statement);
115
117
 
118
+ // #1286: appending to a spec a generator owns writes a criterion that
119
+ // disappears at the next regeneration, having consumed an SC id that
120
+ // nothing then declares. Refuse loudly rather than allocate into a file
121
+ // that cannot keep it.
122
+ const early = maySpecBeWritten(content);
123
+ if (!early.allowed) {
124
+ console.error(skipLine(specPath, early.reading));
125
+ process.exit(1);
126
+ }
127
+
116
128
  // Append SC line to the end of the file
117
129
  const newContent = content.trimEnd() + "\n" + scLine + "\n";
118
- writeFileSync(specPath, newContent);
130
+ writeSpec(specPath, newContent);
119
131
  console.log(`Appended to ${specPath}: ${scLine}`);
120
132
  // What the number is a floor over, stated rather than implied. A clone on
121
133
  // another machine is outside anything this process can reach, and an
@@ -13,7 +13,8 @@
13
13
  * SCs tagged with (behavioral) bypass matchPattern validation.
14
14
  */
15
15
 
16
- import { existsSync, writeFileSync, mkdirSync } from "fs";
16
+ import { existsSync, mkdirSync } from "fs";
17
+ import { writeSpec } from "../lib/write-spec";
17
18
  import { join } from "path";
18
19
  import { isMatchablePattern, isBehavioralSC, type ParsedSC } from "../lib/conformity";
19
20
  import { loadRegistry, type RegistryEntry } from "../lib/create-sc";
@@ -158,7 +159,9 @@ compliance: strict
158
159
  ${scSection}
159
160
  `;
160
161
 
161
- writeFileSync(filePath, content);
162
+ // #1552: create-only, like `convert-spec.ts` — it refuses by name above when
163
+ // the file exists. Routed through the chokepoint regardless; see there.
164
+ writeSpec(filePath, content, { label: `specs/${filename}` });
162
165
  console.log(`Created specs/${filename}`);
163
166
  if (governs.startsWith("TODO")) {
164
167
  console.log(` governs: is TODO — update it before scaffolding`);
@@ -13,6 +13,7 @@
13
13
 
14
14
  import { existsSync, readFileSync } from "fs";
15
15
  import { collectSpecFiles } from "../lib/spec-files";
16
+ import { SC_ID_SOURCE } from "../lib/sc-ids";
16
17
  import { join } from "path";
17
18
 
18
19
  export interface DriftResult {
@@ -112,8 +113,15 @@ export function detectDrift(specsDir: string, projectRoot: string): DriftResult
112
113
  const specPath = join(specsDir, specFile);
113
114
  const content = readFileSync(specPath, "utf-8");
114
115
 
115
- // Find all SC lines (both checked and unchecked)
116
- const scPattern = /^- \[[ x]\] (SC-\d+):\s*(.+)$/gm;
116
+ // Find all SC lines (both checked and unchecked).
117
+ //
118
+ // Built from `SC_ID_SOURCE` (#1298). This is the gate
119
+ // `scripts/sync-sc-status.ts` runs before it flips a box, so a criterion
120
+ // this pattern cannot see is not merely unreported — it is auto-ticked
121
+ // with no drift gate at all. That is the same failure the docblock above
122
+ // records for subdirectory specs, arriving a second time by prefix, and
123
+ // `SC-\d+` could see neither an anti-criterion nor a `CRC-` id.
124
+ const scPattern = new RegExp(`^- \\[[ x]\\] (${SC_ID_SOURCE}):\\s*(.+)$`, "gm");
117
125
  let match;
118
126
 
119
127
  while ((match = scPattern.exec(content)) !== null) {