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
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,9 +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
+ import { SC_ID_SOURCE } from "../sc-ids";
11
+ import { skipLine } from "../derived-spec";
12
+ import { maySpecBeWritten, writeSpec } from "../write-spec";
10
13
 
11
14
  /**
12
15
  * SC-278: Detect specs that exceed 500 lines and suggest splitting.
@@ -61,9 +64,18 @@ export function addFrontmatterToSpecs(specsDir: string, actions: string[]): void
61
64
  const filePath = join(specsDir, file);
62
65
  const content = readFileSync(filePath, "utf-8");
63
66
 
67
+ // #1286: both writes below rewrite this spec's own bytes. On a spec a
68
+ // generator owns, the frontmatter belongs in the generator — injecting
69
+ // it here is discarded at the next run after breaking what pins it.
70
+ const early = maySpecBeWritten(content);
71
+ if (!early.allowed) {
72
+ actions.push(skipLine(`specs/${file}`, early.reading));
73
+ continue;
74
+ }
75
+
64
76
  if (!content.startsWith("---\n")) {
65
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`;
66
- writeFileSync(filePath, frontmatter + content);
78
+ writeSpec(filePath, frontmatter + content, { label: `specs/${file}` });
67
79
  actions.push(`UPDATED: specs/${file} (added frontmatter)`);
68
80
  } else {
69
81
  // Validate existing frontmatter has required fields
@@ -76,7 +88,7 @@ export function addFrontmatterToSpecs(specsDir: string, actions: string[]): void
76
88
  if (!fm.includes("governs:")) missing.push(`governs: TODO`);
77
89
  if (missing.length > 0) {
78
90
  const newFm = `---\n${fm}\n${missing.join("\n")}\n---`;
79
- writeFileSync(filePath, newFm + content.substring(fmEnd + 4));
91
+ writeSpec(filePath, newFm + content.substring(fmEnd + 4), { label: `specs/${file}` });
80
92
  actions.push(`UPDATED: specs/${file} (added missing frontmatter fields: ${missing.map(m => m.split(":")[0]).join(", ")})`);
81
93
  }
82
94
  // SC-269: WARN for specs with missing or TODO governs
@@ -114,8 +126,11 @@ export function detectUnconvertedSpecs(specsDir: string, actions: string[]): voi
114
126
  // Check if this spec has frontmatter with testable field
115
127
  const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
116
128
  if (!fmMatch) continue;
117
- // Check if file has any SC checkbox lines
118
- const hasSCLines = /^- \[[ x]\] SC-\d+:/m.test(content);
129
+ // Check if file has any SC checkbox lines. Built from `SC_ID_SOURCE`
130
+ // (#1298) — a spec whose criteria all carry a tracked prefix this does
131
+ // not know reads as unconverted, and the WARN tells the author to run
132
+ // `convert-spec.ts` over a spec that is already converted.
133
+ const hasSCLines = new RegExp(`^- \\[[ x]\\] ${SC_ID_SOURCE}:`, "m").test(content);
119
134
  if (!hasSCLines) {
120
135
  actions.push(
121
136
  `WARN: specs/${file} has no SC checkboxes — run \`bun scripts/convert-spec.ts specs/${file}\` to convert`
@@ -140,9 +155,21 @@ export function addFrontmatterToAdrs(adrDir: string, actions: string[]): void {
140
155
  const filePath = join(adrDir, file);
141
156
  const content = readFileSync(filePath, "utf-8");
142
157
 
158
+ // #1286: the same guard as `addFrontmatterToSpecs` above, for the same
159
+ // reason. The declaration is about who PRODUCES a file, not about which
160
+ // directory it sits in — a generated ADR loses its injected frontmatter
161
+ // at the next regeneration exactly as a generated spec does, and an
162
+ // unguarded sibling beside a guarded one reads as an oversight because
163
+ // that is what it was.
164
+ const early = maySpecBeWritten(content);
165
+ if (!early.allowed) {
166
+ actions.push(skipLine(`docs/adr/${file}`, early.reading));
167
+ continue;
168
+ }
169
+
143
170
  if (!content.startsWith("---\n")) {
144
171
  const frontmatter = `---\ndoc-type: adr\nstatus: draft\nowner: TODO\ncreated: ${today}\nupdated: ${today}\n---\n\n`;
145
- writeFileSync(filePath, frontmatter + content);
172
+ writeSpec(filePath, frontmatter + content, { label: `docs/adr/${file}` });
146
173
  actions.push(`AUTO-FIXED: docs/adr/${file} (added frontmatter)`);
147
174
  } else {
148
175
  const fmEnd = content.indexOf("\n---", 4);
@@ -177,7 +204,9 @@ export function addFrontmatterToAdrs(adrDir: string, actions: string[]): void {
177
204
  const newFm = missing.length > 0
178
205
  ? `---\n${corrected}\n${missing.join("\n")}\n---`
179
206
  : `---\n${corrected}\n---`;
180
- writeFileSync(filePath, newFm + content.substring(fmEnd + 4));
207
+ writeSpec(filePath, newFm + content.substring(fmEnd + 4), {
208
+ label: `docs/adr/${file}`,
209
+ });
181
210
  const what = [
182
211
  ...(missing.length > 0 ? [`added missing: ${missing.map(m => m.split(":")[0]).join(", ")}`] : []),
183
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.2",
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": {
@@ -30,6 +30,7 @@
30
30
  "scripts/create-success.ts",
31
31
  "scripts/create-sc.ts",
32
32
  "scripts/ai-review-findings.ts",
33
+ "scripts/record-ai-review-unmeasured.ts",
33
34
  "scripts/arbitrate-finding.ts",
34
35
  "scripts/split-spec.ts",
35
36
  "scripts/sync-sc-status.ts",
@@ -39,7 +39,47 @@
39
39
  * here would be a second non-zero exit that the mutation cannot reach, and
40
40
  * the case would go green over a refusal that no longer came from the
41
41
  * constant.
42
+ *
43
+ * ## The one thing this file supplies rather than forwards (CRC-B4)
44
+ *
45
+ * `aiReviewJuryGate` — the verifier quorum that counts the ballot before a
46
+ * finding is allowed to block. It is handed in here because the reader
47
+ * cannot import it: three mutation batteries copy
48
+ * `lib/scaffold/ai-review-findings.ts` into a scratch directory carrying
49
+ * only its one dependency, and this gate pulls the finding arbiter and the
50
+ * filing gate behind it. A mutant that died on module resolution would
51
+ * report zero findings, which reads exactly like a guard behaving
52
+ * differently.
53
+ *
54
+ * **The ballot directory binds HERE, out of the environment, and never as
55
+ * a third positional.** `argumentsBeyondTheContract` refuses `argv[2]` and
56
+ * up, and one invocation it catches is a changed-file path containing a
57
+ * space that an unquoted expansion word-split in two (CF-6 in
58
+ * `test/ai-review-changed-files-step.test.ts`). Widening the argv contract
59
+ * by one slot to carry a ballot would make that refusal an accepted argv
60
+ * whose second half is read as a directory, so the refusal keeps its full
61
+ * width and the path arrives by a channel word-splitting cannot reach.
62
+ *
63
+ * With no `AI_REVIEW_BALLOT_DIR_ENV` set, the gate handed over is `null`
64
+ * and the reader behaves exactly as it did before the group existed. There
65
+ * is no third state: a ballot directory nothing can read is impossible
66
+ * here rather than refused, because the reader never learns a path it has
67
+ * no gate for. `test/ai-review-findings-command.test.ts` holds this file
68
+ * to supplying the gate when the variable is set.
42
69
  */
70
+ import { aiReviewJuryGate } from "../lib/ai-review-jury";
43
71
  import { main } from "../lib/scaffold/ai-review-findings";
72
+ import { AI_REVIEW_BALLOT_DIR_ENV } from "../lib/scaffold/ai-review-step";
73
+
74
+ const ballotDir = process.env[AI_REVIEW_BALLOT_DIR_ENV];
75
+ const jury =
76
+ ballotDir === undefined || ballotDir === ""
77
+ ? null
78
+ : (blocking: readonly unknown[]) => aiReviewJuryGate(blocking, ballotDir);
44
79
 
45
- process.exit(main(process.argv.slice(2)));
80
+ // One line, and `process.exit(main(` is load-bearing text: AC-4 in
81
+ // `test/ai-review-findings-command.test.ts` reads it to prove this file
82
+ // declares no exit code of its own. Wrapping the call across lines makes
83
+ // that case red for a formatting reason, which is worth knowing before
84
+ // reformatting it.
85
+ process.exit(main(process.argv.slice(2), jury));