rungate 0.4.0 → 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 (65) 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/ac-quality.ts +119 -0
  11. package/lib/cli-commands.ts +7 -1
  12. package/lib/config-loader.ts +129 -5
  13. package/lib/conformity.ts +1122 -31
  14. package/lib/context-docs.ts +182 -0
  15. package/lib/create-brief.ts +22 -17
  16. package/lib/create-sc.ts +35 -8
  17. package/lib/doc-scan-targets.ts +435 -0
  18. package/lib/gate-check-audit.ts +9 -9
  19. package/lib/github.ts +195 -0
  20. package/lib/js-top-level-code.ts +27 -2
  21. package/lib/organize.ts +129 -40
  22. package/lib/package-closure.ts +387 -0
  23. package/lib/project-aliases.ts +100 -0
  24. package/lib/release-preflight.ts +352 -48
  25. package/lib/rungate-schema.ts +23 -1
  26. package/lib/sc-cover.ts +92 -1
  27. package/lib/sc-ids.ts +151 -0
  28. package/lib/scaffold/defaults.ts +40 -0
  29. package/lib/scaffold/managed-workflow.ts +125 -27
  30. package/lib/scaffold/owned-files.ts +6 -0
  31. package/lib/scaffold/profiles.ts +94 -0
  32. package/lib/scaffold/rehearsal.ts +355 -0
  33. package/lib/scaffold/steps.ts +787 -105
  34. package/lib/scaffold/write-steps.ts +208 -0
  35. package/lib/scratch-cleanup.ts +198 -0
  36. package/lib/scratch-roots.ts +94 -0
  37. package/lib/source-anchor.ts +144 -0
  38. package/lib/success-doc.ts +779 -0
  39. package/lib/suite-run-reading.ts +194 -0
  40. package/lib/test-census.ts +199 -0
  41. package/lib/trajectory.ts +377 -0
  42. package/lib/validators/spec-validators.ts +52 -35
  43. package/lib/workflow-security.ts +152 -7
  44. package/lib/workflow-test-harness.ts +349 -0
  45. package/lib/worktree-cleanup.ts +123 -7
  46. package/lib/worktree-repo.ts +165 -0
  47. package/package.json +10 -1
  48. package/scripts/audit-specs.ts +134 -37
  49. package/scripts/audit-transcript.ts +259 -0
  50. package/scripts/create-sc.ts +15 -1
  51. package/scripts/create-success.ts +162 -0
  52. package/scripts/detect-sc-drift.ts +200 -0
  53. package/scripts/extract-constraints.ts +16 -36
  54. package/scripts/scaffold-project.ts +51 -137
  55. package/scripts/split-spec.ts +315 -0
  56. package/scripts/sync-sc-status.ts +751 -0
  57. package/specs/SPEC-TEMPLATE.md +200 -0
  58. package/templates/SUCCESS-TEMPLATE.md +72 -0
  59. package/templates/agent-briefs/_shared.md +9 -0
  60. package/templates/agent-briefs/aditi.md +46 -0
  61. package/templates/agent-briefs/discovery.md +37 -0
  62. package/templates/agent-briefs/marcus.md +39 -0
  63. package/templates/agent-briefs/quinn.md +67 -0
  64. package/templates/agent-briefs/rook.md +40 -0
  65. 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,14 +16,28 @@ 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
- import { tryLoadRungateConfig } from "../config-loader";
26
+ import { loadComplianceConfig, tryLoadRungateConfig } from "../config-loader";
27
+ import { organizeProjectReport } from "../organize";
22
28
  import type { ProjectScan, ProjectType, SpecEntry, TestFile, RefFile, DocRoute, Category } from "../generators/types";
23
29
  import { tier1Ere } from "../secret-patterns";
24
30
  import { healthPathIn } from "../liveness-contradiction";
25
31
  import { decideRuleWrite } from "../rule-provenance";
32
+ import { DEFAULT_PROFILE, isRuleIncluded, type ScaffoldProfile } from "./profiles";
26
33
  import { referencedPaths } from "../agents-md-refs";
