rungate 0.2.1 → 0.3.0

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 (119) hide show
  1. package/bin/rungate.ts +70 -0
  2. package/lib/aes-calculator.ts +66 -0
  3. package/lib/agent-audit.ts +139 -0
  4. package/lib/agent-brief-validation.ts +359 -0
  5. package/lib/agents-md-refs.ts +90 -0
  6. package/lib/bash-file-read.ts +197 -0
  7. package/lib/behavioral-cache.ts +78 -0
  8. package/lib/branch-cleanup.ts +234 -0
  9. package/lib/brief-context-parser.ts +35 -0
  10. package/lib/canary.ts +117 -0
  11. package/lib/check-registry.ts +226 -0
  12. package/lib/ci-checkout.ts +400 -0
  13. package/lib/cli-commands.ts +137 -0
  14. package/lib/compliance-backfill.ts +220 -0
  15. package/lib/compliance-report.ts +504 -0
  16. package/lib/compliance.ts +361 -0
  17. package/lib/config-loader.ts +255 -0
  18. package/lib/conformity.ts +1818 -131
  19. package/lib/container-provenance.ts +230 -0
  20. package/lib/create-brief.ts +150 -0
  21. package/lib/create-sc.ts +272 -0
  22. package/lib/deep-merge.ts +69 -0
  23. package/lib/dev-liveness.ts +214 -0
  24. package/lib/directive-extractor.ts +210 -0
  25. package/lib/distribution-standing.ts +113 -0
  26. package/lib/doc-hygiene.ts +238 -0
  27. package/lib/eval-criteria.ts +6 -0
  28. package/lib/evidence-portability.ts +123 -0
  29. package/lib/evidence-prevalidator.ts +390 -0
  30. package/lib/evidence-required.ts +150 -0
  31. package/lib/evidence-satisfiability.ts +288 -0
  32. package/lib/frontmatter.ts +163 -0
  33. package/lib/gap-scanner.ts +348 -0
  34. package/lib/gate-enforcement.ts +366 -0
  35. package/lib/generators/agent-briefs.ts +136 -0
  36. package/lib/generators/agents-md.ts +506 -0
  37. package/lib/generators/code-map.ts +60 -0
  38. package/lib/generators/types.ts +184 -0
  39. package/lib/git-ref-normalizer.ts +107 -0
  40. package/lib/github.ts +539 -0
  41. package/lib/harness-identity.ts +63 -0
  42. package/lib/hill-climb.ts +164 -0
  43. package/lib/instruction-effectiveness.ts +131 -0
  44. package/lib/issue-closure-audit.ts +225 -0
  45. package/lib/issue-create-override.ts +343 -0
  46. package/lib/js-top-level-code.ts +250 -0
  47. package/lib/liveness-contradiction.ts +149 -0
  48. package/lib/organize.ts +505 -0
  49. package/lib/paths.ts +197 -6
  50. package/lib/post-fix-verify.ts +157 -0
  51. package/lib/prior-branch.ts +489 -0
  52. package/lib/project-state-shape.ts +166 -0
  53. package/lib/promote-outputs.ts +156 -0
  54. package/lib/prove-label-gate.ts +35 -0
  55. package/lib/reachability.ts +302 -0
  56. package/lib/release-preflight.ts +186 -0
  57. package/lib/rule-health-pipeline.ts +264 -0
  58. package/lib/rule-health-trend.ts +161 -0
  59. package/lib/rule-provenance.ts +149 -0
  60. package/lib/rule-registry.ts +128 -0
  61. package/lib/rungate-schema.ts +114 -4
  62. package/lib/sc-claim-forms.ts +179 -0
  63. package/lib/sc-cover.ts +150 -0
  64. package/lib/sc-guard.ts +157 -0
  65. package/lib/sc-ids.ts +344 -0
  66. package/lib/scaffold/defaults.ts +165 -0
  67. package/lib/scaffold/managed-workflow.ts +370 -0
  68. package/lib/scaffold/owned-files.ts +265 -0
  69. package/lib/scaffold/steps.ts +2680 -0
  70. package/lib/scanner.ts +701 -0
  71. package/lib/screenshot-upload.ts +73 -0
  72. package/lib/secret-patterns.ts +112 -0
  73. package/lib/security-verdict.ts +616 -0
  74. package/lib/signal-phrases.ts +1 -0
  75. package/lib/spec-change-conformity.ts +80 -0
  76. package/lib/spec-files.ts +62 -0
  77. package/lib/spec-registry.ts +133 -0
  78. package/lib/spec-updater.ts +96 -0
  79. package/lib/stale-cleanup.ts +224 -0
  80. package/lib/stale-issue-scanner.ts +36 -0
  81. package/lib/strip-js-comments.ts +269 -0
  82. package/lib/suite-measurement.ts +228 -0
  83. package/lib/task-completion-checks.ts +177 -0
  84. package/lib/test-suite-lock.ts +1136 -0
  85. package/lib/transcript-checker.ts +1140 -0
  86. package/lib/validators/spec-validators.ts +171 -0
  87. package/lib/verdict-capture.ts +73 -0
  88. package/lib/verified-push.ts +358 -0
  89. package/lib/workflow-security.ts +174 -0
  90. package/lib/worktree-cleanup.ts +250 -0
  91. package/lib/worktree-collect.ts +283 -0
  92. package/lib/worktree-isolation.ts +82 -0
  93. package/package.json +24 -2
  94. package/prompts/ac-adversary.md +14 -2
  95. package/prompts/aditi.md +5 -0
  96. package/prompts/blast-radius.md +5 -0
  97. package/prompts/container-verify.md +5 -0
  98. package/prompts/discovery.md +4 -0
  99. package/prompts/environment.md +5 -0
  100. package/prompts/evidence-hierarchy.md +5 -0
  101. package/prompts/evidence-validator.md +11 -0
  102. package/prompts/marcus.md +5 -0
  103. package/prompts/prevention.md +5 -0
  104. package/prompts/prove-reproducer.md +12 -0
  105. package/prompts/quinn-decision-tree.md +5 -0
  106. package/prompts/quinn-ui-brief.md +5 -0
  107. package/prompts/quinn.md +5 -0
  108. package/prompts/rca.md +5 -0
  109. package/prompts/read-before-write.md +4 -0
  110. package/prompts/regression.md +5 -0
  111. package/prompts/serena.md +5 -0
  112. package/scripts/audit-specs.ts +464 -0
  113. package/scripts/convert-spec.ts +293 -0
  114. package/scripts/create-sc.ts +92 -0
  115. package/scripts/create-spec.ts +166 -0
  116. package/scripts/extract-constraints.ts +4 -3
  117. package/scripts/generate-code-map.ts +1 -1
  118. package/scripts/scaffold-project.ts +138 -1426
  119. package/scripts/sync-spec-tests.ts +211 -126
