rungate 0.4.1 → 0.6.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 (87) hide show
  1. package/config/behavioral-sc-map.json +170 -0
  2. package/config/brief-policies.json +28 -0
  3. package/config/ceremony-profiles.json +207 -0
  4. package/config/check-registry.json +114 -0
  5. package/config/matcher-registry.json +142 -0
  6. package/config/prove-evidence.schema.json +65 -0
  7. package/config/spec-policies.json +36 -0
  8. package/config/universal-rules.yaml +15 -0
  9. package/config/workflow-schema.json +279 -0
  10. package/lib/agents-md-sections.ts +144 -0
  11. package/lib/branch-diff.ts +139 -0
  12. package/lib/bun-version.ts +268 -0
  13. package/lib/ci-checkout.ts +1 -1
  14. package/lib/cli-commands.ts +7 -1
  15. package/lib/compliance.ts +13 -11
  16. package/lib/config-loader.ts +12 -0
  17. package/lib/conformity.ts +1147 -116
  18. package/lib/context-docs.ts +143 -28
  19. package/lib/create-brief.ts +2 -1
  20. package/lib/create-sc.ts +90 -4
  21. package/lib/doc-scan-targets.ts +9 -0
  22. package/lib/evidence-command-transport.ts +160 -0
  23. package/lib/evidence-prevalidator.ts +22 -0
  24. package/lib/fallow-availability.ts +129 -0
  25. package/lib/gate-refusal-currency.ts +112 -0
  26. package/lib/gate-timeouts.ts +82 -0
  27. package/lib/generators/agent-briefs.ts +4 -1
  28. package/lib/generators/agents-md.ts +71 -23
  29. package/lib/generators/code-map.ts +2 -1
  30. package/lib/generators/types.ts +8 -0
  31. package/lib/git-dates.ts +55 -0
  32. package/lib/github.ts +195 -0
  33. package/lib/js-top-level-code.ts +27 -2
  34. package/lib/junit-checks.ts +484 -0
  35. package/lib/local-calendar-day.ts +78 -0
  36. package/lib/package-closure.ts +278 -2
  37. package/lib/project-state-shape.ts +59 -0
  38. package/lib/promote-outputs.ts +6 -2
  39. package/lib/release-preflight.ts +196 -0
  40. package/lib/report-provenance.ts +156 -0
  41. package/lib/sc-claim-forms.ts +75 -0
  42. package/lib/sc-id-cross-tree.ts +311 -0
  43. package/lib/scaffold/ai-review-step.ts +180 -0
  44. package/lib/scaffold/defaults.ts +40 -0
  45. package/lib/scaffold/managed-workflow.ts +125 -27
  46. package/lib/scaffold/owned-files.ts +48 -2
  47. package/lib/scaffold/profiles.ts +94 -0
  48. package/lib/scaffold/rehearsal.ts +232 -73
  49. package/lib/scaffold/steps.ts +777 -152
  50. package/lib/scaffold/write-steps.ts +56 -13
  51. package/lib/scanner.ts +38 -12
  52. package/lib/source-anchor.ts +144 -0
  53. package/lib/spec-listing.ts +148 -0
  54. package/lib/spec-requirements.ts +209 -0
  55. package/lib/success-doc.ts +779 -0
  56. package/lib/suite-run-reading.ts +364 -0
  57. package/lib/test-census.ts +199 -0
  58. package/lib/test-command.ts +133 -0
  59. package/lib/test-suite-lock.ts +166 -10
  60. package/lib/tool-probe.ts +120 -0
  61. package/lib/tracked-vs-ignored.ts +234 -0
  62. package/lib/trajectory.ts +377 -0
  63. package/lib/validators/spec-validators.ts +35 -6
  64. package/lib/workflow-security.ts +101 -0
  65. package/lib/workflow-test-harness.ts +349 -0
  66. package/package.json +6 -1
  67. package/scripts/audit-specs.ts +247 -12
  68. package/scripts/audit-transcript.ts +2 -1
  69. package/scripts/convert-spec.ts +2 -1
  70. package/scripts/create-sc.ts +17 -7
  71. package/scripts/create-spec.ts +2 -1
  72. package/scripts/create-success.ts +163 -0
  73. package/scripts/extract-constraints.ts +90 -19
  74. package/scripts/generate-code-map.ts +53 -12
  75. package/scripts/scaffold-project.ts +31 -4
  76. package/scripts/split-spec.ts +2 -1
  77. package/scripts/sync-sc-status.ts +57 -5
  78. package/scripts/sync-spec-tests.ts +2 -1
  79. package/specs/SPEC-TEMPLATE.md +200 -0
  80. package/templates/SUCCESS-TEMPLATE.md +72 -0
  81. package/templates/agent-briefs/_shared.md +9 -0
  82. package/templates/agent-briefs/aditi.md +46 -0
  83. package/templates/agent-briefs/discovery.md +37 -0
  84. package/templates/agent-briefs/marcus.md +39 -0
  85. package/templates/agent-briefs/quinn.md +67 -0
  86. package/templates/agent-briefs/rook.md +40 -0
  87. package/templates/agent-briefs/serena.md +39 -0
@@ -7,7 +7,7 @@
7
7
  * Extracted per SCAFFOLD-DECOMPOSITION-SPEC to keep scaffold-project.ts
8
8
  * as orchestrator-only (under 200 lines).
9
9
  */
10
- import { existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync, statSync } from "fs";
10
+ import { existsSync, lstatSync, mkdirSync, readFileSync, writeFileSync, readdirSync, statSync } from "fs";
11
11
  import { join, basename, dirname } from "path";
12
12
  import { auditSpecs } from "../../scripts/audit-specs";
13
13
  import { generateAgentsMd as buildAgentsMdContent, generateScopedRules } from "../generators/agents-md";
@@ -16,15 +16,32 @@ import { generateAgentBriefs as buildAgentBriefsContent } from "../generators/ag
16
16
  import { generateCodeMap as buildCodeMapContent } from "../generators/code-map";
17
17
  import { buildAgentMeta, DEFAULT_AGENT_META } from "../create-brief";
18
18
  import { buildDefaultRoles, buildDefaultHooks } from "./defaults";
19
- import { mergeManagedWorkflow } from "./managed-workflow";
19
+ import {
20
+ mergeManagedWorkflow,
21
+ duplicateTopLevelKeys,
22
+ movedTopLevelKeys,
23
+ type MovedKey,
24
+ } from "./managed-workflow";
20
25
  import { PRE_PUSH_MANAGED_MARKER, prePushHookScript } from "./pre-push-hook";
21
26
  import { loadComplianceConfig, tryLoadRungateConfig } from "../config-loader";
22
27
  import { organizeProjectReport } from "../organize";
23
28
  import type { ProjectScan, ProjectType, SpecEntry, TestFile, RefFile, DocRoute, Category } from "../generators/types";
24
29
  import { tier1Ere } from "../secret-patterns";
25
30
  import { healthPathIn } from "../liveness-contradiction";
31
+ import { localCalendarDay } from "../local-calendar-day";
26
32
  import { decideRuleWrite } from "../rule-provenance";
33
+ import { DEFAULT_PROFILE, isRuleIncluded, type ScaffoldProfile } from "./profiles";
27
34
  import { referencedPaths } from "../agents-md-refs";
35
+ import { inferredTestCommand, testCommandDecision } from "../test-command";
36
+ import { declaredBunVersion, setupBunWith } from "../bun-version";
37
+ import { codeMapUnreferenced, unlistedSpecs } from "../spec-listing";
38
+ import {
39
+ readSuccessDoc,
40
+ readSuccessTemplate,
41
+ seedFromTemplate,
42
+ successViolations,
43
+ TEMPLATE_MISSING,
44
+ } from "../success-doc";
28
45
  import { TS_SOURCE_DIRS, typeScriptSourceDirs, typecheckDecision } from "../typescript-project";