34
+ import {
35
+ readSuccessDoc,
36
+ readSuccessTemplate,
37
+ seedFromTemplate,
38
+ successViolations,
39
+ TEMPLATE_MISSING,
40
+ } from "../success-doc";
27
41
  import { TS_SOURCE_DIRS, typeScriptSourceDirs, typecheckDecision } from "../typescript-project";
28
42
  import {
29
43
  OWNED_FILES,
@@ -122,7 +136,47 @@ export function regenerateOwned(
122
136
  actions: string[],
123
137
  strategy: WriteStrategy = ownedStrategy(label),
124
138
  ): void {
125
- 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;
126
180
  const decision = decideOwnedWrite(strategy, existing, content);
127
181
 
128
182
  if (decision.action === "preserve") {
@@ -137,7 +191,14 @@ export function regenerateOwned(
137
191
  return;
138
192
  }
139
193
 
140
- 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);
141
202
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
142
203
  writeFileSync(filePath, decision.content!);
143
204
  actions.push(`${decision.action === "create" ? "CREATED" : "CHANGED"}: ${label}`);
@@ -261,7 +322,12 @@ export function injectEnvironmentSection(root: string, actions: string[]): void
261
322
  actions.push("UPDATED: AGENTS.md environment section from rungate.json");
262
323
  }
263
324
 
264
- 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 {
265
331
  const pkgPath = join(projectPath, "package.json");
266
332
  let pkgDesc = "";
267
333
  let pkgName = basename(projectPath);
@@ -551,7 +617,9 @@ export function generateAgentsMdContent(projectPath: string, type: ProjectType,
551
617
  // why neither "never overwrite" nor "always overwrite" is the answer.
552
618
  const rulesDir = join(projectPath, ".claude", "rules");
553
619
  if (!existsSync(rulesDir)) mkdirSync(rulesDir, { recursive: true });
554
- 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));
555
623
  for (const rule of scopedRules) {
556
624
  const rulePath = join(rulesDir, rule.filename);
557
625
  const existing = existsSync(rulePath) ? readFileSync(rulePath, "utf-8") : null;
@@ -596,9 +664,14 @@ export function generateAgentsMdContent(projectPath: string, type: ProjectType,
596
664
  * through `updateSpecsTable` and `injectEnvironmentSection` by this point, and
597
665
  * rewriting it would undo both.
598
666
  */
599
- 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 {
600
673
  const sink: string[] = [];
601
- generateAgentsMdContent(root, type, sink);
674
+ generateAgentsMdContent(root, type, sink, profile);
602
675
  // Forward everything except the per-rule lines already reported by the
603
676
  // Phase 0.5 pass. Swallowing the rest would hide a warning raised only on
604
677
  // the second scan — the fail-open shape .claude/rules/checks-must-be-able-to-fail.md
@@ -709,7 +782,7 @@ export function generateConformityTest(root?: string): string {
709
782
  const from = root && isHarnessItself(root) ? "../lib/conformity" : "rungate/lib/conformity";
710
783
  return `import { resolve } from "path";
711
784
  import { afterAll } from "bun:test";
712
- 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}";
713
786
 
714
787
  const ROOT = resolve(import.meta.dir, "..");
715
788
 
@@ -724,6 +797,7 @@ runPackageValidation(ROOT);
724
797
  runTsconfigValidation(ROOT);
725
798
  runConfigAccessValidation(ROOT);
726
799
  runPromptConfigAccessValidation(ROOT);
800
+ runSuccessDocValidation(ROOT);
727
801
 
728
802
  afterAll(() => writeFindingsReport(ROOT));
729
803
  `;
@@ -870,7 +944,7 @@ export function generateAgentBriefsStep(root: string, actions: string[]): void {
870
944
 
871
945
  // ── Harness config generation/audit ────────────────────────────
872
946
 
873
- export function generateOrAuditProjectHarness(root: string, actions: string[]): void {
947
+ export function generateOrAuditProjectHarness(root: string, actions: string[], opts: { pruneConsumers?: boolean } = {}): void {
874
948
  const harnessPath = join(root, ".claude", "rungate.json");
875
949
 
876
950
  const detectedHealthPath = detectHealthPath(root);
@@ -1016,7 +1090,7 @@ export function generateOrAuditProjectHarness(root: string, actions: string[]):
1016
1090
  // files #75 only ever fixed for greenfield projects (#121).
1017
1091
  const existing = JSON.parse(readFileSync(join(rungateDir, "config.json"), "utf-8"));
1018
1092
  repairEmptySidecars(rungateDir, actions);
1019
- auditExistingConfig(existing, scannedPages, scannedConsumers, actions, rungateDir);
1093
+ auditExistingConfig(existing, scannedPages, scannedConsumers, actions, rungateDir, opts.pruneConsumers === true);
1020
1094
  } else if (existsSync(harnessPath)) {
1021
1095
  // Monolith exists — split into directory structure
1022
1096
  const existing = JSON.parse(readFileSync(harnessPath, "utf-8"));
@@ -1026,6 +1100,8 @@ export function generateOrAuditProjectHarness(root: string, actions: string[]):
1026
1100
  splitMonolithToDirectory(root, existing, actions);
1027
1101
  } else {
1028
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.
1029
1105
  auditExistingConfig(existing, scannedPages, scannedConsumers, actions);
1030
1106
  }
1031
1107
  } else {
@@ -1182,12 +1258,84 @@ function repairEmptySidecars(rungateDir: string, actions: string[]): void {
1182
1258
  }
1183
1259
  }
1184
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
+
1185
1332
  function auditExistingConfig(
1186
1333
  existing: any,
1187
1334
  scannedPages: Record<string, string>,
1188
1335
  scannedConsumers: string[],
1189
1336
  actions: string[],
1190
- rungateDir?: string
1337
+ rungateDir?: string,
1338
+ prune = false,
1191
1339
  ): void {
1192
1340
  const issues: string[] = [];
1193
1341
 
@@ -1220,7 +1368,10 @@ function auditExistingConfig(
1220
1368
  if (declaredConsumers.length > 0) {
1221
1369
  const staleConsumers = declaredConsumers.filter((c: string) => !scannedConsumers.includes(c));
1222
1370
  if (staleConsumers.length > 0) {
1223
- 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
+ }
1224
1375
  }
1225
1376
  }
1226
1377
 
@@ -1298,18 +1449,16 @@ function writeDirectoryStructure(
1298
1449
  * so no later scaffold ever corrected it. Running this step last is what makes
1299
1450
  * that skip safe — the content it preserves is now right from run 1.
1300
1451
  */
1301
- export function generateCodeMapStep(root: string, actions: string[], opts?: { fix?: boolean; dryRun?: boolean }): void {
1302
- const fixMode = opts?.fix ?? !opts?.dryRun;
1452
+ export function generateCodeMapStep(root: string, actions: string[]): void {
1453
+ // No dry-run branch. It reported `GAP: CODE-MAP.md missing` and nothing
1454
+ // else — one of the four `existsSync` checks that stood in for twenty-five
1455
+ // write steps and made audit report 0 changes on a tree `--fix` rewrote in
1456
+ // 28 places. #398 replaced prediction with rehearsal: audit runs THIS,
1457
+ // against a throwaway clone, and reports `GENERATED: CODE-MAP.md` because
1458
+ // that is what happened. Reachable from one caller, which has always passed
1459
+ // fix mode, so the branch was dead as well as wrong.
1303
1460
  const codeMapPath = join(root, "CODE-MAP.md");
1304
1461
 
1305
- // In dry-run/non-fix mode, only report gaps
1306
- if (!fixMode) {
1307
- if (!existsSync(codeMapPath)) {
1308
- actions.push("GAP: CODE-MAP.md missing — run with --fix to generate");
1309
- }
1310
- return;
1311
- }
1312
-
1313
1462
  // Check staleness
1314
1463
  if (existsSync(codeMapPath)) {
1315
1464
  const content = readFileSync(codeMapPath, "utf-8");
@@ -1533,66 +1682,122 @@ export function createTsconfig(root: string, actions: string[]): void {
1533
1682
  actions.push("CREATED: tsconfig.json");
1534
1683
  }
1535
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
+
1536
1785
  export function createGitignore(root: string, actions: string[]): void {
1537
1786
  const gitignorePath = join(root, ".gitignore");
1538
- const securityTemplate = `# Dependencies
1539
- node_modules/
1540
- .bun/
1541
-
1542
- # Build output
1543
- dist/
1544
- build/
1545
- *.tsbuildinfo
1546
-
1547
- # Environment and secrets
1548
- .env
1549
- .env.*
1550
- !.env.example
1551
- *.pem
1552
- *.key
1553
- *.p12
1554
- *.pfx
1555
- credentials.json
1556
- service-account*
1557
- .secret*
1558
-
1559
- # Harness working directory
1560
- .rungate/
1561
-
1562
- # IDE
1563
- .vscode/
1564
- .idea/
1565
- *.swp
1566
- *.swo
1567
-
1568
- # OS
1569
- .DS_Store
1570
- Thumbs.db
1571
-
1572
- # Test artifacts
1573
- coverage/
1574
- `;
1575
1787
 
1576
1788
  if (existsSync(gitignorePath)) {
1577
1789
  const existing = readFileSync(gitignorePath, "utf-8");
1578
- const required = [
1579
- "node_modules", "dist", ".env", ".rungate",
1580
- "*.pem", "*.key", "credentials.json", "service-account",
1581
- ];
1582
- const missing = required.filter(entry => !existing.includes(entry));
1790
+ const missing = missingGitignorePatterns(existing);
1583
1791
  if (missing.length > 0) {
1584
- const additions = "\n# Added by rungate scaffold\n" +
1585
- missing.map(e => {
1586
- if (e === ".env") return ".env\n.env.*\n!.env.example";
1587
- return e.includes("*") ? e : `${e}/`;
1588
- }).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";
1589
1794
  writeFileSync(gitignorePath, existing.trimEnd() + "\n" + additions);
1590
1795
  actions.push(`UPDATED: .gitignore (added ${missing.length} missing entries)`);
1591
1796
  } else {
1592
1797
  actions.push("SKIP: .gitignore (all required entries present)");
1593
1798
  }
1594
1799
  } else {
1595
- writeFileSync(gitignorePath, securityTemplate);
1800
+ writeFileSync(gitignorePath, gitignoreTemplate());
1596
1801
  actions.push("CREATED: .gitignore (security template)");
1597
1802
  }
1598
1803
  }
@@ -1681,6 +1886,80 @@ export function generateProjectState(root: string, actions: string[]): void {
1681
1886
  safeWrite(stateMd, lines.join("\n") + "\n", "PROJECT-STATE.md", actions);
1682
1887
  }
1683
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
+
1684
1963
  export function createClaudeMdBridge(root: string, actions: string[]): void {
1685
1964
  const claudeMdPath = join(root, "CLAUDE.md");
1686
1965
  const bridgeLine = "@AGENTS.md";
@@ -1739,6 +2018,19 @@ export interface ManagedWrite {
1739
2018
  * CI resilience, and "REPLACED (+33 lines)" does not tell anyone that.
1740
2019
  */
1741
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[];
1742
2034
  /** Non-null ⇒ the write must not happen. Names the dropped jobs and the line delta. */
1743
2035
  refusal: string | null;
1744
2036
  }
@@ -1839,7 +2131,7 @@ function measureWrite(existing: string | null, next: string): { verb: ManagedWri
1839
2131
  export function resolveManagedWrite(existing: string | null, generated: string): ManagedWrite {
1840
2132
  const base: ManagedWrite = {
1841
2133
  content: generated, verb: "CREATED", lineDelta: lineCount(generated),
1842
- preservedJobs: [], droppedJobs: [], overwrittenLines: [], refusal: null,
2134
+ preservedJobs: [], droppedJobs: [], overwrittenLines: [], movedKeys: [], refusal: null,
1843
2135
  };
1844
2136
  if (existing === null) return base;
1845
2137
 
@@ -1879,11 +2171,63 @@ export function resolveManagedWrite(existing: string | null, generated: string):
1879
2171
  const resultJobs = workflowJobNames(content);
1880
2172
  if (resultJobs === null) {
1881
2173
  return {
1882
- ...unchanged, preservedJobs: [], droppedJobs: existingJobs, overwrittenLines: [], lineDelta,
2174
+ ...unchanged, preservedJobs: [], droppedJobs: existingJobs, overwrittenLines: [], movedKeys: [], lineDelta,
1883
2175
  refusal: `the merged workflow does not parse, so it cannot be written (line delta ${signed(lineDelta)})`,
1884
2176
  };
1885
2177
  }
1886
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
+
1887
2231
  // The loss set is LINES, not job names. Every non-blank line the consumer
1888
2232
  // has that the merge did not carry is content the harness is about to drop,
1889
2233
  // wherever in the file it sits.
@@ -1920,7 +2264,7 @@ export function resolveManagedWrite(existing: string | null, generated: string):
1920
2264
  ? `job(s) ${droppedJobs.join(", ")}`
1921
2265
  : "content outside any job";
1922
2266
  return {
1923
- ...unchanged, preservedJobs, droppedJobs, overwrittenLines: [], lineDelta,
2267
+ ...unchanged, preservedJobs, droppedJobs, overwrittenLines: [], movedKeys: [], lineDelta,
1924
2268
  refusal:
1925
2269
  `${lostLines.length} line(s) the harness did not author would be dropped from ${where}` +
1926
2270
  `: ${lostLines.slice(0, 3).map(l => JSON.stringify(l)).join(", ")}` +
@@ -1929,7 +2273,7 @@ export function resolveManagedWrite(existing: string | null, generated: string):
1929
2273
  };
1930
2274
  }
1931
2275
 
1932
- return { content, ...measureWrite(existing, content), preservedJobs, droppedJobs: [], overwrittenLines, refusal: null };
2276
+ return { content, ...measureWrite(existing, content), preservedJobs, droppedJobs: [], overwrittenLines, movedKeys, refusal: null };
1933
2277
  }
1934
2278
 
1935
2279
  /** Non-blank lines, trimmed — the unit the loss set is counted in. */
@@ -2270,6 +2614,19 @@ export function deployHooksToConsumers(root: string, actions: string[]): void {
2270
2614
  }
2271
2615
  }
2272
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
+
2273
2630
  export function createGitHooks(root: string, actions: string[]): void {
2274
2631
  const hooksDir = join(root, ".git", "hooks");
2275
2632
  if (!existsSync(hooksDir)) return;
@@ -2277,9 +2634,12 @@ export function createGitHooks(root: string, actions: string[]): void {
2277
2634
  const { chmodSync } = require("fs");
2278
2635
 
2279
2636
  const preCommit = join(hooksDir, "pre-commit");
2280
- 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 {
2281
2641
  writeFileSync(preCommit, `#!/bin/sh
2282
- # Managed by rungate — secret scan + PROJECT-STATE update
2642
+ ${PRE_COMMIT_MANAGED_MARKER}
2283
2643
  #
2284
2644
  # Scans the staged DIFF, not files on disk. This is deliberate and fixes four
2285
2645
  # failure modes the file-list approach had:
@@ -2326,10 +2686,41 @@ if printf '%s\\n' "$staged_diff" \\
2326
2686
  exit 1
2327
2687
  fi
2328
2688
 
2329
- # 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.
2330
2712
  if [ -f "project-state.json" ]; then
2331
- bun node_modules/rungate/scripts/update-project-state.ts --skip-tests 2>/dev/null || true
2332
- 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
2333
2724
  fi
2334
2725
 
2335
2726
  # A script's exit status is its last command's. Without this, the [ -f ] test
@@ -2339,7 +2730,11 @@ fi
2339
2730
  exit 0
2340
2731
  `);
2341
2732
  chmodSync(preCommit, 0o755);
2342
- 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
+ );
2343
2738
  }
2344
2739
 
2345
2740
  const prePush = join(hooksDir, "pre-push");
@@ -2459,24 +2854,189 @@ function harnessVersion(): string {
2459
2854
  * half is a pure property and needs no registry. See
2460
2855
  * `test/scaffold-installable.test.ts`.
2461
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
+
2462
3004
  export function addPaiHarnessDevDep(root: string, actions: string[], version?: string): void {
2463
3005
  const pkgPath = join(root, "package.json");
2464
3006
  if (!existsSync(pkgPath)) return;
2465
3007
 
2466
3008
  const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
2467
- if (!pkg.devDependencies) {
2468
- 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;
2469
3018
  }
2470
3019
 
2471
- // Also a different question — "is rungate already available here" — but
2472
- // the self-reference half is the same fact, so it routes through the one
2473
- // predicate (#380).
2474
- if (pkg.devDependencies["rungate"] || isHarnessItself(root)) {
2475
- 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})`);
2476
3023
  return;
2477
3024
  }
2478
3025
 
2479
- 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;
2480
3040
 
2481
3041
  if (!pkg.scripts) {
2482
3042
  pkg.scripts = {};
@@ -2486,10 +3046,65 @@ export function addPaiHarnessDevDep(root: string, actions: string[], version?: s
2486
3046
  }
2487
3047
 
2488
3048
  writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
2489
- // Names the PATH it wrote, not just what it did (#216). An action that does
2490
- // not name its file is invisible to the stager and, worse, now reads as an
2491
- // unexplained modification to the dirty-tree check.
2492
- 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
+ );
3058
+ }
3059
+
3060
+ /**
3061
+ * Report what `organizeProject` would adopt, without adopting it (#442).
3062
+ *
3063
+ * `organizeProject` had exactly one caller and it was a human running
3064
+ * `scripts/organize-project.ts`. Nothing in scaffold, ship or any hook
3065
+ * invoked it, so re-scaffolding a project — the thing people expected to
3066
+ * trigger adoption — could not. A feature nothing invokes is a feature that
3067
+ * has never fired, and this one never had.
3068
+ *
3069
+ * DRY-RUN, always. Discovery stops requiring prior knowledge that the
3070
+ * feature exists; adoption stays something a person chooses. The step writes
3071
+ * nothing, which is also why it is safe during rehearsal.
3072
+ */
3073
+ export function reportExternalAdoptionStep(root: string, actions: string[]): void {
3074
+ const config = loadComplianceConfig(root);
3075
+ const sources = config?.organize?.externalSources ?? [];
3076
+
3077
+ if (sources.length === 0) {
3078
+ // SC-5, and the decision is to write the list EMPTY. An external source
3079
+ // is an absolute path on one person's machine; a default would have
3080
+ // scaffold propose adopting documents out of directories the user never
3081
+ // named, in every project it touches. Recorded as a line rather than
3082
+ // left as an absence, so "nobody configured this" is distinguishable
3083
+ // from "this ran and found nothing".
3084
+ actions.push(
3085
+ "SKIP: external adoption (compliance.json declares no organize.externalSources — " +
3086
+ "deliberately empty, an external path is machine-specific and cannot be guessed)",
3087
+ );
3088
+ return;
3089
+ }
3090
+
3091
+ const report = organizeProjectReport(root, { dryRun: true, harnessRoot: root });
3092
+ const external = report.proposals.filter(p => p.source.startsWith("/"));
3093
+
3094
+ for (const path of report.unmeasured) {
3095
+ actions.push(`UNMEASURED: external source ${path} is declared but not on disk`);
3096
+ }
3097
+ for (const path of report.unreadable) {
3098
+ actions.push(`UNMEASURED: external source ${path} could not be read`);
3099
+ }
3100
+ for (const p of external) {
3101
+ actions.push(`PROPOSED: adopt ${p.source} -> ${p.target} (${p.reasoning})`);
3102
+ }
3103
+ if (external.length === 0 && report.unmeasured.length === 0 && report.unreadable.length === 0) {
3104
+ actions.push(
3105
+ `OK: external adoption found nothing (matched against ${report.aliases.join(", ")})`,
3106
+ );
3107
+ }
2493
3108
  }
2494
3109
 
2495
3110
  export function runAuditSpecsFix(root: string, actions: string[]): void {
@@ -2504,16 +3119,38 @@ export function runAuditSpecsFix(root: string, actions: string[]): void {
2504
3119
  return;
2505
3120
  }
2506
3121
  const result = auditSpecs(root, { fix: true });
2507
- const rewriteCount = result.rewrites?.length ?? 0;
2508
- if (rewriteCount > 0) {
2509
- // One action per spec file actually rewritten, naming the path (#216).
3122
+ const entries = result.rewrites ?? [];
3123
+ // #426: a line that was left alone is not a rewrite. Both are reported,
3124
+ // because "the matcher could not bind this" is worth seeing — but only one
3125
+ // of them changed what a reader will read, and conflating them is how a
3126
+ // silent spec edit hid behind a summary line naming `ci.yml`.
3127
+ const rewritten = entries.filter(r => r.kept === undefined);
3128
+ const kept = entries.filter(r => r.kept !== undefined);
3129
+
3130
+ if (entries.length > 0) {
3131
+ // One action per spec file actually touched, naming the path (#216).
2510
3132
  // "rewrote 2 SCs" named no file, so the rewritten specs were never staged
2511
3133
  // and showed up to the dirty-tree check as somebody else's edit.
2512
- const touched = [...new Set((result.rewrites ?? []).map(r => `specs/${r.specFile}`))];
3134
+ const touched = [...new Set(entries.map(r => `specs/${r.specFile}`))];
2513
3135
  for (const file of touched) actions.push(`UPDATED: ${file} (audit-specs --fix)`);
2514
- actions.push(`SKIP: audit-specs summary (rewrote ${rewriteCount} SCs across ${touched.length} spec file(s))`);
2515
- } else {
3136
+ }
3137
+
3138
+ // #426 SC-3: every rewritten criterion is named, with its id and its spec.
3139
+ // A spec line edited under a documented command and reported only as a
3140
+ // count is the defect, not merely the content that was lost.
3141
+ for (const r of rewritten) {
3142
+ actions.push(`REWROTE: specs/${r.specFile} ${r.scId} as ${r.patternUsed} — was: ${r.before}`);
3143
+ }
3144
+ for (const r of kept) {
3145
+ actions.push(`KEPT: specs/${r.specFile} ${r.scId} — ${r.kept}`);
3146
+ }
3147
+
3148
+ if (entries.length === 0) {
2516
3149
  actions.push("SKIP: audit-specs (all SCs already matchable)");
3150
+ } else {
3151
+ actions.push(
3152
+ `SKIP: audit-specs summary (rewrote ${rewritten.length} SCs, left ${kept.length} unmatched but intact)`,
3153
+ );
2517
3154
  }
2518
3155
  }
2519
3156
 
@@ -2544,11 +3181,59 @@ function dirtyPaths(root: string, generated: string[]): string[] {
2544
3181
  * steps, it does not implement them. The caller decides what a refusal costs;
2545
3182
  * this only counts them, so it stays callable from a test.
2546
3183
  */
3184
+ /**
3185
+ * The path a report line says scaffold WROTE, or null if it wrote nothing.
3186
+ *
3187
+ * One binding, because two callers now depend on the same judgement and a
3188
+ * second copy would let them disagree about the same line. `postScaffoldCommit`
3189
+ * uses it to decide what to stage — a verb it fails to recognise leaves a
3190
+ * generated file uncommitted — and #398's audit/fix agreement check uses it to
3191
+ * compare what audit NAMED against what `--fix` actually wrote.
3192
+ *
3193
+ * Deliberately excludes SKIP / GAP / WARN / AUDIT / UNCHANGED / REFUSED: all
3194
+ * of them are lines about a write that did not happen. Getting that wrong in
3195
+ * the permissive direction would make audit and fix "agree" by both
3196
+ * over-reporting, which is agreement for the wrong reason — see
3197
+ * `.claude/rules/checks-must-be-able-to-fail.md` on assertions that hold
3198
+ * vacuously. `test/scaffold-audit-agreement.test.ts` pins both directions.
3199
+ *
3200
+ * **The verb list had drifted from the verbs scaffold emits, and #398's
3201
+ * agreement check is what found it.** `REGENERATED`, `REFRESHED` and
3202
+ * `REPAIRED` are all writes and none of them was here, so for as long as they
3203
+ * have existed `postScaffoldCommit --commit` has quietly failed to stage
3204
+ * `AGENTS.md` (REGENERATED, `write-steps.ts`), `.claude/rules/` (REFRESHED,
3205
+ * `steps.ts:611`) and any seeded config (REPAIRED, `steps.ts:1181`). The
3206
+ * comment above this list used to say missing a verb "silently leaves
3207
+ * generated files uncommitted", which was exactly right and exactly what was
3208
+ * happening.
3209
+ *
3210
+ * A prose warning did not keep the list current, so there is now a test that
3211
+ * greps the sources for emitted write verbs and fails when one is not here.
3212
+ */
3213
+ export const WRITE_VERBS: readonly string[] = [
3214
+ "CREATED", "UPDATED", "REPLACED", "GENERATED", "REGENERATED",
3215
+ "REFRESHED", "REPAIRED", "DEPLOYED", "SPLIT",
3216
+ // #426: a rewritten SC line is a write to the spec that names it. The
3217
+ // `UPDATED:` action for the same file already stages it, so this is
3218
+ // belt-and-braces — but a verb that announces an edit and is not here is
3219
+ // the exact drift this list exists to stop.
3220
+ "REWROTE",
3221
+ ];
3222
+
3223
+ export function writtenPath(line: string): string | null {
3224
+ const m = line.trim().match(new RegExp(`^(?:${WRITE_VERBS.join("|")}): ([^\\s(]+)`));
3225
+ return m?.[1] ?? null;
3226
+ }
3227
+
2547
3228
  export function reportScaffoldActions(actions: string[]): number {
2548
3229
  console.log("\n=== Scaffold Report ===");
2549
3230
  for (const action of actions) console.log(` ${action}`);
2550
3231
  const count = (verb: string) => actions.filter(a => a.startsWith(verb)).length;
2551
- 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`);
2552
3237
  return count("REFUSED");
2553
3238
  }
2554
3239
 
@@ -2575,10 +3260,7 @@ export function postScaffoldCommit(
2575
3260
  // already existed, the real commit then had to be an amend.
2576
3261
  const generated = [...new Set(
2577
3262
  actions
2578
- // Verbs that mean "scaffold wrote this path". Deliberately excludes
2579
- // SKIP / GAP / WARN / AUDIT (no write happened) — and all of them,
2580
- // because missing one silently leaves generated files uncommitted.
2581
- .map(a => a.trim().match(/^(?:CREATED|UPDATED|REPLACED|GENERATED|DEPLOYED|SPLIT): ([^\s(]+)/)?.[1])
3263
+ .map(writtenPath)
2582
3264
  .filter((p): p is string => Boolean(p))
2583
3265
  // .git/ contents are not tracked; hooks live there.
2584
3266
  // .git/ contents are never tracked. Directories are kept — scaffold