rungate 0.5.0 → 0.7.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 (142) hide show
  1. package/lib/affected-tests.ts +398 -0
  2. package/lib/agent-audit.ts +2 -3
  3. package/lib/agent-worktree.ts +287 -0
  4. package/lib/agents-md-sections.ts +209 -0
  5. package/lib/behavioral-cache.ts +150 -2
  6. package/lib/branch-diff.ts +139 -0
  7. package/lib/branch-protection.ts +790 -0
  8. package/lib/brief-ac-alignment.ts +104 -0
  9. package/lib/brief-references.ts +205 -0
  10. package/lib/bun-version.ts +347 -0
  11. package/lib/check-remedy.ts +140 -0
  12. package/lib/ci-checkout.ts +18 -1
  13. package/lib/ci-history-depth.ts +159 -0
  14. package/lib/ci-setup-step.ts +96 -0
  15. package/lib/claude-code-action.ts +85 -0
  16. package/lib/claude-tool-vocabulary.ts +188 -0
  17. package/lib/cli-commands.ts +15 -0
  18. package/lib/commit-sha.ts +42 -0
  19. package/lib/commit-subject.ts +90 -0
  20. package/lib/compliance-report.ts +377 -45
  21. package/lib/compliance.ts +196 -20
  22. package/lib/config-loader.ts +51 -1
  23. package/lib/config-trackable.ts +391 -0
  24. package/lib/conformity.ts +1272 -189
  25. package/lib/containment.ts +238 -0
  26. package/lib/content-hash.ts +24 -0
  27. package/lib/context-docs.ts +143 -28
  28. package/lib/create-brief.ts +2 -1
  29. package/lib/create-sc.ts +323 -4
  30. package/lib/dev-liveness.ts +180 -0
  31. package/lib/discovery-branch-points.ts +432 -0
  32. package/lib/discovery-stability.ts +481 -0
  33. package/lib/distribution-currency.ts +186 -0
  34. package/lib/doc-routing.ts +157 -0
  35. package/lib/doc-scan-targets.ts +9 -0
  36. package/lib/evidence-command-transport.ts +160 -0
  37. package/lib/evidence-prevalidator.ts +246 -2
  38. package/lib/evidence-satisfiability.ts +534 -12
  39. package/lib/failure-intake.ts +317 -0
  40. package/lib/fallow-availability.ts +286 -0
  41. package/lib/fs-write-capabilities.ts +232 -0
  42. package/lib/gate-refusal-currency.ts +112 -0
  43. package/lib/gate-run-split.ts +147 -0
  44. package/lib/gate-timeouts.ts +82 -0
  45. package/lib/generators/agent-briefs.ts +4 -1
  46. package/lib/generators/agents-md.ts +204 -48
  47. package/lib/generators/code-map.ts +2 -1
  48. package/lib/generators/types.ts +8 -0
  49. package/lib/git-dates.ts +55 -0
  50. package/lib/git-isolation.ts +140 -0
  51. package/lib/github.ts +15 -0
  52. package/lib/google-auth-action.ts +93 -0
  53. package/lib/harness-project.ts +48 -0
  54. package/lib/harness-provenance.ts +255 -0
  55. package/lib/hook-evidence.ts +235 -0
  56. package/lib/hook-scopes.ts +386 -0
  57. package/lib/hook-target-tree.ts +398 -0
  58. package/lib/hook-trees.ts +447 -0
  59. package/lib/js-top-level-code.ts +78 -10
  60. package/lib/junit-checks.ts +536 -0
  61. package/lib/launch-base.ts +253 -0
  62. package/lib/line-citation.ts +372 -0
  63. package/lib/local-calendar-day.ts +78 -0
  64. package/lib/orphan-reaper.ts +468 -0
  65. package/lib/parity-binding.ts +205 -0
  66. package/lib/per-test-timeouts.ts +219 -0
  67. package/lib/plan-coverage.ts +151 -0
  68. package/lib/prior-branch.ts +201 -8
  69. package/lib/process-table.ts +146 -0
  70. package/lib/project-state-derivation.ts +219 -0
  71. package/lib/project-state-root.ts +258 -0
  72. package/lib/project-state-shape.ts +59 -0
  73. package/lib/promote-outputs.ts +6 -2
  74. package/lib/published-artifact.ts +525 -0
  75. package/lib/readdir-sorted.ts +45 -0
  76. package/lib/report-provenance.ts +156 -0
  77. package/lib/review-execution-reading.ts +206 -0
  78. package/lib/review-tool-agreement.ts +433 -0
  79. package/lib/rule-promotion.ts +234 -0
  80. package/lib/rule-retirement.ts +525 -0
  81. package/lib/run-branch.ts +612 -0
  82. package/lib/rungate-schema.ts +19 -0
  83. package/lib/runner-home.ts +274 -0
  84. package/lib/sc-claim-forms.ts +75 -0
  85. package/lib/sc-id-cross-tree.ts +323 -0
  86. package/lib/sc-ids.ts +121 -13
  87. package/lib/sc-reservations.ts +289 -0
  88. package/lib/scaffold/ai-review-findings.ts +403 -0
  89. package/lib/scaffold/ai-review-step.ts +4777 -0
  90. package/lib/scaffold/managed-workflow.ts +587 -192
  91. package/lib/scaffold/owned-files.ts +186 -39
  92. package/lib/scaffold/pre-push-hook.ts +49 -5
  93. package/lib/scaffold/rehearsal.ts +205 -71
  94. package/lib/scaffold/steps.ts +1517 -293
  95. package/lib/scaffold/workflow-census.ts +217 -0
  96. package/lib/scaffold/workflow-drift.ts +217 -0
  97. package/lib/scaffold/write-steps.ts +10 -4
  98. package/lib/scan-budget.ts +247 -0
  99. package/lib/scanner.ts +80 -62
  100. package/lib/scratch-roots.ts +50 -5
  101. package/lib/screenshot-discovery.ts +121 -0
  102. package/lib/screenshot-upload.ts +41 -1
  103. package/lib/secret-patterns.ts +511 -8
  104. package/lib/ship-mode.ts +219 -0
  105. package/lib/source-slice.ts +294 -0
  106. package/lib/spec-listing.ts +148 -0
  107. package/lib/spec-requirements.ts +209 -0
  108. package/lib/stale-cleanup.ts +37 -3
  109. package/lib/suite-flake.ts +278 -0
  110. package/lib/suite-measurement.ts +23 -4
  111. package/lib/suite-run-reading.ts +411 -1
  112. package/lib/suite-timeout-margin.ts +193 -0
  113. package/lib/test-case-bodies.ts +883 -0
  114. package/lib/test-case-deletion.ts +653 -0
  115. package/lib/test-census.ts +97 -29
  116. package/lib/test-command-positions.ts +274 -0
  117. package/lib/test-command.ts +133 -0
  118. package/lib/test-suite-lock.ts +325 -26
  119. package/lib/tool-probe.ts +142 -0
  120. package/lib/top-level-cd.ts +393 -0
  121. package/lib/tracked-vs-ignored.ts +234 -0
  122. package/lib/tree-entries.ts +89 -0
  123. package/lib/ts-ast.ts +200 -0
  124. package/lib/validators/spec-validators.ts +3 -2
  125. package/lib/walk-test-files.ts +97 -0
  126. package/lib/workflow-actions.ts +263 -0
  127. package/lib/worktree-collect.ts +177 -5
  128. package/lib/worktree-repo.ts +36 -1
  129. package/package.json +2 -1
  130. package/scripts/ai-review-findings.ts +45 -0
  131. package/scripts/audit-specs.ts +247 -12
  132. package/scripts/audit-transcript.ts +2 -1
  133. package/scripts/convert-spec.ts +2 -1
  134. package/scripts/create-sc.ts +37 -7
  135. package/scripts/create-spec.ts +2 -1
  136. package/scripts/create-success.ts +2 -1
  137. package/scripts/extract-constraints.ts +197 -26
  138. package/scripts/generate-code-map.ts +62 -28
  139. package/scripts/scaffold-project.ts +12 -2
  140. package/scripts/split-spec.ts +2 -1
  141. package/scripts/sync-sc-status.ts +127 -14
  142. package/scripts/sync-spec-tests.ts +2 -1
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Does the Marcus brief cover every AC the state declares? (ADR-009 C2, #700)
3
+ *
4
+ * This is the decision behind `brief-ac-alignment` in `gates/workflow.test.ts`,
5
+ * lifted out so there is ONE binding to mutate and so the two refusals can be
6
+ * driven directly instead of through a spawned gate.
7
+ *
8
+ * ## Why it moved (#700)
9
+ *
10
+ * The check failed on five consecutive pushes to `main` and nobody could say
11
+ * which of its two branches fired. Both refusals were written inline, and
12
+ * neither named the path it had resolved:
13
+ *
14
+ * expect("marcus-brief.md missing").toBe("brief file required when Marcus spawned (ADR-009 C2)")
15
+ * expect(missingIds, `brief-ac-alignment: brief missing AC ids: ${...}`).toEqual([])
16
+ *
17
+ * `brief missing AC ids: AC-2` tells a reader WHICH id is absent and not
18
+ * WHERE the check looked — and the path is the whole question here, because
19
+ * it is assembled at call time from `RUNGATE_WORK_DIR`, a `$HOME/.rungate`
20
+ * fallback and the state's slug. A reading that is wrong about its directory
21
+ * and a brief that is genuinely short are the same sentence today.
22
+ *
23
+ * So every refusal names the resolved path. One interpolated string, and it
24
+ * converts "the brief is wrong" into "the brief at <this path> is wrong",
25
+ * which is a claim somebody can check.
26
+ *
27
+ * ## The reading is total, and `NOT_APPLICABLE` is a state
28
+ *
29
+ * The inline version `return`ed in two places — no slug, and an absent brief
30
+ * with Marcus not spawned — which made "the check decided nothing was wrong"
31
+ * and "the check declined to look" the same observation from outside. They
32
+ * are different, so they are different readings. `0`, `{}` and silence are
33
+ * indistinguishable from success (`.claude/rules/config-access.md`).
34
+ */
35
+
36
+ export type BriefAlignmentReading =
37
+ | "ALIGNED"
38
+ | "BRIEF_ABSENT"
39
+ | "IDS_MISSING"
40
+ | "NOT_APPLICABLE";
41
+
42
+ export interface BriefAlignment {
43
+ reading: BriefAlignmentReading;
44
+ /** The path the check resolved, always — including when it found nothing there. */
45
+ briefPath: string;
46
+ /** AC ids the brief does not name. Empty under every reading but `IDS_MISSING`. */
47
+ missingIds: string[];
48
+ /** Why this is a refusal, naming the path. `null` when it is not one. */
49
+ refusal: string | null;
50
+ /** Why the check declined to look. `null` unless the reading is `NOT_APPLICABLE`. */
51
+ declined: string | null;
52
+ }
53
+
54
+ export interface BriefAlignmentInput {
55
+ /** The resolved path, composed by the caller so this function reads no env. */
56
+ briefPath: string;
57
+ briefExists: boolean;
58
+ /** The brief's text. Ignored when `briefExists` is false. */
59
+ briefText: string;
60
+ acIds: string[];
61
+ marcusSpawned: boolean;
62
+ }
63
+
64
+ export function briefAcAlignment(input: BriefAlignmentInput): BriefAlignment {
65
+ const { briefPath, briefExists, briefText, acIds, marcusSpawned } = input;
66
+ const base = { briefPath, missingIds: [] as string[], refusal: null, declined: null };
67
+
68
+ if (!briefExists) {
69
+ // An absent brief is only a refusal when something was supposed to write
70
+ // one. With Marcus never spawned there is no brief to be missing, and
71
+ // calling that a pass would be the same substitution one level down.
72
+ if (!marcusSpawned) {
73
+ return {
74
+ ...base,
75
+ reading: "NOT_APPLICABLE",
76
+ declined:
77
+ `brief-ac-alignment: no brief at ${briefPath}, and Marcus was not spawned — ` +
78
+ "nothing was expected to write one, so this is UNMEASURED rather than a pass",
79
+ };
80
+ }
81
+ return {
82
+ ...base,
83
+ reading: "BRIEF_ABSENT",
84
+ refusal:
85
+ `brief-ac-alignment: Marcus was spawned but no brief exists at ${briefPath} ` +
86
+ "(ADR-009 C2). The path is resolved from RUNGATE_WORK_DIR, or $HOME/.rungate " +
87
+ "when that is unset, plus the state's slug — so a wrong directory and a " +
88
+ "missing file look the same from here. Check the path before the file.",
89
+ };
90
+ }
91
+
92
+ const missingIds = acIds.filter(id => !briefText.includes(id));
93
+ if (missingIds.length === 0) return { ...base, reading: "ALIGNED" };
94
+
95
+ return {
96
+ ...base,
97
+ reading: "IDS_MISSING",
98
+ missingIds,
99
+ refusal:
100
+ `brief-ac-alignment: the brief at ${briefPath} does not name ` +
101
+ `${missingIds.join(", ")} (ADR-009 C2). It exists and was read, so this is ` +
102
+ "the brief's content and not the resolved path.",
103
+ };
104
+ }
@@ -0,0 +1,205 @@
1
+ /**
2
+ * Whether a `node_modules/...` path named in an agent brief could be checked
3
+ * at all (#884).
4
+ *
5
+ * AGENT-6 resolves every `node_modules/...` path the briefs reference. A ship
6
+ * worktree is created without an install, so in one the paths cannot be
7
+ * resolved — and the check reported them as BROKEN. Both of the files it named
8
+ * exist in the main checkout; the briefs were correct and the corpus was
9
+ * missing. `record-local-env` runs the suite in that worktree, so the FAIL was
10
+ * recorded as the project's test health and failed `tests-pass` on every run.
11
+ *
12
+ * A conformity check whose corpus is absent did not run. Three outcomes, not
13
+ * two:
14
+ *
15
+ * | the package is | the path is | status |
16
+ * |---|---|---|
17
+ * | installed | present | `resolved` |
18
+ * | installed | absent | `broken` — AGENT-6 fails, as before |
19
+ * | not installed | unknowable | `unresolvable` — UNMEASURED, by name |
20
+ *
21
+ * The third is NOT a pass. `0`, `{}`, `SKIP` and silence are indistinguishable
22
+ * from success, so an unresolvable reference is recorded as a WARN finding
23
+ * naming the package that is missing, per `.claude/rules/config-access.md`.
24
+ *
25
+ * ## One binding
26
+ *
27
+ * `briefReferenceReading` is the only thing that decides any of this, and
28
+ * `reading` / `absentCorpora` are projections of the lists it builds rather
29
+ * than second answers computed beside them — two deciders that agree are
30
+ * behaviourally one, and no behavioural test can tell them apart.
31
+ *
32
+ * It lives here rather than in `lib/conformity.ts` because conformity imports
33
+ * `bun:test` at module scope and so cannot be imported by a CLI. Same
34
+ * arrangement as `lib/fallow-availability.ts` (#581) and `lib/git-dates.ts`
35
+ * (#508).
36
+ */
37
+
38
+ import { existsSync, readFileSync, readdirSync } from "fs";
39
+ import { join } from "path";
40
+
41
+ /**
42
+ * The packages the project says it depends on, or `null` when it does not say.
43
+ *
44
+ * This is the evidence that stops the UNMEASURED reading swallowing a real
45
+ * finding. In a tree that HAS an install, a reference into a package the
46
+ * manifest never declared cannot be "not installed yet" — it is a wrong
47
+ * reference, and before #884 it was reported as one. `null` is a third answer
48
+ * and not an empty set: a project with no readable manifest has told us
49
+ * nothing, and nothing is not "depends on nothing".
50
+ */
51
+ export function declaredPackages(root: string): Set<string> | null {
52
+ let pkg: any;
53
+ try {
54
+ pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf-8"));
55
+ } catch {
56
+ return null;
57
+ }
58
+ if (pkg === null || typeof pkg !== "object") return null;
59
+ return new Set([
60
+ ...Object.keys(pkg.dependencies ?? {}),
61
+ ...Object.keys(pkg.devDependencies ?? {}),
62
+ ...Object.keys(pkg.optionalDependencies ?? {}),
63
+ ...Object.keys(pkg.peerDependencies ?? {}),
64
+ ]);
65
+ }
66
+
67
+ /** The pattern AGENT-6 has always used to find references. Unchanged. */
68
+ export const BRIEF_REFERENCE_PATTERN = /node_modules\/[^\s`*)"']+/g;
69
+
70
+ /** Markdown punctuation a reference picks up from the prose around it. */
71
+ export function cleanBriefReference(raw: string): string {
72
+ return raw.replace(/[`*)"']+$/, "");
73
+ }
74
+
75
+ export type BriefReferenceStatus = "resolved" | "broken" | "unresolvable";
76
+
77
+ export interface BriefReference {
78
+ /** The brief's file name, e.g. `quinn.md`. */
79
+ brief: string;
80
+ /** The cleaned reference, repo-relative. */
81
+ ref: string;
82
+ /** The installed tree this reference lives inside, repo-relative. */
83
+ packageRoot: string;
84
+ status: BriefReferenceStatus;
85
+ }
86
+
87
+ export interface BriefReferenceReading {
88
+ /** `UNMEASURED` as soon as one reference could not be looked at. */
89
+ reading: "MEASURED" | "UNMEASURED";
90
+ references: BriefReference[];
91
+ broken: BriefReference[];
92
+ unresolvable: BriefReference[];
93
+ /** The corpora the scan could not see, deduped and sorted. */
94
+ absentCorpora: string[];
95
+ }
96
+
97
+ /**
98
+ * The installed tree a reference lives inside — the thing whose absence makes
99
+ * the reference unknowable rather than wrong.
100
+ *
101
+ * For a scoped package that is `node_modules/@scope/name` and not
102
+ * `node_modules/@scope`: a scope directory holding some other package of the
103
+ * same scope is present while the package itself is not, and a corpus computed
104
+ * one segment short reads that tree as an install.
105
+ */
106
+ export function corpusOf(ref: string): string {
107
+ const parts = ref.split("/");
108
+ if (parts.length >= 3 && parts[1]!.startsWith("@")) return parts.slice(0, 3).join("/");
109
+ if (parts.length >= 2) return parts.slice(0, 2).join("/");
110
+ return "node_modules";
111
+ }
112
+
113
+ /**
114
+ * Three outcomes, and the order of the three questions is the whole design.
115
+ *
116
+ * 1. **A traversal segment is broken, and is never probed.** `node_modules/../..`
117
+ * matches the reference pattern, and probing it turns a conformity check
118
+ * into a filesystem-existence oracle for paths outside the repository. A
119
+ * brief naming one is a wrong reference whatever is on disk, so the answer
120
+ * does not need the disk.
121
+ * 2. **No install at all means no reading, unconditionally.** This is #884's
122
+ * case: a ship worktree. Nothing about the project's manifest can make a
123
+ * reference checkable when there is nothing to check it against.
124
+ * 3. **With an install present, the manifest decides.** A declared dependency
125
+ * that is not there is a broken or partial install — unknowable. A package
126
+ * the project never declared is a wrong reference, and it was reported as
127
+ * one before #884. Asking the manifest here is what stops the new
128
+ * UNMEASURED reading swallowing that finding: without it, a typo in a
129
+ * package name goes silent in a fully installed tree.
130
+ *
131
+ * A project with no readable manifest has said nothing, so step 3 cannot run
132
+ * and the answer is `unresolvable`. That is UNMEASURED by name, not a pass.
133
+ */
134
+ export function classifyBriefReference(
135
+ root: string,
136
+ ref: string,
137
+ declared: Set<string> | null = declaredPackages(root),
138
+ ): BriefReferenceStatus {
139
+ if (ref.split("/").includes("..")) return "broken";
140
+ if (!existsSync(join(root, "node_modules"))) return "unresolvable";
141
+ const corpus = corpusOf(ref);
142
+ if (!existsSync(join(root, corpus))) {
143
+ return declared !== null && !declared.has(corpus.replace(/^node_modules\//, ""))
144
+ ? "broken"
145
+ : "unresolvable";
146
+ }
147
+ return existsSync(join(root, ref)) ? "resolved" : "broken";
148
+ }
149
+
150
+ export function briefReferenceReading(root: string, agentsDir: string): BriefReferenceReading {
151
+ const references: BriefReference[] = [];
152
+ // Read once per reading, not once per reference: the manifest cannot change
153
+ // mid-scan, and a second read is a second chance to disagree with the first.
154
+ const declared = declaredPackages(root);
155
+ if (existsSync(agentsDir)) {
156
+ for (const brief of readdirSync(agentsDir).filter(f => f.endsWith(".md"))) {
157
+ const content = readFileSync(join(agentsDir, brief), "utf-8");
158
+ for (const raw of content.match(BRIEF_REFERENCE_PATTERN) ?? []) {
159
+ const ref = cleanBriefReference(raw);
160
+ references.push({
161
+ brief,
162
+ ref,
163
+ packageRoot: corpusOf(ref),
164
+ status: classifyBriefReference(root, ref, declared),
165
+ });
166
+ }
167
+ }
168
+ }
169
+ const broken = references.filter(r => r.status === "broken");
170
+ const unresolvable = references.filter(r => r.status === "unresolvable");
171
+ return {
172
+ reading: unresolvable.length > 0 ? "UNMEASURED" : "MEASURED",
173
+ references,
174
+ broken,
175
+ unresolvable,
176
+ absentCorpora: [...new Set(unresolvable.map(r => r.packageRoot))].sort(),
177
+ };
178
+ }
179
+
180
+ /** What a single unresolvable reference records, as the finding says it. */
181
+ export function unresolvableBriefReferenceMessage(r: BriefReference): string {
182
+ return (
183
+ `UNMEASURED — the brief references "${r.ref}", but "${r.packageRoot}" is not ` +
184
+ `installed in this checkout, so the reference was never checked. ` +
185
+ `This is not a passing reference and it is not a broken one.`
186
+ );
187
+ }
188
+
189
+ /**
190
+ * The line the suite prints in place of a reading it could not take, or `null`
191
+ * when there was nothing it could not take.
192
+ *
193
+ * `null` rather than an empty string: a notice composed unconditionally names
194
+ * UNMEASURED on a clean tree too, and then the word stops meaning anything.
195
+ */
196
+ export function unmeasuredBriefReferenceNotice(r: BriefReferenceReading): string | null {
197
+ if (r.reading !== "UNMEASURED") return null;
198
+ const lines = r.unresolvable.map(u => ` ${u.brief} → ${u.ref}`);
199
+ return (
200
+ `UNMEASURED — ${r.unresolvable.length} brief reference(s) could not be checked ` +
201
+ `because ${r.absentCorpora.join(", ")} ${r.absentCorpora.length === 1 ? "is" : "are"} ` +
202
+ `not installed here. Run the install in this checkout and re-run; a worktree ` +
203
+ `created without dependencies cannot see the package corpus.\n${lines.join("\n")}`
204
+ );
205
+ }
@@ -0,0 +1,347 @@
1
+ /**
2
+ * The one Bun version for a project (#622).
3
+ *
4
+ * Nothing in this repository pinned the runtime. `.github/workflows/ci.yml`
5
+ * and `gates.yml` carried `bun-version: "latest"`, `release.yml` carried the
6
+ * literal `"1.3.14"`, the development machine ran 1.3.14 and CI's `latest`
7
+ * resolved to **1.4.3** — a full minor apart, with nothing comparing any of
8
+ * the four.
9
+ *
10
+ * `latest` is the opposite of a pin: the runtime executing a given commit can
11
+ * change between two runs of that same commit, with nothing in the diff to
12
+ * explain a new failure. Re-running a red job was also a Bun upgrade, and a
13
+ * green local run could not say which runtime produced it.
14
+ *
15
+ * ## Why this is a module and not a string in two template literals
16
+ *
17
+ * It was two, and they were fed by `harness?.ci?.bunVersion || "latest"` in
18
+ * `lib/scaffold/steps.ts` while two other workflow files — neither of them
19
+ * generated — named versions of their own. Four positions, three spellings,
20
+ * no decider. This is #87's fix for the type check and #488's for the test
21
+ * command, applied to the step directly beside them: one binding, so a
22
+ * mutation of it can show that the agreement is load-bearing rather than
23
+ * coincidental.
24
+ *
25
+ * ## The rungs, and what each one is not
26
+ *
27
+ * 1. **`.bun-version` at the project root.** The ecosystem's file:
28
+ * `oven-sh/setup-bun` reads it through `bun-version-file`, and so do
29
+ * `mise` and `asdf`. It wins because it is the file CI itself obeys —
30
+ * a resolver that preferred something else would be naming a version CI
31
+ * does not install.
32
+ * 2. **`ci.bunVersion` in the rungate config.** The field the harness has
33
+ * documented since SC-86, and the only declaration a consumer who has not
34
+ * adopted `.bun-version` has. Emitted as a literal, because there is no
35
+ * file for CI to point at.
36
+ * 3. **Nothing.** `null`, and the state is named `undeclared` rather than
37
+ * quietly becoming `latest`. `.claude/rules/config-access.md`: a built-in
38
+ * default substituted for an absent declaration must be loud, because `0`,
39
+ * `{}`, `null` and silence are all indistinguishable from success.
40
+ *
41
+ * ## What this does NOT cover
42
+ *
43
+ * - **Which bun is on the developer's PATH.** Two installations from two
44
+ * package managers sit on the issue's machine; this reports the mismatch,
45
+ * it cannot fix it. That is what `bunVersionReading` is for.
46
+ * - **Whether the declared version exists.** A pin CI cannot resolve fails
47
+ * the job, loudly, naming the value — which is the point. A
48
+ * well-formedness guard with `|| "latest"` behind it is the cheapest repair
49
+ * for that failure and is exactly the silent fallback AC-7 forbids, so
50
+ * `isPinnedBunVersion` refuses moving tags and nothing else.
51
+ * - **`package.json` `engines.bun` and `.tool-versions`.** Neither exists in
52
+ * this tree, and a rung nobody declares is a rung nothing can test. Add one
53
+ * here, with a case, if a consumer turns up on it — not before.
54
+ * - **`workflows/*.js`.** They cannot import (#69) and none of them installs
55
+ * bun; if one ever does, it reads the resolved config the way every other
56
+ * workflow prompt does.
57
+ */
58
+ import { existsSync, readFileSync } from "fs";
59
+ import { join } from "path";
60
+ import { tryLoadRungateConfig } from "./config-loader";
61
+
62
+ /** The declaration file, at the project root. The name `setup-bun` knows. */
63
+ export const BUN_VERSION_FILE = ".bun-version";
64
+
65
+ /**
66
+ * Tags that resolve to whatever shipped today. Declaring one is a declaration
67
+ * that the project is NOT pinned, which is a legitimate thing for a consumer
68
+ * to choose and is not a thing this repository may choose by accident.
69
+ */
70
+ export const MOVING_BUN_TAGS = ["latest", "canary"] as const;
71
+
72
+ export type BunVersionSource = "bun-version-file" | "config" | "undeclared";
73
+
74
+ export interface BunVersionDecision {
75
+ /** The declared version. Null only when nothing declares one. */
76
+ version: string | null;
77
+ source: BunVersionSource;
78
+ /** Why this version and not another. */
79
+ reason: string;
80
+ /**
81
+ * Both declarations present and disagreeing. Empty when they agree, or when
82
+ * only one of them exists. Reported rather than resolved in silence: two
83
+ * positions naming two versions is #621's defect, and the loser here is the
84
+ * one a human is most likely to have edited.
85
+ */
86
+ conflict: string;
87
+ }
88
+
89
+ /** Where a decision came from, spelled the way a log reader can act on. */
90
+ export function bunVersionSourceLabel(source: BunVersionSource): string {
91
+ if (source === "bun-version-file") return BUN_VERSION_FILE;
92
+ if (source === "config") return "ci.bunVersion in .claude/rungate/config.json";
93
+ return "no declaration";
94
+ }
95
+
96
+ /**
97
+ * Is this a pin — a value that names the same runtime tomorrow?
98
+ *
99
+ * Deliberately NOT a semver test. `1.0.x`, a commit sha and a download URL are
100
+ * all things `setup-bun` resolves, and narrowing this to `\d+\.\d+\.\d+` is
101
+ * the over-narrow detector that would reject a legitimate declaration and send
102
+ * someone looking for a fallback.
103
+ */
104
+ export function isPinnedBunVersion(version: string | null | undefined): boolean {
105
+ if (typeof version !== "string") return false;
106
+ const v = version.trim();
107
+ if (v === "") return false;
108
+ return !(MOVING_BUN_TAGS as readonly string[]).includes(v);
109
+ }
110
+
111
+ function fileDeclaration(root: string): string | null {
112
+ const path = join(root, BUN_VERSION_FILE);
113
+ if (!existsSync(path)) return null;
114
+ // A file that exists and says nothing is not a declaration. It is also not
115
+ // a reason to throw: `setup-bun` would fail on it anyway, and the rung below
116
+ // is a better answer than a dead scaffold.
117
+ const raw = readFileSync(path, "utf-8").trim();
118
+ return raw === "" ? null : raw;
119
+ }
120
+
121
+ function configDeclaration(root: string): string | null {
122
+ // Through the loader, never a constructed path to `.claude/rungate*`
123
+ // (`.claude/rules/config-access.md`), so both config layouts are honoured.
124
+ // It THROWS on a malformed config, deliberately: a corrupt config is never a
125
+ // missing config, and `catch {}` here is the conversion that rule forbids.
126
+ const config = tryLoadRungateConfig(root) as { ci?: { bunVersion?: unknown } } | null;
127
+ const declared = config?.ci?.bunVersion;
128
+ if (typeof declared !== "string" || declared.trim() === "") return null;
129
+ return declared.trim();
130
+ }
131
+
132
+ /** One position that declares a version, and what it says. */
133
+ export interface BunVersionDeclaration {
134
+ source: Exclude<BunVersionSource, "undeclared">;
135
+ version: string;
136
+ }
137
+
138
+ /**
139
+ * Every position in a project that declares a Bun version, in rung order.
140
+ *
141
+ * Separate from `declaredBunVersion` because the two questions are different:
142
+ * the decision is "what will CI install", and this is "who said so". A caller
143
+ * comparing positions — `scripts/contract-parity.ts` — needs the second, and
144
+ * reconstructing it from the decision's `conflict` string was the alternative:
145
+ * a consumer parsing a producer's prose, which is this repository's most
146
+ * expensive recurring mistake (#626).
147
+ */
148
+ export function bunVersionDeclarations(root: string): BunVersionDeclaration[] {
149
+ const out: BunVersionDeclaration[] = [];
150
+ const fromFile = fileDeclaration(root);
151
+ if (fromFile !== null) out.push({ source: "bun-version-file", version: fromFile });
152
+ const fromConfig = configDeclaration(root);
153
+ if (fromConfig !== null) out.push({ source: "config", version: fromConfig });
154
+ return out;
155
+ }
156
+
157
+ export function declaredBunVersion(root: string): BunVersionDecision {
158
+ const declarations = bunVersionDeclarations(root);
159
+ const fromFile = declarations.find(d => d.source === "bun-version-file")?.version ?? null;
160
+ const fromConfig = declarations.find(d => d.source === "config")?.version ?? null;
161
+ const conflict =
162
+ fromFile !== null && fromConfig !== null && fromFile !== fromConfig
163
+ ? `${BUN_VERSION_FILE} declares ${fromFile} and ci.bunVersion declares ${fromConfig}; ` +
164
+ `CI installs what ${BUN_VERSION_FILE} says, so the config field is the stale one`
165
+ : "";
166
+
167
+ if (fromFile !== null) {
168
+ return {
169
+ version: fromFile,
170
+ source: "bun-version-file",
171
+ reason: `the project declares ${BUN_VERSION_FILE}, which is the file setup-bun itself reads`,
172
+ conflict,
173
+ };
174
+ }
175
+ if (fromConfig !== null) {
176
+ return {
177
+ version: fromConfig,
178
+ source: "config",
179
+ reason: `the project declares ci.bunVersion and no ${BUN_VERSION_FILE}`,
180
+ conflict,
181
+ };
182
+ }
183
+ return {
184
+ version: null,
185
+ source: "undeclared",
186
+ reason: `the project declares neither ${BUN_VERSION_FILE} nor ci.bunVersion`,
187
+ conflict,
188
+ };
189
+ }
190
+
191
+ export type BunVersionState = "match" | "mismatch" | "undeclared";
192
+
193
+ export interface BunVersionReading {
194
+ state: BunVersionState;
195
+ /** One line, for a log somebody pastes into an issue. */
196
+ line: string;
197
+ }
198
+
199
+ /**
200
+ * What a run should say about the runtime it is running on.
201
+ *
202
+ * `running` is a parameter rather than `Bun.version` read inside, and that is
203
+ * the whole of AC-4: a comparison that reads the machine can only be driven
204
+ * with the machine's own answer, so the mismatch branch is unreachable from a
205
+ * test on any machine that is already correct — which is every machine where
206
+ * the case would be written.
207
+ */
208
+ export function bunVersionReading(decision: BunVersionDecision, running: string): BunVersionReading {
209
+ const suffix = decision.conflict ? ` WARNING: ${decision.conflict}.` : "";
210
+
211
+ if (decision.version === null) {
212
+ return {
213
+ state: "undeclared",
214
+ line:
215
+ `bun ${running} is running, and the declared version is UNMEASURED — ` +
216
+ `${decision.reason}, so this run says nothing about what CI will install.${suffix}`,
217
+ };
218
+ }
219
+ if (decision.version !== running) {
220
+ return {
221
+ state: "mismatch",
222
+ line:
223
+ `WARNING: bun ${running} is running but ${bunVersionSourceLabel(decision.source)} declares ` +
224
+ `${decision.version} — this run does NOT model CI, and a result pasted from it ` +
225
+ `describes ${running}.${suffix}`,
226
+ };
227
+ }
228
+ return {
229
+ state: "match",
230
+ line: `bun ${running} (declared in ${bunVersionSourceLabel(decision.source)}).${suffix}`,
231
+ };
232
+ }
233
+
234
+ /**
235
+ * What a `setup-bun` step's `with:` block NAMES, one entry per step.
236
+ *
237
+ * The reading half of `setupBunWith` below, and here rather than in
238
+ * `scripts/contract-parity.ts` (#637, AC-9) for one reason: the generator and
239
+ * the reader of the thing it generates are a producer and a consumer that must
240
+ * agree, and keeping them in one module is what makes a round-trip case —
241
+ * emit a step, read it back, compare — an ordinary import rather than a second
242
+ * copy of this regex somewhere a script can reach.
243
+ *
244
+ * Deliberately text, not YAML: `#622c`'s position is the step the SCAFFOLD
245
+ * would emit, which is a string that has never been a file.
246
+ */
247
+ export function setupBunDeclarations(text: string): Array<{ key: "bun-version" | "bun-version-file"; value: string }> {
248
+ const out: Array<{ key: "bun-version" | "bun-version-file"; value: string }> = [];
249
+ for (const m of text.matchAll(/^\s*(bun-version|bun-version-file):\s*"?([^"\s#]+)"?\s*$/gm)) {
250
+ out.push({ key: m[1] as "bun-version" | "bun-version-file", value: m[2] });
251
+ }
252
+ return out;
253
+ }
254
+
255
+ /**
256
+ * The `# UNPINNED:` block, spelled in exactly one place (#932).
257
+ *
258
+ * Three rungs can now reach it — a moving tag in `.bun-version`, a moving tag
259
+ * in `ci.bunVersion`, and no declaration at all — and a second copy of the
260
+ * marker would survive a mutation of the first, leaving a case green over a
261
+ * rung that had gone quiet (`.claude/rules/checks-must-be-able-to-fail.md`).
262
+ */
263
+ function unpinnedComment(indent: string, why: string, remedy: string): string {
264
+ return (
265
+ `${indent}# UNPINNED: ${why}, so every run of this job installs whatever\n` +
266
+ `${indent}# shipped today and re-running a red job is also a Bun upgrade. ${remedy}\n`
267
+ );
268
+ }
269
+
270
+ /** How to stop being unpinned, from a rung that already declares something. */
271
+ function repinRemedy(source: Exclude<BunVersionSource, "undeclared">): string {
272
+ return `Name an exact version in ${bunVersionSourceLabel(source)} and re-scaffold.`;
273
+ }
274
+
275
+ /**
276
+ * The `with:` body of a generated `oven-sh/setup-bun` step.
277
+ *
278
+ * One function, so the generator has nothing to decide and no second place
279
+ * for a fallback to grow. It returns LINES rather than writing anything,
280
+ * which is what lets a test assert the emission for a declaration no machine
281
+ * has — including one CI cannot resolve.
282
+ *
283
+ * ## Why the pin test is asked here and not only by the checker (#932)
284
+ *
285
+ * `isPinnedBunVersion` had exactly one consumer — `scripts/contract-parity.ts`
286
+ * — and the generator was not it. So a consumer declaring
287
+ * `ci.bunVersion: "latest"` had `bun-version: "latest"` written into a managed
288
+ * workflow under prose describing a successful declaration, and the only way
289
+ * to learn otherwise was to run the checker, which then called that same line
290
+ * a violation. One predicate, two positions, opposite behaviour.
291
+ *
292
+ * Worse, it inverted the rungs: a project declaring NOTHING got the loud block
293
+ * below, and a project declaring a moving tag got silence. Declaring `latest`
294
+ * was reported strictly better than declaring nothing, while installing the
295
+ * same runtime.
296
+ *
297
+ * The VALUE is still emitted verbatim at every rung. `MOVING_BUN_TAGS` says
298
+ * declaring one "is a legitimate thing for a consumer to choose", and
299
+ * substituting a pin here would change a consumer's runtime without being
300
+ * asked — which is AC-7's forbidden silent fallback wearing a fix. What
301
+ * changes is only that the file says what it is.
302
+ */
303
+ export function setupBunWith(decision: BunVersionDecision, indent: string): string {
304
+ const pinned = isPinnedBunVersion(decision.version);
305
+
306
+ if (decision.source === "bun-version-file") {
307
+ // The file still wins and CI still reads it: what is wrong about a
308
+ // `.bun-version` holding `canary` is the prose, not the mechanism, and
309
+ // spelling a literal here instead would put a second position naming the
310
+ // version back into the workflow — #622's defect, repaired into existence.
311
+ const comment = pinned
312
+ ? `${indent}# Pinned by ${BUN_VERSION_FILE} — the project's single declaration (#622).\n` +
313
+ `${indent}# setup-bun reads that file, so there is no version spelled here to drift from it.\n`
314
+ : unpinnedComment(
315
+ indent,
316
+ `${BUN_VERSION_FILE} declares the moving tag \`${decision.version}\``,
317
+ repinRemedy("bun-version-file"),
318
+ );
319
+ return comment + `${indent}bun-version-file: "${BUN_VERSION_FILE}"`;
320
+ }
321
+
322
+ if (decision.source === "config") {
323
+ const comment = pinned
324
+ ? `${indent}# From ci.bunVersion in .claude/rungate/config.json — this project declares no\n` +
325
+ `${indent}# ${BUN_VERSION_FILE}. Add one and re-scaffold to let CI read the declaration directly.\n`
326
+ : unpinnedComment(
327
+ indent,
328
+ `ci.bunVersion in .claude/rungate/config.json declares the moving tag ` +
329
+ `\`${decision.version}\``,
330
+ repinRemedy("config"),
331
+ );
332
+ return comment + `${indent}bun-version: "${decision.version}"`;
333
+ }
334
+
335
+ // UNPINNED, said out loud. The value is unchanged from what this generator
336
+ // has always emitted for a project that declares nothing — changing a
337
+ // consumer's runtime without being asked is not this issue's business — but
338
+ // the silence is. An unpinned CI is a state, and a state that is not
339
+ // reportable is one nobody fixes.
340
+ return (
341
+ unpinnedComment(
342
+ indent,
343
+ decision.reason,
344
+ `Declare a version in ${BUN_VERSION_FILE} (or ci.bunVersion) and re-scaffold.`,
345
+ ) + `${indent}bun-version: "latest"`
346
+ );
347
+ }