rungate 0.8.3 → 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.
package/lib/ts-ast.ts CHANGED
@@ -101,6 +101,32 @@ export function parseTsModule(source: string): ParsedModule | null {
101
101
  }
102
102
  }
103
103
 
104
+ /**
105
+ * Parse JavaScript that needs no type stripping, or `null` if it does not
106
+ * parse.
107
+ *
108
+ * Distinct from `parseTsModule` for two reasons, both measured on
109
+ * `workflows/*.js` (#1566):
110
+ *
111
+ * - **`Bun.Transpiler` refuses all six of them**, on every loader — `js`,
112
+ * `jsx`, `ts` and `tsx` — while acorn parses the raw source without
113
+ * complaint. Routing `.js` through the transpiler turns six readable files
114
+ * into six refusals.
115
+ * - **Positions index the ORIGINAL text**, because nothing was rewritten. So
116
+ * a caller can report an exact line instead of reconciling by ordinal,
117
+ * which is the one real cost `parseTsModule` imposes.
118
+ *
119
+ * `js` is the input, unchanged, so the `ParsedModule` contract still holds:
120
+ * node positions index `js`.
121
+ */
122
+ export function parseJsModule(source: string): ParsedModule | null {
123
+ try {
124
+ return { tree: parse(source, PARSE_OPTIONS) as unknown as AstNode, js: source };
125
+ } catch {
126
+ return null;
127
+ }
128
+ }
129
+
104
130
  /** Every node in the tree, depth-first, parents before children. */
