rungate 0.4.1 → 0.5.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 (42) 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/cli-commands.ts +7 -1
  11. package/lib/conformity.ts +965 -30
  12. package/lib/github.ts +195 -0
  13. package/lib/js-top-level-code.ts +27 -2
  14. package/lib/package-closure.ts +278 -2
  15. package/lib/release-preflight.ts +196 -0
  16. package/lib/scaffold/defaults.ts +40 -0
  17. package/lib/scaffold/managed-workflow.ts +125 -27
  18. package/lib/scaffold/owned-files.ts +6 -0
  19. package/lib/scaffold/profiles.ts +94 -0
  20. package/lib/scaffold/rehearsal.ts +27 -2
  21. package/lib/scaffold/steps.ts +654 -84
  22. package/lib/scaffold/write-steps.ts +50 -9
  23. package/lib/source-anchor.ts +144 -0
  24. package/lib/success-doc.ts +779 -0
  25. package/lib/suite-run-reading.ts +194 -0
  26. package/lib/test-census.ts +199 -0
  27. package/lib/trajectory.ts +377 -0
  28. package/lib/validators/spec-validators.ts +32 -4
  29. package/lib/workflow-security.ts +101 -0
  30. package/lib/workflow-test-harness.ts +349 -0
  31. package/package.json +6 -1
  32. package/scripts/create-success.ts +162 -0
  33. package/scripts/scaffold-project.ts +27 -3
  34. package/specs/SPEC-TEMPLATE.md +200 -0
  35. package/templates/SUCCESS-TEMPLATE.md +72 -0
  36. package/templates/agent-briefs/_shared.md +9 -0
  37. package/templates/agent-briefs/aditi.md +46 -0
  38. package/templates/agent-briefs/discovery.md +37 -0
  39. package/templates/agent-briefs/marcus.md +39 -0
  40. package/templates/agent-briefs/quinn.md +67 -0
  41. package/templates/agent-briefs/rook.md +40 -0
  42. 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,7 +16,12 @@ 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";