@@ -0,0 +1,156 @@
1
+ import { existsSync, readdirSync, readFileSync, writeFileSync, mkdirSync, renameSync, statSync } from "fs";
2
+ import { join, basename } from "path";
3
+
4
+ interface PromoteResult {
5
+ promoted: string[];
6
+ skipped: string[];
7
+ archived: string[];
8
+ errors: string[];
9
+ }
10
+
11
+ export function promoteOutputs(projectRoot: string): PromoteResult {
12
+ const home = process.env.HOME || "";
13
+ const rungatDir = join(home, ".rungate");
14
+ const result: PromoteResult = { promoted: [], skipped: [], archived: [], errors: [] };
15
+
16
+ if (!existsSync(rungatDir)) return result;
17
+
18
+ const archiveDir = join(rungatDir, "_archived");
19
+ const maxAgeDays = 7;
20
+
21
+ const slugDirs = readdirSync(rungatDir, { withFileTypes: true })
22
+ .filter(d => d.isDirectory() && !d.name.startsWith("_"))
23
+ .map(d => join(rungatDir, d.name));
24
+
25
+ for (const dir of slugDirs) {
26
+ const slug = basename(dir);
27
+
28
+ // Council synthesis → docs/council/
29
+ const councilJson = join(dir, "council-synthesis.json");
30
+ if (existsSync(councilJson)) {
31
+ try {
32
+ const data = JSON.parse(readFileSync(councilJson, "utf-8"));
33
+ const topic = data.topic || slug;
34
+ const topicSlug = topic.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 60);
35
+ const date = data.capturedAt?.slice(0, 10) || new Date().toISOString().slice(0, 10);
36
+ const destDir = join(projectRoot, "docs", "council");
37
+ const destFile = join(destDir, `${date}-${topicSlug}.md`);
38
+
39
+ if (!existsSync(destFile)) {
40
+ mkdirSync(destDir, { recursive: true });
41
+ const md = buildCouncilMarkdown(data, date, topic);
42
+ writeFileSync(destFile, md);
43
+ result.promoted.push(`council: ${basename(destFile)}`);
44
+ } else {
45
+ result.skipped.push(`council: ${basename(destFile)} (exists)`);
46
+ }
47
+ } catch (e: any) {
48
+ result.errors.push(`council ${slug}: ${e.message}`);
49
+ }
50
+ }
51
+
52
+ // Research output → docs/research/
53
+ const researchJson = join(dir, "research-output.json");
54
+ if (existsSync(researchJson)) {
55
+ try {
56
+ const data = JSON.parse(readFileSync(researchJson, "utf-8"));
57
+ const topic = data.topic || slug;
58
+ const topicSlug = topic.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 60);
59
+ const destDir = join(projectRoot, "docs", "research");
60
+ const destFile = join(destDir, `${topicSlug}.md`);
61
+
62
+ if (!existsSync(destFile)) {
63
+ mkdirSync(destDir, { recursive: true });
64
+ const md = buildResearchMarkdown(data, topic);
65
+ writeFileSync(destFile, md);
66
+ result.promoted.push(`research: ${basename(destFile)}`);
67
+ } else {
68
+ result.skipped.push(`research: ${basename(destFile)} (exists)`);
69
+ }
70
+ } catch (e: any) {
71
+ result.errors.push(`research ${slug}: ${e.message}`);
72
+ }
73
+ }
74
+ }
75
+
76
+ // Archive stale working dirs (older than maxAgeDays, no active workflow-state)
77
+ for (const dir of slugDirs) {
78
+ const slug = basename(dir);
79
+ try {
80
+ const stat = statSync(dir);
81
+ const ageDays = (Date.now() - stat.mtimeMs) / (1000 * 60 * 60 * 24);
82
+ if (ageDays < maxAgeDays) continue;
83
+
84
+ const wsPath = join(dir, "workflow-state.json");
85
+ if (existsSync(wsPath)) {
86
+ try {
87
+ const ws = JSON.parse(readFileSync(wsPath, "utf-8"));
88
+ if (ws.phase && !["DONE", "SHIPPED", "PROVEN"].includes(ws.phase)) continue;
89
+ } catch { /* unparseable — safe to archive */ }
90
+ }
91
+
92
+ mkdirSync(archiveDir, { recursive: true });
93
+ renameSync(dir, join(archiveDir, slug));
94
+ result.archived.push(slug);
95
+ } catch (e: any) {
96
+ result.errors.push(`archive ${slug}: ${e.message}`);
97
+ }
98
+ }
99
+
100
+ return result;
101
+ }
102
+
103
+ function buildCouncilMarkdown(data: any, date: string, topic: string): string {
104
+ const lines = [
105
+ "---",
106
+ "doc-type: council",
107
+ "status: accepted",
108
+ `created: ${date}`,
109
+ `topic: ${topic}`,
110
+ "---",
111
+ "",
112
+ `# Council: ${topic}`,
113
+ "",
114
+ ];
115
+
116
+ if (data.convergencePoints?.length) {
117
+ lines.push("## Convergence", "");
118
+ for (const p of data.convergencePoints) lines.push(`- ${p}`);
119
+ lines.push("");
120
+ }
121
+ if (data.disagreements?.length) {
122
+ lines.push("## Disagreements", "");
123
+ for (const d of data.disagreements) lines.push(`- ${d}`);
124
+ lines.push("");
125
+ }
126
+ if (data.recommendation) {
127
+ lines.push("## Recommendation", "", data.recommendation, "");
128
+ }
129
+ if (data.decisions?.length) {
130
+ lines.push("## Decisions", "");
131
+ for (const d of data.decisions) lines.push(`- ${d}`);
132
+ lines.push("");
133
+ }
134
+
135
+ return lines.join("\n") + "\n";
136
+ }
137
+
138
+ function buildResearchMarkdown(data: any, topic: string): string {
139
+ const lines = [
140
+ "---",
141
+ "doc-type: research",
142
+ "status: active",
143
+ `created: ${new Date().toISOString().slice(0, 10)}`,
144
+ `governs: ${topic}`,
145
+ "---",
146
+ "",
147
+ `# ${topic}`,
148
+ "",
149
+ ];
150
+
151
+ if (data.findings) lines.push(data.findings, "");
152
+ if (data.summary) lines.push(data.summary, "");
153
+ if (typeof data === "string") lines.push(data, "");
154
+
155
+ return lines.join("\n") + "\n";
156
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Whether an issue's labels say the close gate must stop (#1390, #395).
3
+ *
4
+ * `needs-prove` marks an issue whose fix has not been demonstrated against a
5
+ * reproducer. `proven` is what `/prove` adds once it has been. An issue
6
+ * carrying the first without the second is one about to be closed on the
7
+ * strength of a passing suite, which is the thing the prove step exists to
8
+ * stop.
9
+ *
10
+ * ## Why this is a function and not four lines in the gate
11
+ *
12
+ * It was four lines in `gates/workflow.test.ts`, and the decision was
13
+ * entangled with the transport that fetched the labels — a GitHub CLI
14
+ * subprocess. Nothing could exercise the rule without a network, a `gh`
15
+ * binary and an authenticated environment, so nothing did. The criterion
16
+ * forbidding that subprocess (SC-502) was ticked over it for its whole life.
17
+ *
18
+ * One exported predicate over a plain string list means the rule can be
19
+ * driven directly, and means there is a single binding to mutate — the
20
+ * property `.claude/rules/checks-must-be-able-to-fail.md` asks for. The
21
+ * transport is `getIssueLabels` in `lib/github.ts` and is now a separate
22
+ * question, which is the point: a decision tangled with its transport is a
23
+ * decision nobody tests.
24
+ *
25
+ * Returns the refusal text, or `null` to allow.
26
+ */
27
+ export function proveLabelViolation(labels: readonly string[]): string | null {
28
+ const has = (name: string) => labels.includes(name);
29
+ if (!has("needs-prove")) return null;
30
+ if (has("proven")) return null;
31
+ return (
32
+ "Close gate blocked: the issue carries `needs-prove` and not `proven`. " +
33
+ "Run /prove to demonstrate the fix against a reproducer before closing (#1390)."
34
+ );
35
+ }
@@ -0,0 +1,302 @@
1
+ /**
2
+ * Is a marked block actually reachable? (#200, Phase 1)
3
+ *
4
+ * This repo's strong form of verification is marker extraction plus
5
+ * `new Function`: a test slices the source between two comments and executes
6
+ * the slice over a sandbox. It proves the extracted logic refuses for the
7
+ * right reason. It does not prove the block runs.
8
+ *
9
+ * Measured, on 2026-10-08: wrapping the `BLOCKING-GRADES` region of
10
+ * workflows/ship.js in `if (false) { ... }` — with the wrapper placed OUTSIDE
11
+ * the marker comments, so the extracted slice stays byte-identical — left
12
+ * test/blocking-grades.test.ts at 19 pass / 0 fail. The same mutation of
13
+ * `SECURITY-DECISION` left test/security-verdict-blocks.test.ts at
14
+ * 113 pass / 0 fail, and of `COMMIT-STATE-GUARD` left
15
+ * test/record-build-commit.test.ts at 52 pass / 0 fail. Everything those
16
+ * suites observe is a property of the TEXT between the markers, and the text
17
+ * did not change.
18
+ *
19
+ * So this helper never decides from the text. It parses the file, finds where
20
+ * the marked region sits in the resulting tree, and reads two properties off
21
+ * the parse:
22
+ *
23
+ * 1. the region's ancestor chain — `if (false)`, a relocation into a
24
+ * function nobody calls, a loop, a `catch` all change it;
25
+ * 2. the statements that precede the region in each enclosing statement
26
+ * list — an early `return` above the block changes nothing about the
27
+ * chain, and is the one dead-code shape an ancestor check alone misses.
28
+ *
29
+ * None of those mutations changes a single byte between the markers.
30
+ *
31
+ * ## Permitted enclosing constructs — stated, not inferred (AC-3)
32
+ *
33
+ * A permissive list silently restores the defect, so the allowlist is tiny and
34
+ * every entry has a reason attached in `PERMITTED_ENCLOSING`. Anything not on
35
+ * it is a refusal, including constructs nobody has thought of yet: the default
36
+ * is deny. Note that a conditional ancestor is always *in* the chain alongside
37
+ * the `BlockStatement` it owns, so allowing `BlockStatement` generically is
38
+ * safe — an `if`/loop/`catch`/function body is caught by its own entry.
39
+ *
40
+ * Deny-by-default also means a block inside a function that IS called is
41
+ * refused. That is deliberate: nothing here resolves call graphs, so accepting
42
+ * it would mean trusting the author's word, which is the thing this module
43
+ * exists to stop doing.
44
+ *
45
+ * ## What this cannot catch (AC-5)
46
+ *
47
+ * Reachability here is a parse-time property. A block that the parser says is
48
+ * unconditionally reached can still never execute at runtime:
49
+ *
50
+ * - a preceding `if (x) return` whose condition is true on every real input
51
+ * — the terminator scan below only sees UNCONDITIONAL siblings, because a
52
+ * conditional `return` above the block is the normal shape of
53
+ * workflows/ship.js and refusing it would reject the real file;
54
+ * - a preceding call that exits the process or raises on every real input;
55
+ * - a preceding `await` on a promise that never settles;
56
+ * - a top-level guard like `if (!enabled) return` where `enabled` is false
57
+ * in every deployed configuration.
58
+ *
59
+ * No static check sees any of those, and this one does not pretend to. It
60
+ * closes exactly one hole — the block's position in the program is now
61
+ * observed instead of assumed — and leaves the runtime hole open and written
62
+ * down. It is also complementary to, not a replacement for, the `new Function`
63
+ * mutant tests: those prove the logic refuses correctly, this proves the logic
64
+ * is wired in. Both properties are needed; neither implies the other.
65
+ *
66
+ * ## Fail-closed refusals
67
+ *
68
+ * Every refusal leaves through `refuse()`, whose single raise statement — the
69
+ * only one in this file, which the test asserts — is guarded by the one
70
+ * exported `REACHABILITY_REFUSE` constant. That constant exists so
71
+ * test/reachability-refusals.test.ts can build a mutant copy of this file with
72
+ * it set to 0 and show each negative case passing only because the refusal
73
+ * fired — see .claude/rules/checks-must-be-able-to-fail.md.
74
+ */
75
+
76
+ import { parse } from "acorn";
77
+
78
+ /**
79
+ * The one switch every refusal goes through. Declared on a single line and
80
+ * assigned exactly once, so the test's mutant (`= 0`) neutralises ALL
81
+ * refusals and no branch can quietly bypass the mutation by raising directly.
82
+ */
83
+ export const REACHABILITY_REFUSE = 1;
84
+
85
+ /** Raised by every refusal in this module. */
86
+ export class ReachabilityRefusal extends Error {
87
+ constructor(reason: string) {
88
+ super(`reachability REFUSED: ${reason}`);
89
+ this.name = "ReachabilityRefusal";
90
+ }
91
+ }
92
+
93
+ /**
94
+ * The complete allowlist of constructs a marked block may sit inside, with the
95
+ * reason each is unconditional. Everything absent from this map is refused.
96
+ */
97
+ export const PERMITTED_ENCLOSING: Record<string, string> = {
98
+ Program:
99
+ "the module body itself — workflows/ship.js runs top to bottom, so a statement here executes on every run",
100
+ TryStatement:
101
+ "a `try` runs its block unconditionally; the handler is a separate node and is NOT permitted",
102
+ BlockStatement:
103
+ "a bare, `try` or `finally` block body; any conditional owner (if/loop/catch/function) appears in the chain under its own name and is refused there",
104
+ };
105
+
106
+ /**
107
+ * Statements that end control flow for the rest of their statement list. One
108
+ * of these as an UNCONDITIONAL preceding sibling makes everything after it
109
+ * dead, however unconditional the ancestor chain looks.
110
+ */
111
+ export const UNCONDITIONAL_TERMINATORS: Record<string, string> = {
112
+ ReturnStatement:
113
+ "control leaves the enclosing body here, so nothing later in the same statement list can run — the #200 `early return` mutation",
114
+ ThrowStatement:
115
+ "an error is raised unconditionally, so the rest of the statement list is dead code",
116
+ BreakStatement:
117
+ "control leaves the enclosing loop or switch case, skipping everything after it in the list",
118
+ ContinueStatement:
119
+ "control jumps to the next iteration, skipping everything after it in the list",
120
+ };
121
+
122
+ /**
123
+ * acorn options. `allowReturnOutsideFunction` and `allowAwaitOutsideFunction`
124
+ * are required because workflows/ship.js is a module body that the Workflow
125
+ * runtime wraps in an async function before running it, so it legitimately
126
+ * contains top-level `return` and `await`. Both options only widen what
127
+ * PARSES; neither affects the ancestor chain a parsed block gets.
128
+ */
129
+ const PARSE_OPTIONS = {
130
+ ecmaVersion: "latest",
131
+ sourceType: "module",
132
+ allowReturnOutsideFunction: true,
133
+ allowAwaitOutsideFunction: true,
134
+ allowHashBang: true,
135
+ } as const;
136
+
137
+ type AstNode = { type: string; start: number; end: number };
138
+
139
+ function refuse(reason: string): void {
140
+ if (REACHABILITY_REFUSE) throw new ReachabilityRefusal(reason);
141
+ }
142
+
143
+ function isNode(value: unknown): value is AstNode {
144
+ return (
145
+ typeof value === "object" &&
146
+ value !== null &&
147
+ typeof (value as AstNode).type === "string" &&
148
+ typeof (value as AstNode).start === "number" &&
149
+ typeof (value as AstNode).end === "number"
150
+ );
151
+ }
152
+
153
+ /** Depth-first walk collecting every node that fully contains `[start, end]`. */
154
+ function ancestorsOf(node: AstNode, start: number, end: number, into: AstNode[]): void {
155
+ if (node.start <= start && node.end >= end) into.push(node);
156
+ for (const value of Object.values(node as unknown as Record<string, unknown>)) {
157
+ if (Array.isArray(value)) {
158
+ for (const child of value) if (isNode(child)) ancestorsOf(child, start, end, into);
159
+ } else if (isNode(value)) {
160
+ ancestorsOf(value, start, end, into);
161
+ }
162
+ }
163
+ }
164
+
165
+ function parseOrRefuse(source: string): AstNode | null {
166
+ try {
167
+ return parse(source, PARSE_OPTIONS) as unknown as AstNode;
168
+ } catch (err) {
169
+ refuse(`the source does not parse as JavaScript: ${(err as Error).message}`);
170
+ return null;
171
+ }
172
+ }
173
+
174
+ function ancestorNodes(source: string, start: number, end: number): AstNode[] {
175
+ const tree = parseOrRefuse(source);
176
+ if (!tree) return []; // mutant path only; the real one refused above.
177
+
178
+ const chain: AstNode[] = [];
179
+ ancestorsOf(tree, start, end, chain);
180
+
181
+ if (chain.length === 0) {
182
+ refuse(
183
+ `no parsed node contains bytes [${start}, ${end}) — the range is outside the program, so its position cannot be read`,
184
+ );
185
+ }
186
+ return chain;
187
+ }
188
+
189
+ /**
190
+ * The parsed ancestors of the byte range `[start, end)`, outermost first.
191
+ *
192
+ * Returns the `type` of every AST node that fully contains the range —
193
+ * `["Program"]` for a top-level statement,
194
+ * `["Program", "IfStatement", "BlockStatement"]` for one inside an `if`.
195
+ * Refuses if the source does not parse; an empty chain is impossible for a
196
+ * valid range, so it is also refused rather than read as "no ancestors".
197
+ */
198
+ export function enclosingChain(source: string, start: number, end: number): string[] {
199
+ return ancestorNodes(source, start, end).map((node) => node.type);
200
+ }
201
+
202
+ /**
203
+ * The first unconditional terminator that precedes the region in any enclosing
204
+ * statement list, innermost list first. `null` when nothing does.
205
+ *
206
+ * Only DIRECT siblings count. A `return` nested inside a preceding `if` is
207
+ * conditional, and refusing those would reject workflows/ship.js, every marked
208
+ * block of which sits below a guard of exactly that shape.
209
+ */
210
+ function precedingTerminator(
211
+ chain: AstNode[],
212
+ start: number,
213
+ ): { statement: string; owner: string } | null {
214
+ for (const node of [...chain].reverse()) {
215
+ const body = (node as unknown as { body?: unknown }).body;
216
+ if (!Array.isArray(body)) continue;
217
+ for (const statement of body) {
218
+ if (!isNode(statement)) continue;
219
+ if (statement.end > start) break; // reached the region itself
220
+ if (statement.type in UNCONDITIONAL_TERMINATORS) {
221
+ return { statement: statement.type, owner: node.type };
222
+ }
223
+ }
224
+ }
225
+ return null;
226
+ }
227
+
228
+ /**
229
+ * Refuse unless the `${markerName}-START` / `${markerName}-END` region of
230
+ * `source` sits somewhere that runs unconditionally. Returns the ancestor
231
+ * chain on acceptance.
232
+ *
233
+ * The markers are located by text because comments are the only way to name a
234
+ * region — but nothing about the region's CONTENT is inspected, and the
235
+ * accept/refuse decision is read entirely off the parse.
236
+ */
237
+ export function assertMarkedBlockReachable(source: string, markerName: string): string[] {
238
+ const startMarker = `${markerName}-START`;
239
+ const endMarker = `${markerName}-END`;
240
+
241
+ const startCount = source.split(startMarker).length - 1;
242
+ const endCount = source.split(endMarker).length - 1;
243
+
244
+ // Absent markers first: a typo'd or renamed marker must never read as
245
+ // "nothing to check here, carry on".
246
+ if (startCount === 0) {
247
+ refuse(`${startMarker} is absent from the source`);
248
+ return [];
249
+ }
250
+ if (endCount === 0) {
251
+ refuse(`${endMarker} is absent from the source`);
252
+ return [];
253
+ }
254
+ // #200: nothing asserted this before, so a dead duplicate of the pair
255
+ // elsewhere in the file satisfied the slice while the live copy was
256
+ // unreachable. Ambiguity about WHICH pair is being checked is a refusal.
257
+ if (startCount > 1) {
258
+ refuse(`${startMarker} occurs ${startCount} times — the marked block must be unique`);
259
+ return [];
260
+ }
261
+ if (endCount > 1) {
262
+ refuse(`${endMarker} occurs ${endCount} times — the marked block must be unique`);
263
+ return [];
264
+ }
265
+
266
+ const start = source.indexOf(startMarker) + startMarker.length;
267
+ const end = source.indexOf(endMarker);
268
+ if (end <= start) {
269
+ refuse(`${endMarker} appears before ${startMarker} — the region is inside out`);
270
+ return [];
271
+ }
272
+
273
+ const nodes = ancestorNodes(source, start, end);
274
+ if (nodes.length === 0) return []; // mutant path only; the real one refused above.
275
+ const chain = nodes.map((node) => node.type);
276
+
277
+ if (chain[0] !== "Program") {
278
+ refuse(`the ancestor chain does not start at Program: [${chain.join(" > ")}]`);
279
+ return [];
280
+ }
281
+
282
+ for (const node of chain) {
283
+ if (!(node in PERMITTED_ENCLOSING)) {
284
+ refuse(
285
+ `${markerName} sits inside ${node}, which is not an unconditional construct — ` +
286
+ `chain was [${chain.join(" > ")}], permitted: [${Object.keys(PERMITTED_ENCLOSING).join(", ")}]`,
287
+ );
288
+ return [];
289
+ }
290
+ }
291
+
292
+ const dead = precedingTerminator(nodes, start);
293
+ if (dead) {
294
+ refuse(
295
+ `${markerName} follows an unconditional ${dead.statement} in the same ${dead.owner} — ` +
296
+ `control never reaches it, even though its ancestor chain [${chain.join(" > ")}] is permitted`,
297
+ );
298
+ return [];
299
+ }
300
+
301
+ return chain;
302
+ }
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Whether a release may be cut, and whether one actually was (#364).
3
+ *
4
+ * `rungate` has been published twice ever — `0.2.0` and `0.2.1`. `main` is
5
+ * 741 commits past the second. A consumer installing from npm receives a
6
+ * harness without any of the gate, collector or claim-audit work that
7
+ * `SUCCESS.md` cites as evidence, which is why #366 made the file say so and
8
+ * why this file exists to stop it drifting again.
9
+ *
10
+ * ## The failure this is built around
11
+ *
12
+ * The issue named it, and it is the shape `.claude/rules/checks-must-be-able-
13
+ * to-fail.md` opens with:
14
+ *
15
+ * > A publish job that exits 0 because npm rejected a duplicate version is
16
+ * > exactly the "could not measure reads as nothing wrong" shape, and it is
17
+ * > the most likely way this fix ships broken.
18
+ *
19
+ * A release pipeline has an unusually quiet way of doing nothing. The publish
20
+ * step can be skipped by an `if:` that stopped matching, swallowed by a
21
+ * `continue-on-error`, or rejected by the registry as a duplicate — and in
22
+ * every case the job is green and the tag exists. Nothing downstream can tell
23
+ * "we shipped 0.2.3" from "we tagged 0.2.3 and shipped nothing".
24
+ *
25
+ * ## Two readings, before and after
26
+ *
27
+ * So the guard is not one check but two, taken at different times, and
28
+ * neither is sufficient alone:
29
+ *
30
+ * - **Preflight** — the tree's version must NOT be on the registry yet. This
31
+ * is what makes a duplicate publish a red run rather than a no-op.
32
+ * - **Postflight** — after the publish step, the registry's `latest` must BE
33
+ * the tree's version. This is what makes a *skipped* publish a red run.
34
+ *
35
+ * Preflight alone passes a pipeline whose publish step never ran. Postflight
36
+ * alone passes a pipeline that republished nothing because the version was
37
+ * already there from last month. The pair is the same "two numbers, not one"
38
+ * argument `lib/distribution-standing.ts` makes about `SUCCESS.md`, applied
39
+ * to the act rather than to the record.
40
+ */
41
+
42
+ /** What the registry currently holds for a package. */
43
+ export interface RegistryState {
44
+ /** Every published version, in no particular order. */
45
+ versions: string[];
46
+ /** The `latest` dist-tag, or `null` for a package that has never shipped. */
47
+ latest: string | null;
48
+ }
49
+
50
+ /**
51
+ * Read the registry.
52
+ *
53
+ * The packument, not `/latest`: "has 0.2.2 ever been published" cannot be
54
+ * answered by a dist-tag, because `latest` moves on and leaves older versions
55
+ * installable behind it. `distributionViolations` asks a different question
56
+ * and is right to use `/latest`; this one needs the whole list.
57
+ *
58
+ * Deliberately not the `npm` CLI — the registry's JSON endpoint needs no npm
59
+ * on the path and no lockfile, so it measures the same thing on a laptop and
60
+ * on CI.
61
+ *
62
+ * A 404 is a real answer: the package has never been published, so every
63
+ * version is available. Any other failure THROWS rather than returning an
64
+ * empty state, because an unreachable registry would otherwise read as "no
65
+ * version conflicts" and wave a duplicate straight through.
66
+ */
67
+ export const NPM_REGISTRY = "https://registry.npmjs.org";
68
+
69
+ export async function registryState(
70
+ pkg: string,
71
+ fetchImpl: typeof fetch = fetch,
72
+ base: string = NPM_REGISTRY,
73
+ ): Promise<RegistryState> {
74
+ const res = await fetchImpl(`${base}/${pkg}`);
75
+ if (res.status === 404) return { versions: [], latest: null };
76
+ if (!res.ok) throw new Error(`registry returned ${res.status} for ${pkg}`);
77
+ const body = (await res.json()) as {
78
+ versions?: Record<string, unknown>;
79
+ "dist-tags"?: { latest?: unknown };
80
+ };
81
+ const versions = body.versions ? Object.keys(body.versions) : [];
82
+ const latest = body["dist-tags"]?.latest;
83
+ return { versions, latest: typeof latest === "string" ? latest : null };
84
+ }
85
+
86
+ /** `1.2.3`, `1.2.3-rc.1`, `1.2.3+build` — npm's shape, not a full semver parser. */
87
+ const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
88
+
89
+ /**
90
+ * Does `version` satisfy a `^x.y.z` range, by npm's rules? (#364)
91
+ *
92
+ * Exists because the scaffold pins consumers to a caret floored at the
93
+ * harness's own minor, and whether that range can ever resolve decided
94
+ * whether a release could be cut at all. A tree carrying an unpublished
95
+ * minor emits a range nothing satisfies — `0.3.0` emits `^0.3.0` while the
96
+ * registry's newest is `0.2.1` — and `release.yml` runs the suite before
97
+ * publishing, so a check wanting the tree's version already on npm cannot
98
+ * pass on the run that would put it there.
99
+ *
100
+ * The caret's 0.x behaviour is the whole point and is the part hand-rolled
101
+ * comparisons get wrong: below 1.0.0 a caret is pinned to the MINOR, not the
102
+ * major, so `^0.3.0` excludes `0.4.0`. Getting that backwards would make
103
+ * this answer `true` for every bump and the guard would certify nothing.
104
+ *
105
+ * Deliberately narrow: `harnessDevDepRange` only ever emits `^x.y.0`, so
106
+ * this handles carets and refuses anything else rather than pretending to be
107
+ * a semver range parser.
108
+ */
109
+ export function satisfiesCaret(version: string, range: string): boolean {
110
+ const r = /^\^(\d+)\.(\d+)\.(\d+)$/.exec(range);
111
+ const v = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(version);
112
+ if (!r || !v) return false;
113
+ const [rMaj, rMin, rPat] = r.slice(1, 4).map(Number);
114
+ const [vMaj, vMin, vPat] = v.slice(1, 4).map(Number);
115
+
116
+ // Lower bound: the version must be at or above the floor.
117
+ const atOrAbove =
118
+ vMaj > rMaj ||
119
+ (vMaj === rMaj && (vMin > rMin || (vMin === rMin && vPat >= rPat)));
120
+ if (!atOrAbove) return false;
121
+
122
+ // Upper bound, and the 0.x special case is the reason this function exists.
123
+ if (rMaj > 0) return vMaj === rMaj;
124
+ if (rMin > 0) return vMaj === 0 && vMin === rMin;
125
+ return vMaj === 0 && vMin === 0 && vPat === rPat;
126
+ }
127
+
128
+ /**
129
+ * The single place that decides whether a release may be cut. `null` allows.
130
+ *
131
+ * One exported function so there is one binding to mutate. `tag` is the git
132
+ * ref the workflow fired on, with any `refs/tags/` prefix already stripped;
133
+ * pass `null` for a run that is not tag-triggered.
134
+ *
135
+ * The tag comparison is here and not left to the workflow because a tag that
136
+ * disagrees with `package.json` publishes the version in `package.json` while
137
+ * every human reads the tag. That is not a release, it is two releases with
138
+ * one set of notes.
139
+ */
140
+ export function preflightRefusal(
141
+ treeVersion: string,
142
+ tag: string | null,
143
+ state: RegistryState,
144
+ ): string | null {
145
+ if (!SEMVER.test(treeVersion)) {
146
+ return `package.json version ${JSON.stringify(treeVersion)} is not a version npm will accept`;
147
+ }
148
+ if (tag !== null && tag !== `v${treeVersion}`) {
149
+ return (
150
+ `tag ${tag} does not name the version being published — package.json says ` +
151
+ `${treeVersion}, so the tag would describe a release that is not the one cut`
152
+ );
153
+ }
154
+ if (state.versions.includes(treeVersion)) {
155
+ return (
156
+ `rungate@${treeVersion} is already on the registry — publishing it again is ` +
157
+ `rejected by npm, and a job that treats that rejection as success reports a ` +
158
+ `release nobody can install. Bump package.json.`
159
+ );
160
+ }
161
+ return null;
162
+ }
163
+
164
+ /**
165
+ * The single place that decides whether a release actually happened. `null`
166
+ * allows.
167
+ *
168
+ * Run AFTER the publish step, against a freshly read registry. This is the
169
+ * half that cannot be satisfied by doing nothing: a skipped, swallowed or
170
+ * silently-failed publish leaves `latest` where it was.
171
+ */
172
+ export function postflightRefusal(treeVersion: string, latestAfter: string | null): string | null {
173
+ if (latestAfter === null) {
174
+ return (
175
+ `the registry has no latest version for rungate after the publish step — ` +
176
+ `the release did not happen, whatever the job's exit code says`
177
+ );
178
+ }
179
+ if (latestAfter !== treeVersion) {
180
+ return (
181
+ `the registry's latest is ${latestAfter}, not the ${treeVersion} this run was ` +
182
+ `cutting — the publish step did not take effect`
183
+ );
184
+ }
185
+ return null;
186
+ }