105
131
  export function* walkNodes(node: AstNode): Generator<AstNode> {
106
132
  yield node;
@@ -4,11 +4,12 @@
4
4
  * Handles frontmatter injection, oversized spec detection, and governs alignment checks.
5
5
  * All functions take a directory path and an actions array for reporting.
6
6
  */
7
- import { existsSync, readFileSync, writeFileSync, readdirSync } from "fs";
7
+ import { existsSync, readFileSync, readdirSync } from "fs";
8
8
  import { join } from "path";
9
9
  import { localCalendarDay } from "../local-calendar-day";
10
10
  import { SC_ID_SOURCE } from "../sc-ids";
11
- import { mayWrite, readDerivedDeclaration, skipLine } from "../derived-spec";
11
+ import { skipLine } from "../derived-spec";
12
+ import { maySpecBeWritten, writeSpec } from "../write-spec";
12
13
 
13
14
  /**
14
15
  * SC-278: Detect specs that exceed 500 lines and suggest splitting.
@@ -66,15 +67,15 @@ export function addFrontmatterToSpecs(specsDir: string, actions: string[]): void
66
67
  // #1286: both writes below rewrite this spec's own bytes. On a spec a
67
68
  // generator owns, the frontmatter belongs in the generator — injecting
68
69
  // it here is discarded at the next run after breaking what pins it.
69
- const derived = readDerivedDeclaration(content);
70
- if (!mayWrite(derived)) {
71
- actions.push(skipLine(`specs/${file}`, derived));
70
+ const early = maySpecBeWritten(content);
71
+ if (!early.allowed) {
72
+ actions.push(skipLine(`specs/${file}`, early.reading));
72
73
  continue;
73
74
  }
74
75
 
75
76
  if (!content.startsWith("---\n")) {
76
77
  const frontmatter = `---\ndoc-type: spec\nstatus: draft\nowner: TODO\ncreated: ${today}\nupdated: ${today}\ngoverns: TODO — describe what this spec governs\ntestable: false\n---\n\n`;
77
- writeFileSync(filePath, frontmatter + content);
78
+ writeSpec(filePath, frontmatter + content, { label: `specs/${file}` });
78
79
  actions.push(`UPDATED: specs/${file} (added frontmatter)`);
79
80
  } else {
80
81
  // Validate existing frontmatter has required fields
@@ -87,7 +88,7 @@ export function addFrontmatterToSpecs(specsDir: string, actions: string[]): void
87
88
  if (!fm.includes("governs:")) missing.push(`governs: TODO`);
88
89
  if (missing.length > 0) {
89
90
  const newFm = `---\n${fm}\n${missing.join("\n")}\n---`;
90
- writeFileSync(filePath, newFm + content.substring(fmEnd + 4));
91
+ writeSpec(filePath, newFm + content.substring(fmEnd + 4), { label: `specs/${file}` });
91
92
  actions.push(`UPDATED: specs/${file} (added missing frontmatter fields: ${missing.map(m => m.split(":")[0]).join(", ")})`);
92
93
  }
93
94
  // SC-269: WARN for specs with missing or TODO governs
@@ -160,15 +161,15 @@ export function addFrontmatterToAdrs(adrDir: string, actions: string[]): void {
160
161
  // at the next regeneration exactly as a generated spec does, and an
161
162
  // unguarded sibling beside a guarded one reads as an oversight because
162
163
  // that is what it was.
163
- const derived = readDerivedDeclaration(content);
164
- if (!mayWrite(derived)) {
165
- actions.push(skipLine(`docs/adr/${file}`, derived));
164
+ const early = maySpecBeWritten(content);
165
+ if (!early.allowed) {
166
+ actions.push(skipLine(`docs/adr/${file}`, early.reading));
166
167
  continue;
167
168
  }
168
169
 
169
170
  if (!content.startsWith("---\n")) {
170
171
  const frontmatter = `---\ndoc-type: adr\nstatus: draft\nowner: TODO\ncreated: ${today}\nupdated: ${today}\n---\n\n`;
171
- writeFileSync(filePath, frontmatter + content);
172
+ writeSpec(filePath, frontmatter + content, { label: `docs/adr/${file}` });
172
173
  actions.push(`AUTO-FIXED: docs/adr/${file} (added frontmatter)`);
173
174
  } else {
174
175
  const fmEnd = content.indexOf("\n---", 4);
@@ -203,7 +204,9 @@ export function addFrontmatterToAdrs(adrDir: string, actions: string[]): void {
203
204
  const newFm = missing.length > 0
204
205
  ? `---\n${corrected}\n${missing.join("\n")}\n---`
205
206
  : `---\n${corrected}\n---`;
206
- writeFileSync(filePath, newFm + content.substring(fmEnd + 4));
207
+ writeSpec(filePath, newFm + content.substring(fmEnd + 4), {
208
+ label: `docs/adr/${file}`,
209
+ });
207
210
  const what = [
208
211
  ...(missing.length > 0 ? [`added missing: ${missing.map(m => m.split(":")[0]).join(", ")}`] : []),
209
212
  ...(retyped !== null ? [`doc-type was "${retyped}", set to adr`] : []),
@@ -0,0 +1,138 @@
1
+ /**
2
+ * The one place rungate puts bytes on a path under `specs/` (#1552).
3
+ *
4
+ * ## Why a chokepoint and not thirteen guards
5
+ *
6
+ * #1286 and #1549 guarded thirteen spec write paths individually, each one
7
+ * asking `mayWrite` beside its own `writeFileSync`. That is thirteen places
8
+ * that have to remember, and **the measured forget rate was 2 of 12** — both
9
+ * found by re-deriving the population, not by any check. A completeness sweep
10
+ * over classified files cannot fix that: classification is list membership,
11
+ * not reachability, so it fails when a known writer is *unclassified* and
12
+ * stays green when somebody adds a brand new unguarded one.
13
+ *
14
+ * So the remembering moves into a function. Call `writeSpec` and the question
15
+ * is asked for you; write a raw primitive at a spec path and
16
+ * `specChokepointViolations` in `lib/spec-write-sweep.ts` names the call site.
17
+ *
18
+ * ## This is NOT a second decider
19
+ *
20
+ * `mayWrite` in `lib/derived-spec.ts` owns the refusal and still does. This
21
+ * module **consults** it and routes the answer; it contains no comparison of
22
+ * its own against `DerivedStatus`, and `test/spec-write-chokepoint.test.ts`
23
+ * asserts that by mutating `mayWrite` and watching every call site here flip.
24
+ *
25
+ * Two guards answering the same question about the same input are
26
+ * behaviourally one guard, and a mutation of either leaves the other holding
27
+ * every case up — the fourth shape in
28
+ * `.claude/rules/checks-must-be-able-to-fail.md`. Adding a `reading.status ===`
29
+ * comparison to this file would be exactly that, in the module whose whole
30
+ * purpose is to have one answer.
31
+ *
32
+ * ## No relative imports except the guard, on purpose
33
+ *
34
+ * `test/derived-spec-guard.test.ts` copies this file and `lib/derived-spec.ts`
35
+ * into an `mkdtemp` tree to mutate the guard underneath the real write paths.
36
+ * `./derived-spec` must stay the one relative specifier so it binds to the
37
+ * mutant copy; anything else relative would have to be carried too, and a
38
+ * mutant that dies on module resolution is indistinguishable from a guard that
39
+ * held.
40
+ */
41
+ import { existsSync, readFileSync, writeFileSync } from "fs";
42
+ import { mayWrite, readDerivedDeclaration, skipLine, type DerivedReading } from "./derived-spec";
43
+
44
+ export interface SpecWriteResult {
45
+ /** Whether the bytes reached disk. */
46
+ written: boolean;
47
+ /** What the file on disk claimed about who produces it. */
48
+ reading: DerivedReading;
49
+ /**
50
+ * Why the write was held, in one line naming the file and the reason.
51
+ * Present exactly when `written` is false — a refusal nobody can report is
52
+ * the same defect as a silent write.
53
+ */
54
+ refusal: string | null;
55
+ }
56
+
57
+ export interface WriteSpecOptions {
58
+ /**
59
+ * How the refusal should name the file. Defaults to `specPath`. Callers that
60
+ * report repo-relative paths pass the relative one so the line they print
61
+ * matches the rest of their output.
62
+ */
63
+ label?: string;
64
+ }
65
+
66
+ /**
67
+ * Write a spec, unless the file on disk says a generator owns its bytes.
68
+ *
69
+ * A path that does not exist yet is a creation: there are no bytes to own, so
70
+ * it is written. That keeps the create-only writers (`create-spec.ts`,
71
+ * `convert-spec.ts`) on the same route as everything else rather than beside
72
+ * it — they each refuse by name when the target exists, which is a *second*
73
+ * reason they are safe, not the reason this function is.
74
+ */
75
+ export function writeSpec(
76
+ specPath: string,
77
+ content: string,
78
+ opts?: WriteSpecOptions,
79
+ ): SpecWriteResult {
80
+ const reading: DerivedReading = existsSync(specPath)
81
+ ? readDerivedDeclaration(readFileSync(specPath, "utf-8"))
82
+ : { status: "authored" };
83
+
84
+ if (!mayWrite(reading)) {
85
+ return { written: false, reading, refusal: skipLine(opts?.label ?? specPath, reading) };
86
+ }
87
+
88
+ writeFileSync(specPath, content);
89
+ return { written: true, reading, refusal: null };
90
+ }
91
+
92
+ /**
93
+ * The same decision, for a caller that already holds the file's current bytes
94
+ * and wants to ask before doing the work rather than after.
95
+ *
96
+ * `audit-specs.ts` needs this: a derived file must contribute no `RewriteEntry`
97
+ * either, because the scaffold turns those into `UPDATED: specs/<file>` and
98
+ * stages the path, so recording rewrites for a file nobody wrote reports an
99
+ * edit that did not happen. Asking early and asking at the write are two
100
+ * consults of ONE decider, not two deciders — both land on `mayWrite`.
101
+ */
102
+ export function maySpecBeWritten(currentContent: string): {
103
+ allowed: boolean;
104
+ reading: DerivedReading;
105
+ } {
106
+ const reading = readDerivedDeclaration(currentContent);
107
+ return { allowed: mayWrite(reading), reading };
108
+ }
109
+
110
+ /**
111
+ * The same decision about bytes that are about to be DESTROYED rather than
112
+ * rewritten — a rename or a copy whose destination already exists.
113
+ *
114
+ * POSIX `rename()` replaces its destination silently, so a move into `specs/`
115
+ * can annihilate a generator-owned spec without ever calling a write
116
+ * primitive on it. The PR that built this chokepoint claimed otherwise —
117
+ * *"a move does not rewrite bytes, so no reading applies"* — which is true of
118
+ * the bytes moved and says nothing about the bytes overwritten. Found by the
119
+ * AI review on #1552.
120
+ *
121
+ * A destination that does not exist is a creation and is allowed; this
122
+ * function never looks at the source, because the question is only ever about
123
+ * who owns what is already there.
124
+ */
125
+ export function maySpecBeReplaced(
126
+ targetPath: string,
127
+ opts?: WriteSpecOptions,
128
+ ): { allowed: boolean; reading: DerivedReading; refusal: string | null } {
129
+ if (!existsSync(targetPath)) {
130
+ return { allowed: true, reading: { status: "authored" }, refusal: null };
131
+ }
132
+ const { allowed, reading } = maySpecBeWritten(readFileSync(targetPath, "utf-8"));
133
+ return {
134
+ allowed,
135
+ reading,
136
+ refusal: allowed ? null : skipLine(opts?.label ?? targetPath, reading),
137
+ };
138
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rungate",
3
- "version": "0.8.3",
3
+ "version": "0.8.4",
4
4
  "type": "module",
5
5
  "description": "Ship harness — conformity tests, scaffold, and agent briefs for AI-first development",
6
6
  "repository": {
@@ -19,12 +19,8 @@ import {
19
19
  } from "../lib/conformity";
20
20
  import { parseScDeclarations } from "../lib/sc-ids";
21
21
  import { collectSpecFiles } from "../lib/spec-files";
22
- import {
23
- mayWrite,
24
- readDerivedDeclaration,
25
- skipLine,
26
- type DerivedReading,
27
- } from "../lib/derived-spec";
22
+ import { skipLine, type DerivedReading } from "../lib/derived-spec";
23
+ import { maySpecBeWritten, writeSpec } from "../lib/write-spec";
28
24
 
29
25
  // ── Types ─────────────────────────────────────────────────────
30
26
 
@@ -780,8 +776,11 @@ export function auditSpecs(
780
776
  // scaffold turns those into `UPDATED: specs/<file>` and stages the path,
781
777
  // so recording rewrites for a file nobody wrote reports an edit that did
782
778
  // not happen and dirties a tree that is clean.
783
- const reading = readDerivedDeclaration(content);
784
- if (opts?.fix && rewritable.length > 0 && !mayWrite(reading)) {
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) {
785
784
  skipped.push({
786
785
  specFile,
787
786
  reading,
@@ -849,7 +848,7 @@ export function auditSpecs(
849
848
  }
850
849
 
851
850
  if (hasChanges) {
852
- writeFileSync(filePath, modified);
851
+ writeSpec(filePath, modified, { label: specFile });
853
852
  }
854
853
  }
855
854
  }
@@ -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,7 +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 { mayWrite, readDerivedDeclaration, skipLine } from "../lib/derived-spec";
27
+ import { skipLine } from "../lib/derived-spec";
28
+ import { maySpecBeWritten, writeSpec } from "../lib/write-spec";
28
29
  import { join } from "path";
29
30
 
30
31
  /** Same resolution sync-sc-status uses, so both halves read one tree. */
@@ -118,15 +119,15 @@ try {
118
119
  // disappears at the next regeneration, having consumed an SC id that
119
120
  // nothing then declares. Refuse loudly rather than allocate into a file
120
121
  // that cannot keep it.
121
- const reading = readDerivedDeclaration(content);
122
- if (!mayWrite(reading)) {
123
- console.error(skipLine(specPath, reading));
122
+ const early = maySpecBeWritten(content);
123
+ if (!early.allowed) {
124
+ console.error(skipLine(specPath, early.reading));
124
125
  process.exit(1);
125
126
  }
126
127
 
127
128
  // Append SC line to the end of the file
128
129
  const newContent = content.trimEnd() + "\n" + scLine + "\n";
129
- writeFileSync(specPath, newContent);
130
+ writeSpec(specPath, newContent);
130
131
  console.log(`Appended to ${specPath}: ${scLine}`);
131
132
  // What the number is a floor over, stated rather than implied. A clone on
132
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`);
@@ -1,9 +1,10 @@
1
1
  #!/usr/bin/env bun
2
2
 
3
- import { readFileSync, writeFileSync, mkdirSync } from "fs";
3
+ import { readFileSync, mkdirSync } from "fs";
4
4
  import { join, dirname } from "path";
5
5
  import { localCalendarDay } from "../lib/local-calendar-day";
6
- import { mayWrite, readDerivedDeclaration, skipLine } from "../lib/derived-spec";
6
+ import { skipLine } from "../lib/derived-spec";
7
+ import { maySpecBeWritten, writeSpec } from "../lib/write-spec";
7
8
 
8
9
  export interface SplitBoundary {
9
10
  heading: string;
@@ -264,9 +265,9 @@ if (import.meta.main) {
264
265
  // generator owns would lose its entire body to a stub the generator then
265
266
  // overwrites — and refusing after the split files are on disk leaves the
266
267
  // tree half-migrated.
267
- const reading = readDerivedDeclaration(content);
268
- if (!mayWrite(reading)) {
269
- console.error(skipLine(specPath, reading));
268
+ const early = maySpecBeWritten(content);
269
+ if (!early.allowed) {
270
+ console.error(skipLine(specPath, early.reading));
270
271
  process.exit(1);
271
272
  }
272
273
 
@@ -307,19 +308,19 @@ if (import.meta.main) {
307
308
  // Write split files
308
309
  for (const file of splitFiles) {
309
310
  const filePath = join(splitDir, file.filename);
310
- writeFileSync(filePath, file.content);
311
+ writeSpec(filePath, file.content);
311
312
  console.log(`Created: ${filePath} (${file.lineCount} lines)`);
312
313
  }
313
314
 
314
315
  // Write INDEX.md
315
316
  const indexContent = generateIndex(splitFiles, originalGoverns);
316
317
  const indexPath = join(splitDir, "INDEX.md");
317
- writeFileSync(indexPath, indexContent);
318
+ writeSpec(indexPath, indexContent);
318
319
  console.log(`Created: ${indexPath}`);
319
320
 
320
321
  // Replace original with redirect
321
322
  const redirectContent = generateRedirect(specPath, splitDir, splitFiles);
322
- writeFileSync(specPath, redirectContent);
323
+ writeSpec(specPath, redirectContent);
323
324
  console.log(`Updated: ${specPath} (now a redirect)`);
324
325
 
325
326
  console.log(
@@ -14,7 +14,7 @@
14
14
  * bun scripts/sync-sc-status.ts --report # Output per-spec coverage report
15
15
  */
16
16
 
17
- import { existsSync, readFileSync, writeFileSync, readdirSync } from "fs";
17
+ import { existsSync, readFileSync, readdirSync } from "fs";
18
18
 
19
19
  import { walkTestFiles } from "../lib/walk-test-files";
20
20
  import { commentMask, enclosingComment, stripJsComments } from "../lib/strip-js-comments";
@@ -23,7 +23,8 @@ import { join } from "path";
23
23
  import { execSync } from "child_process";
24
24
  import { matchPattern, isBehavioralSC, type ParsedSC } from "../lib/conformity";
25
25
  import { behavioralCachePath, readFreshCache } from "../lib/behavioral-cache";
26
- import { mayWrite, readDerivedDeclaration, skipLine } from "../lib/derived-spec";
26
+ import { skipLine } from "../lib/derived-spec";
27
+ import { maySpecBeWritten, writeSpec } from "../lib/write-spec";
27
28
  import { detectDrift } from "./detect-sc-drift";
28
29
  import {
29
30
  ambiguityOf,
@@ -689,9 +690,9 @@ export function flipCheckboxes(specFile: string, scIds: string[], specsDir?: str
689
690
  // #1286: ticking a checkbox is an in-place edit like any other. A spec a
690
691
  // generator owns gets its ticks from the generator, and flipping one here
691
692
  // is discarded at the next regeneration after breaking whatever pins it.
692
- const reading = readDerivedDeclaration(content);
693
- if (!mayWrite(reading)) {
694
- console.warn(skipLine(specFile, reading));
693
+ const early = maySpecBeWritten(content);
694
+ if (!early.allowed) {
695
+ console.warn(skipLine(specFile, early.reading));
695
696
  return 0;
696
697
  }
697
698
 
@@ -708,7 +709,7 @@ export function flipCheckboxes(specFile: string, scIds: string[], specsDir?: str
708
709
  // Write unless dry-run: use explicit isDryRun param if provided, else module-level flag
709
710
  const shouldSkipWrite = isDryRun !== undefined ? isDryRun : dryRun;
710
711
  if (flipped > 0 && !shouldSkipWrite) {
711
- writeFileSync(filePath, content);
712
+ writeSpec(filePath, content, { label: specFile });
712
713
  }
713
714
  return flipped;
714
715
  }