@@ -24,7 +29,15 @@ import type { ProjectScan, ProjectType, SpecEntry, TestFile, RefFile, DocRoute,
24
29
  import { tier1Ere } from "../secret-patterns";
25
30
  import { healthPathIn } from "../liveness-contradiction";
26
31
  import { decideRuleWrite } from "../rule-provenance";
32
+ import { DEFAULT_PROFILE, isRuleIncluded, type ScaffoldProfile } from "./profiles";
27
33
  import { referencedPaths } from "../agents-md-refs";
34
+ import {
35
+ readSuccessDoc,
36
+ readSuccessTemplate,
37
+ seedFromTemplate,
38
+ successViolations,
39
+ TEMPLATE_MISSING,
40
+ } from "../success-doc";
28
41
  import { TS_SOURCE_DIRS, typeScriptSourceDirs, typecheckDecision } from "../typescript-project";
29
42
  import {
30
43
  OWNED_FILES,
@@ -123,7 +136,47 @@ export function regenerateOwned(
123
136
  actions: string[],
124
137
  strategy: WriteStrategy = ownedStrategy(label),
125
138
  ): void {
126
- const existing = existsSync(filePath) ? readFileSync(filePath, "utf-8") : null;
139
+ // `lstatSync`, NOT `existsSync` — BUG-440-A's shape, found by security
140
+ // review of #502 and PRE-EXISTING: it reaches `project-state.json` and
141
+ // every other owned file, not just the one that surfaced it.
142
+ //
143
+ // `existsSync` RESOLVES a symlink and `writeFileSync` FOLLOWS one, so the
144
+ // two disagree about exactly one input: a dangling `SUCCESS.md ->
145
+ // /elsewhere/x` is "absent" to the guard and a live write target to the
146
+ // writer. Measured: the scaffold created `/tmp/dang/victim/newfile.json`
147
+ // from a symlink planted at `project-state.json`, outside the project root
148
+ // entirely, and reported `CREATED: project-state.json`.
149
+ //
150
+ // `lstatSync` describes the LINK, so a symlink of either kind is something
151
+ // that is already there — which is what create-only means by "exists", and
152
+ // what the regenerate strategies must refuse rather than write through.
153
+ let link: ReturnType<typeof lstatSync> | null = null;
154
+ try {
155
+ link = lstatSync(filePath);
156
+ } catch {
157
+ link = null;
158
+ }
159
+ if (link?.isSymbolicLink()) {
160
+ actions.push(
161
+ `${SCAFFOLD_REFUSE}: ${label} is a symlink, and the generator does not write through ` +
162
+ `one — the target may be outside this project. Replace it with a real file, or ` +
163
+ `delete it and re-run.`,
164
+ );
165
+ return;
166
+ }
167
+ if (link && !link.isFile()) {
168
+ // A directory (or a device, or a socket) where an owned file belongs.
169
+ // `readFileSync` throws EISDIR, and that throw ESCAPES the step and
170
+ // aborts the whole scaffold run mid-way — after some files are written
171
+ // and before others. A refusal that names the path leaves the tree in a
172
+ // state someone can reason about; a half-finished run does not.
173
+ actions.push(
174
+ `${SCAFFOLD_REFUSE}: ${label} exists but is not a regular file, so the generator ` +
175
+ `will not read or replace it. Remove it and re-run.`,
176
+ );
177
+ return;
178
+ }
179
+ const existing = link ? readFileSync(filePath, "utf-8") : null;
127
180
  const decision = decideOwnedWrite(strategy, existing, content);
128
181
 
129
182
  if (decision.action === "preserve") {
@@ -138,7 +191,14 @@ export function regenerateOwned(
138
191
  return;
139
192
  }
140
193
 
141
- const dir = filePath.substring(0, filePath.lastIndexOf("/"));
194
+ // `dirname`, not a hand-rolled slice (#481). `substring(0, lastIndexOf("/"))`
195
+ // is correct for every path carrying a separator and silently wrong for the
196
+ // one that does not: `lastIndexOf` returns -1, `substring` CLAMPS a negative
197
+ // end to zero, and the directory to create becomes `""` — which does not
198
+ // exist, so the guard admits it, and `mkdirSync("")` throws ENOENT. Every
199
+ // repo-root owned file hits that under a relative root, which is the form
200
+ // the harness documents.
201
+ const dir = dirname(filePath);
142
202
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
143
203
  writeFileSync(filePath, decision.content!);
144
204
  actions.push(`${decision.action === "create" ? "CREATED" : "CHANGED"}: ${label}`);
@@ -262,7 +322,12 @@ export function injectEnvironmentSection(root: string, actions: string[]): void
262
322
  actions.push("UPDATED: AGENTS.md environment section from rungate.json");
263
323
  }
264
324
 
265
- export function generateAgentsMdContent(projectPath: string, type: ProjectType, actions: string[]): string {
325
+ export function generateAgentsMdContent(
326
+ projectPath: string,
327
+ type: ProjectType,
328
+ actions: string[],
329
+ profile: ScaffoldProfile = DEFAULT_PROFILE,
330
+ ): string {
266
331
  const pkgPath = join(projectPath, "package.json");
267
332
  let pkgDesc = "";
268
333
  let pkgName = basename(projectPath);
@@ -552,7 +617,9 @@ export function generateAgentsMdContent(projectPath: string, type: ProjectType,
552
617
  // why neither "never overwrite" nor "always overwrite" is the answer.
553
618
  const rulesDir = join(projectPath, ".claude", "rules");
554
619
  if (!existsSync(rulesDir)) mkdirSync(rulesDir, { recursive: true });
555
- const scopedRules = generateScopedRules(scan);
620
+ // A rule is instructions to an agent, so one naming machinery the profile
621
+ // did not install is worse than no rule at all. See RULES_NOT_MINIMAL.
622
+ const scopedRules = generateScopedRules(scan).filter(r => isRuleIncluded(r.filename, profile));
556
623
  for (const rule of scopedRules) {
557
624
  const rulePath = join(rulesDir, rule.filename);
558
625
  const existing = existsSync(rulePath) ? readFileSync(rulePath, "utf-8") : null;
@@ -597,9 +664,14 @@ export function generateAgentsMdContent(projectPath: string, type: ProjectType,
597
664
  * through `updateSpecsTable` and `injectEnvironmentSection` by this point, and
598
665
  * rewriting it would undo both.
599
666
  */
600
- export function refreshScopedRulesStep(root: string, type: ProjectType, actions: string[]): void {
667
+ export function refreshScopedRulesStep(
668
+ root: string,
669
+ type: ProjectType,
670
+ actions: string[],
671
+ profile: ScaffoldProfile = DEFAULT_PROFILE,
672
+ ): void {
601
673
  const sink: string[] = [];
602
- generateAgentsMdContent(root, type, sink);
674
+ generateAgentsMdContent(root, type, sink, profile);
603
675
  // Forward everything except the per-rule lines already reported by the
604
676
  // Phase 0.5 pass. Swallowing the rest would hide a warning raised only on
605
677
  // the second scan — the fail-open shape .claude/rules/checks-must-be-able-to-fail.md
@@ -710,7 +782,7 @@ export function generateConformityTest(root?: string): string {
710
782
  const from = root && isHarnessItself(root) ? "../lib/conformity" : "rungate/lib/conformity";
711
783
  return `import { resolve } from "path";
712
784
  import { afterAll } from "bun:test";
713
- import { runScaffoldConformity, runSpecDiscovery, runSpecDrift, runDocHygiene, runFallowCheck, runAgentFileValidation, runDirectoryValidation, runPackageValidation, runTsconfigValidation, runConfigAccessValidation, runPromptConfigAccessValidation, writeFindingsReport } from "${from}";
785
+ import { runScaffoldConformity, runSpecDiscovery, runSpecDrift, runDocHygiene, runFallowCheck, runAgentFileValidation, runDirectoryValidation, runPackageValidation, runTsconfigValidation, runConfigAccessValidation, runPromptConfigAccessValidation, runSuccessDocValidation, writeFindingsReport } from "${from}";
714
786
 
715
787
  const ROOT = resolve(import.meta.dir, "..");
716
788
 
@@ -725,6 +797,7 @@ runPackageValidation(ROOT);
725
797
  runTsconfigValidation(ROOT);
726
798
  runConfigAccessValidation(ROOT);
727
799
  runPromptConfigAccessValidation(ROOT);
800
+ runSuccessDocValidation(ROOT);
728
801
 
729
802
  afterAll(() => writeFindingsReport(ROOT));
730
803
  `;
@@ -871,7 +944,7 @@ export function generateAgentBriefsStep(root: string, actions: string[]): void {
871
944
 
872
945
  // ── Harness config generation/audit ────────────────────────────
873
946
 
874
- export function generateOrAuditProjectHarness(root: string, actions: string[]): void {
947
+ export function generateOrAuditProjectHarness(root: string, actions: string[], opts: { pruneConsumers?: boolean } = {}): void {
875
948
  const harnessPath = join(root, ".claude", "rungate.json");
876
949
 
877
950
  const detectedHealthPath = detectHealthPath(root);
@@ -1017,7 +1090,7 @@ export function generateOrAuditProjectHarness(root: string, actions: string[]):
1017
1090
  // files #75 only ever fixed for greenfield projects (#121).
1018
1091
  const existing = JSON.parse(readFileSync(join(rungateDir, "config.json"), "utf-8"));
1019
1092
  repairEmptySidecars(rungateDir, actions);
1020
- auditExistingConfig(existing, scannedPages, scannedConsumers, actions, rungateDir);
1093
+ auditExistingConfig(existing, scannedPages, scannedConsumers, actions, rungateDir, opts.pruneConsumers === true);
1021
1094
  } else if (existsSync(harnessPath)) {
1022
1095
  // Monolith exists — split into directory structure
1023
1096
  const existing = JSON.parse(readFileSync(harnessPath, "utf-8"));
@@ -1027,6 +1100,8 @@ export function generateOrAuditProjectHarness(root: string, actions: string[]):
1027
1100
  splitMonolithToDirectory(root, existing, actions);
1028
1101
  } else {
1029
1102
  // Simple monolith without split-worthy content — audit only
1103
+ // No rungateDir on this path (the monolith layout), so pruning has
1104
+ // nowhere to write and is not offered rather than silently not happening.
1030
1105
  auditExistingConfig(existing, scannedPages, scannedConsumers, actions);
1031
1106
  }
1032
1107
  } else {
@@ -1183,12 +1258,84 @@ function repairEmptySidecars(rungateDir: string, actions: string[]): void {
1183
1258
  }
1184
1259
  }
1185
1260
 
1261
+ /**
1262
+ * Remove consumers the source scan did not find — only when asked (#42).
1263
+ *
1264
+ * **Opt-in, against the issue's own SC-4, and the asymmetry is the reason.**
1265
+ * SC-2 says to remove them "when source scan confirms they don't exist". A
1266
+ * source scan cannot confirm absence; it reports that it did not find
1267
+ * something, and the gap between those two claims is where a dynamic import,
1268
+ * a generated file, a file type the scanner does not read, and a scanner that
1269
+ * errored all live. A stale entry left in config costs a warning line. A live
1270
+ * entry deleted costs that consumer its role grading, compliance policy and
1271
+ * pre-flight checks — silently, in a report nobody reads line by line.
1272
+ *
1273
+ * So adding a frontmatter field stays opt-out as SC-4 asks, and this one
1274
+ * operation does not: deleting is not in the same risk class as adding.
1275
+ *
1276
+ * Returns true when it pruned, so the caller reports the finding only when it
1277
+ * did not — a run must never both remove something and complain it is there.
1278
+ */
1279
+ export function pruneStaleConsumers(
1280
+ existing: any,
1281
+ scannedConsumers: string[],
1282
+ stale: string[],
1283
+ actions: string[],
1284
+ rungateDir: string | undefined,
1285
+ prune: boolean,
1286
+ ): boolean {
1287
+ if (!prune) return false;
1288
+
1289
+ // The refusal that matters most, and the one nothing in #42 asked for: a
1290
+ // scanner that returns nothing makes EVERY declared consumer look stale, so
1291
+ // one broken scan would empty the list in a single pass. "The scan found no
1292
+ // consumers" and "this project has no consumers" are not the same reading,
1293
+ // and treating them alike is Silent Default Substitution
1294
+ // (`.claude/rules/config-access.md`).
1295
+ if (scannedConsumers.length === 0) {
1296
+ actions.push(
1297
+ `REFUSED: --prune-consumers (the source scan found no consumers at all, so all ${stale.length} ` +
1298
+ `look stale — a scan that found nothing is a broken scan, not an empty project)`,
1299
+ );
1300
+ return false;
1301
+ }
1302
+
1303
+ if (!rungateDir || !existsSync(join(rungateDir, "config.json"))) {
1304
+ actions.push(
1305
+ "REFUSED: --prune-consumers (no .claude/rungate/config.json to write — " +
1306
+ "refusing rather than guessing which file holds the consumer list)",
1307
+ );
1308
+ return false;
1309
+ }
1310
+
1311
+ const configPath = join(rungateDir, "config.json");
1312
+ let config: any;
1313
+ try {
1314
+ config = JSON.parse(readFileSync(configPath, "utf-8"));
1315
+ } catch (err) {
1316
+ // A corrupt config is never an empty config. Rewriting it from `existing`
1317
+ // would discard every key this function does not know about.
1318
+ actions.push(`REFUSED: --prune-consumers (config.json is unreadable: ${(err as Error).message})`);
1319
+ return false;
1320
+ }
1321
+
1322
+ config.consumers = (config.consumers || []).filter((c: string) => !stale.includes(c));
1323
+ writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n");
1324
+ existing.consumers = config.consumers;
1325
+
1326
+ // Every name, not a count. A removal the report summarises as a number is
1327
+ // one nobody can audit or put back.
1328
+ actions.push(`AUTO-FIXED: .claude/rungate/config.json (pruned ${stale.length} stale consumers: ${stale.join(", ")})`);
1329
+ return true;
1330
+ }
1331
+
1186
1332
  function auditExistingConfig(
1187
1333
  existing: any,
1188
1334
  scannedPages: Record<string, string>,
1189
1335
  scannedConsumers: string[],
1190
1336
  actions: string[],
1191
- rungateDir?: string
1337
+ rungateDir?: string,
1338
+ prune = false,
1192
1339
  ): void {
1193
1340
  const issues: string[] = [];
1194
1341
 
@@ -1221,7 +1368,10 @@ function auditExistingConfig(
1221
1368
  if (declaredConsumers.length > 0) {
1222
1369
  const staleConsumers = declaredConsumers.filter((c: string) => !scannedConsumers.includes(c));
1223
1370
  if (staleConsumers.length > 0) {
1224
- issues.push(`CONSUMERS: ${staleConsumers.length} stale consumers in rungate.json not found in source: ${staleConsumers.slice(0, 5).join(", ")}`);
1371
+ const pruned = pruneStaleConsumers(existing, scannedConsumers, staleConsumers, actions, rungateDir, prune);
1372
+ if (!pruned) {
1373
+ issues.push(`CONSUMERS: ${staleConsumers.length} stale consumers in rungate.json not found in source: ${staleConsumers.slice(0, 5).join(", ")}`);
1374
+ }
1225
1375
  }
1226
1376
  }
1227
1377
 
@@ -1532,66 +1682,122 @@ export function createTsconfig(root: string, actions: string[]): void {
1532
1682
  actions.push("CREATED: tsconfig.json");
1533
1683
  }
1534
1684
 
1685
+ /**
1686
+ * One `.gitignore` section, and whether an ADOPTING project must get it (#474).
1687
+ *
1688
+ * The two branches of `createGitignore` used to hold two lists written in two
1689
+ * syntaxes, and they disagreed. The fresh-template branch wrote
1690
+ * `credentials.json`; the append branch derived its own form with
1691
+ * `e.includes("*") ? e : \`${e}/\``, which appends a trailing slash — and a
1692
+ * trailing slash in gitignore syntax RESTRICTS THE PATTERN TO DIRECTORIES:
1693
+ *
1694
+ * | Intended | Appended | Matches a file `credentials.json`? |
1695
+ * |---|---|---|
1696
+ * | `credentials.json` | `credentials.json/` | no |
1697
+ * | `service-account*` | `service-account/` | no |
1698
+ *
1699
+ * Six of the eight entries are directories, so the bug was invisible for them
1700
+ * and the block it broke is the one labelled "Environment and secrets" — the
1701
+ * two entries that are FILES are the two it silently inverted. The scaffold
1702
+ * reported `UPDATED: .gitignore (added 8 missing entries)` with two of them
1703
+ * inert, on exactly the path an existing project takes when it adopts
1704
+ * rungate. Found while scaffolding a plugin whose whole integration is Google
1705
+ * Drive, where `credentials.json` is the default client-secrets filename.
1706
+ *
1707
+ * So there is ONE list, and every pattern is written here EXACTLY as it must
1708
+ * appear on disk. Nothing downstream may transform a pattern — a second place
1709
+ * that decides syntax is the shape this bug had.
1710
+ */
1711
+ interface GitignoreSection {
1712
+ heading: string;
1713
+ patterns: string[];
1714
+ /**
1715
+ * Ensured when appending to a `.gitignore` that already exists. A project
1716
+ * adopting rungate keeps its own conventions for build output and editors;
1717
+ * what it does not get to opt out of is leaking a credential.
1718
+ */
1719
+ requiredOnAdoption: boolean;
1720
+ }
1721
+
1722
+ /** The single source for both branches below. Patterns are verbatim. */
1723
+ export const GITIGNORE_SECTIONS: GitignoreSection[] = [
1724
+ { heading: "Dependencies", requiredOnAdoption: true, patterns: ["node_modules/", ".bun/"] },
1725
+ // Required because the list this replaced required `dist`. Rounded up to
1726
+ // the whole section rather than down: #474 is about the two branches
1727
+ // disagreeing, and quietly shrinking what an adopting project gets would
1728
+ // be a second behaviour change hiding inside the fix for the first.
1729
+ { heading: "Build output", requiredOnAdoption: true, patterns: ["dist/", "build/", "*.tsbuildinfo"] },
1730
+ {
1731
+ heading: "Environment and secrets",
1732
+ requiredOnAdoption: true,
1733
+ patterns: [
1734
+ ".env",
1735
+ ".env.*",
1736
+ "!.env.example",
1737
+ "*.pem",
1738
+ "*.key",
1739
+ "*.p12",
1740
+ "*.pfx",
1741
+ "credentials.json",
1742
+ "service-account*",
1743
+ ".secret*",
1744
+ ],
1745
+ },
1746
+ { heading: "Harness working directory", requiredOnAdoption: true, patterns: [".rungate/"] },
1747
+ { heading: "IDE", requiredOnAdoption: false, patterns: [".vscode/", ".idea/", "*.swp", "*.swo"] },
1748
+ { heading: "OS", requiredOnAdoption: false, patterns: [".DS_Store", "Thumbs.db"] },
1749
+ { heading: "Test artifacts", requiredOnAdoption: false, patterns: ["coverage/"] },
1750
+ ];
1751
+
1752
+ /** The patterns an adopting project must end up with, in order. */
1753
+ export function requiredGitignorePatterns(): string[] {
1754
+ return GITIGNORE_SECTIONS.filter(s => s.requiredOnAdoption).flatMap(s => s.patterns);
1755
+ }
1756
+
1757
+ /** The fresh-project file, rendered from the one list. */
1758
+ export function gitignoreTemplate(): string {
1759
+ return (
1760
+ GITIGNORE_SECTIONS.map(s => `# ${s.heading}\n${s.patterns.join("\n")}\n`).join("\n") + ""
1761
+ );
1762
+ }
1763
+
1764
+ /**
1765
+ * Which required patterns an existing `.gitignore` does not already carry.
1766
+ *
1767
+ * Compared LINE-WISE against uncommented lines, not with `existing.includes`
1768
+ * (#474). A substring test over the whole file reports `credentials.json` as
1769
+ * present because of a comment reading `# credentials.json lives in
1770
+ * 1Password`, and then appends nothing — the entry is "handled" by a sentence
1771
+ * about it. It also made `*.key` satisfied by `*.keystore` and
1772
+ * `service-account` satisfied by the longer `service-account*`, which is how
1773
+ * the two lists stayed different without anything noticing.
1774
+ */
1775
+ export function missingGitignorePatterns(existing: string): string[] {
1776
+ const present = new Set(
1777
+ existing
1778
+ .split("\n")
1779
+ .map(l => l.trim())
1780
+ .filter(l => l !== "" && !l.startsWith("#")),
1781
+ );
1782
+ return requiredGitignorePatterns().filter(p => !present.has(p));
1783
+ }
1784
+
1535
1785
  export function createGitignore(root: string, actions: string[]): void {
1536
1786
  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
1787
 
1575
1788
  if (existsSync(gitignorePath)) {
1576
1789
  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));
1790
+ const missing = missingGitignorePatterns(existing);
1582
1791
  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";
1792
+ // Written VERBATIM. The transform that used to live here is the bug.
1793
+ const additions = "\n# Added by rungate scaffold\n" + missing.join("\n") + "\n";
1588
1794
  writeFileSync(gitignorePath, existing.trimEnd() + "\n" + additions);
1589
1795
  actions.push(`UPDATED: .gitignore (added ${missing.length} missing entries)`);
1590
1796
  } else {
1591
1797
  actions.push("SKIP: .gitignore (all required entries present)");
1592
1798
  }
1593
1799
  } else {
1594
- writeFileSync(gitignorePath, securityTemplate);
1800
+ writeFileSync(gitignorePath, gitignoreTemplate());
1595
1801
  actions.push("CREATED: .gitignore (security template)");
1596
1802
  }
1597
1803
  }
@@ -1680,6 +1886,80 @@ export function generateProjectState(root: string, actions: string[]): void {
1680
1886
  safeWrite(stateMd, lines.join("\n") + "\n", "PROJECT-STATE.md", actions);
1681
1887
  }
1682
1888
 
1889
+ /**
1890
+ * Seed `SUCCESS.md`, then say out loud that the seed is not an answer (#485).
1891
+ *
1892
+ * `CLAUDE.md` opens its rules with "SUCCESS.md is the measure" and the
1893
+ * scaffold never wrote one. rungate's was hand-written once and nothing
1894
+ * reproduced it for anyone else, so a consumer scaffolded a project, read the
1895
+ * generated `AGENTS.md`, and never learned the file was supposed to exist.
1896
+ *
1897
+ * Two halves, and the second is the one that makes this more than a nicety.
1898
+ *
1899
+ * **It is `create-only`.** A project's claims are the one thing the harness
1900
+ * must never regenerate over. `safeWrite` is the single writer for that, and
1901
+ * it is delegated to rather than reimplemented for the reason recorded on
1902
+ * that function: a second copy of the decision absorbs any mutation of the
1903
+ * first.
1904
+ *
1905
+ * **The WARN reads the real checker.** `successViolations` is the same
1906
+ * binding `SUCCESS-1` refuses with, so the scaffold's warning and the
1907
+ * conformity suite's refusal cannot disagree. A second "is it filled in?"
1908
+ * predicate here would be two deciders answering one question — the fourth
1909
+ * shape in `.claude/rules/checks-must-be-able-to-fail.md`, which no
1910
+ * behavioural test can tell apart.
1911
+ *
1912
+ * The direction this is deliberately wrong in: a project that runs the
1913
+ * scaffold and stops is now LOUDER than one that never ran it. An unfilled
1914
+ * template is refused; an absent file is only UNMEASURED. That is the point —
1915
+ * an unfilled template is indistinguishable from a considered one to
1916
+ * everything except a reader, so the generator must not make the project
1917
+ * quieter than it found it.
1918
+ */
1919
+ export function seedSuccessDoc(root: string, actions: string[]): void {
1920
+ // `readSuccessTemplate()` rather than a fourth expression resolving the
1921
+ // same path. There were three — here, `lib/success-doc.ts` and
1922
+ // `scripts/create-success.ts` — agreeing today and with nothing making them
1923
+ // agree tomorrow.
1924
+ const template = readSuccessTemplate();
1925
+ if (template === TEMPLATE_MISSING) {
1926
+ // Named, not swallowed. #484 was a documented command that ENOENTed for
1927
+ // every consumer because `files[]` omitted the directory it read from,
1928
+ // and the symptom was a check that reported 21 pass over a library that
1929
+ // could not load its own data.
1930
+ actions.push(
1931
+ "WARN: SUCCESS.md not seeded — templates/SUCCESS-TEMPLATE.md is missing from this " +
1932
+ "rungate installation (see test/package-closure.test.ts)",
1933
+ );
1934
+ return;
1935
+ }
1936
+
1937
+ const today = new Date().toISOString().slice(0, 10);
1938
+ const owner = process.env.USER || "TODO-OWNER";
1939
+ // The SHARED substitution. Writing the template raw here while
1940
+ // `create-success` substituted meant one seed with two possible byte
1941
+ // sequences, and a scaffolded SUCCESS.md kept `owner: TODO-OWNER` forever.
1942
+ const seeded = seedFromTemplate(template, owner, today);
1943
+ safeWrite(join(root, "SUCCESS.md"), seeded, "SUCCESS.md", actions);
1944
+
1945
+ const verdict = successViolations(readSuccessDoc(root), template);
1946
+ if (verdict.unmeasured) {
1947
+ actions.push(`WARN: ${verdict.unmeasured}`);
1948
+ return;
1949
+ }
1950
+ if (verdict.violations.length > 0) {
1951
+ actions.push(
1952
+ // NOT "run create-success" — by the time anyone reads this the file is
1953
+ // already there, so that command refuses and the advice is a dead end.
1954
+ `WARN: SUCCESS.md is not filled in — ${verdict.violations.length} item(s). ` +
1955
+ `The conformity suite REFUSES it in this state, deliberately. Edit ` +
1956
+ `${join(root, "SUCCESS.md")} (or re-seed it with ` +
1957
+ `\`bunx rungate create-success --force\`):`,
1958
+ );
1959
+ for (const v of verdict.violations) actions.push(` - ${v}`);
1960
+ }
1961
+ }
1962
+
1683
1963
  export function createClaudeMdBridge(root: string, actions: string[]): void {
1684
1964
  const claudeMdPath = join(root, "CLAUDE.md");
1685
1965
  const bridgeLine = "@AGENTS.md";
@@ -1738,6 +2018,19 @@ export interface ManagedWrite {
1738
2018
  * CI resilience, and "REPLACED (+33 lines)" does not tell anyone that.
1739
2019
  */
1740
2020
  overwrittenLines: string[];
2021
+ /**
2022
+ * Top-level keys the merge put somewhere else (#482).
2023
+ *
2024
+ * Not a refusal — YAML top-level keys are order-independent, so a moved key
2025
+ * means what it meant. It IS reported, because `UPDATED` with nothing said
2026
+ * about position is a report that is accurate and still misleads: a
2027
+ * consumer's `concurrency:` arrived below `jobs:` while the comment
2028
+ * introducing it stayed above, the reader concluded it had been deleted,
2029
+ * restored it by hand, and the file stopped parsing. "Nothing was lost" and
2030
+ * "everything is where you left it" are different claims and only the first
2031
+ * was being made.
2032
+ */
2033
+ movedKeys: MovedKey[];
1741
2034
  /** Non-null ⇒ the write must not happen. Names the dropped jobs and the line delta. */
1742
2035
  refusal: string | null;
1743
2036
  }
@@ -1838,7 +2131,7 @@ function measureWrite(existing: string | null, next: string): { verb: ManagedWri
1838
2131
  export function resolveManagedWrite(existing: string | null, generated: string): ManagedWrite {
1839
2132
  const base: ManagedWrite = {
1840
2133
  content: generated, verb: "CREATED", lineDelta: lineCount(generated),
1841
- preservedJobs: [], droppedJobs: [], overwrittenLines: [], refusal: null,
2134
+ preservedJobs: [], droppedJobs: [], overwrittenLines: [], movedKeys: [], refusal: null,
1842
2135
  };
1843
2136
  if (existing === null) return base;
1844
2137
 
@@ -1878,11 +2171,63 @@ export function resolveManagedWrite(existing: string | null, generated: string):
1878
2171
  const resultJobs = workflowJobNames(content);
1879
2172
  if (resultJobs === null) {
1880
2173
  return {
1881
- ...unchanged, preservedJobs: [], droppedJobs: existingJobs, overwrittenLines: [], lineDelta,
2174
+ ...unchanged, preservedJobs: [], droppedJobs: existingJobs, overwrittenLines: [], movedKeys: [], lineDelta,
1882
2175
  refusal: `the merged workflow does not parse, so it cannot be written (line delta ${signed(lineDelta)})`,
1883
2176
  };
1884
2177
  }
1885
2178
 
2179
+ // A top-level key declared twice is a workflow YAML rejects and GitHub
2180
+ // Actions refuses to run (#482). The realistic way one appears is the
2181
+ // correction this issue is about — somebody restores a block they believe
2182
+ // the merge deleted while the original is still further down — so the
2183
+ // refusal has to look at the EXISTING file as well as the merged one, and
2184
+ // name the key rather than the symptom.
2185
+ const duplicated = [
2186
+ ...duplicateTopLevelKeys(existing).map(k => [k, "the existing file"] as const),
2187
+ ...duplicateTopLevelKeys(content)
2188
+ .filter(k => !duplicateTopLevelKeys(existing).includes(k))
2189
+ .map(k => [k, "the merged output"] as const),
2190
+ ];
2191
+ if (duplicated.length > 0) {
2192
+ return {
2193
+ ...unchanged, preservedJobs: [], droppedJobs: [], overwrittenLines: [], movedKeys: [], lineDelta,
2194
+ refusal:
2195
+ `${duplicated.length} top-level key(s) declared more than once in ` +
2196
+ `${duplicated.map(([k, where]) => `${k} (${where})`).join(", ")} — ` +
2197
+ `YAML rejects a duplicate mapping key, so the workflow would not run. ` +
2198
+ `Delete the extra declaration and re-run (line delta ${signed(lineDelta)})`,
2199
+ };
2200
+ }
2201
+
2202
+ // The merge's contract since #482 is that the consumer's top-level ORDER is
2203
+ // the consumer's. So movement is no longer something to report — it is a
2204
+ // bug in the merge, and shipping one is what produced the incident: a
2205
+ // `concurrency:` block 460 lines below the comment introducing it, read as
2206
+ // a deletion, "restored", and the workflow stopped parsing.
2207
+ //
2208
+ // A refusal rather than a warning, because the cost is asymmetric. A
2209
+ // consumer who hits an unenumerated edge case gets a named refusal and
2210
+ // `--force`; a consumer who does not get one gets a file they will
2211
+ // misread. Measured against this repo's three real workflow files — one of
2212
+ // which carries a `permissions:` key between `on:` and `jobs:`, exactly the
2213
+ // shape that used to move: zero movement in all three.
2214
+ //
2215
+ // The file is not named here on purpose. `test/anti.test.ts` SC-A1 keeps
2216
+ // the scaffold from naming a workflow it does not own, and a comment is as
2217
+ // nameable as a code path.
2218
+ const movedKeys = movedTopLevelKeys(existing, content);
2219
+ if (movedKeys.length > 0) {
2220
+ return {
2221
+ ...unchanged, preservedJobs, droppedJobs: [], overwrittenLines: [], movedKeys, lineDelta,
2222
+ refusal:
2223
+ `${movedKeys.length} top-level key(s) would move: ` +
2224
+ `${movedKeys.slice(0, 3).map(m => `${m.key} (line ${m.from + 1} -> ${m.to + 1})`).join(", ")}` +
2225
+ `${movedKeys.length > 3 ? ` and ${movedKeys.length - 3} more` : ""} — ` +
2226
+ `a key that moves away from the comment introducing it reads as a deletion ` +
2227
+ `(line delta ${signed(lineDelta)})`,
2228
+ };
2229
+ }
2230
+
1886
2231
  // The loss set is LINES, not job names. Every non-blank line the consumer
1887
2232
  // has that the merge did not carry is content the harness is about to drop,
1888
2233
  // wherever in the file it sits.
@@ -1919,7 +2264,7 @@ export function resolveManagedWrite(existing: string | null, generated: string):
1919
2264
  ? `job(s) ${droppedJobs.join(", ")}`
1920
2265
  : "content outside any job";
1921
2266
  return {
1922
- ...unchanged, preservedJobs, droppedJobs, overwrittenLines: [], lineDelta,
2267
+ ...unchanged, preservedJobs, droppedJobs, overwrittenLines: [], movedKeys: [], lineDelta,
1923
2268
  refusal:
1924
2269
  `${lostLines.length} line(s) the harness did not author would be dropped from ${where}` +
1925
2270
  `: ${lostLines.slice(0, 3).map(l => JSON.stringify(l)).join(", ")}` +
@@ -1928,7 +2273,7 @@ export function resolveManagedWrite(existing: string | null, generated: string):
1928
2273
  };
1929
2274
  }
1930
2275
 
1931
- return { content, ...measureWrite(existing, content), preservedJobs, droppedJobs: [], overwrittenLines, refusal: null };
2276
+ return { content, ...measureWrite(existing, content), preservedJobs, droppedJobs: [], overwrittenLines, movedKeys, refusal: null };
1932
2277
  }
1933
2278
 
1934
2279
  /** Non-blank lines, trimmed — the unit the loss set is counted in. */
@@ -2269,6 +2614,19 @@ export function deployHooksToConsumers(root: string, actions: string[]): void {
2269
2614
  }
2270
2615
  }
2271
2616
 
2617
+ /**
2618
+ * The line that marks a pre-commit hook as ours, so a fix can reach one that
2619
+ * already exists (#450).
2620
+ *
2621
+ * The guard here was `if (!existsSync(preCommit))`, which meant every
2622
+ * checkout that already had a hook kept whatever version it was given the
2623
+ * first time — including the one that stages DA-owned state from every
2624
+ * worktree, which is what #450 is about. The pre-push hook had exactly this
2625
+ * bug and #85 fixed it the same way: overwrite our own managed hook, and
2626
+ * leave a hand-written one alone.
2627
+ */
2628
+ export const PRE_COMMIT_MANAGED_MARKER = "# Managed by rungate — secret scan + PROJECT-STATE update";
2629
+
2272
2630
  export function createGitHooks(root: string, actions: string[]): void {
2273
2631
  const hooksDir = join(root, ".git", "hooks");
2274
2632
  if (!existsSync(hooksDir)) return;
@@ -2276,9 +2634,12 @@ export function createGitHooks(root: string, actions: string[]): void {
2276
2634
  const { chmodSync } = require("fs");
2277
2635
 
2278
2636
  const preCommit = join(hooksDir, "pre-commit");
2279
- if (!existsSync(preCommit)) {
2637
+ const existingPreCommit = existsSync(preCommit) ? readFileSync(preCommit, "utf-8") : null;
2638
+ if (existingPreCommit !== null && !existingPreCommit.includes(PRE_COMMIT_MANAGED_MARKER)) {
2639
+ actions.push("SKIP: .git/hooks/pre-commit (hand-written, not overwriting)");
2640
+ } else {
2280
2641
  writeFileSync(preCommit, `#!/bin/sh
2281
- # Managed by rungate — secret scan + PROJECT-STATE update
2642
+ ${PRE_COMMIT_MANAGED_MARKER}
2282
2643
  #
2283
2644
  # Scans the staged DIFF, not files on disk. This is deliberate and fixes four
2284
2645
  # failure modes the file-list approach had:
@@ -2325,10 +2686,41 @@ if printf '%s\\n' "$staged_diff" \\
2325
2686
  exit 1
2326
2687
  fi
2327
2688
 
2328
- # Update PROJECT-STATE if it exists
2689
+ # Update PROJECT-STATE if it exists — but NEVER from a linked worktree (#450).
2690
+ #
2691
+ # project-state.json, PROJECT-STATE.md and SUCCESS.md are DA-owned: a single
2692
+ # shared state document that several worktrees must not each write their own
2693
+ # version of (#296). The rule is written down in CLAUDE.md and in
2694
+ # .claude/rules/key-files.md, and this hook used to do the opposite of it on
2695
+ # every commit in every worktree — so an agent that obeyed the rule perfectly
2696
+ # still shipped the violation, because the staging happened after it had
2697
+ # decided not to touch the file. A rule something actively undoes is worse
2698
+ # than a rule nothing executes.
2699
+ #
2700
+ # The hook cannot tell whether it is the DA. It CAN tell whether it is in a
2701
+ # linked worktree: --git-dir points at .git/worktrees/<name> there while
2702
+ # --git-common-dir points at the shared .git, and in the primary checkout the
2703
+ # two are the same answer.
2704
+ #
2705
+ # The first draft resolved both through a cd-then-pwd-P round trip first, on
2706
+ # the theory that one could come back relative and the other absolute. The
2707
+ # mutation battery scored that normalisation 0 of 20 — both arms behave
2708
+ # identically without it, executed against a real primary checkout and a real
2709
+ # linked worktree. An unmeasured guard is indistinguishable from an absent
2710
+ # one, so it is absent. git hooks run from the toplevel, and both calls share
2711
+ # a cwd, so there was never a case that needed it.
2329
2712
  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
2713
+ gitdir=$(git rev-parse --git-dir)
2714
+ commondir=$(git rev-parse --git-common-dir)
2715
+ if [ -n "$gitdir" ] && [ "$gitdir" = "$commondir" ]; then
2716
+ bun node_modules/rungate/scripts/update-project-state.ts --skip-tests 2>/dev/null || true
2717
+ git add PROJECT-STATE.md project-state.json 2>/dev/null || true
2718
+ else
2719
+ # Announced, not silent. A developer who expected the state files to move
2720
+ # would otherwise be left guessing, and SKIP that says nothing is
2721
+ # indistinguishable from the update having happened.
2722
+ 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."
2723
+ fi
2332
2724
  fi
2333
2725
 
2334
2726
  # A script's exit status is its last command's. Without this, the [ -f ] test
@@ -2338,7 +2730,11 @@ fi
2338
2730
  exit 0
2339
2731
  `);
2340
2732
  chmodSync(preCommit, 0o755);
2341
- actions.push("CREATED: .git/hooks/pre-commit (secret scan + PROJECT-STATE update)");
2733
+ actions.push(
2734
+ existingPreCommit === null
2735
+ ? "CREATED: .git/hooks/pre-commit (secret scan + PROJECT-STATE update)"
2736
+ : "UPDATED: .git/hooks/pre-commit (secret scan + PROJECT-STATE update)",
2737
+ );
2342
2738
  }
2343
2739
 
2344
2740
  const prePush = join(hooksDir, "pre-push");
@@ -2458,24 +2854,189 @@ function harnessVersion(): string {
2458
2854
  * half is a pure property and needs no registry. See
2459
2855
  * `test/scaffold-installable.test.ts`.
2460
2856
  */
2857
+ /** Every section a dependency declaration can hide in (#475). */
2858
+ export const DEP_SECTIONS = ["dependencies", "devDependencies", "optionalDependencies"] as const;
2859
+
2860
+ /**
2861
+ * Both names the harness has shipped under.
2862
+ *
2863
+ * `pai-harness` is the former name and older scaffold runs wrote it. A
2864
+ * migration that knows only the current name leaves the old declaration in
2865
+ * place and adds a new one beside it — two packages for one dependency.
2866
+ */
2867
+ export const HARNESS_PKG_NAMES = ["rungate", "pai-harness"] as const;
2868
+
2869
+ /**
2870
+ * The name the harness ships under today; the rest of `HARNESS_PKG_NAMES` is
2871
+ * history, and migration targets this one.
2872
+ *
2873
+ * Derived rather than written out so the two cannot drift — and named rather
2874
+ * than inlined for a second reason worth stating, because it looks like
2875
+ * evasion otherwise. #380's `IDENTITY_COMPARISON` guard matches a
2876
+ * `name`-equality against the harness's own package name anywhere in
2877
+ * `lib/`, to keep "is this project the harness" decided in exactly one
2878
+ * place — and this paragraph deliberately does not spell that comparison
2879
+ * out, because the guard reads raw source and a docstring quoting the
2880
+ * pattern reports itself as a second site. The comparison below asks a
2881
+ * different question of a different type — "is this DECLARATION named
2882
+ * rungate", where `name` is a key in someone's `devDependencies` — and the
2883
+ * textual guard cannot tell the two apart. Widening the guard would narrow
2884
+ * it; this keeps #380's single binding intact and says which question is
2885
+ * being asked.
2886
+ */
2887
+ export const CURRENT_HARNESS_PKG: (typeof HARNESS_PKG_NAMES)[number] = HARNESS_PKG_NAMES[0];
2888
+
2889
+ export interface HarnessDeclaration {
2890
+ section: (typeof DEP_SECTIONS)[number];
2891
+ name: (typeof HARNESS_PKG_NAMES)[number];
2892
+ spec: string;
2893
+ }
2894
+
2895
+ /** Every place this package.json declares the harness. */
2896
+ export function findHarnessDeclarations(pkg: unknown): HarnessDeclaration[] {
2897
+ const out: HarnessDeclaration[] = [];
2898
+ const obj = pkg as Record<string, Record<string, unknown>> | null;
2899
+ if (!obj || typeof obj !== "object") return out;
2900
+ for (const section of DEP_SECTIONS) {
2901
+ const deps = obj[section];
2902
+ if (!deps || typeof deps !== "object") continue;
2903
+ for (const name of HARNESS_PKG_NAMES) {
2904
+ const spec = deps[name];
2905
+ if (typeof spec === "string") out.push({ section, name, spec });
2906
+ }
2907
+ }
2908
+ return out;
2909
+ }
2910
+
2911
+ /** What the scaffold intends to do about the harness dependency. */
2912
+ export interface HarnessDepPlan {
2913
+ action: "skip" | "add" | "migrate";
2914
+ /** Declarations to delete before writing. */
2915
+ remove: HarnessDeclaration[];
2916
+ /** The spec to write into `devDependencies.rungate`, or null when skipping. */
2917
+ write: string | null;
2918
+ /** Said out loud in the action line, with the before and after (#475 SC-4). */
2919
+ reason: string;
2920
+ }
2921
+
2922
+ /**
2923
+ * The ONE decision about the harness dependency (#475).
2924
+ *
2925
+ * The guard this replaces read **one key in one section under one name**:
2926
+ *
2927
+ * ```ts
2928
+ * if (pkg.devDependencies["rungate"] || isHarnessItself(root)) { ...skip... }
2929
+ * ```
2930
+ *
2931
+ * So it could not see `rungate` in `dependencies` or `optionalDependencies`,
2932
+ * could not see `pai-harness` anywhere, and could not see a `file:` spec
2933
+ * under any of them. `harnessDevDepRange`'s own comment says "`file:` is the
2934
+ * bug" — the EMISSION was fixed and nothing was ever written to undo what the
2935
+ * broken emission left behind.
2936
+ *
2937
+ * The sharper half is that re-scaffolding does not merely fail to clean it
2938
+ * up. With `optionalDependencies: { "rungate": "file:../rungate" }` and no
2939
+ * `devDependencies.rungate`, the guard does not fire, so the scaffold writes
2940
+ * `devDependencies.rungate = "^0.4.0"` BESIDE it. The consumer then declares
2941
+ * one package twice, in two sections, with two incompatible specs, and the
2942
+ * run reports `UPDATED: package.json (rungate devDep)` as a success.
2943
+ *
2944
+ * Measured in a real consumer, two declarations written by two scaffold runs
2945
+ * two days apart under the two different names:
2946
+ *
2947
+ * ```
2948
+ * file:../pai-harness -> 34f03818 2026-09-17
2949
+ * file:../rungate -> 3a6501a9 2026-09-19
2950
+ * ```
2951
+ *
2952
+ * They survived every re-scaffold since September, and the cost was a dead
2953
+ * container build: bun resolves `file:` optionals and fails on a folder that
2954
+ * is not in the build context. A later commit moved both to
2955
+ * `optionalDependencies` trying to make the build tolerate them, which put
2956
+ * them further out of the old guard's reach — wrong section AND wrong name.
2957
+ *
2958
+ * Kept separate from the writer so there is one binding to mutate, and so
2959
+ * the whole matrix can be driven without a filesystem.
2960
+ */
2961
+ export function harnessDepPlan(pkg: unknown, targetRange: string): HarnessDepPlan {
2962
+ const found = findHarnessDeclarations(pkg);
2963
+
2964
+ if (found.length === 0) {
2965
+ return { action: "add", remove: [], write: targetRange, reason: "no harness dependency declared" };
2966
+ }
2967
+
2968
+ // A single declaration in the RIGHT PLACE is left exactly as it is,
2969
+ // whatever its spec. Two reasons, and the second resolves a conflict
2970
+ // between two issues:
2971
+ //
2972
+ // 1. The range is not rewritten to today's floor. A scaffold that rewrites
2973
+ // a working spec on every run is indistinguishable from one that cannot
2974
+ // tell a working spec from a broken one, and it would churn every
2975
+ // consumer's package.json on every release.
2976
+ //
2977
+ // 2. `file:` is included, which is #362 SC-815: "A consumer who
2978
+ // deliberately points at a local checkout is not this bug, and silently
2979
+ // rewriting their package.json is not this fix's business." #475 SC-2
2980
+ // asks for `file:` to be replaced "in any of those cells", and taken
2981
+ // literally the two contradict.
2982
+ //
2983
+ // The line drawn here is PLACEMENT, not spec, because that is what #475's
2984
+ // own evidence supports: both `file:` entries it traced were written by
2985
+ // scaffold runs (`34f03818`, `3a6501a9`), and both ended up in
2986
+ // `optionalDependencies` under two different names. A declaration the
2987
+ // scaffold would never have written in that position is the scaffold's to
2988
+ // clean up; a lone `devDependencies.rungate` is where a developer linking
2989
+ // a local checkout would put one, and it is indistinguishable from intent.
2990
+ const only = found.length === 1 ? found[0] : null;
2991
+ if (only && only.section === "devDependencies" && only.name === CURRENT_HARNESS_PKG) {
2992
+ return { action: "skip", remove: [], write: null, reason: `devDependencies.rungate is ${only.spec}` };
2993
+ }
2994
+
2995
+ const where = found.map(d => `${d.section}.${d.name}=${d.spec}`).join(", ");
2996
+ return {
2997
+ action: "migrate",
2998
+ remove: found,
2999
+ write: targetRange,
3000
+ reason: `${where} -> devDependencies.rungate=${targetRange}`,
3001
+ };
3002
+ }
3003
+
2461
3004
  export function addPaiHarnessDevDep(root: string, actions: string[], version?: string): void {
2462
3005
  const pkgPath = join(root, "package.json");
2463
3006
  if (!existsSync(pkgPath)) return;
2464
3007
 
2465
3008
  const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
2466
- if (!pkg.devDependencies) {
2467
- pkg.devDependencies = {};
3009
+
3010
+ // A different question — "is rungate already available here" — but the
3011
+ // self-reference half is the same fact, so it routes through the one
3012
+ // predicate (#380). Asked FIRST: the harness's own package.json names
3013
+ // itself, and running the migration over it would rewrite the harness into
3014
+ // depending on itself.
3015
+ if (isHarnessItself(root)) {
3016
+ actions.push("SKIP: rungate devDep (self-reference)");
3017
+ return;
2468
3018
  }
2469
3019
 
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)");
3020
+ const plan = harnessDepPlan(pkg, harnessDevDepRange(version));
3021
+ if (plan.action === "skip") {
3022
+ actions.push(`SKIP: rungate devDep (${plan.reason})`);
2475
3023
  return;
2476
3024
  }
2477
3025
 
2478
- pkg.devDependencies["rungate"] = harnessDevDepRange(version);
3026
+ // Removed BEFORE the write, and across every section, so a declaration
3027
+ // cannot survive in the section the writer does not touch. This is the
3028
+ // whole of SC-2: the invariant is one declaration in total, not a correct
3029
+ // `devDependencies`.
3030
+ for (const d of plan.remove) delete (pkg as Record<string, Record<string, unknown>>)[d.section][d.name];
3031
+ for (const section of DEP_SECTIONS) {
3032
+ const deps = (pkg as Record<string, unknown>)[section];
3033
+ if (deps && typeof deps === "object" && Object.keys(deps).length === 0) {
3034
+ delete (pkg as Record<string, unknown>)[section];
3035
+ }
3036
+ }
3037
+
3038
+ if (!pkg.devDependencies) pkg.devDependencies = {};
3039
+ pkg.devDependencies["rungate"] = plan.write;
2479
3040
 
2480
3041
  if (!pkg.scripts) {
2481
3042
  pkg.scripts = {};
@@ -2485,10 +3046,15 @@ export function addPaiHarnessDevDep(root: string, actions: string[], version?: s
2485
3046
  }
2486
3047
 
2487
3048
  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)");
3049
+ // Names the PATH it wrote, not just what it did (#216), and for a
3050
+ // migration also the before and after (#475 SC-4) — the reported cost was
3051
+ // a consumer who did not know this was in their package.json until a
3052
+ // container build died over it.
3053
+ actions.push(
3054
+ plan.action === "migrate"
3055
+ ? `UPDATED: package.json (rungate devDep migrated: ${plan.reason})`
3056
+ : "UPDATED: package.json (rungate devDep)",
3057
+ );
2492
3058
  }
2493
3059
 
2494
3060
  /**
@@ -2663,7 +3229,11 @@ export function reportScaffoldActions(actions: string[]): number {
2663
3229
  console.log("\n=== Scaffold Report ===");
2664
3230
  for (const action of actions) console.log(` ${action}`);
2665
3231
  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`);
3232
+ // AUTO-FIXED is reported separately from AUDITED on purpose (#42 SC-3).
3233
+ // What the scaffold CHANGED and what it merely NOTICED are different facts,
3234
+ // and a reader who cannot tell them apart has to diff the tree to find out
3235
+ // which of the reported gaps are still gaps.
3236
+ console.log(`\nTotal: ${count("CREATED")} created, ${count("REPLACED")} replaced, ${count("AUTO-FIXED")} auto-fixed, ${count("SKIP")} skipped, ${count("REFUSED")} refused`);
2667
3237
  return count("REFUSED");
2668
3238
  }
2669
3239