rungate 0.3.0 → 0.4.1

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 (49) hide show
  1. package/lib/ac-quality.ts +119 -0
  2. package/lib/brief-precedence.ts +114 -0
  3. package/lib/ci-checkout.ts +27 -1
  4. package/lib/compliance-backfill.ts +16 -4
  5. package/lib/compliance-report.ts +109 -8
  6. package/lib/config-loader.ts +129 -5
  7. package/lib/config-readers.ts +86 -0
  8. package/lib/conformity.ts +520 -27
  9. package/lib/context-docs.ts +182 -0
  10. package/lib/create-brief.ts +22 -17
  11. package/lib/create-sc.ts +55 -33
  12. package/lib/decomposition-waves.ts +197 -0
  13. package/lib/doc-scan-targets.ts +435 -0
  14. package/lib/gate-check-audit.ts +190 -0
  15. package/lib/generators/agents-md.ts +10 -5
  16. package/lib/issue-extraction.ts +368 -0
  17. package/lib/organize.ts +129 -40
  18. package/lib/package-closure.ts +111 -0
  19. package/lib/phase2-decomposition.ts +270 -0
  20. package/lib/prior-branch.ts +24 -1
  21. package/lib/project-aliases.ts +100 -0
  22. package/lib/prove-label-gate.ts +93 -0
  23. package/lib/release-preflight.ts +225 -15
  24. package/lib/rungate-schema.ts +36 -2
  25. package/lib/sc-cover.ts +92 -1
  26. package/lib/sc-ids.ts +151 -0
  27. package/lib/scaffold/pre-push-hook.ts +165 -0
  28. package/lib/scaffold/rehearsal.ts +330 -0
  29. package/lib/scaffold/steps.ts +175 -122
  30. package/lib/scaffold/write-steps.ts +167 -0
  31. package/lib/scope-denylist.ts +258 -0
  32. package/lib/scratch-cleanup.ts +198 -0
  33. package/lib/scratch-roots.ts +94 -0
  34. package/lib/task-completion-checks.ts +50 -3
  35. package/lib/typescript-project.ts +233 -0
  36. package/lib/validators/spec-validators.ts +23 -34
  37. package/lib/verified-push.ts +179 -2
  38. package/lib/workflow-security.ts +51 -7
  39. package/lib/worktree-cleanup.ts +318 -20
  40. package/lib/worktree-repo.ts +465 -0
  41. package/package.json +8 -2
  42. package/scripts/audit-specs.ts +134 -37
  43. package/scripts/audit-transcript.ts +259 -0
  44. package/scripts/create-sc.ts +15 -1
  45. package/scripts/detect-sc-drift.ts +200 -0
  46. package/scripts/extract-constraints.ts +16 -36
  47. package/scripts/scaffold-project.ts +26 -136
  48. package/scripts/split-spec.ts +315 -0
  49. package/scripts/sync-sc-status.ts +751 -0
@@ -17,12 +17,15 @@ 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
19
  import { mergeManagedWorkflow } from "./managed-workflow";
20
- import { tryLoadRungateConfig } from "../config-loader";
20
+ import { PRE_PUSH_MANAGED_MARKER, prePushHookScript } from "./pre-push-hook";
21
+ import { loadComplianceConfig, tryLoadRungateConfig } from "../config-loader";
22
+ import { organizeProjectReport } from "../organize";
21
23
  import type { ProjectScan, ProjectType, SpecEntry, TestFile, RefFile, DocRoute, Category } from "../generators/types";
22
24
  import { tier1Ere } from "../secret-patterns";
23
25
  import { healthPathIn } from "../liveness-contradiction";
24
26
  import { decideRuleWrite } from "../rule-provenance";
25
27
  import { referencedPaths } from "../agents-md-refs";