29
46
  import {
30
47
  OWNED_FILES,
@@ -123,7 +140,47 @@ export function regenerateOwned(
123
140
  actions: string[],
124
141
  strategy: WriteStrategy = ownedStrategy(label),
125
142
  ): void {
126
- const existing = existsSync(filePath) ? readFileSync(filePath, "utf-8") : null;
143
+ // `lstatSync`, NOT `existsSync` — BUG-440-A's shape, found by security
144
+ // review of #502 and PRE-EXISTING: it reaches `project-state.json` and
145
+ // every other owned file, not just the one that surfaced it.
146
+ //
147
+ // `existsSync` RESOLVES a symlink and `writeFileSync` FOLLOWS one, so the
148
+ // two disagree about exactly one input: a dangling `SUCCESS.md ->
149
+ // /elsewhere/x` is "absent" to the guard and a live write target to the
150
+ // writer. Measured: the scaffold created `/tmp/dang/victim/newfile.json`
151
+ // from a symlink planted at `project-state.json`, outside the project root
152
+ // entirely, and reported `CREATED: project-state.json`.
153
+ //
154
+ // `lstatSync` describes the LINK, so a symlink of either kind is something
155
+ // that is already there — which is what create-only means by "exists", and
156
+ // what the regenerate strategies must refuse rather than write through.
157
+ let link: ReturnType<typeof lstatSync> | null = null;
158
+ try {
159
+ link = lstatSync(filePath);
160
+ } catch {
161
+ link = null;
162
+ }
163
+ if (link?.isSymbolicLink()) {
164
+ actions.push(
165
+ `${SCAFFOLD_REFUSE}: ${label} is a symlink, and the generator does not write through ` +
166
+ `one — the target may be outside this project. Replace it with a real file, or ` +
167
+ `delete it and re-run.`,
168
+ );
169
+ return;
170
+ }
171
+ if (link && !link.isFile()) {
172
+ // A directory (or a device, or a socket) where an owned file belongs.
173
+ // `readFileSync` throws EISDIR, and that throw ESCAPES the step and
174
+ // aborts the whole scaffold run mid-way — after some files are written
175
+ // and before others. A refusal that names the path leaves the tree in a
176
+ // state someone can reason about; a half-finished run does not.
177
+ actions.push(
178
+ `${SCAFFOLD_REFUSE}: ${label} exists but is not a regular file, so the generator ` +
179
+ `will not read or replace it. Remove it and re-run.`,
180
+ );
181
+ return;
182
+ }
183
+ const existing = link ? readFileSync(filePath, "utf-8") : null;
127
184
  const decision = decideOwnedWrite(strategy, existing, content);
128
185
 
129
186
  if (decision.action === "preserve") {
@@ -133,12 +190,28 @@ export function regenerateOwned(
133
190
  );
134
191
  return;
135
192
  }
193
+ if (decision.action === "refuse") {
194
+ // Not the same thing as `preserve`, and the advice is the opposite:
195
+ // `preserve` means the file on disk is yours and the generator stood
196
+ // down, so deleting it accepts the generator. This means the generator
197
+ // cannot produce an output that keeps a promise the spec makes, and
198
+ // deleting the file would destroy exactly the content at issue.
199
+ actions.push(`${SCAFFOLD_REFUSE}: ${label} not written — ${decision.reason}`);
200
+ return;
201
+ }
136
202
  if (decision.action === "unchanged") {
137
203
  actions.push(`UNCHANGED: ${label} (${decision.reason})`);
138
204
  return;
139
205
  }
140
206
 
141
- const dir = filePath.substring(0, filePath.lastIndexOf("/"));
207
+ // `dirname`, not a hand-rolled slice (#481). `substring(0, lastIndexOf("/"))`
208
+ // is correct for every path carrying a separator and silently wrong for the
209
+ // one that does not: `lastIndexOf` returns -1, `substring` CLAMPS a negative
210
+ // end to zero, and the directory to create becomes `""` — which does not
211
+ // exist, so the guard admits it, and `mkdirSync("")` throws ENOENT. Every
212
+ // repo-root owned file hits that under a relative root, which is the form
213
+ // the harness documents.
214
+ const dir = dirname(filePath);
142
215
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
143
216
  writeFileSync(filePath, decision.content!);
144
217
  actions.push(`${decision.action === "create" ? "CREATED" : "CHANGED"}: ${label}`);
@@ -181,40 +254,6 @@ function loadHarnessConfig(root: string): any {
181
254
 
182
255
  // ── AGENTS.md generation and updates ───────────────────────────
183
256
 
184
- export function updateSpecsTable(agentsMdPath: string, actions: string[]): void {
185
- if (!existsSync(agentsMdPath)) return;
186
- const specsDir = join(dirname(agentsMdPath), "specs");
187
- if (!existsSync(specsDir)) return;
188
-
189
- const specFiles = readdirSync(specsDir).filter(f => f.endsWith(".md") && f !== "SPEC-TEMPLATE.md");
190
- if (specFiles.length === 0) return;
191
-
192
- const specRows: string[] = [];
193
- for (const f of specFiles) {
194
- const content = readFileSync(join(specsDir, f), "utf-8");
195
- const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
196
- let testable = "false";
197
- let governs = f.replace(/\.md$/, "");
198
- if (fmMatch) {
199
- const tMatch = fmMatch[1].match(/testable:\s*(true|false)/);
200
- if (tMatch) testable = tMatch[1];
201
- const gMatch = fmMatch[1].match(/governs:\s*(.+)/);
202
- if (gMatch) governs = gMatch[1].trim();
203
- }
204
- specRows.push(`| ${f} | ${governs} | ${testable === "true" ? "yes" : "no"} |`);
205
- }
206
-
207
- const existing = readFileSync(agentsMdPath, "utf-8");
208
- const tablePattern = /(\|[^\n]*Spec[^\n]*\|\n\|[-| ]+\|\n)((?:\|[^\n]+\|\n)*)/;
209
- const match = existing.match(tablePattern);
210
- if (match) {
211
- const newTable = match[1] + specRows.join("\n") + "\n";
212
- const updated = existing.replace(tablePattern, newTable);
213
- writeFileSync(agentsMdPath, updated);
214
- actions.push("UPDATED: AGENTS.md specs table from frontmatter");
215
- }
216
- }
217
-
218
257
  export function injectEnvironmentSection(root: string, actions: string[]): void {
219
258
  const agentsMdPath = join(root, "AGENTS.md");
220
259
  if (!existsSync(agentsMdPath)) return;
@@ -262,7 +301,12 @@ export function injectEnvironmentSection(root: string, actions: string[]): void
262
301
  actions.push("UPDATED: AGENTS.md environment section from rungate.json");
263
302
  }
264
303
 
265
- export function generateAgentsMdContent(projectPath: string, type: ProjectType, actions: string[]): string {
304
+ export function generateAgentsMdContent(
305
+ projectPath: string,
306
+ type: ProjectType,
307
+ actions: string[],
308
+ profile: ScaffoldProfile = DEFAULT_PROFILE,
309
+ ): string {
266
310
  const pkgPath = join(projectPath, "package.json");
267
311
  let pkgDesc = "";
268
312
  let pkgName = basename(projectPath);
@@ -410,14 +454,10 @@ export function generateAgentsMdContent(projectPath: string, type: ProjectType,
410
454
  }
411
455
  }
412
456
 
413
- // Detect test command
414
- let testCmd = "bun test";
415
- if (existsSync(pkgPath)) {
416
- try {
417
- const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
418
- if (pkg.scripts?.test) testCmd = pkg.scripts.test;
419
- } catch {}
420
- }
457
+ // Detect test command — through the one binding (#488). This copy read
458
+ // package.json and nothing else, so AGENTS.md's Commands row ignored a
459
+ // `dev.testCmd` the agent briefs honoured and CI ignored both.
460
+ const testCmd = testCommandDecision(projectPath).command;
421
461
 
422
462
  // Scan reference files
423
463
  const refDir = join(projectPath, "reference");
@@ -552,7 +592,9 @@ export function generateAgentsMdContent(projectPath: string, type: ProjectType,
552
592
  // why neither "never overwrite" nor "always overwrite" is the answer.
553
593
  const rulesDir = join(projectPath, ".claude", "rules");
554
594
  if (!existsSync(rulesDir)) mkdirSync(rulesDir, { recursive: true });
555
- const scopedRules = generateScopedRules(scan);
595
+ // A rule is instructions to an agent, so one naming machinery the profile
596
+ // did not install is worse than no rule at all. See RULES_NOT_MINIMAL.
597
+ const scopedRules = generateScopedRules(scan).filter(r => isRuleIncluded(r.filename, profile));
556
598
  for (const rule of scopedRules) {
557
599
  const rulePath = join(rulesDir, rule.filename);
558
600
  const existing = existsSync(rulePath) ? readFileSync(rulePath, "utf-8") : null;
@@ -594,12 +636,23 @@ export function generateAgentsMdContent(projectPath: string, type: ProjectType,
594
636
  * Re-running the generator is safe and cheap: `generateAgentsMdContent` writes
595
637
  * only the rules, and returns AGENTS.md content for its caller to write. The
596
638
  * return value is discarded here on purpose — AGENTS.md has already been
597
- * through `updateSpecsTable` and `injectEnvironmentSection` by this point, and
598
- * rewriting it would undo both.
639
+ * through `injectEnvironmentSection` by this point, and rewriting it would
640
+ * undo that.
641
+ *
642
+ * It used to say `updateSpecsTable` as well. That function ran immediately
643
+ * after the generator had rewritten AGENTS.md, edited an EXISTING table
644
+ * matched on a header row containing `Spec`, and the generator emits no such
645
+ * table — so the match never succeeded, the `if` had no `else`, and its
646
+ * action string never once appeared in a report. It is deleted (#382).
599
647
  */
600
- export function refreshScopedRulesStep(root: string, type: ProjectType, actions: string[]): void {
648
+ export function refreshScopedRulesStep(
649
+ root: string,
650
+ type: ProjectType,
651
+ actions: string[],
652
+ profile: ScaffoldProfile = DEFAULT_PROFILE,
653
+ ): void {
601
654
  const sink: string[] = [];
602
- generateAgentsMdContent(root, type, sink);
655
+ generateAgentsMdContent(root, type, sink, profile);
603
656
  // Forward everything except the per-rule lines already reported by the
604
657
  // Phase 0.5 pass. Swallowing the rest would hide a warning raised only on
605
658
  // the second scan — the fail-open shape .claude/rules/checks-must-be-able-to-fail.md
@@ -652,19 +705,23 @@ export function refreshAgentsMd(root: string, type: ProjectType, actions: string
652
705
  } catch (e: unknown) { console.warn('Staleness check failed for', ref, (e as Error).message); }
653
706
  }
654
707
 
655
- // Check specs table
656
- const specsDir = join(root, "specs");
657
- if (existsSync(specsDir)) {
658
- const actualSpecs = readdirSync(specsDir).filter(f => f.endsWith(".md"));
659
- const unlisted = actualSpecs.filter(f => !content.includes(f));
660
- if (unlisted.length > 0) {
661
- issues.push(`UNLISTED specs: ${unlisted.join(", ")} (in specs/ but not in AGENTS.md)`);
662
- }
708
+ // Check specs table.
709
+ //
710
+ // Across AGENTS.md AND `.claude/rules/`, because D-15 capped AGENTS.md at
711
+ // 100 lines and moved both tables there (#382). Asked of `lib/spec-listing.ts`
712
+ // rather than inline: this site had its own idea of what counts as a spec —
713
+ // every `.md` in `specs/`, including `SPEC-TEMPLATE.md` — and the routing
714
+ // generator had another, so the one entry that could never be listed
715
+ // anywhere was reported on every run.
716
+ const unlisted = unlistedSpecs(root);
717
+ if (unlisted.length > 0) {
718
+ issues.push(`UNLISTED specs: ${unlisted.join(", ")} (in specs/ but not in AGENTS.md or .claude/rules/)`);
663
719
  }
664
720
 
665
- // Check CODE-MAP.md reference
666
- if (existsSync(join(root, "CODE-MAP.md")) && !content.includes("CODE-MAP")) {
667
- issues.push("CODE-MAP.md exists but not referenced in AGENTS.md routing table");
721
+ // Check CODE-MAP.md reference — same surfaces, same reason. It is named in
722
+ // the first row of `.claude/rules/docs-routing.md`.
723
+ if (codeMapUnreferenced(root)) {
724
+ issues.push("CODE-MAP.md exists but not referenced in AGENTS.md or .claude/rules/");
668
725
  }
669
726
 
670
727
  if (issues.length > 0 || staleFiles.length > 0) {
@@ -710,7 +767,7 @@ export function generateConformityTest(root?: string): string {
710
767
  const from = root && isHarnessItself(root) ? "../lib/conformity" : "rungate/lib/conformity";
711
768
  return `import { resolve } from "path";
712
769
  import { afterAll } from "bun:test";
713
- import { runScaffoldConformity, runSpecDiscovery, runSpecDrift, runDocHygiene, runFallowCheck, runAgentFileValidation, runDirectoryValidation, runPackageValidation, runTsconfigValidation, runConfigAccessValidation, runPromptConfigAccessValidation, writeFindingsReport } from "${from}";
770
+ import { runScaffoldConformity, runSpecDiscovery, runSpecDrift, runDocHygiene, runFallowCheck, runAgentFileValidation, runDirectoryValidation, runPackageValidation, runTsconfigValidation, runConfigAccessValidation, runPromptConfigAccessValidation, runSuccessDocValidation, writeFindingsReport } from "${from}";
714
771
 
715
772
  const ROOT = resolve(import.meta.dir, "..");
716
773
 
@@ -725,6 +782,7 @@ runPackageValidation(ROOT);
725
782
  runTsconfigValidation(ROOT);
726
783
  runConfigAccessValidation(ROOT);
727
784
  runPromptConfigAccessValidation(ROOT);
785
+ runSuccessDocValidation(ROOT);
728
786
 
729
787
  afterAll(() => writeFindingsReport(ROOT));
730
788
  `;
@@ -837,7 +895,7 @@ export function generateAgentBriefsStep(root: string, actions: string[]): void {
837
895
  identity: projectIdentity,
838
896
  techStack: [],
839
897
  repoUrl: "",
840
- testCmd: harness?.dev?.testCmd || "bun test",
898
+ testCmd: testCommandDecision(root).command,
841
899
  keyFiles: [],
842
900
  specs: [],
843
901
  testFiles: [],
@@ -871,7 +929,7 @@ export function generateAgentBriefsStep(root: string, actions: string[]): void {
871
929
 
872
930
  // ── Harness config generation/audit ────────────────────────────
873
931
 
874
- export function generateOrAuditProjectHarness(root: string, actions: string[]): void {
932
+ export function generateOrAuditProjectHarness(root: string, actions: string[], opts: { pruneConsumers?: boolean } = {}): void {
875
933
  const harnessPath = join(root, ".claude", "rungate.json");
876
934
 
877
935
  const detectedHealthPath = detectHealthPath(root);
@@ -907,13 +965,12 @@ export function generateOrAuditProjectHarness(root: string, actions: string[]):
907
965
  }
908
966
  }
909
967
 
910
- // Scan test commands
968
+ // `inferredTestCommand`, not the full decision (#488). This value is what
969
+ // gets WRITTEN into `dev.testCmd`, so reading `dev.testCmd` to choose it
970
+ // is circular — and this step runs against trees whose config is
971
+ // malformed, which is what it exists to repair.
972
+ const testCmd = inferredTestCommand(root).command;
911
973
  const pkgPath = join(root, "package.json");
912
- let testCmd = "bun test";
913
- if (existsSync(pkgPath)) {
914
- const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
915
- if (pkg.scripts?.test) testCmd = pkg.scripts.test;
916
- }
917
974
  // #87 — this defaulted to `bunx tsc --noEmit` for every project, including
918
975
  // one with no tsconfig, and `gates/gate-executor.ts` RUNS what lands here.
919
976
  // Without a tsconfig that command prints 147 lines of help and exits 1, so
@@ -1017,7 +1074,7 @@ export function generateOrAuditProjectHarness(root: string, actions: string[]):
1017
1074
  // files #75 only ever fixed for greenfield projects (#121).
1018
1075
  const existing = JSON.parse(readFileSync(join(rungateDir, "config.json"), "utf-8"));
1019
1076
  repairEmptySidecars(rungateDir, actions);
1020
- auditExistingConfig(existing, scannedPages, scannedConsumers, actions, rungateDir);
1077
+ auditExistingConfig(existing, scannedPages, scannedConsumers, actions, rungateDir, opts.pruneConsumers === true);
1021
1078
  } else if (existsSync(harnessPath)) {
1022
1079
  // Monolith exists — split into directory structure
1023
1080
  const existing = JSON.parse(readFileSync(harnessPath, "utf-8"));
@@ -1027,6 +1084,8 @@ export function generateOrAuditProjectHarness(root: string, actions: string[]):
1027
1084
  splitMonolithToDirectory(root, existing, actions);
1028
1085
  } else {
1029
1086
  // Simple monolith without split-worthy content — audit only
1087
+ // No rungateDir on this path (the monolith layout), so pruning has
1088
+ // nowhere to write and is not offered rather than silently not happening.
1030
1089
  auditExistingConfig(existing, scannedPages, scannedConsumers, actions);
1031
1090
  }
1032
1091
  } else {
@@ -1083,7 +1142,14 @@ export function generateOrAuditProjectHarness(root: string, actions: string[]):
1083
1142
  envVars: envVars || [],
1084
1143
  ci: {
1085
1144
  runner: "ubuntu-latest",
1086
- bunVersion: "latest",
1145
+ // Detected, never defaulted (#346, #622). `"latest"` here wrote an
1146
+ // UNPINNED runtime into every greenfield project's CI and called it a
1147
+ // configuration: the job installs whatever shipped this morning, so
1148
+ // re-running a red build is also a Bun upgrade. The bun that ran the
1149
+ // scaffold is a measurement of what this project has been built with,
1150
+ // which is the honest thing to write down, and the operator can change
1151
+ // it in one place afterwards.
1152
+ bunVersion: Bun.version,
1087
1153
  branches: ["main"],
1088
1154
  },
1089
1155
  contextDocs: {},
@@ -1183,12 +1249,84 @@ function repairEmptySidecars(rungateDir: string, actions: string[]): void {
1183
1249
  }
1184
1250
  }
1185
1251
 
1252
+ /**
1253
+ * Remove consumers the source scan did not find — only when asked (#42).
1254
+ *
1255
+ * **Opt-in, against the issue's own SC-4, and the asymmetry is the reason.**
1256
+ * SC-2 says to remove them "when source scan confirms they don't exist". A
1257
+ * source scan cannot confirm absence; it reports that it did not find
1258
+ * something, and the gap between those two claims is where a dynamic import,
1259
+ * a generated file, a file type the scanner does not read, and a scanner that
1260
+ * errored all live. A stale entry left in config costs a warning line. A live
1261
+ * entry deleted costs that consumer its role grading, compliance policy and
1262
+ * pre-flight checks — silently, in a report nobody reads line by line.
1263
+ *
1264
+ * So adding a frontmatter field stays opt-out as SC-4 asks, and this one
1265
+ * operation does not: deleting is not in the same risk class as adding.
1266
+ *
1267
+ * Returns true when it pruned, so the caller reports the finding only when it
1268
+ * did not — a run must never both remove something and complain it is there.
1269
+ */
1270
+ export function pruneStaleConsumers(
1271
+ existing: any,
1272
+ scannedConsumers: string[],
1273
+ stale: string[],
1274
+ actions: string[],
1275
+ rungateDir: string | undefined,
1276
+ prune: boolean,
1277
+ ): boolean {
1278
+ if (!prune) return false;
1279
+
1280
+ // The refusal that matters most, and the one nothing in #42 asked for: a
1281
+ // scanner that returns nothing makes EVERY declared consumer look stale, so
1282
+ // one broken scan would empty the list in a single pass. "The scan found no
1283
+ // consumers" and "this project has no consumers" are not the same reading,
1284
+ // and treating them alike is Silent Default Substitution
1285
+ // (`.claude/rules/config-access.md`).
1286
+ if (scannedConsumers.length === 0) {
1287
+ actions.push(
1288
+ `REFUSED: --prune-consumers (the source scan found no consumers at all, so all ${stale.length} ` +
1289
+ `look stale — a scan that found nothing is a broken scan, not an empty project)`,
1290
+ );
1291
+ return false;
1292
+ }
1293
+
1294
+ if (!rungateDir || !existsSync(join(rungateDir, "config.json"))) {
1295
+ actions.push(
1296
+ "REFUSED: --prune-consumers (no .claude/rungate/config.json to write — " +
1297
+ "refusing rather than guessing which file holds the consumer list)",
1298
+ );
1299
+ return false;
1300
+ }
1301
+
1302
+ const configPath = join(rungateDir, "config.json");
1303
+ let config: any;
1304
+ try {
1305
+ config = JSON.parse(readFileSync(configPath, "utf-8"));
1306
+ } catch (err) {
1307
+ // A corrupt config is never an empty config. Rewriting it from `existing`
1308
+ // would discard every key this function does not know about.
1309
+ actions.push(`REFUSED: --prune-consumers (config.json is unreadable: ${(err as Error).message})`);
1310
+ return false;
1311
+ }
1312
+
1313
+ config.consumers = (config.consumers || []).filter((c: string) => !stale.includes(c));
1314
+ writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n");
1315
+ existing.consumers = config.consumers;
1316
+
1317
+ // Every name, not a count. A removal the report summarises as a number is
1318
+ // one nobody can audit or put back.
1319
+ actions.push(`AUTO-FIXED: .claude/rungate/config.json (pruned ${stale.length} stale consumers: ${stale.join(", ")})`);
1320
+ return true;
1321
+ }
1322
+
1186
1323
  function auditExistingConfig(
1187
1324
  existing: any,
1188
1325
  scannedPages: Record<string, string>,
1189
1326
  scannedConsumers: string[],
1190
1327
  actions: string[],
1191
- rungateDir?: string
1328
+ rungateDir?: string,
1329
+ prune = false,
1192
1330
  ): void {
1193
1331
  const issues: string[] = [];
1194
1332
 
@@ -1221,7 +1359,10 @@ function auditExistingConfig(
1221
1359
  if (declaredConsumers.length > 0) {
1222
1360
  const staleConsumers = declaredConsumers.filter((c: string) => !scannedConsumers.includes(c));
1223
1361
  if (staleConsumers.length > 0) {
1224
- issues.push(`CONSUMERS: ${staleConsumers.length} stale consumers in rungate.json not found in source: ${staleConsumers.slice(0, 5).join(", ")}`);
1362
+ const pruned = pruneStaleConsumers(existing, scannedConsumers, staleConsumers, actions, rungateDir, prune);
1363
+ if (!pruned) {
1364
+ issues.push(`CONSUMERS: ${staleConsumers.length} stale consumers in rungate.json not found in source: ${staleConsumers.slice(0, 5).join(", ")}`);
1365
+ }
1225
1366
  }
1226
1367
  }
1227
1368
 
@@ -1532,66 +1673,135 @@ export function createTsconfig(root: string, actions: string[]): void {
1532
1673
  actions.push("CREATED: tsconfig.json");
1533
1674
  }
1534
1675
 
1676
+ /**
1677
+ * One `.gitignore` section, and whether an ADOPTING project must get it (#474).
1678
+ *
1679
+ * The two branches of `createGitignore` used to hold two lists written in two
1680
+ * syntaxes, and they disagreed. The fresh-template branch wrote
1681
+ * `credentials.json`; the append branch derived its own form with
1682
+ * `e.includes("*") ? e : \`${e}/\``, which appends a trailing slash — and a
1683
+ * trailing slash in gitignore syntax RESTRICTS THE PATTERN TO DIRECTORIES:
1684
+ *
1685
+ * | Intended | Appended | Matches a file `credentials.json`? |
1686
+ * |---|---|---|
1687
+ * | `credentials.json` | `credentials.json/` | no |
1688
+ * | `service-account*` | `service-account/` | no |
1689
+ *
1690
+ * Six of the eight entries are directories, so the bug was invisible for them
1691
+ * and the block it broke is the one labelled "Environment and secrets" — the
1692
+ * two entries that are FILES are the two it silently inverted. The scaffold
1693
+ * reported `UPDATED: .gitignore (added 8 missing entries)` with two of them
1694
+ * inert, on exactly the path an existing project takes when it adopts
1695
+ * rungate. Found while scaffolding a plugin whose whole integration is Google
1696
+ * Drive, where `credentials.json` is the default client-secrets filename.
1697
+ *
1698
+ * So there is ONE list, and every pattern is written here EXACTLY as it must
1699
+ * appear on disk. Nothing downstream may transform a pattern — a second place
1700
+ * that decides syntax is the shape this bug had.
1701
+ */
1702
+ interface GitignoreSection {
1703
+ heading: string;
1704
+ patterns: string[];
1705
+ /**
1706
+ * Ensured when appending to a `.gitignore` that already exists. A project
1707
+ * adopting rungate keeps its own conventions for build output and editors;
1708
+ * what it does not get to opt out of is leaking a credential.
1709
+ */
1710
+ requiredOnAdoption: boolean;
1711
+ }
1712
+
1713
+ /** The single source for both branches below. Patterns are verbatim. */
1714
+ export const GITIGNORE_SECTIONS: GitignoreSection[] = [
1715
+ { heading: "Dependencies", requiredOnAdoption: true, patterns: ["node_modules/", ".bun/"] },
1716
+ // Required because the list this replaced required `dist`. Rounded up to
1717
+ // the whole section rather than down: #474 is about the two branches
1718
+ // disagreeing, and quietly shrinking what an adopting project gets would
1719
+ // be a second behaviour change hiding inside the fix for the first.
1720
+ { heading: "Build output", requiredOnAdoption: true, patterns: ["dist/", "build/", "*.tsbuildinfo"] },
1721
+ {
1722
+ heading: "Environment and secrets",
1723
+ requiredOnAdoption: true,
1724
+ patterns: [
1725
+ ".env",
1726
+ ".env.*",
1727
+ "!.env.example",
1728
+ "*.pem",
1729
+ "*.key",
1730
+ "*.p12",
1731
+ "*.pfx",
1732
+ "credentials.json",
1733
+ "service-account*",
1734
+ ".secret*",
1735
+ ],
1736
+ },
1737
+ { heading: "Harness working directory", requiredOnAdoption: true, patterns: [".rungate/"] },
1738
+ { heading: "IDE", requiredOnAdoption: false, patterns: [".vscode/", ".idea/", "*.swp", "*.swo"] },
1739
+ { heading: "OS", requiredOnAdoption: false, patterns: [".DS_Store", "Thumbs.db"] },
1740
+ { heading: "Test artifacts", requiredOnAdoption: false, patterns: ["coverage/"] },
1741
+ ];
1742
+
1743
+ /** The patterns an adopting project must end up with, in order. */
1744
+ export function requiredGitignorePatterns(): string[] {
1745
+ return GITIGNORE_SECTIONS.filter(s => s.requiredOnAdoption).flatMap(s => s.patterns);
1746
+ }
1747
+
1748
+ /** The fresh-project file, rendered from the one list. */
1749
+ export function gitignoreTemplate(): string {
1750
+ return (
1751
+ GITIGNORE_SECTIONS.map(s => `# ${s.heading}\n${s.patterns.join("\n")}\n`).join("\n") + ""
1752
+ );
1753
+ }
1754
+
1755
+ /**
1756
+ * Which required patterns an existing `.gitignore` does not already carry.
1757
+ *
1758
+ * Compared LINE-WISE against uncommented lines, not with `existing.includes`
1759
+ * (#474). A substring test over the whole file reports `credentials.json` as
1760
+ * present because of a comment reading `# credentials.json lives in
1761
+ * 1Password`, and then appends nothing — the entry is "handled" by a sentence
1762
+ * about it. It also made `*.key` satisfied by `*.keystore` and
1763
+ * `service-account` satisfied by the longer `service-account*`, which is how
1764
+ * the two lists stayed different without anything noticing.
1765
+ */
1766
+ export function missingGitignorePatterns(existing: string): string[] {
1767
+ const present = new Set(
1768
+ existing
1769
+ .split("\n")
1770
+ .map(l => l.trim())
1771
+ .filter(l => l !== "" && !l.startsWith("#")),
1772
+ );
1773
+ // #586: `X/` is satisfied by an existing `X`, and ONLY in that direction.
1774
+ // This repo's `.gitignore` opens with `node_modules` and the required
1775
+ // pattern is `node_modules/`, so exact matching reported it absent and
1776
+ // every scaffold run re-added a line that changes nothing.
1777
+ //
1778
+ // The direction is the whole safety argument, and it is the opposite of
1779
+ // the trap the docstring above names. A bare `node_modules` matches files
1780
+ // AND directories, so it is STRICTLY BROADER than `node_modules/` — the
1781
+ // requirement is already met. `service-account` present against a required
1782
+ // `service-account*` is the reverse: the required pattern is broader, the
1783
+ // requirement is NOT met, and that case must keep failing.
1784
+ const satisfied = (p: string): boolean =>
1785
+ present.has(p) || (p.endsWith("/") && present.has(p.slice(0, -1)));
1786
+ return requiredGitignorePatterns().filter(p => !satisfied(p));
1787
+ }
1788
+
1535
1789
  export function createGitignore(root: string, actions: string[]): void {
1536
1790
  const gitignorePath = join(root, ".gitignore");
1537
- const securityTemplate = `# Dependencies
1538
- node_modules/
1539
- .bun/
1540
-
1541
- # Build output
1542
- dist/
1543
- build/
1544
- *.tsbuildinfo
1545
-
1546
- # Environment and secrets
1547
- .env
1548
- .env.*
1549
- !.env.example
1550
- *.pem
1551
- *.key
1552
- *.p12
1553
- *.pfx
1554
- credentials.json
1555
- service-account*
1556
- .secret*
1557
-
1558
- # Harness working directory
1559
- .rungate/
1560
-
1561
- # IDE
1562
- .vscode/
1563
- .idea/
1564
- *.swp
1565
- *.swo
1566
-
1567
- # OS
1568
- .DS_Store
1569
- Thumbs.db
1570
-
1571
- # Test artifacts
1572
- coverage/
1573
- `;
1574
1791
 
1575
1792
  if (existsSync(gitignorePath)) {
1576
1793
  const existing = readFileSync(gitignorePath, "utf-8");
1577
- const required = [
1578
- "node_modules", "dist", ".env", ".rungate",
1579
- "*.pem", "*.key", "credentials.json", "service-account",
1580
- ];
1581
- const missing = required.filter(entry => !existing.includes(entry));
1794
+ const missing = missingGitignorePatterns(existing);
1582
1795
  if (missing.length > 0) {
1583
- const additions = "\n# Added by rungate scaffold\n" +
1584
- missing.map(e => {
1585
- if (e === ".env") return ".env\n.env.*\n!.env.example";
1586
- return e.includes("*") ? e : `${e}/`;
1587
- }).join("\n") + "\n";
1796
+ // Written VERBATIM. The transform that used to live here is the bug.
1797
+ const additions = "\n# Added by rungate scaffold\n" + missing.join("\n") + "\n";
1588
1798
  writeFileSync(gitignorePath, existing.trimEnd() + "\n" + additions);
1589
1799
  actions.push(`UPDATED: .gitignore (added ${missing.length} missing entries)`);
1590
1800
  } else {
1591
1801
  actions.push("SKIP: .gitignore (all required entries present)");
1592
1802
  }
1593
1803
  } else {
1594
- writeFileSync(gitignorePath, securityTemplate);
1804
+ writeFileSync(gitignorePath, gitignoreTemplate());
1595
1805
  actions.push("CREATED: .gitignore (security template)");
1596
1806
  }
1597
1807
  }
@@ -1603,7 +1813,7 @@ export function generateProjectState(root: string, actions: string[]): void {
1603
1813
  return;
1604
1814
  }
1605
1815
 
1606
- const today = new Date().toISOString().split("T")[0];
1816
+ const today = localCalendarDay();
1607
1817
 
1608
1818
  interface SC { id: string; what: string; done: boolean; }
1609
1819
  const scs: SC[] = [];
@@ -1680,6 +1890,80 @@ export function generateProjectState(root: string, actions: string[]): void {
1680
1890
  safeWrite(stateMd, lines.join("\n") + "\n", "PROJECT-STATE.md", actions);
1681
1891
  }
1682
1892
 
1893
+ /**
1894
+ * Seed `SUCCESS.md`, then say out loud that the seed is not an answer (#485).
1895
+ *
1896
+ * `CLAUDE.md` opens its rules with "SUCCESS.md is the measure" and the
1897
+ * scaffold never wrote one. rungate's was hand-written once and nothing
1898
+ * reproduced it for anyone else, so a consumer scaffolded a project, read the
1899
+ * generated `AGENTS.md`, and never learned the file was supposed to exist.
1900
+ *
1901
+ * Two halves, and the second is the one that makes this more than a nicety.
1902
+ *
1903
+ * **It is `create-only`.** A project's claims are the one thing the harness
1904
+ * must never regenerate over. `safeWrite` is the single writer for that, and
1905
+ * it is delegated to rather than reimplemented for the reason recorded on
1906
+ * that function: a second copy of the decision absorbs any mutation of the
1907
+ * first.
1908
+ *
1909
+ * **The WARN reads the real checker.** `successViolations` is the same
1910
+ * binding `SUCCESS-1` refuses with, so the scaffold's warning and the
1911
+ * conformity suite's refusal cannot disagree. A second "is it filled in?"
1912
+ * predicate here would be two deciders answering one question — the fourth
1913
+ * shape in `.claude/rules/checks-must-be-able-to-fail.md`, which no
1914
+ * behavioural test can tell apart.
1915
+ *
1916
+ * The direction this is deliberately wrong in: a project that runs the
1917
+ * scaffold and stops is now LOUDER than one that never ran it. An unfilled
1918
+ * template is refused; an absent file is only UNMEASURED. That is the point —
1919
+ * an unfilled template is indistinguishable from a considered one to
1920
+ * everything except a reader, so the generator must not make the project
1921
+ * quieter than it found it.
1922
+ */
1923
+ export function seedSuccessDoc(root: string, actions: string[]): void {
1924
+ // `readSuccessTemplate()` rather than a fourth expression resolving the
1925
+ // same path. There were three — here, `lib/success-doc.ts` and
1926
+ // `scripts/create-success.ts` — agreeing today and with nothing making them
1927
+ // agree tomorrow.
1928
+ const template = readSuccessTemplate();
1929
+ if (template === TEMPLATE_MISSING) {
1930
+ // Named, not swallowed. #484 was a documented command that ENOENTed for
1931
+ // every consumer because `files[]` omitted the directory it read from,
1932
+ // and the symptom was a check that reported 21 pass over a library that
1933
+ // could not load its own data.
1934
+ actions.push(
1935
+ "WARN: SUCCESS.md not seeded — templates/SUCCESS-TEMPLATE.md is missing from this " +
1936
+ "rungate installation (see test/package-closure.test.ts)",
1937
+ );
1938
+ return;
1939
+ }
1940
+
1941
+ const today = localCalendarDay();
1942
+ const owner = process.env.USER || "TODO-OWNER";
1943
+ // The SHARED substitution. Writing the template raw here while
1944
+ // `create-success` substituted meant one seed with two possible byte
1945
+ // sequences, and a scaffolded SUCCESS.md kept `owner: TODO-OWNER` forever.
1946
+ const seeded = seedFromTemplate(template, owner, today);
1947
+ safeWrite(join(root, "SUCCESS.md"), seeded, "SUCCESS.md", actions);
1948
+
1949
+ const verdict = successViolations(readSuccessDoc(root), template);
1950
+ if (verdict.unmeasured) {
1951
+ actions.push(`WARN: ${verdict.unmeasured}`);
1952
+ return;
1953
+ }
1954
+ if (verdict.violations.length > 0) {
1955
+ actions.push(
1956
+ // NOT "run create-success" — by the time anyone reads this the file is
1957
+ // already there, so that command refuses and the advice is a dead end.
1958
+ `WARN: SUCCESS.md is not filled in — ${verdict.violations.length} item(s). ` +
1959
+ `The conformity suite REFUSES it in this state, deliberately. Edit ` +
1960
+ `${join(root, "SUCCESS.md")} (or re-seed it with ` +
1961
+ `\`bunx rungate create-success --force\`):`,
1962
+ );
1963
+ for (const v of verdict.violations) actions.push(` - ${v}`);
1964
+ }
1965
+ }
1966
+
1683
1967
  export function createClaudeMdBridge(root: string, actions: string[]): void {
1684
1968
  const claudeMdPath = join(root, "CLAUDE.md");
1685
1969
  const bridgeLine = "@AGENTS.md";
@@ -1738,6 +2022,19 @@ export interface ManagedWrite {
1738
2022
  * CI resilience, and "REPLACED (+33 lines)" does not tell anyone that.
1739
2023
  */
1740
2024
  overwrittenLines: string[];
2025
+ /**
2026
+ * Top-level keys the merge put somewhere else (#482).
2027
+ *
2028
+ * Not a refusal — YAML top-level keys are order-independent, so a moved key
2029
+ * means what it meant. It IS reported, because `UPDATED` with nothing said
2030
+ * about position is a report that is accurate and still misleads: a
2031
+ * consumer's `concurrency:` arrived below `jobs:` while the comment
2032
+ * introducing it stayed above, the reader concluded it had been deleted,
2033
+ * restored it by hand, and the file stopped parsing. "Nothing was lost" and
2034
+ * "everything is where you left it" are different claims and only the first
2035
+ * was being made.
2036
+ */
2037
+ movedKeys: MovedKey[];
1741
2038
  /** Non-null ⇒ the write must not happen. Names the dropped jobs and the line delta. */
1742
2039
  refusal: string | null;
1743
2040
  }
@@ -1838,7 +2135,7 @@ function measureWrite(existing: string | null, next: string): { verb: ManagedWri
1838
2135
  export function resolveManagedWrite(existing: string | null, generated: string): ManagedWrite {
1839
2136
  const base: ManagedWrite = {
1840
2137
  content: generated, verb: "CREATED", lineDelta: lineCount(generated),
1841
- preservedJobs: [], droppedJobs: [], overwrittenLines: [], refusal: null,
2138
+ preservedJobs: [], droppedJobs: [], overwrittenLines: [], movedKeys: [], refusal: null,
1842
2139
  };
1843
2140
  if (existing === null) return base;
1844
2141
 
@@ -1878,11 +2175,63 @@ export function resolveManagedWrite(existing: string | null, generated: string):
1878
2175
  const resultJobs = workflowJobNames(content);
1879
2176
  if (resultJobs === null) {
1880
2177
  return {
1881
- ...unchanged, preservedJobs: [], droppedJobs: existingJobs, overwrittenLines: [], lineDelta,
2178
+ ...unchanged, preservedJobs: [], droppedJobs: existingJobs, overwrittenLines: [], movedKeys: [], lineDelta,
1882
2179
  refusal: `the merged workflow does not parse, so it cannot be written (line delta ${signed(lineDelta)})`,
1883
2180
  };
1884
2181
  }
1885
2182
 
2183
+ // A top-level key declared twice is a workflow YAML rejects and GitHub
2184
+ // Actions refuses to run (#482). The realistic way one appears is the
2185
+ // correction this issue is about — somebody restores a block they believe
2186
+ // the merge deleted while the original is still further down — so the
2187
+ // refusal has to look at the EXISTING file as well as the merged one, and
2188
+ // name the key rather than the symptom.
2189
+ const duplicated = [
2190
+ ...duplicateTopLevelKeys(existing).map(k => [k, "the existing file"] as const),
2191
+ ...duplicateTopLevelKeys(content)
2192
+ .filter(k => !duplicateTopLevelKeys(existing).includes(k))
2193
+ .map(k => [k, "the merged output"] as const),
2194
+ ];
2195
+ if (duplicated.length > 0) {
2196
+ return {
2197
+ ...unchanged, preservedJobs: [], droppedJobs: [], overwrittenLines: [], movedKeys: [], lineDelta,
2198
+ refusal:
2199
+ `${duplicated.length} top-level key(s) declared more than once in ` +
2200
+ `${duplicated.map(([k, where]) => `${k} (${where})`).join(", ")} — ` +
2201
+ `YAML rejects a duplicate mapping key, so the workflow would not run. ` +
2202
+ `Delete the extra declaration and re-run (line delta ${signed(lineDelta)})`,
2203
+ };
2204
+ }
2205
+
2206
+ // The merge's contract since #482 is that the consumer's top-level ORDER is
2207
+ // the consumer's. So movement is no longer something to report — it is a
2208
+ // bug in the merge, and shipping one is what produced the incident: a
2209
+ // `concurrency:` block 460 lines below the comment introducing it, read as
2210
+ // a deletion, "restored", and the workflow stopped parsing.
2211
+ //
2212
+ // A refusal rather than a warning, because the cost is asymmetric. A
2213
+ // consumer who hits an unenumerated edge case gets a named refusal and
2214
+ // `--force`; a consumer who does not get one gets a file they will
2215
+ // misread. Measured against this repo's three real workflow files — one of
2216
+ // which carries a `permissions:` key between `on:` and `jobs:`, exactly the
2217
+ // shape that used to move: zero movement in all three.
2218
+ //
2219
+ // The file is not named here on purpose. `test/anti.test.ts` SC-A1 keeps
2220
+ // the scaffold from naming a workflow it does not own, and a comment is as
2221
+ // nameable as a code path.
2222
+ const movedKeys = movedTopLevelKeys(existing, content);
2223
+ if (movedKeys.length > 0) {
2224
+ return {
2225
+ ...unchanged, preservedJobs, droppedJobs: [], overwrittenLines: [], movedKeys, lineDelta,
2226
+ refusal:
2227
+ `${movedKeys.length} top-level key(s) would move: ` +
2228
+ `${movedKeys.slice(0, 3).map(m => `${m.key} (line ${m.from + 1} -> ${m.to + 1})`).join(", ")}` +
2229
+ `${movedKeys.length > 3 ? ` and ${movedKeys.length - 3} more` : ""} — ` +
2230
+ `a key that moves away from the comment introducing it reads as a deletion ` +
2231
+ `(line delta ${signed(lineDelta)})`,
2232
+ };
2233
+ }
2234
+
1886
2235
  // The loss set is LINES, not job names. Every non-blank line the consumer
1887
2236
  // has that the merge did not carry is content the harness is about to drop,
1888
2237
  // wherever in the file it sits.
@@ -1919,7 +2268,7 @@ export function resolveManagedWrite(existing: string | null, generated: string):
1919
2268
  ? `job(s) ${droppedJobs.join(", ")}`
1920
2269
  : "content outside any job";
1921
2270
  return {
1922
- ...unchanged, preservedJobs, droppedJobs, overwrittenLines: [], lineDelta,
2271
+ ...unchanged, preservedJobs, droppedJobs, overwrittenLines: [], movedKeys: [], lineDelta,
1923
2272
  refusal:
1924
2273
  `${lostLines.length} line(s) the harness did not author would be dropped from ${where}` +
1925
2274
  `: ${lostLines.slice(0, 3).map(l => JSON.stringify(l)).join(", ")}` +
@@ -1928,7 +2277,7 @@ export function resolveManagedWrite(existing: string | null, generated: string):
1928
2277
  };
1929
2278
  }
1930
2279
 
1931
- return { content, ...measureWrite(existing, content), preservedJobs, droppedJobs: [], overwrittenLines, refusal: null };
2280
+ return { content, ...measureWrite(existing, content), preservedJobs, droppedJobs: [], overwrittenLines, movedKeys, refusal: null };
1932
2281
  }
1933
2282
 
1934
2283
  /** Non-blank lines, trimmed — the unit the loss set is counted in. */
@@ -2011,7 +2360,17 @@ export function createCiWorkflows(root: string, actions: string[], opts: { force
2011
2360
  }
2012
2361
 
2013
2362
  const harness = loadHarnessConfig(root);
2014
- const bunVersion = harness?.ci?.bunVersion || "latest";
2363
+ // #622. This was `harness?.ci?.bunVersion || "latest"`, emitted at the two
2364
+ // sites below, while the two hand-owned workflow files this generator never
2365
+ // touches named versions of their own — four positions, three spellings,
2366
+ // and nothing comparing any of them. (Neither of those filenames is spelled
2367
+ // here: test/release-guard.test.ts asserts this module names no workflow it
2368
+ // does not write, and prose is indistinguishable from a write to it.) The
2369
+ // decision and the YAML it becomes are now `lib/bun-version.ts`'s, for the
2370
+ // same reason #87 took the typecheck step and #488 took the test step: two
2371
+ // sites that agree today are one decider too many, and only a mutation of a
2372
+ // SHARED binding can show the agreement is load-bearing.
2373
+ const bunStep = setupBunWith(declaredBunVersion(root), " ");
2015
2374
  const runner = harness?.ci?.runner || "ubuntu-latest";
2016
2375
  const branches = harness?.ci?.branches || ["main"];
2017
2376
  // Branch patterns are globs: a bare `*` is a YAML alias indicator and `*-dev`
@@ -2077,6 +2436,14 @@ export function createCiWorkflows(root: string, actions: string[], opts: { force
2077
2436
  // `dev.typeCheck` read (#87). This site used to check for
2078
2437
  // `scripts/typecheck.ts` on disk, a branch `files:` makes unreachable for
2079
2438
  // every consumer, and never looked at a project's own `typecheck` script.
2439
+ // #488. This was `- run: bun test`, hardcoded, while `harness` was in
2440
+ // scope and three of its siblings read `harness?.ci?.*` four lines above.
2441
+ // Same binding AGENTS.md's Commands row and the agent briefs read, for the
2442
+ // same reason the typecheck step below it got one in #87: two sites that
2443
+ // agree today are one decider too many, and only a mutation of a shared
2444
+ // binding can show the agreement is load-bearing.
2445
+ const test = testCommandDecision(root);
2446
+
2080
2447
  const typecheck = typecheckDecision(root);
2081
2448
  const typecheckStep = typecheck.command
2082
2449
  ? `\n - run: ${typecheck.command}`
@@ -2101,9 +2468,9 @@ jobs:
2101
2468
  ${baseRefStep}
2102
2469
  - uses: oven-sh/setup-bun@v2
2103
2470
  with:
2104
- bun-version: "${bunVersion}"
2471
+ ${bunStep}
2105
2472
  - run: bun install
2106
- - run: bun test${typecheckStep}
2473
+ - run: ${test.command}${typecheckStep}
2107
2474
  `;
2108
2475
 
2109
2476
  const gatesYml = `# Managed by rungate — do not edit. Customize the ci section of .claude/rungate/config.json.
@@ -2124,7 +2491,7 @@ jobs:
2124
2491
  - uses: actions/checkout@v4
2125
2492
  - uses: oven-sh/setup-bun@v2
2126
2493
  with:
2127
- bun-version: "${bunVersion}"
2494
+ ${bunStep}
2128
2495
  - run: bun install
2129
2496
  - name: Conformity + spec drift
2130
2497
  run: bun test test/scaffold-conformity.test.ts
@@ -2269,6 +2636,19 @@ export function deployHooksToConsumers(root: string, actions: string[]): void {
2269
2636
  }
2270
2637
  }
2271
2638
 
2639
+ /**
2640
+ * The line that marks a pre-commit hook as ours, so a fix can reach one that
2641
+ * already exists (#450).
2642
+ *
2643
+ * The guard here was `if (!existsSync(preCommit))`, which meant every
2644
+ * checkout that already had a hook kept whatever version it was given the
2645
+ * first time — including the one that stages DA-owned state from every
2646
+ * worktree, which is what #450 is about. The pre-push hook had exactly this
2647
+ * bug and #85 fixed it the same way: overwrite our own managed hook, and
2648
+ * leave a hand-written one alone.
2649
+ */
2650
+ export const PRE_COMMIT_MANAGED_MARKER = "# Managed by rungate — secret scan + PROJECT-STATE update";
2651
+
2272
2652
  export function createGitHooks(root: string, actions: string[]): void {
2273
2653
  const hooksDir = join(root, ".git", "hooks");
2274
2654
  if (!existsSync(hooksDir)) return;
@@ -2276,9 +2656,12 @@ export function createGitHooks(root: string, actions: string[]): void {
2276
2656
  const { chmodSync } = require("fs");
2277
2657
 
2278
2658
  const preCommit = join(hooksDir, "pre-commit");
2279
- if (!existsSync(preCommit)) {
2659
+ const existingPreCommit = existsSync(preCommit) ? readFileSync(preCommit, "utf-8") : null;
2660
+ if (existingPreCommit !== null && !existingPreCommit.includes(PRE_COMMIT_MANAGED_MARKER)) {
2661
+ actions.push("SKIP: .git/hooks/pre-commit (hand-written, not overwriting)");
2662
+ } else {
2280
2663
  writeFileSync(preCommit, `#!/bin/sh
2281
- # Managed by rungate — secret scan + PROJECT-STATE update
2664
+ ${PRE_COMMIT_MANAGED_MARKER}
2282
2665
  #
2283
2666
  # Scans the staged DIFF, not files on disk. This is deliberate and fixes four
2284
2667
  # failure modes the file-list approach had:
@@ -2325,10 +2708,74 @@ if printf '%s\\n' "$staged_diff" \\
2325
2708
  exit 1
2326
2709
  fi
2327
2710
 
2328
- # Update PROJECT-STATE if it exists
2711
+ # Update PROJECT-STATE if it exists — but NEVER from a linked worktree (#450).
2712
+ #
2713
+ # project-state.json, PROJECT-STATE.md and SUCCESS.md are DA-owned: a single
2714
+ # shared state document that several worktrees must not each write their own
2715
+ # version of (#296). The rule is written down in CLAUDE.md and in
2716
+ # .claude/rules/key-files.md, and this hook used to do the opposite of it on
2717
+ # every commit in every worktree — so an agent that obeyed the rule perfectly
2718
+ # still shipped the violation, because the staging happened after it had
2719
+ # decided not to touch the file. A rule something actively undoes is worse
2720
+ # than a rule nothing executes.
2721
+ #
2722
+ # The hook cannot tell whether it is the DA. It CAN tell whether it is in a
2723
+ # linked worktree: --git-dir points at .git/worktrees/<name> there while
2724
+ # --git-common-dir points at the shared .git, and in the primary checkout the
2725
+ # two are the same answer.
2726
+ #
2727
+ # The first draft resolved both through a cd-then-pwd-P round trip first, on
2728
+ # the theory that one could come back relative and the other absolute. The
2729
+ # mutation battery scored that normalisation 0 of 20 — both arms behave
2730
+ # identically without it, executed against a real primary checkout and a real
2731
+ # linked worktree. An unmeasured guard is indistinguishable from an absent
2732
+ # one, so it is absent. git hooks run from the toplevel, and both calls share
2733
+ # a cwd, so there was never a case that needed it.
2734
+ #
2735
+ # The primary arm had three fail-opens in two lines (#599), and the shape is
2736
+ # this file's recurring one: a check that passed because of what it never
2737
+ # looked at. The path was the CONSUMER layout, so in the harness's own
2738
+ # checkout — which has scripts/update-project-state.ts and no
2739
+ # node_modules/rungate at all — bun exited non-zero on a file that is not
2740
+ # there. 2>/dev/null threw the ENOENT away, || true threw the status away, and
2741
+ # the git add below then staged whatever happened to be on disk. A commit that
2742
+ # regenerated nothing was byte-indistinguishable from one that regenerated
2743
+ # everything, and the only reason anyone noticed is that the stamp is UTC, so
2744
+ # the stale copy differs from the fresh one for four hours an evening.
2745
+ #
2746
+ # Every message is on STDERR: stdout is what a caller captures as the
2747
+ # command's answer, and a decline, a reading and an updater's progress are all
2748
+ # diagnosis rather than output.
2329
2749
  if [ -f "project-state.json" ]; then
2330
- bun node_modules/rungate/scripts/update-project-state.ts --skip-tests 2>/dev/null || true
2331
- git add PROJECT-STATE.md project-state.json 2>/dev/null || true
2750
+ gitdir=$(git rev-parse --git-dir)
2751
+ commondir=$(git rev-parse --git-common-dir)
2752
+ if [ -n "$gitdir" ] && [ "$gitdir" = "$commondir" ]; then
2753
+ # The order is deliberate. A checkout carrying its own scripts/ copy IS
2754
+ # the harness, and the harness must not regenerate its state with a stale
2755
+ # vendored duplicate of its own updater.
2756
+ updater=""
2757
+ if [ -f "scripts/update-project-state.ts" ]; then
2758
+ updater="scripts/update-project-state.ts"
2759
+ elif [ -f "node_modules/rungate/scripts/update-project-state.ts" ]; then
2760
+ updater="node_modules/rungate/scripts/update-project-state.ts"
2761
+ fi
2762
+ if [ -z "$updater" ]; then
2763
+ echo "project-state: UNMEASURED — project-state.json is here, but no update-project-state.ts was found at scripts/update-project-state.ts or node_modules/rungate/scripts/update-project-state.ts. Nothing was regenerated and nothing was staged." >&2
2764
+ elif bun "$updater" --skip-tests >&2; then
2765
+ # Staged only after the updater SUCCEEDED. Staging regardless is the
2766
+ # fail-open the readings above exist to replace: it puts yesterday's
2767
+ # PROJECT-STATE.md in today's commit, and the commit then looks exactly
2768
+ # like one that updated it.
2769
+ git add PROJECT-STATE.md project-state.json 2>/dev/null || true
2770
+ else
2771
+ echo "project-state: UNMEASURED — $updater exited non-zero, so PROJECT-STATE.md and project-state.json were NOT staged. Run it by hand to see why." >&2
2772
+ fi
2773
+ else
2774
+ # Announced, not silent. A developer who expected the state files to move
2775
+ # would otherwise be left guessing, and SKIP that says nothing is
2776
+ # indistinguishable from the update having happened.
2777
+ echo "project-state: SKIPPED — linked worktree. project-state.json, PROJECT-STATE.md and SUCCESS.md are DA-owned (#296); update them from the primary checkout." >&2
2778
+ fi
2332
2779
  fi
2333
2780
 
2334
2781
  # A script's exit status is its last command's. Without this, the [ -f ] test
@@ -2338,7 +2785,11 @@ fi
2338
2785
  exit 0
2339
2786
  `);
2340
2787
  chmodSync(preCommit, 0o755);
2341
- actions.push("CREATED: .git/hooks/pre-commit (secret scan + PROJECT-STATE update)");
2788
+ actions.push(
2789
+ existingPreCommit === null
2790
+ ? "CREATED: .git/hooks/pre-commit (secret scan + PROJECT-STATE update)"
2791
+ : "UPDATED: .git/hooks/pre-commit (secret scan + PROJECT-STATE update)",
2792
+ );
2342
2793
  }
2343
2794
 
2344
2795
  const prePush = join(hooksDir, "pre-push");
@@ -2458,24 +2909,189 @@ function harnessVersion(): string {
2458
2909
  * half is a pure property and needs no registry. See
2459
2910
  * `test/scaffold-installable.test.ts`.
2460
2911
  */
2912
+ /** Every section a dependency declaration can hide in (#475). */
2913
+ export const DEP_SECTIONS = ["dependencies", "devDependencies", "optionalDependencies"] as const;
2914
+
2915
+ /**
2916
+ * Both names the harness has shipped under.
2917
+ *
2918
+ * `pai-harness` is the former name and older scaffold runs wrote it. A
2919
+ * migration that knows only the current name leaves the old declaration in
2920
+ * place and adds a new one beside it — two packages for one dependency.
2921
+ */
2922
+ export const HARNESS_PKG_NAMES = ["rungate", "pai-harness"] as const;
2923
+
2924
+ /**
2925
+ * The name the harness ships under today; the rest of `HARNESS_PKG_NAMES` is
2926
+ * history, and migration targets this one.
2927
+ *
2928
+ * Derived rather than written out so the two cannot drift — and named rather
2929
+ * than inlined for a second reason worth stating, because it looks like
2930
+ * evasion otherwise. #380's `IDENTITY_COMPARISON` guard matches a
2931
+ * `name`-equality against the harness's own package name anywhere in
2932
+ * `lib/`, to keep "is this project the harness" decided in exactly one
2933
+ * place — and this paragraph deliberately does not spell that comparison
2934
+ * out, because the guard reads raw source and a docstring quoting the
2935
+ * pattern reports itself as a second site. The comparison below asks a
2936
+ * different question of a different type — "is this DECLARATION named
2937
+ * rungate", where `name` is a key in someone's `devDependencies` — and the
2938
+ * textual guard cannot tell the two apart. Widening the guard would narrow
2939
+ * it; this keeps #380's single binding intact and says which question is
2940
+ * being asked.
2941
+ */
2942
+ export const CURRENT_HARNESS_PKG: (typeof HARNESS_PKG_NAMES)[number] = HARNESS_PKG_NAMES[0];
2943
+
2944
+ export interface HarnessDeclaration {
2945
+ section: (typeof DEP_SECTIONS)[number];
2946
+ name: (typeof HARNESS_PKG_NAMES)[number];
2947
+ spec: string;
2948
+ }
2949
+
2950
+ /** Every place this package.json declares the harness. */
2951
+ export function findHarnessDeclarations(pkg: unknown): HarnessDeclaration[] {
2952
+ const out: HarnessDeclaration[] = [];
2953
+ const obj = pkg as Record<string, Record<string, unknown>> | null;
2954
+ if (!obj || typeof obj !== "object") return out;
2955
+ for (const section of DEP_SECTIONS) {
2956
+ const deps = obj[section];
2957
+ if (!deps || typeof deps !== "object") continue;
2958
+ for (const name of HARNESS_PKG_NAMES) {
2959
+ const spec = deps[name];
2960
+ if (typeof spec === "string") out.push({ section, name, spec });
2961
+ }
2962
+ }
2963
+ return out;
2964
+ }
2965
+
2966
+ /** What the scaffold intends to do about the harness dependency. */
2967
+ export interface HarnessDepPlan {
2968
+ action: "skip" | "add" | "migrate";
2969
+ /** Declarations to delete before writing. */
2970
+ remove: HarnessDeclaration[];
2971
+ /** The spec to write into `devDependencies.rungate`, or null when skipping. */
2972
+ write: string | null;
2973
+ /** Said out loud in the action line, with the before and after (#475 SC-4). */
2974
+ reason: string;
2975
+ }
2976
+
2977
+ /**
2978
+ * The ONE decision about the harness dependency (#475).
2979
+ *
2980
+ * The guard this replaces read **one key in one section under one name**:
2981
+ *
2982
+ * ```ts
2983
+ * if (pkg.devDependencies["rungate"] || isHarnessItself(root)) { ...skip... }
2984
+ * ```
2985
+ *
2986
+ * So it could not see `rungate` in `dependencies` or `optionalDependencies`,
2987
+ * could not see `pai-harness` anywhere, and could not see a `file:` spec
2988
+ * under any of them. `harnessDevDepRange`'s own comment says "`file:` is the
2989
+ * bug" — the EMISSION was fixed and nothing was ever written to undo what the
2990
+ * broken emission left behind.
2991
+ *
2992
+ * The sharper half is that re-scaffolding does not merely fail to clean it
2993
+ * up. With `optionalDependencies: { "rungate": "file:../rungate" }` and no
2994
+ * `devDependencies.rungate`, the guard does not fire, so the scaffold writes
2995
+ * `devDependencies.rungate = "^0.4.0"` BESIDE it. The consumer then declares
2996
+ * one package twice, in two sections, with two incompatible specs, and the
2997
+ * run reports `UPDATED: package.json (rungate devDep)` as a success.
2998
+ *
2999
+ * Measured in a real consumer, two declarations written by two scaffold runs
3000
+ * two days apart under the two different names:
3001
+ *
3002
+ * ```
3003
+ * file:../pai-harness -> 34f03818 2026-09-17
3004
+ * file:../rungate -> 3a6501a9 2026-09-19
3005
+ * ```
3006
+ *
3007
+ * They survived every re-scaffold since September, and the cost was a dead
3008
+ * container build: bun resolves `file:` optionals and fails on a folder that
3009
+ * is not in the build context. A later commit moved both to
3010
+ * `optionalDependencies` trying to make the build tolerate them, which put
3011
+ * them further out of the old guard's reach — wrong section AND wrong name.
3012
+ *
3013
+ * Kept separate from the writer so there is one binding to mutate, and so
3014
+ * the whole matrix can be driven without a filesystem.
3015
+ */
3016
+ export function harnessDepPlan(pkg: unknown, targetRange: string): HarnessDepPlan {
3017
+ const found = findHarnessDeclarations(pkg);
3018
+
3019
+ if (found.length === 0) {
3020
+ return { action: "add", remove: [], write: targetRange, reason: "no harness dependency declared" };
3021
+ }
3022
+
3023
+ // A single declaration in the RIGHT PLACE is left exactly as it is,
3024
+ // whatever its spec. Two reasons, and the second resolves a conflict
3025
+ // between two issues:
3026
+ //
3027
+ // 1. The range is not rewritten to today's floor. A scaffold that rewrites
3028
+ // a working spec on every run is indistinguishable from one that cannot
3029
+ // tell a working spec from a broken one, and it would churn every
3030
+ // consumer's package.json on every release.
3031
+ //
3032
+ // 2. `file:` is included, which is #362 SC-815: "A consumer who
3033
+ // deliberately points at a local checkout is not this bug, and silently
3034
+ // rewriting their package.json is not this fix's business." #475 SC-2
3035
+ // asks for `file:` to be replaced "in any of those cells", and taken
3036
+ // literally the two contradict.
3037
+ //
3038
+ // The line drawn here is PLACEMENT, not spec, because that is what #475's
3039
+ // own evidence supports: both `file:` entries it traced were written by
3040
+ // scaffold runs (`34f03818`, `3a6501a9`), and both ended up in
3041
+ // `optionalDependencies` under two different names. A declaration the
3042
+ // scaffold would never have written in that position is the scaffold's to
3043
+ // clean up; a lone `devDependencies.rungate` is where a developer linking
3044
+ // a local checkout would put one, and it is indistinguishable from intent.
3045
+ const only = found.length === 1 ? found[0] : null;
3046
+ if (only && only.section === "devDependencies" && only.name === CURRENT_HARNESS_PKG) {
3047
+ return { action: "skip", remove: [], write: null, reason: `devDependencies.rungate is ${only.spec}` };
3048
+ }
3049
+
3050
+ const where = found.map(d => `${d.section}.${d.name}=${d.spec}`).join(", ");
3051
+ return {
3052
+ action: "migrate",
3053
+ remove: found,
3054
+ write: targetRange,
3055
+ reason: `${where} -> devDependencies.rungate=${targetRange}`,
3056
+ };
3057
+ }
3058
+
2461
3059
  export function addPaiHarnessDevDep(root: string, actions: string[], version?: string): void {
2462
3060
  const pkgPath = join(root, "package.json");
2463
3061
  if (!existsSync(pkgPath)) return;
2464
3062
 
2465
3063
  const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
2466
- if (!pkg.devDependencies) {
2467
- pkg.devDependencies = {};
3064
+
3065
+ // A different question — "is rungate already available here" — but the
3066
+ // self-reference half is the same fact, so it routes through the one
3067
+ // predicate (#380). Asked FIRST: the harness's own package.json names
3068
+ // itself, and running the migration over it would rewrite the harness into
3069
+ // depending on itself.
3070
+ if (isHarnessItself(root)) {
3071
+ actions.push("SKIP: rungate devDep (self-reference)");
3072
+ return;
2468
3073
  }
2469
3074
 
2470
- // Also a different question — "is rungate already available here" — but
2471
- // the self-reference half is the same fact, so it routes through the one
2472
- // predicate (#380).
2473
- if (pkg.devDependencies["rungate"] || isHarnessItself(root)) {
2474
- actions.push("SKIP: rungate devDep (already present or self-reference)");
3075
+ const plan = harnessDepPlan(pkg, harnessDevDepRange(version));
3076
+ if (plan.action === "skip") {
3077
+ actions.push(`SKIP: rungate devDep (${plan.reason})`);
2475
3078
  return;
2476
3079
  }
2477
3080
 
2478
- pkg.devDependencies["rungate"] = harnessDevDepRange(version);
3081
+ // Removed BEFORE the write, and across every section, so a declaration
3082
+ // cannot survive in the section the writer does not touch. This is the
3083
+ // whole of SC-2: the invariant is one declaration in total, not a correct
3084
+ // `devDependencies`.
3085
+ for (const d of plan.remove) delete (pkg as Record<string, Record<string, unknown>>)[d.section][d.name];
3086
+ for (const section of DEP_SECTIONS) {
3087
+ const deps = (pkg as Record<string, unknown>)[section];
3088
+ if (deps && typeof deps === "object" && Object.keys(deps).length === 0) {
3089
+ delete (pkg as Record<string, unknown>)[section];
3090
+ }
3091
+ }
3092
+
3093
+ if (!pkg.devDependencies) pkg.devDependencies = {};
3094
+ pkg.devDependencies["rungate"] = plan.write;
2479
3095
 
2480
3096
  if (!pkg.scripts) {
2481
3097
  pkg.scripts = {};
@@ -2485,10 +3101,15 @@ export function addPaiHarnessDevDep(root: string, actions: string[], version?: s
2485
3101
  }
2486
3102
 
2487
3103
  writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
2488
- // Names the PATH it wrote, not just what it did (#216). An action that does
2489
- // not name its file is invisible to the stager and, worse, now reads as an
2490
- // unexplained modification to the dirty-tree check.
2491
- actions.push("UPDATED: package.json (rungate devDep)");
3104
+ // Names the PATH it wrote, not just what it did (#216), and for a
3105
+ // migration also the before and after (#475 SC-4) — the reported cost was
3106
+ // a consumer who did not know this was in their package.json until a
3107
+ // container build died over it.
3108
+ actions.push(
3109
+ plan.action === "migrate"
3110
+ ? `UPDATED: package.json (rungate devDep migrated: ${plan.reason})`
3111
+ : "UPDATED: package.json (rungate devDep)",
3112
+ );
2492
3113
  }
2493
3114
 
2494
3115
  /**
@@ -2663,7 +3284,11 @@ export function reportScaffoldActions(actions: string[]): number {
2663
3284
  console.log("\n=== Scaffold Report ===");
2664
3285
  for (const action of actions) console.log(` ${action}`);
2665
3286
  const count = (verb: string) => actions.filter(a => a.startsWith(verb)).length;
2666
- console.log(`\nTotal: ${count("CREATED")} created, ${count("REPLACED")} replaced, ${count("SKIP")} skipped, ${count("REFUSED")} refused`);
3287
+ // AUTO-FIXED is reported separately from AUDITED on purpose (#42 SC-3).
3288
+ // What the scaffold CHANGED and what it merely NOTICED are different facts,
3289
+ // and a reader who cannot tell them apart has to diff the tree to find out
3290
+ // which of the reported gaps are still gaps.
3291
+ console.log(`\nTotal: ${count("CREATED")} created, ${count("REPLACED")} replaced, ${count("AUTO-FIXED")} auto-fixed, ${count("SKIP")} skipped, ${count("REFUSED")} refused`);
2667
3292
  return count("REFUSED");
2668
3293
  }
2669
3294