28
+ import { TS_SOURCE_DIRS, typeScriptSourceDirs, typecheckDecision } from "../typescript-project";
26
29
  import {
27
30
  OWNED_FILES,
28
31
  SCAFFOLD_REFUSE,
@@ -707,7 +710,7 @@ export function generateConformityTest(root?: string): string {
707
710
  const from = root && isHarnessItself(root) ? "../lib/conformity" : "rungate/lib/conformity";
708
711
  return `import { resolve } from "path";
709
712
  import { afterAll } from "bun:test";
710
- import { runScaffoldConformity, runSpecDiscovery, runSpecDrift, runDocHygiene, runFallowCheck, runAgentFileValidation, runDirectoryValidation, runPackageValidation, runTsconfigValidation, writeFindingsReport } from "${from}";
713
+ import { runScaffoldConformity, runSpecDiscovery, runSpecDrift, runDocHygiene, runFallowCheck, runAgentFileValidation, runDirectoryValidation, runPackageValidation, runTsconfigValidation, runConfigAccessValidation, runPromptConfigAccessValidation, writeFindingsReport } from "${from}";
711
714
 
712
715
  const ROOT = resolve(import.meta.dir, "..");
713
716
 
@@ -720,6 +723,8 @@ runAgentFileValidation(ROOT);
720
723
  runDirectoryValidation(ROOT);
721
724
  runPackageValidation(ROOT);
722
725
  runTsconfigValidation(ROOT);
726
+ runConfigAccessValidation(ROOT);
727
+ runPromptConfigAccessValidation(ROOT);
723
728
 
724
729
  afterAll(() => writeFindingsReport(ROOT));
725
730
  `;
@@ -905,12 +910,17 @@ export function generateOrAuditProjectHarness(root: string, actions: string[]):
905
910
  // Scan test commands
906
911
  const pkgPath = join(root, "package.json");
907
912
  let testCmd = "bun test";
908
- let typeCheckCmd = "bunx tsc --noEmit";
909
913
  if (existsSync(pkgPath)) {
910
914
  const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
911
915
  if (pkg.scripts?.test) testCmd = pkg.scripts.test;
912
- if (pkg.scripts?.typecheck) typeCheckCmd = pkg.scripts.typecheck;
913
916
  }
917
+ // #87 — this defaulted to `bunx tsc --noEmit` for every project, including
918
+ // one with no tsconfig, and `gates/gate-executor.ts` RUNS what lands here.
919
+ // Without a tsconfig that command prints 147 lines of help and exits 1, so
920
+ // the verify gate reported "Type check FAIL" at every consumer that the
921
+ // three other sites had already agreed should not be type-checked at all.
922
+ // `null` is the honest value and the gate already skips on a falsy one.
923
+ const typeCheckCmd = typecheckDecision(root).command;
914
924
 
915
925
  // Scan port from Makefile, docker-compose.yml, or .env.example
916
926
  const makefile = join(root, "Makefile");
@@ -1289,18 +1299,16 @@ function writeDirectoryStructure(
1289
1299
  * so no later scaffold ever corrected it. Running this step last is what makes
1290
1300
  * that skip safe — the content it preserves is now right from run 1.
1291
1301
  */
1292
- export function generateCodeMapStep(root: string, actions: string[], opts?: { fix?: boolean; dryRun?: boolean }): void {
1293
- const fixMode = opts?.fix ?? !opts?.dryRun;
1302
+ export function generateCodeMapStep(root: string, actions: string[]): void {
1303
+ // No dry-run branch. It reported `GAP: CODE-MAP.md missing` and nothing
1304
+ // else — one of the four `existsSync` checks that stood in for twenty-five
1305
+ // write steps and made audit report 0 changes on a tree `--fix` rewrote in
1306
+ // 28 places. #398 replaced prediction with rehearsal: audit runs THIS,
1307
+ // against a throwaway clone, and reports `GENERATED: CODE-MAP.md` because
1308
+ // that is what happened. Reachable from one caller, which has always passed
1309
+ // fix mode, so the branch was dead as well as wrong.
1294
1310
  const codeMapPath = join(root, "CODE-MAP.md");
1295
1311
 
1296
- // In dry-run/non-fix mode, only report gaps
1297
- if (!fixMode) {
1298
- if (!existsSync(codeMapPath)) {
1299
- actions.push("GAP: CODE-MAP.md missing — run with --fix to generate");
1300
- }
1301
- return;
1302
- }
1303
-
1304
1312
  // Check staleness
1305
1313
  if (existsSync(codeMapPath)) {
1306
1314
  const content = readFileSync(codeMapPath, "utf-8");
@@ -1462,43 +1470,10 @@ export function copySpecTemplateIfEmpty(specsDir: string, actions: string[]): vo
1462
1470
 
1463
1471
  // ── tsconfig.json ──────────────────────────────────────────────
1464
1472
 
1465
- /**
1466
- * Trees a generated tsconfig type-checks. Same list as the scanner's source
1467
- * directories, plus `scripts/` — a consumer keeps real TypeScript there and
1468
- * nothing else would check it.
1469
- *
1470
- * `test/` is deliberately absent. The conformity test rungate generates into
1471
- * every consumer imports `bun:test` and `rungate/lib/conformity`, and neither
1472
- * resolves for tsc without `@types/bun` and an installed `rungate` — so
1473
- * including the test tree would hand a freshly scaffolded project a type check
1474
- * that reports 4 errors it did not cause and cannot fix. That is the #65/#76
1475
- * defect again in the other direction: a documented command whose result says
1476
- * nothing about the project's code.
1477
- */
1478
- const TS_SOURCE_DIRS = ["src", "lib", "scripts", "gates", "hooks", "workflows"] as const;
1479
-
1480
- /** True when `dir` holds at least one hand-written .ts/.tsx file. */
1481
- function containsTypeScript(dir: string): boolean {
1482
- let stack = [dir];
1483
- while (stack.length > 0) {
1484
- const current = stack.pop()!;
1485
- let entries;
1486
- try {
1487
- entries = readdirSync(current, { withFileTypes: true });
1488
- } catch {
1489
- continue;
1490
- }
1491
- for (const entry of entries) {
1492
- if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
1493
- if (entry.isDirectory()) {
1494
- stack.push(join(current, entry.name));
1495
- } else if (/\.tsx?$/.test(entry.name) && !entry.name.endsWith(".d.ts")) {
1496
- return true;
1497
- }
1498
- }
1499
- }
1500
- return false;
1501
- }
1473
+ // `TS_SOURCE_DIRS`, `containsTypeScript` and the directory filter all moved to
1474
+ // lib/typescript-project.ts in #87. Five sites decided "is this a TypeScript
1475
+ // project" and they disagreed; two copies of a predicate survive any mutation
1476
+ // of either, which is what SC-842 and SC-843 already say about this file.
1502
1477
 
1503
1478
  /**
1504
1479
  * Write a tsconfig.json for a TypeScript consumer that has none (#72, #65/#76).
@@ -1524,13 +1499,14 @@ export function createTsconfig(root: string, actions: string[]): void {
1524
1499
  return;
1525
1500
  }
1526
1501
 
1527
- // The include list and the "is this a TypeScript project" test are the same
1528
- // question, answered once. Deriving them separately is how you get a
1502
+ // The include list, the "is this a TypeScript project" test and TSC-1's
1503
+ // applicability are the same question, answered once in
1504
+ // lib/typescript-project.ts. Deriving them separately is how you get a
1529
1505
  // tsconfig whose include matches no files — tsc error TS18003, which reads
1530
- // as a broken type check rather than as "nothing to check".
1531
- const include = TS_SOURCE_DIRS
1532
- .filter(dir => containsTypeScript(join(root, dir)))
1533
- .map(dir => `${dir}/**/*.ts`);
1506
+ // as a broken type check rather than as "nothing to check" — and how TSC-1
1507
+ // came to hard-fail over a file this function had deliberately not written
1508
+ // (#87).
1509
+ const include = typeScriptSourceDirs(root).map(dir => `${dir}/**/*.ts`);
1534
1510
 
1535
1511
  if (include.length === 0) {
1536
1512
  actions.push(`SKIP: tsconfig.json (no TypeScript source in ${TS_SOURCE_DIRS.join("/, ")}/)`);
@@ -2096,16 +2072,15 @@ export function createCiWorkflows(root: string, actions: string[], opts: { force
2096
2072
  // Rungate itself was shielded from noticing because `bun test` failed first
2097
2073
  // and the step never ran.
2098
2074
  //
2099
- // Emit it only when the project actually has a tsconfig, and prefer the
2100
- // project's own ratchet script when it has one — consumers do not get
2101
- // rungate's scripts/, so they must fall back to plain tsc.
2102
- const hasTsconfig = existsSync(join(root, "tsconfig.json"));
2103
- const hasRatchet = existsSync(join(root, "scripts", "typecheck.ts"));
2104
- const typecheckStep = !hasTsconfig
2105
- ? ""
2106
- : hasRatchet
2107
- ? `\n - run: bun scripts/typecheck.ts`
2108
- : `\n - run: bunx tsc --noEmit`;
2075
+ // Which command, and whether there is one at all, is `typecheckDecision`'s
2076
+ // to answer — the same binding AGENTS.md's row and the scanned
2077
+ // `dev.typeCheck` read (#87). This site used to check for
2078
+ // `scripts/typecheck.ts` on disk, a branch `files:` makes unreachable for
2079
+ // every consumer, and never looked at a project's own `typecheck` script.
2080
+ const typecheck = typecheckDecision(root);
2081
+ const typecheckStep = typecheck.command
2082
+ ? `\n - run: ${typecheck.command}`
2083
+ : `\n # No type check: ${typecheck.reason}.`;
2109
2084
 
2110
2085
  const ciYml = `# Managed by rungate — do not edit. Customize the ci section of .claude/rungate/config.json.
2111
2086
  name: CI
@@ -2367,7 +2342,7 @@ exit 0
2367
2342
  }
2368
2343
 
2369
2344
  const prePush = join(hooksDir, "pre-push");
2370
- const MANAGED_MARKER = "# Managed by rungate — conformity check before push";
2345
+ const MANAGED_MARKER = PRE_PUSH_MANAGED_MARKER;
2371
2346
 
2372
2347
  // `2>/dev/null` threw away the only output that said WHY conformity failed,
2373
2348
  // leaving the developer a bare "fix before pushing" and no diagnosis. And the
@@ -2399,50 +2374,15 @@ exit 0
2399
2374
  // actually differ — the common push changes no dependencies and keeps the
2400
2375
  // fast path, and the push that does change them cannot quietly test against
2401
2376
  // the wrong ones.
2402
- writeFileSync(prePush, `#!/bin/sh
2403
- ${MANAGED_MARKER}
2404
- ZERO=0000000000000000000000000000000000000000
2405
- TOPLEVEL=$(git rev-parse --show-toplevel) || exit 1
2406
- status=0
2407
-
2408
- while read -r _lref lsha _rref _rsha; do
2409
- # Branch deletion: there is no commit to check out.
2410
- [ "$lsha" = "$ZERO" ] && continue
2411
-
2412
- tmp=$(mktemp -d) || exit 1
2413
- if ! git worktree add --detach --quiet "$tmp" "$lsha"; then
2414
- echo "ERROR: could not check out $lsha to verify the push" >&2
2415
- rm -rf "$tmp"
2416
- exit 1
2417
- fi
2418
-
2419
- # Reuse the installed modules only when the pushed commit expects the same
2420
- # ones; otherwise install from the pushed lockfile.
2421
- if [ -f "$TOPLEVEL/bun.lock" ] && [ -f "$tmp/bun.lock" ] && cmp -s "$TOPLEVEL/bun.lock" "$tmp/bun.lock"; then
2422
- ln -s "$TOPLEVEL/node_modules" "$tmp/node_modules" 2>/dev/null
2423
- else
2424
- echo "pre-push: dependencies differ from the working tree — installing from the pushed lockfile" >&2
2425
- ( cd "$tmp" && bun install --frozen-lockfile ) >&2 || status=1
2426
- fi
2427
-
2428
- if [ "$status" -eq 0 ]; then
2429
- ( cd "$tmp" && bun test test/scaffold-conformity.test.ts ) || status=1
2430
- fi
2431
-
2432
- # Always clean up. An early exit here would leak a worktree on every failed
2433
- # push, which is how #68 reached 39 stale worktrees and 243 MB.
2434
- git worktree remove --force "$tmp" 2>/dev/null
2435
- rm -rf "$tmp"
2436
-
2437
- [ "$status" -ne 0 ] && break
2438
- done
2439
-
2440
- if [ "$status" -ne 0 ]; then
2441
- echo "ERROR: Conformity tests failed against the commits being pushed — fix before pushing" >&2
2442
- exit 1
2443
- fi
2444
- exit 0
2445
- `);
2377
+ //
2378
+ // The script itself lives in lib/scaffold/pre-push-hook.ts (#397). As a
2379
+ // template literal here it was unrunnable, and the thing nothing runs is
2380
+ // the thing nothing checks: the lockfile comparison read the CHECKOUT's
2381
+ // `bun.lock`, so a consumer that gitignores its lockfile could never take
2382
+ // the fast path and could never pass. Over there it is one binding with one
2383
+ // exit-code constant, and test/pre-push-hook.test.ts drives it against
2384
+ // planted repositories.
2385
+ writeFileSync(prePush, prePushHookScript());
2446
2386
  chmodSync(prePush, 0o755);
2447
2387
  actions.push(existing === null
2448
2388
  ? "CREATED: .git/hooks/pre-push (conformity check)"
@@ -2551,6 +2491,56 @@ export function addPaiHarnessDevDep(root: string, actions: string[], version?: s
2551
2491
  actions.push("UPDATED: package.json (rungate devDep)");
2552
2492
  }
2553
2493
 
2494
+ /**
2495
+ * Report what `organizeProject` would adopt, without adopting it (#442).
2496
+ *
2497
+ * `organizeProject` had exactly one caller and it was a human running
2498
+ * `scripts/organize-project.ts`. Nothing in scaffold, ship or any hook
2499
+ * invoked it, so re-scaffolding a project — the thing people expected to
2500
+ * trigger adoption — could not. A feature nothing invokes is a feature that
2501
+ * has never fired, and this one never had.
2502
+ *
2503
+ * DRY-RUN, always. Discovery stops requiring prior knowledge that the
2504
+ * feature exists; adoption stays something a person chooses. The step writes
2505
+ * nothing, which is also why it is safe during rehearsal.
2506
+ */
2507
+ export function reportExternalAdoptionStep(root: string, actions: string[]): void {
2508
+ const config = loadComplianceConfig(root);
2509
+ const sources = config?.organize?.externalSources ?? [];
2510
+
2511
+ if (sources.length === 0) {
2512
+ // SC-5, and the decision is to write the list EMPTY. An external source
2513
+ // is an absolute path on one person's machine; a default would have
2514
+ // scaffold propose adopting documents out of directories the user never
2515
+ // named, in every project it touches. Recorded as a line rather than
2516
+ // left as an absence, so "nobody configured this" is distinguishable
2517
+ // from "this ran and found nothing".
2518
+ actions.push(
2519
+ "SKIP: external adoption (compliance.json declares no organize.externalSources — " +
2520
+ "deliberately empty, an external path is machine-specific and cannot be guessed)",
2521
+ );
2522
+ return;
2523
+ }
2524
+
2525
+ const report = organizeProjectReport(root, { dryRun: true, harnessRoot: root });
2526
+ const external = report.proposals.filter(p => p.source.startsWith("/"));
2527
+
2528
+ for (const path of report.unmeasured) {
2529
+ actions.push(`UNMEASURED: external source ${path} is declared but not on disk`);
2530
+ }
2531
+ for (const path of report.unreadable) {
2532
+ actions.push(`UNMEASURED: external source ${path} could not be read`);
2533
+ }
2534
+ for (const p of external) {
2535
+ actions.push(`PROPOSED: adopt ${p.source} -> ${p.target} (${p.reasoning})`);
2536
+ }
2537
+ if (external.length === 0 && report.unmeasured.length === 0 && report.unreadable.length === 0) {
2538
+ actions.push(
2539
+ `OK: external adoption found nothing (matched against ${report.aliases.join(", ")})`,
2540
+ );
2541
+ }
2542
+ }
2543
+
2554
2544
  export function runAuditSpecsFix(root: string, actions: string[]): void {
2555
2545
  const specsDir = join(root, "specs");
2556
2546
  if (!existsSync(specsDir)) {
@@ -2563,16 +2553,38 @@ export function runAuditSpecsFix(root: string, actions: string[]): void {
2563
2553
  return;
2564
2554
  }
2565
2555
  const result = auditSpecs(root, { fix: true });
2566
- const rewriteCount = result.rewrites?.length ?? 0;
2567
- if (rewriteCount > 0) {
2568
- // One action per spec file actually rewritten, naming the path (#216).
2556
+ const entries = result.rewrites ?? [];
2557
+ // #426: a line that was left alone is not a rewrite. Both are reported,
2558
+ // because "the matcher could not bind this" is worth seeing — but only one
2559
+ // of them changed what a reader will read, and conflating them is how a
2560
+ // silent spec edit hid behind a summary line naming `ci.yml`.
2561
+ const rewritten = entries.filter(r => r.kept === undefined);
2562
+ const kept = entries.filter(r => r.kept !== undefined);
2563
+
2564
+ if (entries.length > 0) {
2565
+ // One action per spec file actually touched, naming the path (#216).
2569
2566
  // "rewrote 2 SCs" named no file, so the rewritten specs were never staged
2570
2567
  // and showed up to the dirty-tree check as somebody else's edit.
2571
- const touched = [...new Set((result.rewrites ?? []).map(r => `specs/${r.specFile}`))];
2568
+ const touched = [...new Set(entries.map(r => `specs/${r.specFile}`))];
2572
2569
  for (const file of touched) actions.push(`UPDATED: ${file} (audit-specs --fix)`);
2573
- actions.push(`SKIP: audit-specs summary (rewrote ${rewriteCount} SCs across ${touched.length} spec file(s))`);
2574
- } else {
2570
+ }
2571
+
2572
+ // #426 SC-3: every rewritten criterion is named, with its id and its spec.
2573
+ // A spec line edited under a documented command and reported only as a
2574
+ // count is the defect, not merely the content that was lost.
2575
+ for (const r of rewritten) {
2576
+ actions.push(`REWROTE: specs/${r.specFile} ${r.scId} as ${r.patternUsed} — was: ${r.before}`);
2577
+ }
2578
+ for (const r of kept) {
2579
+ actions.push(`KEPT: specs/${r.specFile} ${r.scId} — ${r.kept}`);
2580
+ }
2581
+
2582
+ if (entries.length === 0) {
2575
2583
  actions.push("SKIP: audit-specs (all SCs already matchable)");
2584
+ } else {
2585
+ actions.push(
2586
+ `SKIP: audit-specs summary (rewrote ${rewritten.length} SCs, left ${kept.length} unmatched but intact)`,
2587
+ );
2576
2588
  }
2577
2589
  }
2578
2590
 
@@ -2603,6 +2615,50 @@ function dirtyPaths(root: string, generated: string[]): string[] {
2603
2615
  * steps, it does not implement them. The caller decides what a refusal costs;
2604
2616
  * this only counts them, so it stays callable from a test.
2605
2617
  */
2618
+ /**
2619
+ * The path a report line says scaffold WROTE, or null if it wrote nothing.
2620
+ *
2621
+ * One binding, because two callers now depend on the same judgement and a
2622
+ * second copy would let them disagree about the same line. `postScaffoldCommit`
2623
+ * uses it to decide what to stage — a verb it fails to recognise leaves a
2624
+ * generated file uncommitted — and #398's audit/fix agreement check uses it to
2625
+ * compare what audit NAMED against what `--fix` actually wrote.
2626
+ *
2627
+ * Deliberately excludes SKIP / GAP / WARN / AUDIT / UNCHANGED / REFUSED: all
2628
+ * of them are lines about a write that did not happen. Getting that wrong in
2629
+ * the permissive direction would make audit and fix "agree" by both
2630
+ * over-reporting, which is agreement for the wrong reason — see
2631
+ * `.claude/rules/checks-must-be-able-to-fail.md` on assertions that hold
2632
+ * vacuously. `test/scaffold-audit-agreement.test.ts` pins both directions.
2633
+ *
2634
+ * **The verb list had drifted from the verbs scaffold emits, and #398's
2635
+ * agreement check is what found it.** `REGENERATED`, `REFRESHED` and
2636
+ * `REPAIRED` are all writes and none of them was here, so for as long as they
2637
+ * have existed `postScaffoldCommit --commit` has quietly failed to stage
2638
+ * `AGENTS.md` (REGENERATED, `write-steps.ts`), `.claude/rules/` (REFRESHED,
2639
+ * `steps.ts:611`) and any seeded config (REPAIRED, `steps.ts:1181`). The
2640
+ * comment above this list used to say missing a verb "silently leaves
2641
+ * generated files uncommitted", which was exactly right and exactly what was
2642
+ * happening.
2643
+ *
2644
+ * A prose warning did not keep the list current, so there is now a test that
2645
+ * greps the sources for emitted write verbs and fails when one is not here.
2646
+ */
2647
+ export const WRITE_VERBS: readonly string[] = [
2648
+ "CREATED", "UPDATED", "REPLACED", "GENERATED", "REGENERATED",
2649
+ "REFRESHED", "REPAIRED", "DEPLOYED", "SPLIT",
2650
+ // #426: a rewritten SC line is a write to the spec that names it. The
2651
+ // `UPDATED:` action for the same file already stages it, so this is
2652
+ // belt-and-braces — but a verb that announces an edit and is not here is
2653
+ // the exact drift this list exists to stop.
2654
+ "REWROTE",
2655
+ ];
2656
+
2657
+ export function writtenPath(line: string): string | null {
2658
+ const m = line.trim().match(new RegExp(`^(?:${WRITE_VERBS.join("|")}): ([^\\s(]+)`));
2659
+ return m?.[1] ?? null;
2660
+ }
2661
+
2606
2662
  export function reportScaffoldActions(actions: string[]): number {
2607
2663
  console.log("\n=== Scaffold Report ===");
2608
2664
  for (const action of actions) console.log(` ${action}`);
@@ -2634,10 +2690,7 @@ export function postScaffoldCommit(
2634
2690
  // already existed, the real commit then had to be an amend.
2635
2691
  const generated = [...new Set(
2636
2692
  actions
2637
- // Verbs that mean "scaffold wrote this path". Deliberately excludes
2638
- // SKIP / GAP / WARN / AUDIT (no write happened) — and all of them,
2639
- // because missing one silently leaves generated files uncommitted.
2640
- .map(a => a.trim().match(/^(?:CREATED|UPDATED|REPLACED|GENERATED|DEPLOYED|SPLIT): ([^\s(]+)/)?.[1])
2693
+ .map(writtenPath)
2641
2694
  .filter((p): p is string => Boolean(p))
2642
2695
  // .git/ contents are not tracked; hooks live there.
2643
2696
  // .git/ contents are never tracked. Directories are kept — scaffold
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Every step that writes, as one callable body (#398).
3
+ *
4
+ * This used to be the inside of `if (fix) { … }` in
5
+ * `scripts/scaffold-project.ts`, with a four-`existsSync` `else` standing in
6
+ * for it during an audit. Those two branches shared no code, so they could
7
+ * only agree by somebody keeping them in step, and the measured disagreement
8
+ * was 28 paths to 0.
9
+ *
10
+ * Pulling the body out here is what lets audit RUN it against a clone instead
11
+ * of predicting it — see `lib/scaffold/rehearsal.ts`. Nothing about the
12
+ * ordering changed in the move, including the two comments that explain why
13
+ * particular steps sit where they do (#72, #123); they are load-bearing and
14
+ * are carried verbatim.
15
+ */
16
+
17
+ import { existsSync, writeFileSync } from "fs";
18
+ import { join } from "path";
19
+
20
+ import {
21
+ safeDir,
22
+ safeWrite,
23
+ regenerateOwned,
24
+ generateAgentsMdContent,
25
+ refreshScopedRulesStep,
26
+ refreshAgentsMd,
27
+ updateSpecsTable,
28
+ injectEnvironmentSection,
29
+ generateConformityTest,
30
+ generateAgentBriefsStep,
31
+ generateOrAuditProjectHarness,
32
+ generateCodeMapStep,
33
+ copySpecTemplateIfEmpty,
34
+ createGitignore,
35
+ createTsconfig,
36
+ generateProjectState,
37
+ createClaudeMdBridge,
38
+ createCiWorkflows,
39
+ createGitHooks,
40
+ deployHooksToConsumers,
41
+ addPaiHarnessDevDep,
42
+ reportExternalAdoptionStep,
43
+ runAuditSpecsFix,
44
+ postScaffoldCommit,
45
+ } from "./steps";
46
+ import {
47
+ addFrontmatterToSpecs, addFrontmatterToAdrs, detectOversizedSpecs,
48
+ checkGovernsAlignment, detectMisplacedSpecs, detectUnconvertedSpecs,
49
+ } from "../validators/spec-validators";
50
+ import type { ProjectType } from "../generators/types";
51
+
52
+ export interface WriteStepOptions {
53
+ force?: boolean;
54
+ commit?: boolean;
55
+ /**
56
+ * True when running against a disposable clone. The two steps that reach
57
+ * outside the tree are skipped — see `STEPS_NOT_REHEARSED` in
58
+ * `./rehearsal.ts`, which carries the reason for each.
59
+ */
60
+ rehearsing?: boolean;
61
+ }
62
+
63
+ export function runScaffoldWriteSteps(
64
+ projectPath: string,
65
+ projectType: ProjectType,
66
+ actions: string[],
67
+ opts: WriteStepOptions = {},
68
+ ): void {
69
+ const { force = false, commit = false, rehearsing = false } = opts;
70
+
71
+ // Phase 0: Security and directory setup
72
+ createGitignore(projectPath, actions);
73
+ safeDir(join(projectPath, "specs"), "specs", actions);
74
+ safeDir(join(projectPath, "reference"), "reference", actions);
75
+ safeDir(join(projectPath, ".github"), ".github", actions);
76
+ safeDir(join(projectPath, ".github", "workflows"), ".github/workflows", actions);
77
+ safeDir(join(projectPath, "scripts"), "scripts", actions);
78
+ safeDir(join(projectPath, "docs"), "docs", actions);
79
+ safeDir(join(projectPath, "docs", "adr"), "docs/adr", actions);
80
+
81
+ const testDirName = existsSync(join(projectPath, "test")) ? "test" : "tests";
82
+ safeDir(join(projectPath, testDirName), testDirName, actions);
83
+
84
+ // Before Phase 0.5 and before createCiWorkflows on purpose (#72): both decide
85
+ // whether to emit a type check by looking for tsconfig.json on disk.
86
+ createTsconfig(projectPath, actions);
87
+
88
+ // Phase 0.5: Generate AGENTS.md
89
+ const agentsMd = generateAgentsMdContent(projectPath, projectType, actions);
90
+ writeFileSync(join(projectPath, "AGENTS.md"), agentsMd);
91
+ actions.push("REGENERATED: AGENTS.md");
92
+ refreshAgentsMd(projectPath, projectType, actions);
93
+ updateSpecsTable(join(projectPath, "AGENTS.md"), actions);
94
+
95
+ // Phase 0.6: Create copilot instructions
96
+ const copilotInstructions = `# Copilot Instructions\n\nRead [AGENTS.md](../AGENTS.md) for project context, key files, specs, and workflow.\n\nAll project knowledge lives in AGENTS.md. Start there.\n`;
97
+ safeWrite(join(projectPath, ".github", "copilot-instructions.md"), copilotInstructions, ".github/copilot-instructions.md", actions);
98
+
99
+ // Phase 0.7: regenerate the conformity test. Strategy passed, not looked up — the label carries the project's own test dir, which may not be `test/` (#208).
100
+ regenerateOwned(join(projectPath, testDirName, "scaffold-conformity.test.ts"), generateConformityTest(projectPath), `${testDirName}/scaffold-conformity.test.ts`, actions, "regenerate");
101
+
102
+ // Validators. These used to run outside the `if (fix)` block with a `{ fix }`
103
+ // flag, which is why `addFrontmatterToSpecs` is the one step audit ever
104
+ // reported anything from.
105
+ addFrontmatterToSpecs(join(projectPath, "specs"), actions);
106
+ addFrontmatterToAdrs(join(projectPath, "docs", "adr"), actions);
107
+ detectOversizedSpecs(join(projectPath, "specs"), actions);
108
+ checkGovernsAlignment(join(projectPath, "specs"), actions);
109
+ detectMisplacedSpecs(projectPath, actions);
110
+ detectUnconvertedSpecs(join(projectPath, "specs"), actions);
111
+
112
+ // Phase 0.8: Workflow project setup
113
+ if (projectType === "workflow") {
114
+ const workflowDef = `---
115
+ doc-type: spec
116
+ testable: no
117
+ governs: workflow-definition
118
+ ---
119
+
120
+ # Workflow Definition
121
+
122
+ ## Trigger
123
+
124
+ When should this workflow run?
125
+
126
+ ## Inputs
127
+
128
+ What inputs does this workflow require?
129
+
130
+ ## Process
131
+
132
+ What steps does this workflow perform?
133
+
134
+ ## Output
135
+
136
+ What does this workflow produce?
137
+ `;
138
+ safeWrite(join(projectPath, "specs", "WORKFLOW-DEFINITION.md"), workflowDef, "specs/WORKFLOW-DEFINITION.md", actions);
139
+ }
140
+
141
+ // Phase 1.5: Harness config + briefs for ALL project types
142
+ generateOrAuditProjectHarness(projectPath, actions);
143
+ injectEnvironmentSection(projectPath, actions);
144
+ generateAgentBriefsStep(projectPath, actions);
145
+
146
+ // Phase 3: Final setup
147
+ copySpecTemplateIfEmpty(join(projectPath, "specs"), actions);
148
+ generateProjectState(projectPath, actions);
149
+ runAuditSpecsFix(projectPath, actions);
150
+ addPaiHarnessDevDep(projectPath, actions);
151
+ createClaudeMdBridge(projectPath, actions);
152
+ createCiWorkflows(projectPath, actions, { force });
153
+ createGitHooks(projectPath, actions);
154
+
155
+ // Leaves the tree. See STEPS_NOT_REHEARSED.
156
+ if (!rehearsing) deployHooksToConsumers(projectPath, actions);
157
+
158
+ // Phase 3.5: steps that DESCRIBE the project run last, so they describe the tree this run left (#123).
159
+ reportExternalAdoptionStep(projectPath, actions);
160
+ refreshScopedRulesStep(projectPath, projectType, actions);
161
+ if (projectType === "code") {
162
+ generateCodeMapStep(projectPath, actions);
163
+ }
164
+
165
+ // Leaves the tree. See STEPS_NOT_REHEARSED.
166
+ if (!rehearsing) postScaffoldCommit(projectPath, actions, { commit });
167
+ }