rungate 0.6.0 → 0.8.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 (164) hide show
  1. package/hooks/ActionVerificationGate.hook.ts +96 -0
  2. package/hooks/AgentBriefGuard.hook.ts +38 -0
  3. package/hooks/AgentVerdictCapture.hook.ts +87 -0
  4. package/hooks/AutoVerifyGate.hook.ts +79 -0
  5. package/hooks/BashToolGuard.hook.ts +65 -0
  6. package/hooks/BashWriteGuard.hook.ts +60 -0
  7. package/hooks/CommitEnforcement.hook.ts +130 -0
  8. package/hooks/DocHygiene.hook.ts +148 -0
  9. package/hooks/GateEnforcement.hook.ts +58 -0
  10. package/hooks/GateResultProtection.hook.ts +69 -0
  11. package/hooks/HarnessAFKGate.hook.ts +85 -0
  12. package/hooks/HookCurrency.hook.ts +99 -0
  13. package/hooks/IssueCloseGuard.hook.ts +149 -0
  14. package/hooks/MergeGuard.hook.ts +58 -0
  15. package/hooks/PostCompact.hook.ts +60 -0
  16. package/hooks/ProjectStateSync.hook.ts +103 -0
  17. package/hooks/SkillGuard.hook.ts +69 -0
  18. package/hooks/SpecConformityTrigger.hook.ts +43 -0
  19. package/hooks/SpecSCGuard.hook.ts +123 -0
  20. package/hooks/StaleTTLCleanup.hook.ts +141 -0
  21. package/hooks/TaskCompleted.hook.ts +51 -0
  22. package/hooks/TeamInit.hook.ts +85 -0
  23. package/hooks/TestSuiteGuard.hook.ts +70 -0
  24. package/hooks/TestSuiteRelease.hook.ts +85 -0
  25. package/hooks/TopLevelCdGuard.hook.ts +108 -0
  26. package/hooks/VerifyPhaseLock.hook.ts +84 -0
  27. package/hooks/WorkflowStateGuard.hook.ts +40 -0
  28. package/hooks/lib/agent-config.json +9 -0
  29. package/hooks/lib/agentDetection.ts +201 -0
  30. package/hooks/lib/comment-template.ts +86 -0
  31. package/hooks/lib/findWorkflow.ts +101 -0
  32. package/hooks/lib/parseStdin.ts +37 -0
  33. package/hooks/lib/paths.ts +111 -0
  34. package/hooks/lib/utils.ts +338 -0
  35. package/lib/affected-tests.ts +427 -0
  36. package/lib/agent-audit.ts +2 -3
  37. package/lib/agent-worktree.ts +287 -0
  38. package/lib/agents-md-sections.ts +81 -16
  39. package/lib/bash-write-guard.ts +373 -0
  40. package/lib/behavioral-cache.ts +150 -2
  41. package/lib/branch-cleanup.ts +279 -7
  42. package/lib/branch-protection.ts +790 -0
  43. package/lib/brief-ac-alignment.ts +104 -0
  44. package/lib/brief-references.ts +205 -0
  45. package/lib/bun-version.ts +93 -14
  46. package/lib/check-remedy.ts +140 -0
  47. package/lib/ci-checkout.ts +17 -0
  48. package/lib/ci-history-depth.ts +159 -0
  49. package/lib/ci-setup-step.ts +96 -0
  50. package/lib/claude-code-action.ts +85 -0
  51. package/lib/claude-tool-vocabulary.ts +188 -0
  52. package/lib/cli-commands.ts +15 -0
  53. package/lib/commit-sha.ts +42 -0
  54. package/lib/commit-subject.ts +90 -0
  55. package/lib/compliance-report.ts +377 -45
  56. package/lib/compliance.ts +191 -17
  57. package/lib/config-loader.ts +39 -1
  58. package/lib/config-trackable.ts +400 -0
  59. package/lib/conformity.ts +1087 -100
  60. package/lib/containment.ts +238 -0
  61. package/lib/content-hash.ts +24 -0
  62. package/lib/create-sc.ts +249 -16
  63. package/lib/dev-liveness.ts +180 -0
  64. package/lib/discovery-branch-points.ts +432 -0
  65. package/lib/discovery-stability.ts +481 -0
  66. package/lib/distribution-currency.ts +236 -0
  67. package/lib/doc-routing.ts +157 -0
  68. package/lib/evidence-prevalidator.ts +224 -2
  69. package/lib/evidence-satisfiability.ts +534 -12
  70. package/lib/failure-intake.ts +323 -0
  71. package/lib/fallow-availability.ts +157 -0
  72. package/lib/fs-write-capabilities.ts +232 -0
  73. package/lib/gate-enforcement.ts +222 -28
  74. package/lib/gate-names.ts +72 -0
  75. package/lib/gate-result-protection.ts +427 -0
  76. package/lib/gate-run-split.ts +147 -0
  77. package/lib/generators/agents-md.ts +140 -32
  78. package/lib/git-isolation.ts +140 -0
  79. package/lib/github.ts +15 -0
  80. package/lib/google-auth-action.ts +93 -0
  81. package/lib/harness-project.ts +48 -0
  82. package/lib/harness-provenance.ts +255 -0
  83. package/lib/hook-evidence.ts +235 -0
  84. package/lib/hook-scopes.ts +386 -0
  85. package/lib/hook-target-tree.ts +398 -0
  86. package/lib/hook-trees.ts +447 -0
  87. package/lib/intake-sources.ts +380 -0
  88. package/lib/js-top-level-code.ts +78 -10
  89. package/lib/junit-checks.ts +52 -0
  90. package/lib/late-env-spawn.ts +331 -0
  91. package/lib/launch-base.ts +376 -0
  92. package/lib/line-citation.ts +372 -0
  93. package/lib/orphan-reaper.ts +468 -0
  94. package/lib/parity-binding.ts +205 -0
  95. package/lib/paths.ts +96 -3
  96. package/lib/per-test-timeouts.ts +219 -0
  97. package/lib/phase2-decomposition.ts +1 -1
  98. package/lib/plan-coverage.ts +151 -0
  99. package/lib/prior-branch.ts +201 -8
  100. package/lib/process-table.ts +146 -0
  101. package/lib/project-state-derivation.ts +219 -0
  102. package/lib/project-state-root.ts +258 -0
  103. package/lib/published-artifact.ts +669 -0
  104. package/lib/readdir-sorted.ts +45 -0
  105. package/lib/review-execution-reading.ts +206 -0
  106. package/lib/review-tool-agreement.ts +433 -0
  107. package/lib/rule-promotion.ts +234 -0
  108. package/lib/rule-retirement.ts +525 -0
  109. package/lib/run-branch.ts +612 -0
  110. package/lib/rungate-schema.ts +19 -0
  111. package/lib/runner-home.ts +274 -0
  112. package/lib/sc-id-cross-tree.ts +103 -15
  113. package/lib/sc-ids.ts +121 -13
  114. package/lib/sc-reservations.ts +289 -0
  115. package/lib/scaffold/ai-review-findings.ts +409 -0
  116. package/lib/scaffold/ai-review-step.ts +5406 -64
  117. package/lib/scaffold/defaults.ts +82 -1
  118. package/lib/scaffold/managed-workflow.ts +587 -192
  119. package/lib/scaffold/owned-files.ts +152 -45
  120. package/lib/scaffold/pre-push-hook.ts +49 -5
  121. package/lib/scaffold/steps.ts +1836 -275
  122. package/lib/scaffold/workflow-census.ts +217 -0
  123. package/lib/scaffold/workflow-drift.ts +217 -0
  124. package/lib/scaffold/write-steps.ts +4 -0
  125. package/lib/scan-budget.ts +247 -0
  126. package/lib/scanner.ts +43 -51
  127. package/lib/scratch-roots.ts +50 -5
  128. package/lib/screenshot-discovery.ts +121 -0
  129. package/lib/screenshot-upload.ts +41 -1
  130. package/lib/secret-patterns.ts +511 -8
  131. package/lib/security-verdict.ts +1 -1
  132. package/lib/shell-path-interpolation.ts +594 -0
  133. package/lib/ship-mode.ts +219 -0
  134. package/lib/source-slice.ts +294 -0
  135. package/lib/stale-cleanup.ts +37 -3
  136. package/lib/suite-flake.ts +278 -0
  137. package/lib/suite-measurement.ts +23 -4
  138. package/lib/suite-run-reading.ts +241 -1
  139. package/lib/suite-timeout-margin.ts +193 -0
  140. package/lib/test-case-bodies.ts +883 -0
  141. package/lib/test-case-deletion.ts +653 -0
  142. package/lib/test-census.ts +97 -29
  143. package/lib/test-command-positions.ts +274 -0
  144. package/lib/test-suite-lock.ts +159 -16
  145. package/lib/text-dependents.ts +875 -0
  146. package/lib/tool-probe.ts +31 -9
  147. package/lib/top-level-cd.ts +393 -0
  148. package/lib/tree-entries.ts +89 -0
  149. package/lib/ts-ast.ts +200 -0
  150. package/lib/walk-test-files.ts +97 -0
  151. package/lib/workflow-actions.ts +263 -0
  152. package/lib/workflow-security.ts +29 -0
  153. package/lib/workflow-taint.ts +732 -0
  154. package/lib/worktree-cleanup.ts +65 -38
  155. package/lib/worktree-collect.ts +177 -5
  156. package/lib/worktree-repo.ts +68 -3
  157. package/package.json +4 -1
  158. package/scripts/ai-review-findings.ts +45 -0
  159. package/scripts/check-installed-hook-currency.ts +825 -0
  160. package/scripts/create-sc.ts +21 -1
  161. package/scripts/extract-constraints.ts +107 -7
  162. package/scripts/generate-code-map.ts +23 -30
  163. package/scripts/scaffold-project.ts +8 -1
  164. package/scripts/sync-sc-status.ts +77 -16
@@ -7,34 +7,66 @@
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, lstatSync, mkdirSync, readFileSync, writeFileSync, readdirSync, statSync } from "fs";
11
- import { join, basename, dirname } from "path";
10
+ import { existsSync, lstatSync, mkdirSync, readFileSync, writeFileSync, statSync } from "fs";
11
+ import { readdirSorted } from "../readdir-sorted";
12
+ import { join, basename, dirname, resolve, sep } from "path";
12
13
  import { auditSpecs } from "../../scripts/audit-specs";
13
14
  import { generateAgentsMd as buildAgentsMdContent, generateScopedRules } from "../generators/agents-md";
14
- import { isHarnessItself } from "../harness-identity";
15
+ import { HARNESS_PACKAGE, isHarnessItself } from "../harness-identity";
16
+ import { scanSpecs } from "../scanner";
17
+ import { projectStateDerivation, projectStateKeyFileNote } from "../project-state-derivation";
15
18
  import { generateAgentBriefs as buildAgentBriefsContent } from "../generators/agent-briefs";
16
19
  import { generateCodeMap as buildCodeMapContent } from "../generators/code-map";
17
20
  import { buildAgentMeta, DEFAULT_AGENT_META } from "../create-brief";
18
21
  import { buildDefaultRoles, buildDefaultHooks } from "./defaults";
19
22
  import {
20
- mergeManagedWorkflow,
23
+ mergeManagedWorkflowRecording,
21
24
  duplicateTopLevelKeys,
25
+ managedPreamble,
26
+ MANAGED_BANNER_PREFIX,
22
27
  movedTopLevelKeys,
28
+ WORKFLOW_OVERRIDE_COMMENT,
29
+ workflowOverrides,
30
+ type ComputedSubKeys,
31
+ type MergeProvenance,
23
32
  type MovedKey,
33
+ type RevokedSubKey,
24
34
  } from "./managed-workflow";
25
35
  import { PRE_PUSH_MANAGED_MARKER, prePushHookScript } from "./pre-push-hook";
36
+ import {
37
+ AI_REVIEW_JOB,
38
+ aiReviewScaffoldAction,
39
+ buildAuthDetectStep,
40
+ buildOutcomesHeader,
41
+ buildReviewRunStep,
42
+ vertexCiConfig,
43
+ } from "./ai-review-step";
44
+ import { CI_SUITE_FETCH_DEPTH, baseRefFetchDepth } from "../ci-history-depth";
45
+ import { CLAUDE_CODE_ACTION } from "../claude-code-action";
46
+ import { GOOGLE_AUTH_ACTION } from "../google-auth-action";
26
47
  import { loadComplianceConfig, tryLoadRungateConfig } from "../config-loader";
27
48
  import { organizeProjectReport } from "../organize";
28
49
  import type { ProjectScan, ProjectType, SpecEntry, TestFile, RefFile, DocRoute, Category } from "../generators/types";
29
- import { tier1Ere } from "../secret-patterns";
50
+ import {
51
+ TIER2_ALLOWED_VALUE_ERE,
52
+ TIER2_GREP_CASE_FLAG,
53
+ TIER3_ALLOWED_VALUE_ERE,
54
+ tier1Ere,
55
+ tier2Ere,
56
+ tier3Ere,
57
+ } from "../secret-patterns";
30
58
  import { healthPathIn } from "../liveness-contradiction";
31
59
  import { localCalendarDay } from "../local-calendar-day";
32
60
  import { decideRuleWrite } from "../rule-provenance";
61
+ import { actionRef } from "../workflow-actions";
62
+ import { ciSetupStep } from "../ci-setup-step";
33
63
  import { DEFAULT_PROFILE, isRuleIncluded, type ScaffoldProfile } from "./profiles";
34
64
  import { referencedPaths } from "../agents-md-refs";
65
+ import { scanDocsDirectory } from "../doc-routing";
35
66
  import { inferredTestCommand, testCommandDecision } from "../test-command";
36
67
  import { declaredBunVersion, setupBunWith } from "../bun-version";
37
68
  import { codeMapUnreferenced, unlistedSpecs } from "../spec-listing";
69
+ import { censusReport, stampWorkflow, workflowBody, workflowCensus } from "./workflow-census";
38
70
  import {
39
71
  readSuccessDoc,
40
72
  readSuccessTemplate,
@@ -44,11 +76,13 @@ import {
44
76
  } from "../success-doc";
45
77
  import { TS_SOURCE_DIRS, typeScriptSourceDirs, typecheckDecision } from "../typescript-project";
46
78
  import {
47
- OWNED_FILES,
48
79
  SCAFFOLD_REFUSE,
49
80
  decideOwnedWrite,
81
+ ownedFileFor,
50
82
  type WriteStrategy,
51
83
  } from "./owned-files";
84
+ import type { SectionSpec } from "../agents-md-sections";
85
+ import { executedHookPath, hookRegistrationPath } from "../hook-trees";
52
86
 
53
87
  /**
54
88
  * Look for a declared health route in the places a server declares one.
@@ -119,18 +153,23 @@ export function safeWrite(filePath: string, content: string, label: string, acti
119
153
  * prose while being written by a helper that skips it.
120
154
  */
121
155
  export function ownedStrategy(label: string): WriteStrategy {
122
- for (const owned of OWNED_FILES) {
123
- if (owned.path === label) return owned.strategy;
124
- if (owned.path.includes("*")) {
125
- const [prefix, suffix] = owned.path.split("*");
126
- if (label.startsWith(prefix) && label.endsWith(suffix)) return owned.strategy;
127
- }
128
- }
129
156
  // An unlisted file is regenerated. The direction this is allowed to be
130
157
  // wrong in: a file nobody declared gets rewritten with the generator's
131
158
  // own output, which is recoverable. Defaulting to create-only would make
132
159
  // forgetting to declare a file look exactly like #208.
133
- return "regenerate";
160
+ return ownedFileFor(label)?.strategy ?? "regenerate";
161
+ }
162
+
163
+ /**
164
+ * Which section of this label carries forward, from the declaration (#655).
165
+ *
166
+ * `undefined` for every strategy that preserves nothing, and for a
167
+ * `section-preserving` row that forgot to declare one — which
168
+ * `test/scaffold-ownership.test.ts` refuses, because reading it here would
169
+ * make the omission resolve to AGENTS.md's heading and look deliberate.
170
+ */
171
+ export function ownedSections(label: string): SectionSpec | undefined {
172
+ return ownedFileFor(label)?.sections;
134
173
  }
135
174
 
136
175
  export function regenerateOwned(
@@ -181,7 +220,7 @@ export function regenerateOwned(
181
220
  return;
182
221
  }
183
222
  const existing = link ? readFileSync(filePath, "utf-8") : null;
184
- const decision = decideOwnedWrite(strategy, existing, content);
223
+ const decision = decideOwnedWrite(strategy, existing, content, ownedSections(label));
185
224
 
186
225
  if (decision.action === "preserve") {
187
226
  actions.push(
@@ -369,7 +408,7 @@ export function generateAgentsMdContent(
369
408
  // Scan key files
370
409
  const keyFiles: Array<{ file: string; what: string; when: string }> = [
371
410
  { file: "AGENTS.md", what: "Project entry point", when: "Always first" },
372
- { file: "PROJECT-STATE.md", what: "Live status + handoff (generated from project-state.json — don't edit directly)", when: "Session start, always first after AGENTS.md" },
411
+ { file: "PROJECT-STATE.md", what: projectStateKeyFileNote(projectStateDerivation(projectPath)), when: "Session start, always first after AGENTS.md" },
373
412
  { file: "project-state.json", what: "Source of truth for project status", when: "When editing state" },
374
413
  ];
375
414
  const conditionalPatterns: Array<{ pattern: string; what: string; when: string }> = [
@@ -396,59 +435,21 @@ export function generateAgentsMdContent(
396
435
  }
397
436
  }
398
437
 
399
- // Scan specs
400
- const specsDir = join(projectPath, "specs");
401
- const specEntries: SpecEntry[] = [];
402
- if (existsSync(specsDir)) {
403
- const specFiles = readdirSync(specsDir).filter(f => f.endsWith(".md") && f !== "SPEC-TEMPLATE.md");
404
- for (const f of specFiles) {
405
- const content = readFileSync(join(specsDir, f), "utf-8");
406
- const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
407
- let governs = "";
408
- let testable = "TODO";
409
- if (fmMatch) {
410
- const gMatch = fmMatch[1].match(/governs:\s*(.+)/);
411
- if (gMatch && gMatch[1].trim() !== "TODO" && gMatch[1].trim().length > 5) {
412
- governs = gMatch[1].trim().replace(/\|/g, "—").slice(0, 120);
413
- }
414
- const tMatch = fmMatch[1].match(/testable:\s*(.+)/);
415
- if (tMatch) testable = tMatch[1].trim();
416
- }
417
- specEntries.push({ file: f, governs, testable });
418
- }
419
-
420
- // Also scan specs subdirectories
421
- try {
422
- const specSubDirs = readdirSync(specsDir, { withFileTypes: true })
423
- .filter(d => d.isDirectory())
424
- .map(d => d.name);
425
- for (const sub of specSubDirs) {
426
- const subPath = join(specsDir, sub);
427
- const subFiles = readdirSync(subPath).filter(f => f.endsWith(".md") && f !== "INDEX.md");
428
- if (subFiles.length > 0) {
429
- const indexPath = join(subPath, "INDEX.md");
430
- let groupGoverns = `${sub} (${subFiles.length} specs)`;
431
- if (existsSync(indexPath)) {
432
- const indexContent = readFileSync(indexPath, "utf-8");
433
- const fmMatch = indexContent.match(/^---\n([\s\S]*?)\n---/);
434
- if (fmMatch) {
435
- const gMatch = fmMatch[1].match(/governs:\s*(.+)/);
436
- if (gMatch && gMatch[1].trim().length > 5) {
437
- groupGoverns = gMatch[1].trim().replace(/\|/g, "—").slice(0, 120);
438
- }
439
- }
440
- }
441
- specEntries.push({ file: `${sub}/ (${subFiles.length} specs)`, governs: groupGoverns, testable: "yes" });
442
- }
443
- }
444
- } catch {}
445
- }
438
+ // Scan specs — delegated to `lib/scanner.ts`, which is the one derivation.
439
+ // This function used to carry its own copy, and the copy drifted three
440
+ // times (#827): it never set `criteriaNone`, so `STATES NO CRITERIA` was
441
+ // dropped from every row that earned it; it hardcoded `testable: "yes"` on
442
+ // group rows, a word `scanner.ts` notes "means false to the code and true
443
+ // to a reader"; and it filtered spec files by name instead of `isSpecFile`,
444
+ // which is how #382's two scans disagreed about `SPEC-TEMPLATE.md`. All
445
+ // three were fixed in `scanner.ts` alone, because nobody knew this existed.
446
+ const specEntries: SpecEntry[] = scanSpecs(projectPath);
446
447
 
447
448
  // Scan tests
448
449
  const testDir = existsSync(join(projectPath, "test")) ? "test" : existsSync(join(projectPath, "tests")) ? "tests" : null;
449
450
  const testEntries: TestFile[] = [];
450
451
  if (testDir) {
451
- for (const f of readdirSync(join(projectPath, testDir)).filter(f => f.endsWith(".test.ts"))) {
452
+ for (const f of readdirSorted(join(projectPath, testDir)).filter(f => f.endsWith(".test.ts"))) {
452
453
  const label = f.replace(".test.ts", "").replace(/-/g, " ");
453
454
  testEntries.push({ label, file: f });
454
455
  }
@@ -463,7 +464,7 @@ export function generateAgentsMdContent(
463
464
  const refDir = join(projectPath, "reference");
464
465
  const refEntries: RefFile[] = [];
465
466
  if (existsSync(refDir)) {
466
- for (const f of readdirSync(refDir)) {
467
+ for (const f of readdirSorted(refDir)) {
467
468
  refEntries.push({ file: f, what: "Historical reference" });
468
469
  }
469
470
  }
@@ -516,42 +517,23 @@ export function generateAgentsMdContent(
516
517
  // Recursive — see the same fix in scanner.ts. This is a second copy of
517
518
  // scanDocRouting and it is the one the scaffold actually calls, so the
518
519
  // scanner fix alone changed no generated output at all (#91).
519
- const files = readdirSync(catPath, { recursive: true }).map(String).filter(f => f.endsWith(".md"));
520
+ const files = readdirSorted(catPath, { recursive: true }).filter(f => f.endsWith(".md"));
520
521
  docRouting.push({ need: `${cat.label} (${files.length} files)`, file: `${cat.dir}/` });
521
522
  } else {
522
523
  docRouting.push({ need: cat.label, file: `${cat.dir}/` });
523
524
  actions.push(`WARN: ${cat.dir}/ listed in routing but directory does not exist`);
524
525
  }
525
526
  }
526
- if (existsSync(docsDir)) {
527
- const allDocs = readdirSync(docsDir).filter(f => f.endsWith(".md"));
528
- for (const f of allDocs) {
529
- const docPath = join(docsDir, f);
530
- const content = readFileSync(docPath, "utf-8");
531
- const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
532
- let need = f.replace(/\.md$/, "").replace(/-/g, " ");
533
- if (fmMatch) {
534
- const gMatch = fmMatch[1].match(/governs:\s*(.+)/);
535
- if (gMatch && gMatch[1].trim() !== "TODO") need = gMatch[1].trim();
536
- }
537
- docRouting.push({ need, file: `docs/${f}` });
538
- }
539
- const subDirs = readdirSync(docsDir, { withFileTypes: true })
540
- .filter(d => d.isDirectory() && !categories.some(c => c.dir === `docs/${d.name}`))
541
- .map(d => d.name);
542
- for (const sub of subDirs) {
543
- const subPath = join(docsDir, sub);
544
- const subFiles = readdirSync(subPath).filter(f => f.endsWith(".md"));
545
- if (subFiles.length > 0) {
546
- docRouting.push({ need: `${sub} (${subFiles.length} files)`, file: `docs/${sub}/` });
547
- }
548
- }
549
- }
550
- const filteredRouting = docRouting.filter(d => {
551
- const slug = d.file.replace(/\.md$/, "").replace(/.*\//, "").toLowerCase().replace(/-/g, " ");
552
- const needLower = d.need.toLowerCase();
553
- return !needLower.startsWith(slug) || d.need.includes("—") || d.need.includes("(");
554
- });
527
+ // Through the one binding (#617, #619). This was a complete second copy of
528
+ // `scanDocRouting`, with its own inline `governs:` regex — and it is the copy
529
+ // the scaffold actually calls, so a fix applied only to the scanner changes
530
+ // no generated output at all (#91).
531
+ docRouting.push(...scanDocsDirectory(docsDir, categories.map(c => c.dir)));
532
+
533
+ // The "filter to non-obvious mappings" is deleted here for the same reason
534
+ // as in lib/scanner.ts: it could only ever drop a top-level `docs/*.md`, and
535
+ // dropping those is #617. See lib/doc-routing.ts.
536
+ const filteredRouting = docRouting;
555
537
 
556
538
  const consumers = harness?.consumers || [];
557
539
 
@@ -767,7 +749,7 @@ export function generateConformityTest(root?: string): string {
767
749
  const from = root && isHarnessItself(root) ? "../lib/conformity" : "rungate/lib/conformity";
768
750
  return `import { resolve } from "path";
769
751
  import { afterAll } from "bun:test";
770
- import { runScaffoldConformity, runSpecDiscovery, runSpecDrift, runDocHygiene, runFallowCheck, runAgentFileValidation, runDirectoryValidation, runPackageValidation, runTsconfigValidation, runConfigAccessValidation, runPromptConfigAccessValidation, runSuccessDocValidation, writeFindingsReport } from "${from}";
752
+ import { runScaffoldConformity, runSpecDiscovery, runSpecDrift, runDocHygiene, runFallowCheck, runAgentFileValidation, runDirectoryValidation, runPackageValidation, runTsconfigValidation, runConfigAccessValidation, runPromptConfigAccessValidation, runSuccessDocValidation, runAiReviewValidation, runBranchProtectionValidation, runWorkflowDriftValidation, writeFindingsReport } from "${from}";
771
753
 
772
754
  const ROOT = resolve(import.meta.dir, "..");
773
755
 
@@ -783,6 +765,9 @@ runTsconfigValidation(ROOT);
783
765
  runConfigAccessValidation(ROOT);
784
766
  runPromptConfigAccessValidation(ROOT);
785
767
  runSuccessDocValidation(ROOT);
768
+ runAiReviewValidation(ROOT);
769
+ runBranchProtectionValidation(ROOT);
770
+ runWorkflowDriftValidation(ROOT);
786
771
 
787
772
  afterAll(() => writeFindingsReport(ROOT));
788
773
  `;
@@ -790,7 +775,26 @@ afterAll(() => writeFindingsReport(ROOT));
790
775
 
791
776
  // ── Agent briefs generation ────────────────────────────────────
792
777
 
793
- export function generateAgentBriefsStep(root: string, actions: string[]): void {
778
+ export function generateAgentBriefsStep(
779
+ root: string,
780
+ actions: string[],
781
+ opts: {
782
+ /**
783
+ * Where the brief templates live. Defaults to the harness's own
784
+ * `templates/agent-briefs/`, which is what every production caller
785
+ * wants and what makes the templates harness-wide (#655).
786
+ *
787
+ * The seam exists because the `section-preserving` refusal below can
788
+ * only fire when the GENERATED brief carries the project-owned heading
789
+ * itself, and no input `root` accepts can produce that — the identity
790
+ * extractor stops at the first `\n##` and the README fallback flattens
791
+ * newlines. Without a seam the refusal would be reachable in
792
+ * production and unreachable in a test, which is the shape
793
+ * `.claude/rules/checks-must-be-able-to-fail.md` is about.
794
+ */
795
+ templatesDir?: string;
796
+ } = {},
797
+ ): void {
794
798
  const agentsDir = join(root, ".claude", "agents");
795
799
  safeDir(agentsDir, ".claude/agents", actions);
796
800
 
@@ -832,7 +836,7 @@ export function generateAgentBriefsStep(root: string, actions: string[]): void {
832
836
  marcus: [], quinn: [], rook: [], serena: [], aditi: [], discovery: []
833
837
  };
834
838
  if (existsSync(promptsDir)) {
835
- const promptFiles = readdirSync(promptsDir).filter(f => f.endsWith(".md"));
839
+ const promptFiles = readdirSorted(promptsDir).filter(f => f.endsWith(".md"));
836
840
  for (const f of promptFiles) {
837
841
  const content = readFileSync(join(promptsDir, f), "utf-8");
838
842
  const lower = f.toLowerCase();
@@ -863,7 +867,8 @@ export function generateAgentBriefsStep(root: string, actions: string[]): void {
863
867
  const consumers = harness?.consumers || [];
864
868
 
865
869
  // Resolve templates directory relative to this module
866
- const harnessTemplatesDir = join(dirname(dirname(__dirname)), "templates", "agent-briefs");
870
+ const harnessTemplatesDir =
871
+ opts.templatesDir ?? join(dirname(dirname(__dirname)), "templates", "agent-briefs");
867
872
 
868
873
  // buildAgentMeta takes the whole harness config and reads .roles itself.
869
874
  // Passing harness?.roles made it look for roles.roles, so every consumer's
@@ -922,8 +927,40 @@ export function generateAgentBriefsStep(root: string, actions: string[]): void {
922
927
 
923
928
  for (const [agentName, content] of Object.entries(briefs)) {
924
929
  const p = join(agentsDir, `${agentName}.md`);
925
- writeFileSync(p, content);
926
- actions.push(existsSync(p) ? `UPDATED: .claude/agents/${agentName}.md` : `CREATED: .claude/agents/${agentName}.md`);
930
+ const label = `.claude/agents/${agentName}.md`;
931
+ // #654. The probe is taken BEFORE the write it describes. Asked
932
+ // afterwards it is true on every path that reaches it — `writeFileSync`
933
+ // either succeeded, in which case the file is there, or threw, in which
934
+ // case this line never runs — so the `CREATED:` arm was unreachable and
935
+ // a consumer scaffolding for the first time was told its briefs were
936
+ // updated.
937
+ const existedBefore = existsSync(p);
938
+
939
+ // #655. The write used to be a bare `writeFileSync(p, content)` — no
940
+ // `decideOwnedWrite`, no strategy read, nothing. The row in
941
+ // `OWNED_FILES` said `regenerate` and a bare overwrite happens to
942
+ // behave like `regenerate`, so nothing ever disagreed and the
943
+ // declaration test could not see it: reading a strategy is not the same
944
+ // as honouring it. Flipping the row alone would have changed nothing
945
+ // here; this is the other half.
946
+ const existing = existedBefore ? readFileSync(p, "utf-8") : null;
947
+ const decision = decideOwnedWrite(
948
+ ownedStrategy(label),
949
+ existing,
950
+ content,
951
+ ownedSections(label),
952
+ );
953
+
954
+ if (decision.action === "refuse" || decision.action === "preserve") {
955
+ actions.push(`${SCAFFOLD_REFUSE}: ${label} not written — ${decision.reason}`);
956
+ continue;
957
+ }
958
+ if (decision.action === "unchanged") {
959
+ actions.push(`UNCHANGED: ${label} (${decision.reason})`);
960
+ continue;
961
+ }
962
+ writeFileSync(p, decision.content!);
963
+ actions.push(`${existedBefore ? "UPDATED" : "CREATED"}: ${label}`);
927
964
  }
928
965
  }
929
966
 
@@ -954,7 +991,7 @@ export function generateOrAuditProjectHarness(root: string, actions: string[], o
954
991
  // Scan pages from dashboard/src/pages/*.tsx (file-based routing)
955
992
  const dashboardPagesDir = join(root, "dashboard", "src", "pages");
956
993
  if (existsSync(dashboardPagesDir)) {
957
- const pageFiles = readdirSync(dashboardPagesDir).filter(f => f.endsWith(".tsx") || f.endsWith(".jsx"));
994
+ const pageFiles = readdirSorted(dashboardPagesDir).filter(f => f.endsWith(".tsx") || f.endsWith(".jsx"));
958
995
  for (const f of pageFiles) {
959
996
  const componentName = f.replace(/\.(tsx|jsx)$/, "");
960
997
  // Convert CamelCase to kebab-case route path
@@ -1055,7 +1092,7 @@ export function generateOrAuditProjectHarness(root: string, actions: string[], o
1055
1092
  const srcDir = join(root, "src");
1056
1093
  if (existsSync(srcDir)) {
1057
1094
  const consumerPatterns = ["-routes.ts", "-generator.ts", "-plan.ts", "-intel.ts"];
1058
- for (const f of readdirSync(srcDir).filter(f => f.endsWith(".ts"))) {
1095
+ for (const f of readdirSorted(srcDir).filter(f => f.endsWith(".ts"))) {
1059
1096
  const content = readFileSync(join(srcDir, f), "utf-8");
1060
1097
  const isConsumer = consumerPatterns.some(p => f.includes(p)) ||
1061
1098
  content.includes("app.get(") || content.includes("app.post(") ||
@@ -1440,7 +1477,17 @@ function writeDirectoryStructure(
1440
1477
  * so no later scaffold ever corrected it. Running this step last is what makes
1441
1478
  * that skip safe — the content it preserves is now right from run 1.
1442
1479
  */
1443
- export function generateCodeMapStep(root: string, actions: string[]): void {
1480
+ export function generateCodeMapStep(
1481
+ root: string,
1482
+ actions: string[],
1483
+ // #654 — the one injection seam, so the branch where the generator exits 0
1484
+ // and writes nothing can be entered. There is no input to the real
1485
+ // generator that provokes it, and a branch no test can enter is the thing
1486
+ // `.claude/rules/checks-must-be-able-to-fail.md` is about. Optional and
1487
+ // defaulted to the real script, so every caller is unchanged and a test
1488
+ // that forgets it is testing the real thing.
1489
+ opts: { generatorPath?: string } = {},
1490
+ ): void {
1444
1491
  // No dry-run branch. It reported `GAP: CODE-MAP.md missing` and nothing
1445
1492
  // else — one of the four `existsSync` checks that stood in for twenty-five
1446
1493
  // write steps and made audit report 0 changes on a tree `--fix` rewrote in
@@ -1472,11 +1519,31 @@ export function generateCodeMapStep(root: string, actions: string[]): void {
1472
1519
  }
1473
1520
 
1474
1521
  // Run generate-code-map.ts if available
1475
- const scriptPath = join(dirname(dirname(__dirname)), "scripts", "generate-code-map.ts");
1522
+ const scriptPath =
1523
+ opts.generatorPath ?? join(dirname(dirname(__dirname)), "scripts", "generate-code-map.ts");
1476
1524
  if (existsSync(scriptPath)) {
1525
+ // #654, and the same shape as the brief loop above with one extra arm.
1526
+ // Asked after the generator ran, `existsSync` answered two questions at
1527
+ // once and got both wrong: a successful generation reported `UPDATED:`
1528
+ // whether or not the file was new, and a generator that exits 0 WITHOUT
1529
+ // writing reported `CREATED:` for a file that is not there. The second
1530
+ // is the one that matters — `lib/scaffold/rehearsal.ts:481` records the
1531
+ // same defect at a site that was fixed, and it survived here because
1532
+ // the note was attached to the site rather than to the shape.
1533
+ const existedBefore = existsSync(codeMapPath);
1477
1534
  const result = Bun.spawnSync(["bun", scriptPath, root], { timeout: 60_000 });
1478
1535
  if (result.exitCode === 0) {
1479
- actions.push(existsSync(codeMapPath) ? "UPDATED: CODE-MAP.md" : "CREATED: CODE-MAP.md");
1536
+ const existsNow = existsSync(codeMapPath);
1537
+ actions.push(
1538
+ !existsNow
1539
+ // Neither created nor updated: the generator reported success and
1540
+ // produced nothing, which is a measurement that did not happen
1541
+ // and must not read as one that did.
1542
+ ? "UNMEASURED: CODE-MAP.md — the generator exited 0 and wrote no file"
1543
+ : existedBefore
1544
+ ? "UPDATED: CODE-MAP.md"
1545
+ : "CREATED: CODE-MAP.md",
1546
+ );
1480
1547
  } else {
1481
1548
  actions.push("WARN: CODE-MAP.md generation failed via script — trying inline");
1482
1549
  generateCodeMapInline(root, codeMapPath, actions);
@@ -1490,13 +1557,13 @@ function generateCodeMapInline(root: string, outPath: string, actions: string[])
1490
1557
  const name = basename(root);
1491
1558
  const skip = new Set(["node_modules", ".git", "reference", "dist", "build", ".next", ".fallow"]);
1492
1559
  const dirs: Array<{ name: string; fileCount: number; types: string[] }> = [];
1493
- for (const entry of readdirSync(root)) {
1560
+ for (const entry of readdirSorted(root)) {
1494
1561
  if (entry.startsWith(".") && entry !== ".claude") continue;
1495
1562
  if (skip.has(entry)) continue;
1496
1563
  const full = join(root, entry);
1497
1564
  try {
1498
1565
  if (!statSync(full).isDirectory()) continue;
1499
- const files = readdirSync(full, { recursive: true }).map(String);
1566
+ const files = readdirSorted(full, { recursive: true });
1500
1567
  const exts = new Set(files.map(f => f.split(".").pop()).filter((e): e is string => Boolean(e)));
1501
1568
  dirs.push({ name: entry, fileCount: files.length, types: [...exts].slice(0, 5) });
1502
1569
  } catch {}
@@ -1516,7 +1583,7 @@ function generateCodeMapInline(root: string, outPath: string, actions: string[])
1516
1583
  const srcDir = join(root, "src");
1517
1584
  const modules: Array<{ file: string; exports: string[] }> = [];
1518
1585
  if (existsSync(srcDir)) {
1519
- for (const f of readdirSync(srcDir).filter(f => f.endsWith(".ts") || f.endsWith(".js"))) {
1586
+ for (const f of readdirSorted(srcDir).filter(f => f.endsWith(".ts") || f.endsWith(".js"))) {
1520
1587
  const content = readFileSync(join(srcDir, f), "utf-8");
1521
1588
  const exports: string[] = [];
1522
1589
  const exportPattern = /export\s+(?:function|const|class|type|interface)\s+(\w+)/g;
@@ -1529,7 +1596,7 @@ function generateCodeMapInline(root: string, outPath: string, actions: string[])
1529
1596
  // Detect API routes
1530
1597
  const routes: Array<{ method: string; path: string; file: string }> = [];
1531
1598
  if (existsSync(srcDir)) {
1532
- for (const f of readdirSync(srcDir).filter(f => f.endsWith(".ts") || f.endsWith(".js"))) {
1599
+ for (const f of readdirSorted(srcDir).filter(f => f.endsWith(".ts") || f.endsWith(".js"))) {
1533
1600
  const content = readFileSync(join(srcDir, f), "utf-8");
1534
1601
  const routePatterns = [
1535
1602
  /app\.(get|post|put|delete|patch)\s*\(\s*["'`]([^"'`]+)["'`]/gi,
@@ -1590,7 +1657,7 @@ export function copySpecTemplateIfEmpty(specsDir: string, actions: string[]): vo
1590
1657
  if (!existsSync(specsDir)) return;
1591
1658
 
1592
1659
  // Skip if specs/ already has .md files (besides SPEC-TEMPLATE.md itself)
1593
- const existingSpecs = readdirSync(specsDir).filter(
1660
+ const existingSpecs = readdirSorted(specsDir).filter(
1594
1661
  f => f.endsWith(".md") && f !== "SPEC-TEMPLATE.md"
1595
1662
  );
1596
1663
  if (existingSpecs.length > 0) {
@@ -2035,6 +2102,26 @@ export interface ManagedWrite {
2035
2102
  * was being made.
2036
2103
  */
2037
2104
  movedKeys: MovedKey[];
2105
+ /**
2106
+ * Derived grants the merge withdrew because the generator stopped computing
2107
+ * them (#923).
2108
+ *
2109
+ * Not a refusal and not an overwrite — a third thing, and it needs its own
2110
+ * field because the other two would both misreport it. In `lostLines` it is
2111
+ * a refusal over two lines the harness wrote itself; in `overwrittenLines`
2112
+ * it is a report that says "in harness-owned jobs" about a top-level key.
2113
+ *
2114
+ * Reported rather than silent, because the removal is the whole point: a
2115
+ * consumer who removes `ci.vertex` keeps `id-token: write` — the right to
2116
+ * mint an OIDC token for a federation that no longer exists — and a
2117
+ * permission nobody consumes is a permission nobody audits. Taking it away
2118
+ * without saying so would make the scaffold do, silently, the one thing
2119
+ * `ci.workflowOverrides` was built to guarantee is always visible.
2120
+ *
2121
+ * The record travels from the merge rather than being recomputed here. See
2122
+ * `mergeManagedWorkflowRecording`.
2123
+ */
2124
+ revokedGrants: RevokedSubKey[];
2038
2125
  /** Non-null ⇒ the write must not happen. Names the dropped jobs and the line delta. */
2039
2126
  refusal: string | null;
2040
2127
  }
@@ -2132,10 +2219,11 @@ function measureWrite(existing: string | null, next: string): { verb: ManagedWri
2132
2219
  * test/scaffold-ci-preservation-mutation.test.ts performs, so that
2133
2220
  * "preservation works" is a claim with a demonstrated way of being false.
2134
2221
  */
2135
- export function resolveManagedWrite(existing: string | null, generated: string): ManagedWrite {
2222
+ export function resolveManagedWrite(existing: string | null, generated: string, overrides: readonly string[] = [], provenance: MergeProvenance = "UNPROVEN", computed: ComputedSubKeys = new Map()): ManagedWrite {
2136
2223
  const base: ManagedWrite = {
2137
2224
  content: generated, verb: "CREATED", lineDelta: lineCount(generated),
2138
- preservedJobs: [], droppedJobs: [], overwrittenLines: [], movedKeys: [], refusal: null,
2225
+ preservedJobs: [], droppedJobs: [], overwrittenLines: [], movedKeys: [], revokedGrants: [],
2226
+ refusal: null,
2139
2227
  };
2140
2228
  if (existing === null) return base;
2141
2229
 
@@ -2164,7 +2252,7 @@ export function resolveManagedWrite(existing: string | null, generated: string):
2164
2252
  // A refusal that is structurally incapable of firing on the thing being
2165
2253
  // destroyed is the defect class .claude/rules/checks-must-be-able-to-fail.md
2166
2254
  // exists for, and it was in the fix written to prevent a data-loss bug.
2167
- const content = mergeManagedWorkflow(existing, generated);
2255
+ const { content, revoked: revokedGrants } = mergeManagedWorkflowRecording(existing, generated, overrides, provenance, computed);
2168
2256
  const lineDelta = lineCount(content) - before;
2169
2257
 
2170
2258
  const preservedJobs = existingJobs.filter(j => !generatedJobs.includes(j));
@@ -2248,19 +2336,98 @@ export function resolveManagedWrite(existing: string | null, generated: string):
2248
2336
  const block = blocks.get(name);
2249
2337
  if (block !== undefined) for (const l of nonBlankLines(block)) harnessOwned.add(l);
2250
2338
  }
2251
- // The harness's own banner is the harness's to reword. Without this, the
2252
- // first run after the banner's text changed refused to update a file the
2253
- // harness had written itself, naming its own previous sentence as consumer
2254
- // content it declined to drop — a refusal is only useful if it is about
2255
- // somebody else's work.
2339
+ // The harness's own bookkeeping lines are the harness's to reword or
2340
+ // withdraw. Without this, the first run after the banner's text changed
2341
+ // refused to update a file the harness had written itself, naming its own
2342
+ // previous sentence as consumer content it declined to drop — a refusal is
2343
+ // only useful if it is about somebody else's work. The override notice is
2344
+ // here for the same reason and one more: it is DELETED, not reworded, the
2345
+ // run after a consumer removes the config entry, so without this the way
2346
+ // back from an override is a refusal (#839).
2256
2347
  for (const l of nonBlankLines(existing)) {
2257
- if (l.startsWith(MANAGED_BANNER_PREFIX)) harnessOwned.add(l);
2348
+ if (HARNESS_BOOKKEEPING_PREFIXES.some(p => l.startsWith(p))) harnessOwned.add(l);
2258
2349
  }
2259
2350
 
2351
+ // The harness's own preamble is the harness's to reword — the WHOLE of it
2352
+ // from the banner down, not just the banner line (#834). A bookkeeping
2353
+ // PREFIX catches the sentence it opens and nothing else, so the paragraphs
2354
+ // underneath read as consumer content: a consumer that added `ci.vertex`
2355
+ // had its re-scaffold refused over three lines of the harness's own "no
2356
+ // credential is configured" header, which is precisely the header the new
2357
+ // one replaces. The merge already declares that preamble its own, so this
2358
+ // reads the boundary from `managedPreamble` rather than restating it —
2359
+ // the two disagreeing is what made the refusal possible.
2360
+ //
2361
+ // This SUBSUMES the banner entry in `HARNESS_BOOKKEEPING_PREFIXES` for the
2362
+ // LEADING PREAMBLE, and only there. The banner of a generated workflow is
2363
+ // always in that preamble, so for the file the generator wrote the two
2364
+ // deciders cannot disagree — which is why giving the constant a second
2365
+ // spelling in this module turned 0 of 107 red when #916 landed, and why
2366
+ // saying so was cheaper than implying a guard that is not there
2367
+ // (`.claude/rules/checks-must-be-able-to-fail.md`, fourth shape).
2368
+ //
2369
+ // "Only there" is the part that was missing, and #926 is where it was
2370
+ // measured. `managedPreamble` reads the HEAD section and returns `[]` when
2371
+ // the banner is not in it, so a bookkeeping line anywhere else in the file
2372
+ // — beside the job key it introduces, which is exactly where the override
2373
+ // notice sits — reaches this loss set with nothing above covering it. The
2374
+ // entry is what keeps it out, and the write refuses without it. Both
2375
+ // entries now carry that witness in
2376
+ // `test/scaffold-permissions-merge.test.ts`, generated from the array.
2377
+ //
2378
+ // What the entry is not any more is the thing keeping the HEADER out of the
2379
+ // loss set. That job is `harnessPreamble`'s.
2380
+ const harnessPreamble = new Set(nonBlankLines(managedPreamble(existing).join("\n")));
2381
+
2382
+ // The grants the merge withdrew, as the lines it took out (#923).
2383
+ //
2384
+ // Taken FROM THE MERGE, not recomputed. A second reading here of which
2385
+ // sub-keys ought to have gone would be a decider that can disagree with the
2386
+ // one that actually removed them, and #834 is the bill for exactly that
2387
+ // arrangement: the merge computed the correct file, the write's own view of
2388
+ // what it was allowed to drop refused to put it on disk, and `id-token:
2389
+ // write` stayed off every consumer for it. Here the disagreement would run
2390
+ // the other way and be worse — a line the merge removed and this set did
2391
+ // not cover is a REFUSED re-scaffold, and a line this set covered and the
2392
+ // merge did not remove is a consumer's own content dropped in silence.
2393
+ // A MULTISET, and spending it is what makes it one. A `Set` of line TEXT
2394
+ // excuses every line in the file that happens to share that text, and
2395
+ // ` id-token: write` is a line a multi-job workflow plausibly carries more
2396
+ // than once — one legitimately withdrawn occurrence would then silently
2397
+ // excuse an unrelated one the consumer still wants. A set also cannot
2398
+ // count: two revoked and five present is indistinguishable from one and
2399
+ // one. Exactly as many occurrences are forgiven as the merge removed, and
2400
+ // the rest refuse like any other dropped line.
2401
+ const revocationBudget = new Map<string, number>();
2402
+ for (const r of revokedGrants) {
2403
+ for (const l of nonBlankLines(r.lines.join("\n"))) {
2404
+ revocationBudget.set(l, (revocationBudget.get(l) ?? 0) + 1);
2405
+ }
2406
+ }
2407
+ /** Spend one occurrence, or report that there is none left to spend. */
2408
+ const spendRevocation = (line: string): boolean => {
2409
+ const left = revocationBudget.get(line) ?? 0;
2410
+ if (left === 0) return false;
2411
+ revocationBudget.set(line, left - 1);
2412
+ return true;
2413
+ };
2414
+
2260
2415
  const kept = new Set(nonBlankLines(content));
2261
2416
  const gone = nonBlankLines(existing).filter(l => !kept.has(l));
2262
- const lostLines = gone.filter(l => !harnessOwned.has(l));
2263
- const overwrittenLines = gone.filter(l => harnessOwned.has(l) && !l.startsWith(MANAGED_BANNER_PREFIX));
2417
+ // Order matters: `spendRevocation` is reached only when the two cheaper
2418
+ // owners decline, so a line the harness already owns does not burn a
2419
+ // revocation another occurrence may need.
2420
+ const lostLines = gone.filter(
2421
+ l => !harnessOwned.has(l) && !harnessPreamble.has(l) && !spendRevocation(l),
2422
+ );
2423
+ // Rewording its own header is not overwriting somebody's edit, and this
2424
+ // report says "in harness-owned jobs" — which the preamble is not.
2425
+ const overwrittenLines = gone.filter(
2426
+ l =>
2427
+ harnessOwned.has(l) &&
2428
+ !harnessPreamble.has(l) &&
2429
+ !HARNESS_BOOKKEEPING_PREFIXES.some(p => l.startsWith(p)),
2430
+ );
2264
2431
  const droppedJobs = existingJobs.filter(j => !resultJobs.includes(j));
2265
2432
 
2266
2433
  if (lostLines.length > 0) {
@@ -2277,7 +2444,11 @@ export function resolveManagedWrite(existing: string | null, generated: string):
2277
2444
  };
2278
2445
  }
2279
2446
 
2280
- return { content, ...measureWrite(existing, content), preservedJobs, droppedJobs: [], overwrittenLines, movedKeys, refusal: null };
2447
+ // `revokedGrants` only reaches a caller on this path. Every return above is
2448
+ // a refusal and `unchanged` carries the empty list from `base`: nothing was
2449
+ // written, so nothing was withdrawn, and a report naming a grant that is
2450
+ // still in the file on disk is the reading disagreeing with reality again.
2451
+ return { content, ...measureWrite(existing, content), preservedJobs, droppedJobs: [], overwrittenLines, movedKeys, revokedGrants, refusal: null };
2281
2452
  }
2282
2453
 
2283
2454
  /** Non-blank lines, trimmed — the unit the loss set is counted in. */
@@ -2286,13 +2457,85 @@ function nonBlankLines(text: string): string[] {
2286
2457
  }
2287
2458
 
2288
2459
  /**
2289
- * Opening of the banner every generated workflow carries.
2460
+ * Lines in a managed file that are the harness talking to the consumer, not
2461
+ * the consumer's content.
2462
+ *
2463
+ * Both are prefixes rather than whole sentences: the rest of each names a
2464
+ * config path, and that tail is exactly the part that changes.
2465
+ *
2466
+ * EXPORTED so the list itself can be tested rather than its members (#926).
2467
+ * `test/scaffold-permissions-merge.test.ts` demands a WITNESS for every entry
2468
+ * — an input where matching the prefix is what decides the outcome — and
2469
+ * ratchets this array against the witnessed population, so an entry added
2470
+ * here with no case there is red. An entry nothing asserts reads as covered,
2471
+ * and adding the next one is how a dead decider gets in; this is what stops
2472
+ * the next one arriving dead the way the banner entry did.
2290
2473
  *
2291
- * Deliberately the stable prefix and not the whole sentence: the rest of it
2292
- * names the config path, and that is exactly the part that changed and caused
2293
- * the harness to refuse to update its own file.
2474
+ * The witnesses plant lines built from the constants in `managed-workflow.ts`
2475
+ * rather than from this array, deliberately. A fixture read out of the list
2476
+ * under test matches whatever the list says and cannot see it drift.
2294
2477
  */
2295
- const MANAGED_BANNER_PREFIX = "# Managed by rungate";
2478
+ export const HARNESS_BOOKKEEPING_PREFIXES = [MANAGED_BANNER_PREFIX, WORKFLOW_OVERRIDE_COMMENT];
2479
+
2480
+ /**
2481
+ * The sub-keys each generated workflow COMPUTES, by file and then by the
2482
+ * top-level key they sit under (#923).
2483
+ *
2484
+ * Same shape as `HARNESS_OWNED_JOBS` and for the same reason: a
2485
+ * conditionally emitted thing cannot be recognised from the generated side
2486
+ * once it stops being emitted. `mergeTopLevelSection`'s rule — a sub-key
2487
+ * only the consumer declares is the consumer's — is right for a LOCAL KNOB
2488
+ * and wrong for a DERIVED GRANT. `pull-requests: write` that a consumer
2489
+ * added for a job of their own is theirs. `id-token: write` that this
2490
+ * generator emitted because `ci.vertex` resolved is nobody's choice; the
2491
+ * config made it, and when the config goes the justification goes with it.
2492
+ * By the time the merge runs both are just lines in the consumer's file and
2493
+ * nothing records which side wrote them, so this records it instead.
2494
+ *
2495
+ * A sub-key named here is REMOVED from the consumer's section when that
2496
+ * file's generated side does not declare it. Add a conditionally emitted
2497
+ * sub-key in the same commit that makes it conditional.
2498
+ *
2499
+ * ## Keyed by FILE, which is the whole of the scoping
2500
+ *
2501
+ * The merge runs over every managed workflow. Keyed by section alone,
2502
+ * `permissions.id-token` becomes revocable in files whose generator never
2503
+ * emits it under any config — and all three of these emit a top-level
2504
+ * `permissions:`, so a consumer with a deploy job of their own would have
2505
+ * the grant withdrawn out of a workflow this feature was not reasoning
2506
+ * about. That is #923's own defect wearing the other hat: the issue is a
2507
+ * grant outliving its reason, and an unscoped revoker is a WITHDRAWAL
2508
+ * outliving its reason.
2509
+ *
2510
+ * Declared HERE rather than in `managed-workflow.ts` because the write loop
2511
+ * below is the only place that knows which file it is writing, and because
2512
+ * this module already spells that tuple as a literal for
2513
+ * `test/release-guard.test.ts`. A file absent from this map revokes nothing.
2514
+ *
2515
+ * ## Scoped to what the generator COMPUTES
2516
+ *
2517
+ * Not to everything it emits. `contents: read` is unconditional in all three
2518
+ * files, so both sides always declare it, #839's rule already settles it,
2519
+ * and an entry for it would be one no input can reach.
2520
+ * `test/scaffold-permissions-merge.test.ts` holds this map against the
2521
+ * generators themselves — it scaffolds every generated workflow with and
2522
+ * without the config that drives the grant and takes the per-file symmetric
2523
+ * difference of the emitted sub-keys — so the population is read off the
2524
+ * emitting module rather than off this list, and an entry for a file whose
2525
+ * generator never computes the sub-key is red.
2526
+ *
2527
+ * ## Not `ci.workflowOverrides`, which could not be the mechanism
2528
+ *
2529
+ * That is an opt-OUT: a consumer names a key and the merge stops touching
2530
+ * it. Revocation needs the opposite default, because the consumer who has
2531
+ * stopped using Vertex is exactly the consumer who will not think to declare
2532
+ * anything about it. The override still wins where it is declared — naming
2533
+ * the top-level key short-circuits `mergeTopLevelSection` before this is
2534
+ * read — so the escape hatch covers the path with no new config surface.
2535
+ */
2536
+ export const HARNESS_COMPUTED_SUBKEYS: ReadonlyMap<string, ComputedSubKeys> = new Map([
2537
+ ["ai-review.yml", new Map([["permissions", new Set(["id-token"])]])],
2538
+ ]);
2296
2539
 
2297
2540
  /**
2298
2541
  * Write a harness-managed file, preserving whatever the harness did not author.
@@ -2300,27 +2543,75 @@ const MANAGED_BANNER_PREFIX = "# Managed by rungate";
2300
2543
  * Throws on refusal. Callers decide whether a refusal aborts the run or is
2301
2544
  * recorded and reported; what they may not do is write anyway.
2302
2545
  */
2546
+ /**
2547
+ * How a managed file carries the record of who wrote it (#767).
2548
+ *
2549
+ * Optional, because most managed files have no marker. When present it is
2550
+ * applied LAST, to the bytes that land on disk, and stripped from both sides
2551
+ * of every comparison — a marker that describes anything other than the file
2552
+ * it is attached to is worse than no marker, because the census believes it.
2553
+ */
2554
+ export interface WriteProvenance {
2555
+ /** The document with its marker line removed. */
2556
+ body(text: string): string;
2557
+ /** The document with a marker describing its own body. */
2558
+ stamp(text: string): string;
2559
+ }
2560
+
2303
2561
  export function writeManagedFile(
2304
2562
  filePath: string,
2305
2563
  generated: string,
2306
2564
  label: string,
2307
2565
  actions: string[],
2308
- opts: { force?: boolean } = {},
2566
+ opts: { force?: boolean; workflowOverrides?: readonly string[]; computedSubKeys?: ComputedSubKeys } = {},
2567
+ provenance?: WriteProvenance,
2309
2568
  ): void {
2310
- const existing = existsSync(filePath) ? readFileSync(filePath, "utf-8") : null;
2311
- const resolved = resolveManagedWrite(existing, generated);
2569
+ const raw = existsSync(filePath) ? readFileSync(filePath, "utf-8") : null;
2570
+ // The marker is stripped from BOTH sides before anything compares them, and
2571
+ // re-applied to whatever is about to be written (#767).
2572
+ //
2573
+ // It has to be both sides and it has to be last. `resolveManagedWrite`
2574
+ // treats every line outside a job as the consumer's, so the OLD marker —
2575
+ // which differs from the new one exactly when the generator changed — read
2576
+ // as content about to be dropped and REFUSED the write. And stamping the
2577
+ // generated text before the merge produced a file whose marker described
2578
+ // bytes that were never written, so a workflow with one preserved job was
2579
+ // classified `generated-and-hand-edited` for ever, about bytes the harness
2580
+ // itself had just written.
2581
+ const existing = raw === null ? null : (provenance ? provenance.body(raw) : raw);
2582
+ const incoming = provenance ? provenance.body(generated) : generated;
2583
+ // What the marker proves about the bytes on disk, read HERE because here is
2584
+ // the only layer that still holds them (#957). Everything below this line
2585
+ // has had the marker stripped, which is the whole reason #941 could not
2586
+ // repair the residue it left: the merge was handed a file with no way of
2587
+ // telling its own old output from the consumer's.
2588
+ //
2589
+ // One expression, over the `WriteProvenance` the caller already supplies:
2590
+ // re-stamping the body reproduces the file exactly when the marker is
2591
+ // present AND describes that body. An absent marker and a stale one are both
2592
+ // UNPROVEN, which is the only distinction the merge acts on, and a managed
2593
+ // file with no provenance at all reads as UNPROVEN too — the fail-closed
2594
+ // direction and the pre-#957 behaviour unchanged.
2595
+ const proven: MergeProvenance =
2596
+ provenance !== undefined && raw !== null && provenance.stamp(provenance.body(raw)) === raw
2597
+ ? "VERIFIED"
2598
+ : "UNPROVEN";
2599
+ const resolved = resolveManagedWrite(existing, incoming, opts.workflowOverrides ?? [], proven, opts.computedSubKeys ?? new Map());
2600
+ /** The bytes that land on disk: the decision's content, then the marker. */
2601
+ const stamped = (content: string): string => (provenance ? provenance.stamp(content) : content);
2312
2602
 
2313
2603
  if (opts.force) {
2314
2604
  // The escape hatch, and it still reports a measured verb: --force changes
2315
2605
  // what is ALLOWED, not what gets claimed about it. The dropped jobs are
2316
2606
  // still named, because an operator who overrides the refusal should be
2317
2607
  // told in the report exactly what they overrode.
2318
- const { verb, lineDelta } = measureWrite(existing, generated);
2319
- if (verb === "SKIP") { actions.push(`SKIP: ${label} (unchanged)`); return; }
2608
+ const bytes = stamped(incoming);
2609
+ if (bytes === raw) { actions.push(`SKIP: ${label} (unchanged)`); return; }
2610
+ const { verb, lineDelta } = measureWrite(existing, incoming);
2320
2611
  const dropped = resolved.droppedJobs.length > 0 ? `, dropped ${resolved.droppedJobs.join(", ")}` : "";
2321
2612
  mkdirSync(dirname(filePath), { recursive: true });
2322
- writeFileSync(filePath, generated);
2323
- actions.push(`${verb}: ${label} (--force, ${signed(lineDelta)} lines${dropped})`);
2613
+ writeFileSync(filePath, bytes);
2614
+ actions.push(`${verb === "SKIP" ? "UPDATED" : verb}: ${label} (--force, ${signed(lineDelta)} lines${dropped})`);
2324
2615
  return;
2325
2616
  }
2326
2617
 
@@ -2343,16 +2634,350 @@ export function writeManagedFile(
2343
2634
  `${over.slice(0, 2).map(l => JSON.stringify(l)).join(", ")}` +
2344
2635
  `${over.length > 2 ? ` and ${over.length - 2} more` : ""}`;
2345
2636
 
2346
- if (resolved.verb === "SKIP") {
2637
+ const bytes = stamped(resolved.content);
2638
+
2639
+ // Compared as BYTES, not as a verb. `resolved.verb` is a statement about
2640
+ // the bodies, and a file whose body is unchanged can still need writing —
2641
+ // its marker may be absent or describe something else. Reporting SKIP on
2642
+ // that file is how the stamp stayed wrong across every later run.
2643
+ if (bytes === raw) {
2347
2644
  actions.push(`SKIP: ${label} (unchanged${kept})`);
2348
2645
  return;
2349
2646
  }
2350
2647
 
2351
2648
  mkdirSync(dirname(filePath), { recursive: true });
2352
- writeFileSync(filePath, resolved.content);
2353
- actions.push(`${resolved.verb}: ${label} (${signed(resolved.lineDelta)} lines${kept}${overwrote})`);
2649
+ writeFileSync(filePath, bytes);
2650
+ if (resolved.verb === "SKIP") {
2651
+ // Body identical, marker not. Said plainly rather than as `UPDATED (+0
2652
+ // lines)`, which is the line an operator reads as "my generator change
2653
+ // landed" (#767).
2654
+ actions.push(`UPDATED: ${label} (provenance marker refreshed, +0 lines${kept})`);
2655
+ } else {
2656
+ actions.push(`${resolved.verb}: ${label} (${signed(resolved.lineDelta)} lines${kept}${overwrote})`);
2657
+ }
2658
+ actions.push(...revocationActions(label, resolved.revokedGrants));
2659
+ }
2660
+
2661
+ /**
2662
+ * One line per grant the merge withdrew (#923).
2663
+ *
2664
+ * Its OWN line rather than a parenthetical on the write, and after the write
2665
+ * rather than folded into it. "REPLACED (-74 lines)" is already true of a
2666
+ * re-scaffold that withdraws nothing, so a consumer cannot read a withdrawal
2667
+ * out of it, and the thing being reported is not a line count: a standing
2668
+ * right to mint a credential has been taken away. That is the fact #631 says
2669
+ * nobody audits, and burying it inside a byte-delta is how it goes on not
2670
+ * being audited.
2671
+ *
2672
+ * The reason given is the one THIS layer actually knows — the generator
2673
+ * computes this sub-key and has stopped computing it — and not the config
2674
+ * entry that drove it. The merge cannot see `ci.vertex`; a sentence naming it
2675
+ * here would be a second, unverified reading of the generator's own decision,
2676
+ * and it would be wrong the first time a different sub-key joins the map.
2677
+ */
2678
+ function revocationActions(label: string, revoked: readonly RevokedSubKey[]): string[] {
2679
+ return revoked.map(
2680
+ r =>
2681
+ `REVOKED: ${label} no longer declares \`${r.section}: ${r.key}\` — the harness ` +
2682
+ `computes that sub-key and this project's \`ci\` config no longer produces it, so ` +
2683
+ `the grant has nothing left to justify it. Name \`${r.section}\` in ` +
2684
+ `\`ci.workflowOverrides\` to keep it, and re-scaffold.`,
2685
+ );
2354
2686
  }
2355
2687
 
2688
+ /** One globally installed CI tool, and the exact version it is pinned to. */
2689
+ export interface GlobalToolPin {
2690
+ package: string;
2691
+ version: string;
2692
+ }
2693
+
2694
+ export interface GlobalToolDecision {
2695
+ /** YAML spliced into the test job ahead of the test step. Never empty. */
2696
+ step: string;
2697
+ /** What will be installed, in declaration order. */
2698
+ pins: GlobalToolPin[];
2699
+ /** Why this and not something else. */
2700
+ reason: string;
2701
+ /** Declarations refused, each naming itself, so the omission is visible. */
2702
+ rejected: string[];
2703
+ }
2704
+
2705
+ /** An npm package name, optionally scoped. Excludes every shell metacharacter. */
2706
+ const SAFE_GLOBAL_TOOL_PACKAGE = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
2707
+
2708
+ /**
2709
+ * An EXACT version. Deliberately not a semver test and deliberately not a
2710
+ * range: `^1.2.0`, `latest` and `next` all resolve to whatever shipped today,
2711
+ * which is the state #597 is about, and admitting one here would be a fix
2712
+ * that looks like the fix while reintroducing the defect.
2713
+ */
2714
+ const PINNED_GLOBAL_TOOL_VERSION = /^[0-9][A-Za-z0-9.+-]*$/;
2715
+
2716
+ /**
2717
+ * A value on its way into a generated YAML comment.
2718
+ *
2719
+ * Only REJECTED entries ever reach a comment, and they are rejected precisely
2720
+ * because they did not match the two charsets above — so this is the one
2721
+ * place in the generator that formats a string nothing has validated. A
2722
+ * newline in it ends the comment, and the next line is a step.
2723
+ *
2724
+ * That was live, not theoretical. Before this function existed, a config
2725
+ * declaring a package named `pwned\n - name: Injected step\n
2726
+ * run: echo INJECTED` produced a generated `ci.yml` containing exactly that
2727
+ * step, runnable. The version field did the same, and a config pairing one
2728
+ * VALID pin with one evil entry injected through the success path too,
2729
+ * because the refusals string is appended there as well.
2730
+ *
2731
+ * The accepted path does not need this — it is charset-validated and single
2732
+ * quoted, two defences chosen to agree. The rejection path is the one that
2733
+ * handles hostile input by definition, which is what made it the hole: the
2734
+ * branch whose whole job is to refuse an unsafe declaration was the branch
2735
+ * that emitted it verbatim.
2736
+ */
2737
+ function commentSafe(value: string): string {
2738
+ return value.replace(/[\r\n]+/g, " ").replace(/[^\x20-\x7e]/g, "?").slice(0, 120);
2739
+ }
2740
+
2741
+ /**
2742
+ * The global-install step for the generated CI test job (#597).
2743
+ *
2744
+ * `lib/compliance.ts` decides three Layer 1 verdicts by spawning `agnix` and
2745
+ * `npx @reporails/cli`. CI installed neither, so the registry's mood at that
2746
+ * moment was the verdict — an identical SHA re-ran red to green with no code
2747
+ * change. The versions live in ONE position, `ci.globalTools` in
2748
+ * `.claude/rungate/config.json`; this function carries none of them, for the
2749
+ * same reason `setupBunWith` carries no Bun version (#622) and the test step
2750
+ * carries no command (#488).
2751
+ *
2752
+ * It returns LINES rather than writing, which is what lets a test assert the
2753
+ * emission for a declaration no registry has ever served.
2754
+ *
2755
+ * `npm install -g` rather than `bun add -g`: the consumers are
2756
+ * `probeExternalTool("agnix", …)`, which wants a binary on PATH, and
2757
+ * `npx @reporails/cli`, which resolves through npm.
2758
+ *
2759
+ * The absent case emits a REASON, not silence —
2760
+ * `.claude/rules/config-access.md`: `0`, `{}`, `null` and nothing at all are
2761
+ * indistinguishable from success. Same shape as `typecheckStep` below.
2762
+ */
2763
+ /**
2764
+ * How many CI shards to split the test files across (#728).
2765
+ *
2766
+ * One exported binding, read off the same `ci` object as its siblings, so
2767
+ * there is one thing to mutate and the generator cannot grow a second
2768
+ * opinion about the shard count.
2769
+ *
2770
+ * **Absent means 1, and 1 means the single-job workflow byte for byte.** A
2771
+ * consumer who has never configured this gets exactly what they have today;
2772
+ * sharding is something a project opts into once its suite is slow enough to
2773
+ * be worth the runners.
2774
+ *
2775
+ * Refuses anything that is not a positive whole number, and refuses silently
2776
+ * upward rather than downward — a malformed value yields 1 (no sharding),
2777
+ * never 0 shards, because a matrix with an empty list runs NO tests and
2778
+ * reports success. `0`, `{}` and `null` are indistinguishable from a clean
2779
+ * result (`.claude/rules/config-access.md`); a suite that ran nothing and a
2780
+ * suite that passed must not produce the same verdict.
2781
+ *
2782
+ * Capped at 32: the shard count becomes a matrix leg, and an unbounded value
2783
+ * read from config is an unbounded number of runners billed to whoever
2784
+ * mistyped it.
2785
+ */
2786
+ export function shardCount(ci: unknown): number {
2787
+ const raw = (ci as { shards?: unknown } | null | undefined)?.shards;
2788
+ if (typeof raw !== "number" || !Number.isInteger(raw) || raw < 1) return 1;
2789
+ return Math.min(raw, 32);
2790
+ }
2791
+
2792
+ /**
2793
+ * Top-level workflow keys this consumer has taken back from the generator
2794
+ * (#839). Declared in `lib/scaffold/managed-workflow.ts`, beside the merge
2795
+ * that consumes it and the notice it makes the merge write.
2796
+ *
2797
+ * Re-exported from here, unmoved as far as every caller is concerned, because
2798
+ * `lib/conformity.ts` needs the same reading (#915) and importing this module
2799
+ * to get it would pull the whole scaffold generator graph — the scanner, the
2800
+ * spec auditor, every generator — into the conformity suite of every consumer
2801
+ * project. `managed-workflow.ts` imports `crypto` and nothing else.
2802
+ *
2803
+ * One binding, so there is one thing to mutate. A second reader in
2804
+ * `conformity.ts` would agree with this one on every input the suite has, and
2805
+ * two deciders that agree are behaviourally one
2806
+ * (`.claude/rules/checks-must-be-able-to-fail.md`, fourth shape).
2807
+ */
2808
+ export { workflowOverrides } from "./managed-workflow";
2809
+
2810
+ export function globalToolInstallStep(ci: unknown, indent = " "): GlobalToolDecision {
2811
+ const declared = (ci as { globalTools?: unknown } | null | undefined)?.globalTools;
2812
+ const entries =
2813
+ declared !== null && typeof declared === "object" && !Array.isArray(declared)
2814
+ ? Object.entries(declared as Record<string, unknown>)
2815
+ : [];
2816
+
2817
+ const pins: GlobalToolPin[] = [];
2818
+ const rejected: string[] = [];
2819
+ for (const [name, raw] of entries) {
2820
+ const version = typeof raw === "string" ? raw.trim() : "";
2821
+ if (!SAFE_GLOBAL_TOOL_PACKAGE.test(name)) {
2822
+ rejected.push(`${commentSafe(name)}@${commentSafe(version) || "(nothing)"} (not an npm package name)`);
2823
+ continue;
2824
+ }
2825
+ if (!PINNED_GLOBAL_TOOL_VERSION.test(version)) {
2826
+ rejected.push(`${commentSafe(name)}@${commentSafe(version) || "(nothing)"} (not an exact version)`);
2827
+ continue;
2828
+ }
2829
+ pins.push({ package: name, version });
2830
+ }
2831
+
2832
+ const refusals = rejected.length === 0 ? "" : ` Refused, and so NOT installed: ${rejected.join("; ")}.`;
2833
+
2834
+ if (pins.length === 0) {
2835
+ const reason =
2836
+ entries.length === 0 ? "the config declares no ci.globalTools" : "every ci.globalTools entry was refused";
2837
+ return { step: `\n${indent}# No global tools installed: ${reason}.${refusals}`, pins, reason, rejected };
2838
+ }
2839
+
2840
+ // Validated AND quoted, chosen to agree: the charset above admits nothing
2841
+ // the single quotes would have to defend against, which is what makes
2842
+ // neither defence a place for the other to be relaxed.
2843
+ const specs = pins.map(p => `'${p.package}@${p.version}'`).join(" ");
2844
+ return {
2845
+ // The versions appear on the `run:` line and nowhere else in the emitted
2846
+ // YAML, so a test asserting the pin is asserting the command rather than
2847
+ // a comment that happens to quote it.
2848
+ step:
2849
+ `\n${indent}# Pinned by ci.globalTools in .claude/rungate/config.json — one declaration (#597).` +
2850
+ (rejected.length === 0 ? "" : `\n${indent}#${refusals}`) +
2851
+ `\n${indent}- name: Install pinned global tools` +
2852
+ `\n${indent} run: npm install -g ${specs}`,
2853
+ pins,
2854
+ reason: `ci.globalTools pins ${pins.map(p => `${p.package}@${p.version}`).join(", ")}`,
2855
+ rejected,
2856
+ };
2857
+ }
2858
+
2859
+ /**
2860
+ * The top-level concurrency block for the CI workflow.
2861
+ *
2862
+ * The GROUP does the work here, not the flag. A run can only be cancelled by
2863
+ * another run in the SAME group, so a key that is unique per main commit makes
2864
+ * the question moot — there is never a second occupant to do the cancelling.
2865
+ *
2866
+ * #937 tried the other arrangement: a ref-keyed group with
2867
+ * `cancel-in-progress: ${{ github.event_name == 'pull_request' }}`. It does not
2868
+ * work. Measured on this repository's own main after it shipped (#952): three
2869
+ * push runs cancelled inside eight minutes with that expression in the file,
2870
+ * one of them one second after the next run was created, and every cancelled
2871
+ * run had job count 0 — cancellation at queue time. The mechanism is
2872
+ * UNMEASURED; the leading hypothesis is that the result coerces to the
2873
+ * non-empty string "false", which is truthy. This form does not depend on
2874
+ * knowing which, and that is the point of choosing it.
2875
+ *
2876
+ * The three events:
2877
+ *
2878
+ * - A pull request's ref is `refs/pull/<n>/merge`, unique to that PR, so a
2879
+ * new push to PR #5 can only ever cancel PR #5. Superseding it is the
2880
+ * point: the older commit's result is about code nobody will merge.
2881
+ *
2882
+ * - A push to main shares ONE ref with every other push to main. Two merges
2883
+ * landing within a few minutes cancel the first, and the first is the only
2884
+ * run that ever builds that commit — a gap in main's history with no red
2885
+ * check anywhere to say so. Measured on one consumer: five cancelled runs,
2886
+ * all of them main pushes, and the `test` job runs on main push there, so
2887
+ * what was lost was a test result and not just a container build. The repo
2888
+ * and the run IDs are on #937 — the harness does not name its consumers
2889
+ * (#304), and `test/anti.test.ts` SC-A1 is the check that says so.
2890
+ *
2891
+ * - `merge_group` must not be cancelled either. A queue entry builds its own
2892
+ * `gh-readonly-queue/...` ref, so it is already alone in its group, and
2893
+ * cancelling one mid-flight dequeues the PR behind it.
2894
+ *
2895
+ * So: a push keys on `github.sha`, unique per commit and therefore never
2896
+ * shared. Everything else keys on `github.ref`, which is unique per pull
2897
+ * request and per queue entry but STABLE across pushes to the same PR — which
2898
+ * is what lets a PR supersede itself, the one case where cancelling is right.
2899
+ *
2900
+ * This is a SUB-KEY merge under `mergeManagedWorkflow`: a consumer that already
2901
+ * declares `cancel-in-progress` keeps its own value, and this reaches only the
2902
+ * consumers that have no concurrency block at all.
2903
+ */
2904
+ /**
2905
+ * The `on.pull_request` trigger, carrying NO `branches:` filter — the one
2906
+ * shared binding every generated workflow renders (#1136).
2907
+ *
2908
+ * The filter used to be the same `branchList` emitted under `on.push`, which
2909
+ * made a pull request whose BASE was a feature branch match nothing and
2910
+ * trigger nothing: no `test`, no shards, no `gates`, no `ai-review`. Measured
2911
+ * on this repository before the change, by full 40-char head SHA — a short SHA
2912
+ * silently returns zero runs, so the two look identical and the query must use
2913
+ * the full one:
2914
+ *
2915
+ * witness #1128 base feat/713-migrate-product-hooks 0 runs
2916
+ * witness #1133 base feat/713-migrate-product-hooks 0 runs
2917
+ * control #1125 base main 3 runs
2918
+ * control #1134 base main 3 runs
2919
+ *
2920
+ * Base branch is the only input that differs. Both witnesses merged: with no
2921
+ * workflow triggered there is no required check left pending, so a pull
2922
+ * request that measured NOTHING is reported to the merge box exactly as a
2923
+ * green one is. That is the half worth naming — the gap is invisible from the
2924
+ * side that acts on it.
2925
+ *
2926
+ * `on.push` KEEPS its filter, and that is not an oversight. The two keys
2927
+ * answer different questions: `push.branches` is "which branches earn a CI run
2928
+ * on their own", `pull_request.branches` was answering "which bases may be
2929
+ * merged into", which nothing here ever wanted to ask. Deleting `branchList`
2930
+ * from both — the cheapest wrong fix, and it does turn every witness above
2931
+ * green — fires a full CI run on every push to every feature branch on top of
2932
+ * the `pull_request` run already covering that commit. Sampled over 25 recent
2933
+ * merged PRs: 44 commits, mean 1.76 pushes each, against 72 push-event runs in
2934
+ * the last 300. Roughly an order of magnitude of duplicated runner time for no
2935
+ * new coverage. The `on.push` cases in test/stacked-pr-ci-trigger.test.ts are
2936
+ * the control that stays red for it.
2937
+ *
2938
+ * Enumerating the namespaces instead (`feat/**`, `fix/**`) would have covered
2939
+ * all 6 of the non-`main`-based PRs in the last 200, so history cannot falsify
2940
+ * it. The prospective count can: of those 200, 24 head branches sit outside
2941
+ * both namespaces — `chore/`, `rg/`, `wt/`, `docs/`, `revert/`, bare names —
2942
+ * and any of them can be a base tomorrow. An allowlist re-creates this exact
2943
+ * defect the first time someone picks a prefix nobody enumerated, and does it
2944
+ * silently, which is the property that made #1136 cost two merges.
2945
+ */
2946
+ export const CI_PULL_REQUEST_TRIGGER = ` # NO branches: filter, deliberately (#1136). A pull request based on a
2947
+ # feature branch matched no entry here and so triggered nothing at all —
2948
+ # and because no required check was left pending, it reported CLEAN. A
2949
+ # stack is how multi-part work is built in this repo, so the changes
2950
+ # least likely to run CI were the ones most likely to need it.
2951
+ #
2952
+ # Where a \`push\` trigger exists it KEEPS its filter — that key asks which
2953
+ # branches earn a run on their own, which is a different question.
2954
+ # Removing it there too duplicates a run on every feature-branch push for
2955
+ # no new coverage.
2956
+ pull_request:`;
2957
+
2958
+ export const CI_CONCURRENCY = `# The GROUP does the work here, not the flag. A run is only ever cancelled by
2959
+ # another run in the SAME group, so keying a push on its own commit makes the
2960
+ # question moot: there is never a second occupant to do the cancelling.
2961
+ #
2962
+ # A push to \`main\` keys on \`github.sha\`, unique per commit. Every other main
2963
+ # run is in a different group and nothing can cancel it. That matters because
2964
+ # a main run is the ONLY run that will ever build that commit, so losing it
2965
+ # leaves a gap in main's history with no red check anywhere saying so.
2966
+ #
2967
+ # Everything else keys on \`github.ref\`: unique per pull request
2968
+ # (\`refs/pull/<n>/merge\`) and per merge-queue entry
2969
+ # (\`gh-readonly-queue/...\`), but STABLE across pushes to the same pull
2970
+ # request — which is what lets a pull request supersede itself, the one case
2971
+ # where cancelling is the right answer.
2972
+ #
2973
+ # Do NOT "simplify" this to a ref-keyed group with an event expression in
2974
+ # cancel-in-progress. That was tried and measured: three main-push runs
2975
+ # cancelled inside eight minutes with the expression in place.
2976
+ concurrency:
2977
+ group: ci-\${{ github.event_name == 'push' && github.sha || github.ref }}
2978
+ cancel-in-progress: true
2979
+ `;
2980
+
2356
2981
  export function createCiWorkflows(root: string, actions: string[], opts: { force?: boolean } = {}): void {
2357
2982
  const workflowsDir = join(root, ".github", "workflows");
2358
2983
  if (!existsSync(workflowsDir)) {
@@ -2407,16 +3032,51 @@ export function createCiWorkflows(root: string, actions: string[], opts: { force
2407
3032
  // is the gap, not the absence of a validator.
2408
3033
  const baseBranch = String(branches[0] ?? "main");
2409
3034
  const SAFE_BRANCH = /^[A-Za-z0-9][A-Za-z0-9._\/-]*$/;
3035
+ // #987. This step used to be unconditionally `--depth=200`, and that flag is
3036
+ // what made `fetch-depth: 0` above it inert: a bounded `git fetch`
3037
+ // RE-SHALLOWS a repository that was already complete. Measured on a complete
3038
+ // 40-commit clone, `is-shallow-repository` goes false → true and
3039
+ // `rev-list --count HEAD` drops 40 → 20. The depth is therefore derived from
3040
+ // the checkout's own, in `lib/ci-history-depth.ts`, rather than written here
3041
+ // as a second number that has to agree with the first.
3042
+ //
3043
+ // Unbounded is not expensive in the full-history case: the objects are
3044
+ // already local, so the fetch updates a ref and transfers nothing.
3045
+ const baseDepth = baseRefFetchDepth(CI_SUITE_FETCH_DEPTH);
3046
+ const baseDepthFlag = baseDepth === null ? "" : `--depth=${baseDepth} `;
3047
+
3048
+ // #987. `actions/checkout` with nothing declared clones ONE commit, so every
3049
+ // generated job that reads git history has been reading one commit since the
3050
+ // first workflow this harness wrote. `lib/failure-intake.ts` refuses a
3051
+ // shallow clone by name, which means its reading was UNMEASURED on every run
3052
+ // on every runner — uniformly absent rather than occasionally missing, and
3053
+ // absence looked like quiet.
3054
+ //
3055
+ // Both generated jobs declare it, not just the suite job. `test/scaffold-
3056
+ // conformity.test.ts` calls `runDocHygiene`, HYGIENE-6 inside it is the
3057
+ // intake's only caller, and the gates job names that file directly while the
3058
+ // suite job reaches it through the test command.
3059
+ //
3060
+ // The cost, measured on this repository three times each: depth 1 is
3061
+ // 1.23–1.64s for 6MB, full history is 1.43–1.64s for 13MB. A bounded middle
3062
+ // was measured too and is the worst of the three — 1.54–2.75s for 9MB, and
3063
+ // still UNMEASURED, because a shallow clone is shallow whatever its depth.
3064
+ const checkoutStep = ` - uses: ${actionRef("actions/checkout")}
3065
+ with:
3066
+ # Full history. A bounded depth leaves .git/shallow behind, and
3067
+ # lib/failure-intake.ts refuses on that file rather than on a commit
3068
+ # count — so any bounded value here reports UNMEASURED (#987).
3069
+ # Declared once, in lib/ci-history-depth.ts.
3070
+ fetch-depth: ${CI_SUITE_FETCH_DEPTH}`;
2410
3071
  const baseRefStep =
2411
3072
  SAFE_BRANCH.test(baseBranch) && !baseBranch.includes("..")
2412
- ? // `--depth=200`, not `--depth=1`. The conformity ratchet only diffs the
2413
- // tip and was happy with one commit, but a tip with no history behind
2414
- // it makes any check that reads the recent log unmeasurable — and an
2415
- // empty log is indistinguishable from a clean one. Two hundred commits
2416
- // is a few hundred KB and spans months of this project's history.
3073
+ ? // The conformity ratchet only diffs the tip and was happy with one
3074
+ // commit, but a tip with no history behind it makes any check that
3075
+ // reads the recent log unmeasurable — and an empty log is
3076
+ // indistinguishable from a clean one.
2417
3077
  ` - name: Fetch the comparison base for the conformity ratchet
2418
3078
  run: |
2419
- git fetch --no-tags --depth=200 origin '+refs/heads/${baseBranch}:refs/remotes/origin/${baseBranch}' \\
3079
+ git fetch --no-tags ${baseDepthFlag}origin '+refs/heads/${baseBranch}:refs/remotes/origin/${baseBranch}' \\
2420
3080
  || echo "WARN: could not fetch ${baseBranch}; the conformity allowlist growth check will report UNMEASURED."`
2421
3081
  : // Not a fetchable ref: a glob pattern, a leading dash, or a traversal
2422
3082
  // segment. Emitted as a comment so the omission is visible in the
@@ -2444,32 +3104,165 @@ export function createCiWorkflows(root: string, actions: string[], opts: { force
2444
3104
  // binding can show the agreement is load-bearing.
2445
3105
  const test = testCommandDecision(root);
2446
3106
 
3107
+ // #597. The Layer 1 compliance checks shell out to agnix and
3108
+ // @reporails/cli; CI installed neither, so what the registry served at that
3109
+ // moment decided the verdict. Pinned from the one declaration, never a
3110
+ // literal here.
3111
+ const globalTools = globalToolInstallStep(harness?.ci);
3112
+
2447
3113
  const typecheck = typecheckDecision(root);
2448
3114
  const typecheckStep = typecheck.command
2449
3115
  ? `\n - run: ${typecheck.command}`
2450
3116
  : `\n # No type check: ${typecheck.reason}.`;
2451
3117
 
2452
- const ciYml = `# Managed by rungate — do not edit. Customize the ci section of .claude/rungate/config.json.
3118
+ // #728. A suite is a wall every branch pays, and this one was 313s of a
3119
+ // 376s run — one `bun test` on one runner, 13,562 tests, while `strict`
3120
+ // branch protection makes every merge re-run it. Sharding splits the FILES
3121
+ // across runners, which is not the same lever as `--parallel`: that one was
3122
+ // tried, and #621 records it starving 122 I/O-bound tests past bun's
3123
+ // per-test timeout so every ship run reported SHIP_PASSED_SUITE_FAILED over
3124
+ // a tree with zero real failures. Separate runners give each shard a whole
3125
+ // machine, so the starvation mechanism is absent by construction.
3126
+ //
3127
+ // Opt-in, and absent config means one shard and the single-job shape byte
3128
+ // for byte — a consumer who has never heard of this gets what they have
3129
+ // today. `shard` is read from the same `harness?.ci` binding as every
3130
+ // sibling above rather than a second reader.
3131
+ const shards = shardCount(harness?.ci);
3132
+
3133
+ // #839. Which top-level keys this consumer has taken back, read from the
3134
+ // same binding as every sibling above rather than a second reader. Absent
3135
+ // config means none, and none means the generator's structural keys reach
3136
+ // every workflow it has ever written — which is the whole point of the
3137
+ // change this config exists to make reversible.
3138
+ const declined = workflowOverrides(harness?.ci);
3139
+
3140
+ // The required status check is the JOB NAME, and a matrix renames it:
3141
+ // `test` becomes `test (1)`, `test (2)`. A repo whose protection requires
3142
+ // `test` would then require a context nothing ever reports, and GitHub
3143
+ // treats an absent required check as pending forever — every PR wedged,
3144
+ // with no error anywhere saying why. So the matrix is `test-shard` and a
3145
+ // dependent job keeps the name `test`, which is the context protection
3146
+ // already names. Do not collapse these two jobs.
3147
+ const ciYml = shards > 1
3148
+ ? `# Managed by rungate — do not edit. Customize the ci section of .claude/rungate/config.json.
2453
3149
  name: CI
2454
3150
 
2455
3151
  on:
3152
+ # Re-run this workflow on demand, on any ref. Without the trigger the
3153
+ # Actions API refuses with \`HTTP 422: Workflow does not have
3154
+ # 'workflow_dispatch' trigger\` — measured on 2026-10-21 across the fleet,
3155
+ # where 5 of 6 re-run attempts came back 422. The cost is not the button: a
3156
+ # flake cannot be told from a real failure without pushing an empty commit,
3157
+ # and a fix landed on the default branch cannot be confirmed until unrelated
3158
+ # traffic happens to arrive (#940).
3159
+ workflow_dispatch:
3160
+ # merge_group carries NO branches: filter, deliberately. A merge queue builds
3161
+ # a temporary \`gh-readonly-queue/<base>/...\` ref, which no branch list here
3162
+ # would match — so filtering it is the same as not handling the event, and a
3163
+ # trigger that is present and inert is worse than an absent one because the
3164
+ # file then reads as handling it.
3165
+ #
3166
+ # Without this trigger a merge queue cannot work at all, and it fails in the
3167
+ # worst available way: the queue waits for a required check that will never
3168
+ # report, every entry sits pending with no error anywhere, and the repo looks
3169
+ # like it has simply stopped merging. UNMEASURED, not red.
3170
+ #
3171
+ # This is the SHARDED body, and it is the one that matters most: the required
3172
+ # context is the \`test\` aggregate below, which only exists here. The first
3173
+ # draft of #765 added the trigger to the unsharded body only — 91 tests passed
3174
+ # and the repo that needed it was untouched.
3175
+ merge_group:
2456
3176
  push:
2457
3177
  branches:
2458
3178
  ${branchList}
2459
- pull_request:
3179
+ ${CI_PULL_REQUEST_TRIGGER}
3180
+
3181
+ ${CI_CONCURRENCY}
3182
+ permissions:
3183
+ # Least privilege, and it matters most on the consumers. A workflow with
3184
+ # no permissions: block inherits the REPOSITORY default, which is a setting
3185
+ # the harness does not control and cannot read at generation time. Measured
3186
+ # 2026-10-20 across the consumers this harness serves: the default is
3187
+ # read-only on some and WRITE on others, so a generated job that declares
3188
+ # nothing holds a push-capable GITHUB_TOKEN wherever the default is write.
3189
+ # Neither job needs it: both check out, install and run tests.
3190
+ contents: read
3191
+
3192
+ jobs:
3193
+ test-shard:
3194
+ runs-on: ${runsOn}
3195
+ strategy:
3196
+ # One red shard must not cancel the others: the whole point is to see
3197
+ # every failure in one run rather than re-running to find the next.
3198
+ fail-fast: false
3199
+ matrix:
3200
+ shard: [${Array.from({ length: shards }, (_, i) => i + 1).join(", ")}]
3201
+ steps:
3202
+ ${checkoutStep}
3203
+ ${baseRefStep}
3204
+ - uses: ${actionRef("oven-sh/setup-bun")}
3205
+ with:
3206
+ ${bunStep}
3207
+ - run: bun install${globalTools.step}${ciSetupStep()}
3208
+ - run: ${test.command} --shard=\${{ matrix.shard }}/${shards}${typecheckStep}
3209
+
3210
+ # The aggregate. Named "test" because that is the context branch protection
3211
+ # requires; it exists to turn N shard results into the one verdict.
3212
+ test:
3213
+ runs-on: ${runsOn}
3214
+ needs: test-shard
3215
+ # always() so a failed or cancelled shard reaches this job instead of
3216
+ # skipping it. A skipped required check is not a failed one, and some
3217
+ # protection configurations read a skip as satisfied — which would make
3218
+ # this aggregate a gate that cannot refuse.
3219
+ if: always()
3220
+ steps:
3221
+ - name: Every shard passed
3222
+ run: |
3223
+ result='\${{ needs.test-shard.result }}'
3224
+ if [ "$result" != "success" ]; then
3225
+ echo "::error::test-shard concluded '$result' — the suite is not green."
3226
+ exit 1
3227
+ fi
3228
+ echo "All ${shards} shards passed."
3229
+ `
3230
+ : `# Managed by rungate — do not edit. Customize the ci section of .claude/rungate/config.json.
3231
+ name: CI
3232
+
3233
+ on:
3234
+ # See the sharded body above: a re-run of this workflow is a 422 without
3235
+ # this trigger, so a flake and a real failure are indistinguishable.
3236
+ workflow_dispatch:
3237
+ # See the sharded body above: no branches: filter, and its absence hangs a
3238
+ # merge queue silently rather than failing it.
3239
+ merge_group:
3240
+ push:
2460
3241
  branches:
2461
3242
  ${branchList}
3243
+ ${CI_PULL_REQUEST_TRIGGER}
3244
+
3245
+ ${CI_CONCURRENCY}
3246
+ permissions:
3247
+ # Least privilege, and it matters most on the consumers. A workflow with
3248
+ # no permissions: block inherits the REPOSITORY default, which is a setting
3249
+ # the harness does not control and cannot read at generation time. Measured
3250
+ # 2026-10-20 across the consumers this harness serves: the default is
3251
+ # read-only on some and WRITE on others, so a generated job that declares
3252
+ # nothing holds a push-capable GITHUB_TOKEN wherever the default is write.
3253
+ # Neither job needs it: both check out, install and run tests.
3254
+ contents: read
2462
3255
 
2463
3256
  jobs:
2464
3257
  test:
2465
3258
  runs-on: ${runsOn}
2466
3259
  steps:
2467
- - uses: actions/checkout@v4
3260
+ ${checkoutStep}
2468
3261
  ${baseRefStep}
2469
- - uses: oven-sh/setup-bun@v2
3262
+ - uses: ${actionRef("oven-sh/setup-bun")}
2470
3263
  with:
2471
3264
  ${bunStep}
2472
- - run: bun install
3265
+ - run: bun install${globalTools.step}${ciSetupStep()}
2473
3266
  - run: ${test.command}${typecheckStep}
2474
3267
  `;
2475
3268
 
@@ -2477,19 +3270,33 @@ ${bunStep}
2477
3270
  name: Gates
2478
3271
 
2479
3272
  on:
3273
+ # See ci.yml above: without this the Actions API refuses a re-run with a
3274
+ # 422, and the gates are the checks most worth re-running on their own.
3275
+ workflow_dispatch:
3276
+ # See ci.yml above: a merge queue builds a ref no branch list matches, so
3277
+ # this trigger carries no filter and its absence hangs the queue silently.
3278
+ merge_group:
2480
3279
  push:
2481
3280
  branches:
2482
3281
  ${branchList}
2483
- pull_request:
2484
- branches:
2485
- ${branchList}
3282
+ ${CI_PULL_REQUEST_TRIGGER}
3283
+
3284
+ permissions:
3285
+ # Least privilege, and it matters most on the consumers. A workflow with
3286
+ # no permissions: block inherits the REPOSITORY default, which is a setting
3287
+ # the harness does not control and cannot read at generation time. Measured
3288
+ # 2026-10-20 across the consumers this harness serves: the default is
3289
+ # read-only on some and WRITE on others, so a generated job that declares
3290
+ # nothing holds a push-capable GITHUB_TOKEN wherever the default is write.
3291
+ # Neither job needs it: both check out, install and run tests.
3292
+ contents: read
2486
3293
 
2487
3294
  jobs:
2488
3295
  gates:
2489
3296
  runs-on: ${runsOn}
2490
3297
  steps:
2491
- - uses: actions/checkout@v4
2492
- - uses: oven-sh/setup-bun@v2
3298
+ ${checkoutStep}
3299
+ - uses: ${actionRef("oven-sh/setup-bun")}
2493
3300
  with:
2494
3301
  ${bunStep}
2495
3302
  - run: bun install
@@ -2508,6 +3315,9 @@ ${bunStep}
2508
3315
  # CLAIM parity while CI carried 3 patterns and the hook carried 8 —
2509
3316
  # CI missed gho_, ghs_, github_pat_, sk-ant- and PEM private keys
2510
3317
  # entirely. Asserted now in test/unit/secret-patterns.test.ts.
3318
+ # Tier 1 also owns the signed JWT, because it is the one unquoted
3319
+ # credential whose shape is a dotted identifier path and so is
3320
+ # excused by the tier-2 exclusion below (#863).
2511
3321
  if git grep -I -lE '${tier1Ere()}' -- .; then
2512
3322
  echo "::error::Potential secrets detected in tracked files"
2513
3323
  exit 1
@@ -2519,8 +3329,14 @@ ${bunStep}
2519
3329
  # NOTE: do NOT append "|| true" to the assignment below. It makes the
2520
3330
  # assignment itself succeed, so $? is always 0 and the error branch
2521
3331
  # becomes dead code — the scan would fail open on a git error.
3332
+ # -i on tier 2 only, never on the tier-1 scan above: tier 1 matches
3333
+ # anchored key FORMATS whose case is part of the format, and it has
3334
+ # no allowlist to absorb a false positive. The flag is interpolated
3335
+ # from lib/secret-patterns.ts rather than typed here, because four
3336
+ # hand-written flags are four things that can disagree about what
3337
+ # counts as a secret (#844).
2522
3338
  set +e
2523
- tier2=$(git grep -I -hoE '(password|passwd|api[_-]?key|secret)[[:space:]]*[:=][[:space:]]*[A-Za-z0-9/+=_.-]{12,}' -- .)
3339
+ tier2=$(git grep -I -hoE ${TIER2_GREP_CASE_FLAG} '${tier2Ere()}' -- .)
2524
3340
  rc=$?
2525
3341
  set -e
2526
3342
  # git grep: 0 = match, 1 = no match, >1 = real error.
@@ -2531,30 +3347,321 @@ ${bunStep}
2531
3347
  # Exclusion applies to the extracted VALUE, not the whole line.
2532
3348
  # Matching anywhere on the line let a trailing "# placeholder"
2533
3349
  # launder a real secret past the check.
2534
- if printf '%s\\n' "$tier2" | grep -qvE '^$|[:=][[:space:]]*(process\\.env|os\\.environ|Deno\\.env|getenv|REDACTED|CHANGEME|placeholder)'; then
3350
+ # It reads case the same way the capture does, for a reason
3351
+ # recorded in lib/secret-patterns.ts: the population the capture
3352
+ # newly sees is mostly .env.example, where a non-value is spelled
3353
+ # CHANGEME and PLACEHOLDER (#844).
3354
+ # The last alternative excuses a DOTTED IDENTIFIER PATH, anchored at
3355
+ # both ends so the whole value must be one. The value charset has no
3356
+ # quote characters, so in source tier 2 only ever sees an unquoted
3357
+ # value, and an unquoted value is an expression: apiKey:
3358
+ # config.judge.apiKey is a property reference, not a credential
3359
+ # (#863). A JWT has the same shape and is a credential, which is why
3360
+ # the tier-1 scan above carries it.
3361
+ # The optional dash after the separator is the shell-default
3362
+ # separator, so the placeholder vocabulary can reach the value of a
3363
+ # NAME:-default form. That vocabulary is a closed list of documented
3364
+ # non-values, not a judgement that a value looks harmless: a 32-char
3365
+ # random default carries none of its words and is still reported.
3366
+ if printf '%s\\n' "$tier2" | grep -qvE ${TIER2_GREP_CASE_FLAG} '${TIER2_ALLOWED_VALUE_ERE}'; then
2535
3367
  echo "::error::Potential credential assignment in tracked files"
2536
3368
  exit 1
2537
3369
  fi
3370
+ # Tier 3 — a credential written as a shell default, caught by SHAPE
3371
+ # rather than by a name. Tier 2 can only see one whose variable name
3372
+ # carries credential vocabulary; a variable named for what it holds
3373
+ # is invisible to it, and every neighbouring line in such a block
3374
+ # genuinely is a default, so the one that is not sits in a list of
3375
+ # things that look alike (#848).
3376
+ #
3377
+ # Captured first for the same reason tier 2 is: piping git straight
3378
+ # into the filter turns an error into empty input, which reads as
3379
+ # clean. No "|| true" on the assignment — see the note above.
3380
+ #
3381
+ # No -i here, and that is not an oversight: tier 3 has no vocabulary
3382
+ # to spell in the wrong case. Its classes already cover both cases,
3383
+ # and the flag would only widen the value class.
3384
+ set +e
3385
+ tier3=$(git grep -I -hoE '${tier3Ere()}' -- .)
3386
+ rc=$?
3387
+ set -e
3388
+ if [ "$rc" -gt 1 ]; then
3389
+ echo "::error::git grep failed (exit $rc) — refusing to report a clean scan"
3390
+ exit 1
3391
+ fi
3392
+ # The exclusion is the discriminator, not the length floor: a value
3393
+ # with no digit or no letter is a path, a container name or a port,
3394
+ # and those are what this shape is full of.
3395
+ if printf '%s\\n' "$tier3" | grep -qvE '${TIER3_ALLOWED_VALUE_ERE}'; then
3396
+ echo "::error::Potential credential in a shell default in tracked files"
3397
+ exit 1
3398
+ fi
2538
3399
  echo "Secret scan clean"
2539
3400
  `;
2540
3401
 
3402
+ // #630. The ai-review job, and the one property that makes it a check
3403
+ // rather than a decoration: there is NO `if:` here, at job level or step
3404
+ // level. A job skipped by `if:` reports `skipped`, and a skipped required
3405
+ // check can be treated as satisfied — a green required check for a review
3406
+ // that never ran. `secrets` is unavailable in `if:` at any level anyway, so
3407
+ // the mode is resolved inside `run:`, where it can emit an annotation and
3408
+ // choose an exit code. The step text is `buildAuthDetectStep()`'s verbatim,
3409
+ // not a copy: one decider for the script, and a mutation of it has one
3410
+ // binding. See lib/scaffold/ai-review-step.ts.
3411
+ //
3412
+ // `pull_request` and `merge_group`, and NOT `push`. A review of a pull
3413
+ // request has nothing to say about a push to a branch, and a trigger that
3414
+ // fires where the job cannot do its work is a run whose outcome means
3415
+ // nothing.
3416
+ //
3417
+ // `merge_group` is the exception to that sentence, and #867 is why it had to
3418
+ // be. This job was `pull_request`-only on exactly the reasoning above: a
3419
+ // merge group has no pull request, so the review would be vacuous. True, and
3420
+ // the wrong conclusion — it is an argument about what the job can DO on the
3421
+ // event, and it was applied to whether the job REPORTS on it. A consumer
3422
+ // makes `ai-review` a required context precisely because it is the check
3423
+ // that reads the code; a required context that never reports does not fail
3424
+ // the queue, it HANGS it, with every entry pending and nothing red anywhere.
3425
+ //
3426
+ // So the trigger is here and the vacuousness is handled where it belongs, in
3427
+ // the report step, which exits 0 on this event and says in a notice that no
3428
+ // review ran and why. That is sound rather than a green check for nothing: a
3429
+ // pull request cannot enter a merge queue without first satisfying its
3430
+ // required checks, so `ai-review` has already run on that exact head commit.
3431
+ //
3432
+ // No `branches:` filter, for the reason ci.yml states at length: the queue
3433
+ // builds a `gh-readonly-queue/<base>/...` ref that no branch list matches,
3434
+ // so a filtered trigger is an absent one that reads as handled.
3435
+ // #631. Workload Identity Federation, read from the consumer's own config.
3436
+ // One reading, taken here and threaded into both the permission block and
3437
+ // the steps — a second `vertexCiConfig(...)` call beside either would be a
3438
+ // decider that always agrees with this one and could never be told apart
3439
+ // from it (`.claude/rules/checks-must-be-able-to-fail.md`, fourth shape).
3440
+ const vertex = vertexCiConfig(harness?.ci);
3441
+
3442
+ // `id-token: write` is what lets the runner mint the OIDC token GCP's STS
3443
+ // exchanges. Granted ONLY when there is a federation to use it, because a
3444
+ // permission nobody consumes is a permission nobody audits.
3445
+ const aiReviewPermissions =
3446
+ vertex.config === null
3447
+ ? `permissions:\n contents: read`
3448
+ : `permissions:\n contents: read\n # Mint the OIDC token Workload Identity Federation exchanges (#631).\n id-token: write`;
3449
+
3450
+ const aiReviewYml = `# Managed by rungate — do not edit. Customize the ci section of .claude/rungate/config.json.
3451
+ #
3452
+ ${buildOutcomesHeader(vertex)}#
3453
+ # This job is deliberately unconditional. A job skipped by a condition reports
3454
+ # \`skipped\`, which a required status check can be configured to accept, and
3455
+ # that is a green check for a review that never ran. The credential check
3456
+ # happens inside \`run:\` instead, and reports UNMEASURED when there is none.
3457
+ #
3458
+ # The second step says the same thing for the other door: a credential that
3459
+ # resolved with no reviewer wired to use it (#631) has also not produced a
3460
+ # review, and a check that stays quiet about that is the same defect.
3461
+ #
3462
+ # AUTHENTICATION. There is no service-account key in this file and no input
3463
+ # that could carry one. Vertex authenticates with Workload Identity
3464
+ # Federation: GitHub mints a short-lived OIDC token for this run, GCP's STS
3465
+ # exchanges it for an access token that expires in an hour, and no long-lived
3466
+ # credential exists anywhere on the runner (#677 AC-15). What this job holds
3467
+ # as read from this consumer's config:
3468
+ # ${vertex.reason}
3469
+ name: AI Review
3470
+
3471
+ on:
3472
+ # See the block comment in lib/scaffold/steps.ts: no branches: filter, and
3473
+ # its absence hangs a merge queue silently rather than failing it (#867).
3474
+ merge_group:
3475
+ ${CI_PULL_REQUEST_TRIGGER}
3476
+
3477
+ ${aiReviewPermissions}
3478
+
3479
+ jobs:
3480
+ ${AI_REVIEW_JOB}:
3481
+ runs-on: ${runsOn}
3482
+ steps:
3483
+ ${buildAuthDetectStep(vertex)}${buildReviewRunStep(
3484
+ vertex,
3485
+ {
3486
+ checkout: actionRef("actions/checkout"),
3487
+ auth: actionRef(GOOGLE_AUTH_ACTION),
3488
+ review: actionRef(CLAUDE_CODE_ACTION),
3489
+ setupBun: actionRef("oven-sh/setup-bun"),
3490
+ // The same single declaration the test and gates jobs resolve from
3491
+ // (#622), at the indent this job's step bodies use.
3492
+ setupBunWith: setupBunWith(declaredBunVersion(root), " "),
3493
+ },
3494
+ // #1013. The GENERATING version, and the same reading `harnessDevDepRange`
3495
+ // takes — one function, so a scaffold cannot write a `bunx rungate@X` next
3496
+ // to a `devDependencies` entry floored at a different minor.
3497
+ //
3498
+ // A tree running ahead of npm emits a command the registry cannot satisfy
3499
+ // yet, exactly as that function's own docstring describes for the
3500
+ // dependency range, and it becomes resolvable the moment the version
3501
+ // ships. It is not silent in the window: the adjudicator prints no outcome
3502
+ // line, and the verdict step reports UNMEASURED rather than reading the
3503
+ // failure as a refusal.
3504
+ harnessVersion(),
3505
+ )}`;
3506
+
2541
3507
  // Not `writeFileSync`. The harness owns the `test` and `gates` jobs; it does
2542
3508
  // not own the file, and a consumer's own jobs have to survive the update
2543
3509
  // that re-scaffolding IS. A refusal is recorded rather than thrown so that
2544
3510
  // one unpreservable workflow does not abandon the rest of the scaffold
2545
3511
  // half-done — scripts/scaffold-project.ts exits non-zero on it.
2546
- for (const [name, content] of [["ci.yml", ciYml], ["gates.yml", gatesYml]] as const) {
3512
+ // The filenames are spelled here, not read from a constant, because
3513
+ // test/release-guard.test.ts pins this tuple as a literal: a directory-wide
3514
+ // write would take the caller-owned workflows with it, and a name behind an
3515
+ // import is a name that assertion cannot see. (That test also asserts this
3516
+ // module names no workflow it does not write — prose is indistinguishable
3517
+ // from a write to it — so the caller-owned files are not spelled anywhere
3518
+ // here, this comment included.) `AI_REVIEW_WORKFLOW_FILE` is the spelling
3519
+ // lib/conformity.ts reads back, and the two are held together by
3520
+ // test/ai-review-workflow.test.ts AC-1, which looks for the constant's
3521
+ // filename in what this loop actually wrote.
3522
+ for (const [name, content] of [["ci.yml", ciYml], ["gates.yml", gatesYml], ["ai-review.yml", aiReviewYml]] as const) {
2547
3523
  const label = `.github/workflows/${name}`;
2548
3524
  try {
2549
- writeManagedFile(join(workflowsDir, name), content, label, actions, opts);
3525
+ // Keyed by FILE, and the lookup is here because this loop is the only
3526
+ // place that knows which file is being written (#923).
3527
+ const computedSubKeys = HARNESS_COMPUTED_SUBKEYS.get(name) ?? new Map();
3528
+ // Stamped, so the file says who wrote it. The owned-path list is a list
3529
+ // of files this generator writes, which is precisely why it could never
3530
+ // describe a file it does not write — ownership has to travel with the
3531
+ // bytes for an unowned workflow to be visible at all (#722). The marker
3532
+ // is a YAML comment, so nothing that parses the workflow can see it.
3533
+ writeManagedFile(join(workflowsDir, name), content, label, actions, { ...opts, workflowOverrides: declined, computedSubKeys }, {
3534
+ body: workflowBody,
3535
+ stamp: stampWorkflow,
3536
+ });
2550
3537
  } catch (e) {
2551
3538
  actions.push(`REFUSED: ${(e as Error).message}`);
2552
3539
  }
2553
3540
  }
3541
+
3542
+ // #632 AC-14. One line, every scaffold, unconditional. `writeManagedFile`
3543
+ // above already reported that the FILE was written; this reports the thing
3544
+ // writing it does not establish — that the gate it contains is inert until
3545
+ // a credential resolves, which the generator cannot see and must therefore
3546
+ // not guess at. A consumer who reads only the checks list sees a green
3547
+ // `ai-review` and has no reason to look further, and that is #630.
3548
+ actions.push(aiReviewScaffoldAction(vertex));
3549
+
3550
+ // Everything else in the directory, named. This generator writes three
3551
+ // files; a consumer's CI may run any number, and until #722 the ones it did
3552
+ // not write were not merely unmanaged but unreported — a clean run over 2 of
3553
+ // 7 workflow files, which reads exactly like a clean run over 7 of 7.
3554
+ // Reporting only: what a consumer does with a NOT-OWNED workflow is theirs.
3555
+ actions.push(...censusReport(workflowCensus(root)));
2554
3556
  }
2555
3557
 
2556
3558
  // ── Consumer hook deployment ─────────────────────────────────
2557
3559
 
3560
+ /**
3561
+ * The commands Claude Code would actually RUN for one event, read the way
3562
+ * Claude Code reads them (#1088).
3563
+ *
3564
+ * The schema is `event → matcher group → hooks[] → { type, command }`, and a
3565
+ * leaf is a registration only when every level is present:
3566
+ *
3567
+ * ```json
3568
+ * "PreToolUse": [
3569
+ * { "matcher": "Bash", "hooks": [ { "type": "command", "command": "…" } ] }
3570
+ * ]
3571
+ * ```
3572
+ *
3573
+ * `matcher` is omitted for events that do not have one — `SessionStart`,
3574
+ * `SubagentStop`, `PostCompact` and the rest — but `hooks[]` and
3575
+ * `type: "command"` are not optional anywhere. Read off a live
3576
+ * `~/.claude/settings.json` holding twenty-five groups across eleven events,
3577
+ * not off documentation.
3578
+ *
3579
+ * ## Why this is not `settingsCommands` from `lib/hook-trees.ts`
3580
+ *
3581
+ * That function walks the document recursively and collects any `command`
3582
+ * string **at any depth**, deliberately: it answers a census question —
3583
+ * *which trees does this machine register hooks from* — and a census that
3584
+ * knew one shape would report a document in the next shape as empty, which
3585
+ * is indistinguishable from a machine with no registrations.
3586
+ *
3587
+ * That tolerance is exactly why #1088 survived. `deployHooksToConsumers`
3588
+ * wrote a bare `{ command }` straight into the event array; the permissive
3589
+ * walk found the string, every test that asked "is the hook there?" said yes,
3590
+ * and Claude Code — the only reader whose answer decides whether the guard
3591
+ * runs — saw an array element it does not recognise as a hook. Two readers
3592
+ * disagreed and the authoritative one was not under test.
3593
+ *
3594
+ * So this reader is **strict on purpose**, and it is a second binding on
3595
+ * purpose. The two answer different questions and must be able to disagree:
3596
+ * their disagreement on a bare `{ command }` is the whole defect, and a
3597
+ * reading that cannot disagree cannot witness it
3598
+ * (`.claude/rules/checks-must-be-able-to-fail.md`, fourth shape).
3599
+ */
3600
+ export function executingHookCommands(settings: unknown, event: string): string[] {
3601
+ if (settings === null || typeof settings !== "object" || Array.isArray(settings)) return [];
3602
+ const hooks = (settings as Record<string, unknown>).hooks;
3603
+ if (hooks === null || typeof hooks !== "object" || Array.isArray(hooks)) return [];
3604
+ const groups = (hooks as Record<string, unknown>)[event];
3605
+ if (!Array.isArray(groups)) return [];
3606
+
3607
+ const out: string[] = [];
3608
+ for (const group of groups) {
3609
+ if (group === null || typeof group !== "object" || Array.isArray(group)) continue;
3610
+ // A bare `{ command }` has no `hooks[]`, and that is the #1088 shape. It
3611
+ // is not a registration, so it is not reported as one.
3612
+ const leaves = (group as Record<string, unknown>).hooks;
3613
+ if (!Array.isArray(leaves)) continue;
3614
+ for (const leaf of leaves) {
3615
+ if (leaf === null || typeof leaf !== "object" || Array.isArray(leaf)) continue;
3616
+ const rec = leaf as Record<string, unknown>;
3617
+ // The field #1088 omitted. `type` is what tells a command hook from
3618
+ // the other leaf kinds the schema allows, so a leaf without it is not
3619
+ // a command this can claim will run.
3620
+ if (rec.type !== "command") continue;
3621
+ if (typeof rec.command === "string") out.push(rec.command);
3622
+ }
3623
+ }
3624
+ return out;
3625
+ }
3626
+
3627
+ /**
3628
+ * Where a deployed hook command points, in the two spellings one deployment
3629
+ * needs (#1088).
3630
+ *
3631
+ * `command` is what goes into the consumer's settings file; `disk` is the
3632
+ * path this process checks for existence. They are returned together because
3633
+ * writing one and checking the other is the defect: before this, the command
3634
+ * was built from `join(harnessRoot, "hooks")` and nothing was checked at all,
3635
+ * so a consumer that installed rungate from npm received twelve guards whose
3636
+ * commands named a directory on the harness author's machine — and the run
3637
+ * reported `DEPLOYED: 12 hooks`.
3638
+ *
3639
+ * Resolved against the CONSUMER, which is the tree the hook will run in:
3640
+ *
3641
+ * | the consumer is | command | disk |
3642
+ * |---|---|---|
3643
+ * | the harness itself | `${CLAUDE_PROJECT_DIR}/hooks` | `<root>/hooks` |
3644
+ * | anything else | `${CLAUDE_PROJECT_DIR}/node_modules/rungate/hooks` | `<root>/node_modules/rungate/hooks` |
3645
+ *
3646
+ * `${CLAUDE_PROJECT_DIR}` rather than an absolute path, for the same reason
3647
+ * the harness's own `.claude/settings.json` is spelled that way: the variable
3648
+ * survives the checkout moving, and an absolute path baked at scaffold time
3649
+ * is wrong the first time the consumer is cloned somewhere else.
3650
+ *
3651
+ * Identity comes from `isHarnessItself` — the project's own `package.json`
3652
+ * `name` — which is the single existing binding for this question (#380) and
3653
+ * the same one `promptPrefix` and `detectPromptPrefix` read. A second
3654
+ * decider agreeing with it would be behaviourally one decider.
3655
+ */
3656
+ export function consumerHooksDir(consumerRoot: string): { command: string; disk: string } {
3657
+ return isHarnessItself(consumerRoot)
3658
+ ? { command: "${CLAUDE_PROJECT_DIR}/hooks", disk: join(consumerRoot, "hooks") }
3659
+ : {
3660
+ command: "${CLAUDE_PROJECT_DIR}/node_modules/" + HARNESS_PACKAGE + "/hooks",
3661
+ disk: join(consumerRoot, "node_modules", HARNESS_PACKAGE, "hooks"),
3662
+ };
3663
+ }
3664
+
2558
3665
  /**
2559
3666
  * Deploy hooks marked deployToConsumers:true to consumer projects'
2560
3667
  * .claude/settings.local.json with correct hookFor and command paths.
@@ -2566,6 +3673,58 @@ ${bunStep}
2566
3673
  * directly — as this did — meant a project on the directory layout deployed
2567
3674
  * nothing and said nothing, because the early return is indistinguishable
2568
3675
  * from "this project has no hooks" (#70).
3676
+ *
3677
+ * ## Every exit leaves a reading (#1047)
3678
+ *
3679
+ * #70 fixed one silent return and left four. When #1047 was written, zero of
3680
+ * twenty registry entries set `deployToConsumers`, so the eligible set was
3681
+ * empty on every run this function had ever had, and the only line it emitted
3682
+ * was `SKIP: All hooks already deployed to <consumer>` — a claim about hooks
3683
+ * that were never eligible, printed by the `else` of `deployed > 0`. A caller
3684
+ * reading the action list saw a successful no-op. So did the release.
3685
+ *
3686
+ * **That count is no longer true, and this docblock asserted it for longer
3687
+ * than it held.** Re-measured 2026-10-21 by parsing
3688
+ * `.claude/rungate/hooks.json`: **twenty entries, twelve `true`, eight
3689
+ * `false`, none absent.** #1047's AC-11 now refuses an entry that leaves the
3690
+ * field unset, which is why nothing is absent and why the number cannot drift
3691
+ * back. Corrected by #713, which found the same stale claim in two other
3692
+ * places; if you are reading this docblock you are most likely the person
3693
+ * about to decide what a consumer receives, and the old sentence told you
3694
+ * nobody had opted in when twelve entries had.
3695
+ *
3696
+ * What that does and does not mean, since the eligible set being non-empty is
3697
+ * the whole precondition for everything below:
3698
+ *
3699
+ * - Deployment is **armed**, not dormant. `hooks/` is in `package.json`'s
3700
+ * `files[]`, so the `node_modules/<pkg>/hooks` command this function writes
3701
+ * resolves on a consumer.
3702
+ * - **Publishing deploys nothing by itself.** This function runs from the
3703
+ * scaffold's write-steps, not from an install hook, so the trigger is a
3704
+ * scaffold run and the sink is `<consumerRoot>/.claude/settings.local.json`.
3705
+ * - **`consumers` is `[]` on this repository today**, so the guard below
3706
+ * returns before any of that. The first declared consumer to be scaffolded
3707
+ * is when twelve hook registrations first appear in somebody's settings.
3708
+ *
3709
+ * Four outcomes used to arrive as one, or as nothing:
3710
+ *
3711
+ * | what happened | what it said before | what it says now |
3712
+ * |---|---|---|
3713
+ * | no rungate config at all | nothing | `SKIP:` naming the root |
3714
+ * | config has no `hooks` array | nothing | `SKIP:` naming the absence |
3715
+ * | no `consumers` declared | nothing | `SKIP:` naming the absence |
3716
+ * | hooks exist, none opted in | `SKIP: All hooks already deployed` | `UNMEASURED:` with the count |
3717
+ * | all eligible already present | `SKIP: All hooks already deployed` | `SKIP:` with the eligible count |
3718
+ *
3719
+ * The UNMEASURED row is the one the issue turns on. `0 deployed because the
3720
+ * project wanted none` and `0 deployed because nobody set the flag` are
3721
+ * different facts and only one of them is fine; the first is now a `SKIP`
3722
+ * over a non-empty eligible set and the second is an `UNMEASURED` that names
3723
+ * how many entries were read and how many opted in. `.claude/rules/
3724
+ * config-access.md`: a reading is not `0`, `{}`, `null` or silence.
3725
+ *
3726
+ * A DEPLOYED line also names the hooks, because a count cannot be checked
3727
+ * against a registry and a list can.
2569
3728
  */
2570
3729
  export function deployHooksToConsumers(root: string, actions: string[]): void {
2571
3730
  let harness: any;
@@ -2577,15 +3736,55 @@ export function deployHooksToConsumers(root: string, actions: string[]): void {
2577
3736
  actions.push(`SKIP: hook deployment — unreadable rungate config: ${(err as Error).message}`);
2578
3737
  return;
2579
3738
  }
2580
- if (!harness) return;
3739
+ if (!harness) {
3740
+ actions.push(`SKIP: hook deployment — no rungate config under ${root}`);
3741
+ return;
3742
+ }
2581
3743
 
2582
- if (!harness?.hooks || !Array.isArray(harness.hooks)) return;
2583
- if (!harness?.consumers || !Array.isArray(harness.consumers) || harness.consumers.length === 0) return;
3744
+ if (!harness?.hooks || !Array.isArray(harness.hooks)) {
3745
+ actions.push("SKIP: hook deployment — the rungate config declares no hooks array");
3746
+ return;
3747
+ }
3748
+ if (!harness?.consumers || !Array.isArray(harness.consumers) || harness.consumers.length === 0) {
3749
+ actions.push("SKIP: hook deployment — the rungate config declares no consumers");
3750
+ return;
3751
+ }
2584
3752
 
2585
- const hooksDir = join(root, "hooks");
3753
+ // Taken ONCE, before any consumer loop, because it is a fact about the
3754
+ // registry and not about a consumer. Reporting it per-consumer would make
3755
+ // a repository with no consumers unable to say it, which is the same
3756
+ // silence one layer down.
3757
+ const eligible = harness.hooks.filter(
3758
+ (h: any) => h?.enabled && h?.hookFor && h?.command && h?.deployToConsumers === true,
3759
+ );
3760
+ if (eligible.length === 0) {
3761
+ actions.push(
3762
+ `UNMEASURED: hook deployment — 0 of ${harness.hooks.length} registry entries set ` +
3763
+ `deployToConsumers, so nothing was eligible and nothing declined it. This is not ` +
3764
+ `"this project wants no hooks"; it is "nobody said". Set deployToConsumers on the ` +
3765
+ `entries a consumer needs, or false with a notDeployedReason on the ones it does not.`,
3766
+ );
3767
+ return;
3768
+ }
2586
3769
 
2587
3770
  for (const consumer of harness.consumers) {
2588
- const consumerRoot = consumer.startsWith("/") ? consumer : join(root, consumer);
3771
+ // An absolute entry is the repository owner naming a tree outside this
3772
+ // one on purpose, and that is a supported declaration. A RELATIVE entry
3773
+ // says "inside this repository", so one containing `..` is saying two
3774
+ // things at once and only one of them can be true — refuse it rather
3775
+ // than writing to wherever it lands (#1088).
3776
+ const consumerRoot = consumer.startsWith("/") ? consumer : resolve(root, consumer);
3777
+ if (!consumer.startsWith("/")) {
3778
+ const base = resolve(root);
3779
+ if (consumerRoot !== base && !consumerRoot.startsWith(base + sep)) {
3780
+ actions.push(
3781
+ `SKIP: Consumer ${consumer} — a relative consumer path must stay inside ${base}, ` +
3782
+ `and this one resolves to ${consumerRoot}. Declare it as an absolute path if ` +
3783
+ `that is deliberate.`,
3784
+ );
3785
+ continue;
3786
+ }
3787
+ }
2589
3788
  if (!existsSync(consumerRoot)) {
2590
3789
  actions.push(`SKIP: Consumer ${consumer} — directory not found`);
2591
3790
  continue;
@@ -2599,43 +3798,229 @@ export function deployHooksToConsumers(root: string, actions: string[]): void {
2599
3798
  const settingsPath = join(consumerRoot, ".claude", "settings.local.json");
2600
3799
  let settings: any = {};
2601
3800
  if (existsSync(settingsPath)) {
2602
- try { settings = JSON.parse(readFileSync(settingsPath, "utf-8")); } catch {}
3801
+ // A corrupt config is never a missing config (`.claude/rules/
3802
+ // config-access.md`). The `catch {}` this replaces left `settings` as
3803
+ // `{}` and then fell through to `writeFileSync` — so a consumer's
3804
+ // settings.local.json that failed to parse for any reason, including a
3805
+ // half-written file or a merge conflict marker, was OVERWRITTEN with a
3806
+ // file containing nothing but our hooks. Their permissions, their
3807
+ // allowlists, their own hook registrations: gone, silently, during a
3808
+ // run whose purpose was to add three lines.
3809
+ //
3810
+ // Refuse this consumer and keep going to the next. Repairing somebody
3811
+ // else's security settings is not a decision a scaffold step gets to
3812
+ // take, and neither is discarding them.
3813
+ try {
3814
+ settings = JSON.parse(readFileSync(settingsPath, "utf-8"));
3815
+ } catch (err) {
3816
+ actions.push(
3817
+ `SKIP: ${consumer} — .claude/settings.local.json exists but does not parse ` +
3818
+ `(${(err as Error).message}). Refusing to overwrite it. Fix the file and re-run.`,
3819
+ );
3820
+ continue;
3821
+ }
3822
+ if (settings === null || typeof settings !== "object" || Array.isArray(settings)) {
3823
+ // `JSON.parse("null")` and `JSON.parse("[]")` both succeed and both
3824
+ // take `settings.hooks = {}` without complaint, so the parse alone
3825
+ // does not establish that this is a settings object.
3826
+ actions.push(
3827
+ `SKIP: ${consumer} — .claude/settings.local.json parses but is not an object. ` +
3828
+ `Refusing to overwrite it.`,
3829
+ );
3830
+ continue;
3831
+ }
2603
3832
  }
2604
3833
 
2605
3834
  if (!settings.hooks) settings.hooks = {};
2606
3835
 
2607
- let deployed = 0;
2608
- for (const hook of harness.hooks) {
2609
- if (!hook.enabled || !hook.hookFor || !hook.command) continue;
2610
- if (hook.deployToConsumers !== true) continue;
2611
-
2612
- const resolvedCommand = hook.command.replace("${RUNGATE_HOOKS_DIR}", hooksDir);
3836
+ // Resolved against the CONSUMER, not against the harness (#1088). `disk`
3837
+ // is only ever used to ask whether the file is there; `command` is the
3838
+ // only spelling that reaches the consumer's settings file.
3839
+ const dirs = consumerHooksDir(consumerRoot);
3840
+
3841
+ const deployedNames: string[] = [];
3842
+ const repairedNames: string[] = [];
3843
+ let alreadyPresent = 0;
3844
+ for (const hook of eligible) {
3845
+ const resolvedCommand = hook.command.replace("${RUNGATE_HOOKS_DIR}", dirs.command);
3846
+ const diskCommand = hook.command.replace("${RUNGATE_HOOKS_DIR}", dirs.disk);
2613
3847
  const hookType = hook.hookFor as string;
2614
3848
 
2615
- if (!settings.hooks[hookType]) settings.hooks[hookType] = [];
3849
+ if (!Array.isArray(settings.hooks[hookType])) settings.hooks[hookType] = [];
3850
+ const groups: any[] = settings.hooks[hookType];
3851
+
3852
+ // Does the file this command runs exist in the tree it will run in?
3853
+ //
3854
+ // Nothing asked before, so the deployment could not tell "the guard is
3855
+ // installed" from "the guard's path names nothing here" — and both
3856
+ // reported `DEPLOYED`. A silently inert security control is worse than
3857
+ // an absent one; an absent one gets noticed.
3858
+ const executed = executedHookPath(diskCommand);
3859
+ if (executed === null) {
3860
+ actions.push(
3861
+ `UNMEASURED: ${consumer} — ${hook.name}: could not read which file ` +
3862
+ `"${hook.command}" executes, so whether it is present was never established. ` +
3863
+ `Not deployed.`,
3864
+ );
3865
+ continue;
3866
+ }
3867
+ if (!existsSync(executed)) {
3868
+ actions.push(
3869
+ `UNMEASURED: ${consumer} — ${hook.name}: nothing at ${executed}, which is where ` +
3870
+ `the command being written points. Not deployed. Install ${HARNESS_PACKAGE} in ` +
3871
+ `the consumer, or drop deployToConsumers on this entry.`,
3872
+ );
3873
+ continue;
3874
+ }
2616
3875
 
2617
- // Check if this hook is already deployed
2618
- const existing = settings.hooks[hookType].find(
2619
- (h: any) => h.command === resolvedCommand || (h.command && h.command.includes(hook.name))
3876
+ // Registrations as CLAUDE CODE would see them. Reading `groups` for a
3877
+ // top-level `command` — which is what this used to do — counts the
3878
+ // inert pre-#1088 entries as deployments, so a consumer that already
3879
+ // received the broken shape would never receive the working one and
3880
+ // the run would report "already deployed" forever.
3881
+ const registered = executingHookCommands(settings, hookType).filter(
3882
+ c => hookRegistrationPath(c, hook.name) !== null,
2620
3883
  );
2621
- if (existing) continue;
3884
+ if (registered.includes(resolvedCommand)) {
3885
+ alreadyPresent++;
3886
+ continue;
3887
+ }
3888
+ if (registered.length > 0) {
3889
+ // Names the hook, runs something else. That is a disagreement about
3890
+ // which program a guard is, and resolving it by appending a second
3891
+ // registration — or by treating it as already deployed — both pick a
3892
+ // winner silently. Say it and leave the consumer's entry alone.
3893
+ actions.push(
3894
+ `CONFLICT: ${consumer} — ${hook.name} is already registered under ${hookType} as ` +
3895
+ `${registered.join(", ")}, which is not ${resolvedCommand}. Left alone; ` +
3896
+ `nothing was deployed for this hook.`,
3897
+ );
3898
+ continue;
3899
+ }
2622
3900
 
2623
- const hookEntry: any = { command: resolvedCommand };
2624
- if (hook.matcher) hookEntry.matcher = hook.matcher;
3901
+ // Inert leftovers from the shape this fixes: a bare `{ command }` in
3902
+ // the event array, which Claude Code does not recognise as a hook.
3903
+ // Removed rather than left beside the correct entry, because a reader
3904
+ // cannot tell one of ours from one of the consumer's — and ours is
3905
+ // identified exactly: it EXECUTES `<name>.hook.ts`, by the same parse
3906
+ // the registration check uses.
3907
+ for (let i = groups.length - 1; i >= 0; i--) {
3908
+ const g = groups[i];
3909
+ if (g === null || typeof g !== "object" || Array.isArray(g)) continue;
3910
+ if (Array.isArray(g.hooks)) continue;
3911
+ if (typeof g.command !== "string") continue;
3912
+ if (hookRegistrationPath(g.command, hook.name) === null) continue;
3913
+ groups.splice(i, 1);
3914
+ repairedNames.push(hook.name);
3915
+ }
2625
3916
 
2626
- settings.hooks[hookType].push(hookEntry);
2627
- deployed++;
3917
+ // The executing shape: event → matcher group → `hooks[]` → `{ type,
3918
+ // command }`. An existing group with the SAME matcher is reused, so a
3919
+ // re-scaffold does not accumulate one group per run, and events with
3920
+ // no matcher get a group with the key omitted rather than set to
3921
+ // `undefined` — which is what `~/.claude/settings.json` holds for
3922
+ // SessionStart, SubagentStop and PostCompact.
3923
+ const matcher: string | undefined =
3924
+ typeof hook.matcher === "string" && hook.matcher.length > 0 ? hook.matcher : undefined;
3925
+ let group = groups.find(
3926
+ (g: any) =>
3927
+ g !== null &&
3928
+ typeof g === "object" &&
3929
+ !Array.isArray(g) &&
3930
+ Array.isArray(g.hooks) &&
3931
+ (typeof g.matcher === "string" ? g.matcher : undefined) === matcher,
3932
+ );
3933
+ if (!group) {
3934
+ group = matcher === undefined ? { hooks: [] } : { matcher, hooks: [] };
3935
+ groups.push(group);
3936
+ }
3937
+ group.hooks.push({ type: "command", command: resolvedCommand });
3938
+ deployedNames.push(hook.name);
2628
3939
  }
2629
3940
 
2630
- if (deployed > 0) {
3941
+ if (deployedNames.length > 0 || repairedNames.length > 0) {
2631
3942
  writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + "\n");
2632
- actions.push(`DEPLOYED: ${deployed} hooks to ${consumer}/.claude/settings.local.json`);
2633
- } else {
2634
- actions.push(`SKIP: All hooks already deployed to ${consumer}`);
3943
+ if (repairedNames.length > 0) {
3944
+ actions.push(
3945
+ `REPAIRED: ${repairedNames.length} unrecognised hook entries removed from ` +
3946
+ `${consumer}/.claude/settings.local.json — ${repairedNames.join(", ")}. They were ` +
3947
+ `written in a shape Claude Code does not execute (#1088) and never ran.`,
3948
+ );
3949
+ }
3950
+ if (deployedNames.length > 0) {
3951
+ actions.push(
3952
+ `DEPLOYED: ${deployedNames.length} hooks to ${consumer}/.claude/settings.local.json ` +
3953
+ `— ${deployedNames.join(", ")}`,
3954
+ );
3955
+ }
3956
+ } else if (alreadyPresent === eligible.length) {
3957
+ // Reachable only with a non-empty eligible set, so this now means what
3958
+ // it says. The `eligible.length === 0` guard above took the other case,
3959
+ // and an UNMEASURED or CONFLICT hook is no longer swept in here — each
3960
+ // pushed its own line and this count excludes it.
3961
+ actions.push(
3962
+ `SKIP: all ${eligible.length} eligible hooks already deployed to ${consumer}`,
3963
+ );
2635
3964
  }
2636
3965
  }
2637
3966
  }
2638
3967
 
3968
+ /**
3969
+ * ## The generated pre-commit hook, as one binding (#610)
3970
+ *
3971
+ * ## What was wrong
3972
+ *
3973
+ * The hook decided WHICH updater to run by sniffing the working tree at
3974
+ * commit time:
3975
+ *
3976
+ * updater=""
3977
+ * if [ -f "scripts/update-project-state.ts" ]; then
3978
+ * updater="scripts/update-project-state.ts"
3979
+ * elif [ -f "node_modules/rungate/scripts/update-project-state.ts" ]; then
3980
+ * updater="node_modules/rungate/scripts/update-project-state.ts"
3981
+ * fi
3982
+ *
3983
+ * and the comment above it said the order was deliberate because "a checkout
3984
+ * that has its own scripts/ copy is the harness". That is an identity
3985
+ * inferred from a FILENAME. "This tree holds a file at this path" and "this
3986
+ * tree is the rungate harness" are different facts, and the hook treated the
3987
+ * first as proof of the second — so a consumer that keeps a script at that
3988
+ * path for its own reasons was silently reclassified as the harness and ran a
3989
+ * different program than the one rungate installed. Nothing in the commit
3990
+ * recorded which branch fired, so the two outcomes were indistinguishable
3991
+ * afterwards.
3992
+ *
3993
+ * A detector narrower than what it detects
3994
+ * (`.claude/rules/checks-must-be-able-to-fail.md`, second shape), with the
3995
+ * *Silent Default Substitution* that `.claude/rules/config-access.md` refuses
3996
+ * sitting underneath it.
3997
+ *
3998
+ * ## What it does instead
3999
+ *
4000
+ * The decision is taken HERE, at generation time, and one concrete path is
4001
+ * baked into the emitted script. The hook names the program it runs; a tree
4002
+ * that acquires a same-named file afterwards cannot change what executes.
4003
+ *
4004
+ * Identity is read from the project's own declaration — `isHarnessItself`,
4005
+ * which reads `package.json`'s `name` and is the single existing binding for
4006
+ * this question in the tree (#380). It is deliberately NOT a second reading
4007
+ * of the same fact: two deciders that agree are behaviourally one, and no
4008
+ * mutation of either could tell them apart.
4009
+ *
4010
+ * ## Three readings, and UNMEASURED is one of them
4011
+ *
4012
+ * | the tree declares | the candidate | emitted |
4013
+ * |---|---|---|
4014
+ * | `name: "rungate"` | `scripts/update-project-state.ts` | that path, baked |
4015
+ * | anything else | `node_modules/rungate/scripts/…` | that path, baked |
4016
+ * | either, candidate absent | — | UNMEASURED, and no lookup at all |
4017
+ *
4018
+ * The third row is the one that must not be a guess. A hook carrying a
4019
+ * lookup "in case the file turns up later" succeeds at some unknown future
4020
+ * commit for a reason nobody chose, and `0`, `""`, `null` and a
4021
+ * plausible-looking path are all indistinguishable from success.
4022
+ */
4023
+
2639
4024
  /**
2640
4025
  * The line that marks a pre-commit hook as ours, so a fix can reach one that
2641
4026
  * already exists (#450).
@@ -2649,18 +4034,104 @@ export function deployHooksToConsumers(root: string, actions: string[]): void {
2649
4034
  */
2650
4035
  export const PRE_COMMIT_MANAGED_MARKER = "# Managed by rungate — secret scan + PROJECT-STATE update";
2651
4036
 
2652
- export function createGitHooks(root: string, actions: string[]): void {
2653
- const hooksDir = join(root, ".git", "hooks");
2654
- if (!existsSync(hooksDir)) return;
4037
+ /**
4038
+ * Present in EVERY form this generator emits, resolved or not.
4039
+ *
4040
+ * `scripts/check-installed-hook-currency.ts` probes for it to tell a hook
4041
+ * that predates #610 from one that carries it, and that probe has to work for
4042
+ * a consumer and for the harness alike — so it cannot be either baked path.
4043
+ */
4044
+ export const UPDATER_GENERATION_MARKER =
4045
+ "# Which updater runs was decided when this hook was generated (#610), not here.";
2655
4046
 
2656
- const { chmodSync } = require("fs");
4047
+ /** The harness's own copy, relative to the project root. */
4048
+ export const HARNESS_UPDATER = "scripts/update-project-state.ts";
2657
4049
 
2658
- const preCommit = join(hooksDir, "pre-commit");
2659
- const existingPreCommit = existsSync(preCommit) ? readFileSync(preCommit, "utf-8") : null;
2660
- if (existingPreCommit !== null && !existingPreCommit.includes(PRE_COMMIT_MANAGED_MARKER)) {
2661
- actions.push("SKIP: .git/hooks/pre-commit (hand-written, not overwriting)");
2662
- } else {
2663
- writeFileSync(preCommit, `#!/bin/sh
4050
+ /** The copy rungate installs into a consumer, relative to the project root. */
4051
+ export const VENDORED_UPDATER = "node_modules/rungate/scripts/update-project-state.ts";
4052
+
4053
+ export type UpdaterIdentity = "harness" | "consumer";
4054
+
4055
+ export interface UpdaterResolution {
4056
+ /** What the tree declared itself to be, read from package.json's name. */
4057
+ identity: UpdaterIdentity;
4058
+ /** The one path that identity selects — present or not. */
4059
+ candidate: string;
4060
+ /** The path baked into the hook, or null when the candidate is absent. */
4061
+ path: string | null;
4062
+ }
4063
+
4064
+ /**
4065
+ * The single decider. One binding to mutate, asked once by
4066
+ * `preCommitHookScript` and nowhere else.
4067
+ */
4068
+ export function resolveUpdater(root: string): UpdaterResolution {
4069
+ const identity: UpdaterIdentity = isHarnessItself(root) ? "harness" : "consumer";
4070
+ const candidate = identity === "harness" ? HARNESS_UPDATER : VENDORED_UPDATER;
4071
+ return {
4072
+ identity,
4073
+ candidate,
4074
+ path: existsSync(join(root, candidate)) ? candidate : null,
4075
+ };
4076
+ }
4077
+
4078
+ const IDENTITY_NOTE: Record<UpdaterIdentity, string> = {
4079
+ harness:
4080
+ "# package.json names this tree as the rungate harness, so the updater is its own\n" +
4081
+ " # scripts/ copy — never a vendored duplicate of itself, which would be stale.",
4082
+ consumer:
4083
+ "# package.json does not name this tree as the harness, so the updater is the copy\n" +
4084
+ " # rungate installed. A script this project keeps at scripts/ is its own program\n" +
4085
+ " # and is not run here, whatever it is called.",
4086
+ };
4087
+
4088
+ /**
4089
+ * The block that goes inside the primary-checkout arm.
4090
+ *
4091
+ * The resolved form contains the path EXACTLY ONCE — in the assignment — so
4092
+ * there is one literal to mutate and one literal for a test to count. The
4093
+ * echo below it reports `$updater` rather than repeating the path, which is
4094
+ * the same reason: a second copy would survive any mutation of the first.
4095
+ */
4096
+ function updaterBlock(r: UpdaterResolution): string {
4097
+ if (r.path === null) {
4098
+ return ` ${UPDATER_GENERATION_MARKER}
4099
+ ${IDENTITY_NOTE[r.identity]}
4100
+ #
4101
+ # Nothing was found there when this hook was generated, so this hook runs
4102
+ # no updater and performs no lookup. A lookup kept "in case it turns up"
4103
+ # would succeed at some later commit for a reason nobody chose.
4104
+ echo "project-state: UNMEASURED — when this hook was generated this tree read as a ${r.identity} checkout and no updater was present at ${r.candidate}. This hook runs none and stages nothing. Re-scaffold once it is installed." >&2`;
4105
+ }
4106
+ return ` ${UPDATER_GENERATION_MARKER}
4107
+ ${IDENTITY_NOTE[r.identity]}
4108
+ updater="${r.path}"
4109
+ # Say which program is about to run, before running it. Without this the
4110
+ # commit's output records nothing about which updater fired and the
4111
+ # answer is only recoverable by inspecting the tree afterwards (#610).
4112
+ echo "project-state: running $updater (resolved when this hook was generated)" >&2
4113
+ if bun "$updater" --skip-tests >&2; then
4114
+ # Staged only after the updater SUCCEEDED. Staging regardless is the
4115
+ # fail-open the readings above exist to replace: it puts yesterday's
4116
+ # PROJECT-STATE.md in today's commit, and the commit then looks exactly
4117
+ # like one that updated it.
4118
+ git add PROJECT-STATE.md project-state.json 2>/dev/null || true
4119
+ else
4120
+ echo "project-state: UNMEASURED — $updater exited non-zero, so PROJECT-STATE.md and project-state.json were NOT staged. Run it by hand to see why." >&2
4121
+ fi`;
4122
+ }
4123
+
4124
+ /**
4125
+ * What `createGitHooks` writes, for a given project root.
4126
+ *
4127
+ * A function of the root rather than a constant, because the updater is
4128
+ * resolved here. It writes nothing: `scripts/check-installed-hook-currency.ts`
4129
+ * has to obtain the text for a project it is only INSPECTING, and a generator
4130
+ * that could only answer by installing itself would make the check the thing
4131
+ * it is checking.
4132
+ */
4133
+ export function preCommitHookScript(root: string): string {
4134
+ return `#!/bin/sh
2664
4135
  ${PRE_COMMIT_MANAGED_MARKER}
2665
4136
  #
2666
4137
  # Scans the staged DIFF, not files on disk. This is deliberate and fixes four
@@ -2700,14 +4171,43 @@ fi
2700
4171
  # Exclusions are env lookups and explicit non-values. password =
2701
4172
  # process.env.DB_PASSWORD is a reference, not a secret, and flagging it would
2702
4173
  # only train people to reach for --no-verify.
4174
+ #
4175
+ # Both expressions are interpolated from lib/secret-patterns.ts, never
4176
+ # written here. A hardcoded copy is a second binding for one string, and
4177
+ # #489's narrowing then has to be applied in places nothing compares. The
4178
+ # allowlist's leading \`^$|\` alternative cannot fire on this pipeline —
4179
+ # grep -oE emits no empty lines — so using the one constant is the same
4180
+ # behaviour with one fewer decider.
4181
+ #
4182
+ # -i is on both tier-2 greps and on neither tier-1 one, interpolated from the
4183
+ # same constant the CI job uses. Without it the vocabulary could only see
4184
+ # lowercase, which is the spelling an environment variable or a shell default
4185
+ # is least often written in (#844).
2703
4186
  if printf '%s\\n' "$staged_diff" \\
2704
4187
  | grep '^+' \\
2705
- | grep -oE '(password|passwd|api[_-]?key|secret)[[:space:]]*[:=][[:space:]]*[A-Za-z0-9/+=_.-]{12,}' \\
2706
- | grep -qvE '[:=][[:space:]]*(process\\.env|os\\.environ|Deno\\.env|getenv|REDACTED|CHANGEME|placeholder)'; then
4188
+ | grep -oE ${TIER2_GREP_CASE_FLAG} '${tier2Ere()}' \\
4189
+ | grep -qvE ${TIER2_GREP_CASE_FLAG} '${TIER2_ALLOWED_VALUE_ERE}'; then
2707
4190
  echo "ERROR: Potential credential assignment in staged changes"
2708
4191
  exit 1
2709
4192
  fi
2710
4193
 
4194
+ # Tier 3 — a credential written as a shell default, caught by shape rather
4195
+ # than by the variable name. Tier 2 only sees one whose name carries
4196
+ # credential vocabulary (#848).
4197
+ #
4198
+ # Both expressions are interpolated from lib/secret-patterns.ts for the
4199
+ # reason tier 2's are: a hardcoded copy is a second binding for one string.
4200
+ #
4201
+ # No -i, deliberately. Tier 3 has no vocabulary to miss in the wrong case,
4202
+ # and the flag would only widen the value class.
4203
+ if printf '%s\\n' "$staged_diff" \\
4204
+ | grep '^+' \\
4205
+ | grep -oE '${tier3Ere()}' \\
4206
+ | grep -qvE '${TIER3_ALLOWED_VALUE_ERE}'; then
4207
+ echo "ERROR: Potential credential in a shell default in staged changes"
4208
+ exit 1
4209
+ fi
4210
+
2711
4211
  # Update PROJECT-STATE if it exists — but NEVER from a linked worktree (#450).
2712
4212
  #
2713
4213
  # project-state.json, PROJECT-STATE.md and SUCCESS.md are DA-owned: a single
@@ -2738,10 +4238,7 @@ fi
2738
4238
  # checkout — which has scripts/update-project-state.ts and no
2739
4239
  # node_modules/rungate at all — bun exited non-zero on a file that is not
2740
4240
  # there. 2>/dev/null threw the ENOENT away, || true threw the status away, and
2741
- # the git add below then staged whatever happened to be on disk. A commit that
2742
- # regenerated nothing was byte-indistinguishable from one that regenerated
2743
- # everything, and the only reason anyone noticed is that the stamp is UTC, so
2744
- # the stale copy differs from the fresh one for four hours an evening.
4241
+ # the git add below then staged whatever happened to be on disk.
2745
4242
  #
2746
4243
  # Every message is on STDERR: stdout is what a caller captures as the
2747
4244
  # command's answer, and a decline, a reading and an updater's progress are all
@@ -2750,26 +4247,7 @@ if [ -f "project-state.json" ]; then
2750
4247
  gitdir=$(git rev-parse --git-dir)
2751
4248
  commondir=$(git rev-parse --git-common-dir)
2752
4249
  if [ -n "$gitdir" ] && [ "$gitdir" = "$commondir" ]; then
2753
- # The order is deliberate. A checkout carrying its own scripts/ copy IS
2754
- # the harness, and the harness must not regenerate its state with a stale
2755
- # vendored duplicate of its own updater.
2756
- updater=""
2757
- if [ -f "scripts/update-project-state.ts" ]; then
2758
- updater="scripts/update-project-state.ts"
2759
- elif [ -f "node_modules/rungate/scripts/update-project-state.ts" ]; then
2760
- updater="node_modules/rungate/scripts/update-project-state.ts"
2761
- fi
2762
- if [ -z "$updater" ]; then
2763
- echo "project-state: UNMEASURED — project-state.json is here, but no update-project-state.ts was found at scripts/update-project-state.ts or node_modules/rungate/scripts/update-project-state.ts. Nothing was regenerated and nothing was staged." >&2
2764
- elif bun "$updater" --skip-tests >&2; then
2765
- # Staged only after the updater SUCCEEDED. Staging regardless is the
2766
- # fail-open the readings above exist to replace: it puts yesterday's
2767
- # PROJECT-STATE.md in today's commit, and the commit then looks exactly
2768
- # like one that updated it.
2769
- git add PROJECT-STATE.md project-state.json 2>/dev/null || true
2770
- else
2771
- echo "project-state: UNMEASURED — $updater exited non-zero, so PROJECT-STATE.md and project-state.json were NOT staged. Run it by hand to see why." >&2
2772
- fi
4250
+ ${updaterBlock(resolveUpdater(root))}
2773
4251
  else
2774
4252
  # Announced, not silent. A developer who expected the state files to move
2775
4253
  # would otherwise be left guessing, and SKIP that says nothing is
@@ -2783,61 +4261,95 @@ fi
2783
4261
  # made the hook exit non-zero and reject a perfectly good commit. Everything
2784
4262
  # that should block has already exited 1 above.
2785
4263
  exit 0
2786
- `);
2787
- chmodSync(preCommit, 0o755);
2788
- actions.push(
2789
- existingPreCommit === null
2790
- ? "CREATED: .git/hooks/pre-commit (secret scan + PROJECT-STATE update)"
2791
- : "UPDATED: .git/hooks/pre-commit (secret scan + PROJECT-STATE update)",
2792
- );
2793
- }
4264
+ `;
4265
+ }
2794
4266
 
2795
- const prePush = join(hooksDir, "pre-push");
2796
- const MANAGED_MARKER = PRE_PUSH_MANAGED_MARKER;
4267
+ /**
4268
+ * One hook the scaffold installs (#891).
4269
+ *
4270
+ * `createGitHooks` used to name each hook in its own paragraph of imperative
4271
+ * code, and `scripts/check-installed-hook-currency.ts` joined the literal
4272
+ * `pre-commit` and compared that one file. Two positions deciding what the
4273
+ * set of hooks is, with nothing comparing them — so the installed `pre-push`
4274
+ * in this repository sat four months and one mutation battery behind its
4275
+ * generator while the currency check printed a verdict about the other hook
4276
+ * and exited 0.
4277
+ *
4278
+ * This is the declaration both of them read. A hook added here is installed
4279
+ * by the loop below AND reported by the checker, without either being
4280
+ * edited; that is the property `test/unit/hook-currency-population.test.ts`
4281
+ * AC-5 plants a case for, and it is what the cheap repair — adding the
4282
+ * string `"pre-push"` to the checker — does not buy.
4283
+ *
4284
+ * `script` takes the project root because the pre-commit hook's content
4285
+ * depends on it (#610): the updater it names is resolved at generation time
4286
+ * from what the project declares itself to be. A hook that does not care
4287
+ * ignores the argument.
4288
+ */
4289
+ export interface GeneratedHook {
4290
+ /** The file name under the hooks directory, and the name every report uses. */
4291
+ name: string;
4292
+ /** The script this project should have, generated and written nowhere. */
4293
+ script: (root: string) => string;
4294
+ /** The line that marks an installed copy as one of ours. */
4295
+ marker: string;
4296
+ /** What the scaffold's action log calls it. */
4297
+ describes: string;
4298
+ }
2797
4299
 
2798
- // `2>/dev/null` threw away the only output that said WHY conformity failed,
2799
- // leaving the developer a bare "fix before pushing" and no diagnosis. And the
2800
- // old guard was `if (!existsSync(prePush))`, so once a hook existed it was
2801
- // never updated again — every fix to this hook, including this one, would
2802
- // have reached nobody. Overwrite only our own managed hook; a hook a human
2803
- // wrote is left alone.
2804
- const existing = existsSync(prePush) ? readFileSync(prePush, "utf-8") : null;
2805
- if (existing !== null && !existing.includes(MANAGED_MARKER)) {
2806
- actions.push("SKIP: .git/hooks/pre-push (hand-written, not overwriting)");
2807
- return;
2808
- }
4300
+ export const GENERATED_HOOKS: ReadonlyArray<GeneratedHook> = [
4301
+ {
4302
+ name: "pre-commit",
4303
+ script: preCommitHookScript,
4304
+ marker: PRE_COMMIT_MANAGED_MARKER,
4305
+ describes: "secret scan + PROJECT-STATE update",
4306
+ },
4307
+ {
4308
+ // Checks the COMMITS BEING PUSHED, not the working tree (#85). The old
4309
+ // hook ran conformity in the working tree, which is not what is being
4310
+ // pushed: on 2026-10-05 that let a regression reach main, because
4311
+ // HYGIENE-3's reference index recursed into `.claude/worktrees/` and
4312
+ // every file looked referenced. A gate that inspects something other
4313
+ // than what it is gating is not a weaker gate; it is a different gate
4314
+ // wearing the name of the one you wanted.
4315
+ //
4316
+ // The script itself lives in `lib/scaffold/pre-push-hook.ts` (#397). As
4317
+ // a template literal here it was unrunnable, and the thing nothing runs
4318
+ // is the thing nothing checks.
4319
+ name: "pre-push",
4320
+ script: () => prePushHookScript(),
4321
+ marker: PRE_PUSH_MANAGED_MARKER,
4322
+ describes: "conformity check",
4323
+ },
4324
+ ];
2809
4325
 
2810
- // Checks the COMMITS BEING PUSHED, not the working tree (#85).
2811
- //
2812
- // The old hook ran the conformity suite in the working tree, which is not
2813
- // what is being pushed. On 2026-10-05 that let a regression reach main:
2814
- // HYGIENE-3's reference index recursed into .claude/worktrees/, 39 full repo
2815
- // copies that exist locally and not in a clean checkout, so every file
2816
- // looked referenced. It passed before push and Gates went red on main. A
2817
- // gate that inspects something other than what it is gating is not a weaker
2818
- // gate; it is a different gate wearing the name of the one you wanted.
2819
- //
2820
- // On node_modules, which #85 left open: symlinking the working tree's is
2821
- // fast, and it is honest exactly while the pushed commit's lockfile matches
2822
- // the one those modules were installed from. Installing unconditionally is
2823
- // correct and slow enough that people disable the hook, which is worse than
2824
- // either. So compare the lockfiles and only pay for an install when they
2825
- // actually differ — the common push changes no dependencies and keeps the
2826
- // fast path, and the push that does change them cannot quietly test against
2827
- // the wrong ones.
2828
- //
2829
- // The script itself lives in lib/scaffold/pre-push-hook.ts (#397). As a
2830
- // template literal here it was unrunnable, and the thing nothing runs is
2831
- // the thing nothing checks: the lockfile comparison read the CHECKOUT's
2832
- // `bun.lock`, so a consumer that gitignores its lockfile could never take
2833
- // the fast path and could never pass. Over there it is one binding with one
2834
- // exit-code constant, and test/pre-push-hook.test.ts drives it against
2835
- // planted repositories.
2836
- writeFileSync(prePush, prePushHookScript());
2837
- chmodSync(prePush, 0o755);
2838
- actions.push(existing === null
2839
- ? "CREATED: .git/hooks/pre-push (conformity check)"
2840
- : "UPDATED: .git/hooks/pre-push (conformity check)");
4326
+ export function createGitHooks(root: string, actions: string[]): void {
4327
+ const hooksDir = join(root, ".git", "hooks");
4328
+ if (!existsSync(hooksDir)) return;
4329
+
4330
+ const { chmodSync } = require("fs");
4331
+
4332
+ // A loop over the declaration, and not four paragraphs. The old shape also
4333
+ // carried a `return` in the pre-push SKIP arm, which was harmless only
4334
+ // because pre-push happened to be last — a third hook would have been
4335
+ // silently skipped for every project with a hand-written pre-push.
4336
+ for (const hook of GENERATED_HOOKS) {
4337
+ const at = join(hooksDir, hook.name);
4338
+ const existing = existsSync(at) ? readFileSync(at, "utf-8") : null;
4339
+ // Overwrite only our own managed hook; a hook a human wrote is left
4340
+ // alone. The old guard here was `if (!existsSync(prePush))`, so once a
4341
+ // hook existed it was never updated again and every fix to it — this one
4342
+ // included — would have reached nobody.
4343
+ if (existing !== null && !existing.includes(hook.marker)) {
4344
+ actions.push(`SKIP: .git/hooks/${hook.name} (hand-written, not overwriting)`);
4345
+ continue;
4346
+ }
4347
+ writeFileSync(at, hook.script(root));
4348
+ chmodSync(at, 0o755);
4349
+ actions.push(
4350
+ `${existing === null ? "CREATED" : "UPDATED"}: .git/hooks/${hook.name} (${hook.describes})`,
4351
+ );
4352
+ }
2841
4353
  }
2842
4354
 
2843
4355
  /**
@@ -3168,7 +4680,7 @@ export function runAuditSpecsFix(root: string, actions: string[]): void {
3168
4680
  actions.push("SKIP: audit-specs (no specs/ directory)");
3169
4681
  return;
3170
4682
  }
3171
- const specFiles = readdirSync(specsDir).filter(f => f.endsWith(".md"));
4683
+ const specFiles = readdirSorted(specsDir).filter(f => f.endsWith(".md"));
3172
4684
  if (specFiles.length === 0) {
3173
4685
  actions.push("SKIP: audit-specs (no spec files)");
3174
4686
  return;
@@ -3280,15 +4792,64 @@ export function writtenPath(line: string): string | null {
3280
4792
  return m?.[1] ?? null;
3281
4793
  }
3282
4794
 
3283
- export function reportScaffoldActions(actions: string[]): number {
4795
+ /**
4796
+ * What an action line carries when the run that produced it was a rehearsal.
4797
+ *
4798
+ * **A TRAILING marker, and that is a constraint rather than a preference.**
4799
+ * `writtenPath` above matches `^(?:CREATED|UPDATED|…): path` after a trim,
4800
+ * and two callers depend on it: `postScaffoldCommit` stages by it, and
4801
+ * `test/scaffold-audit-agreement.test.ts` compares the paths audit NAMES
4802
+ * against the paths `--fix` WROTE. A leading `REHEARSED ` prefix — the form
4803
+ * #642 suggests — makes `writtenPath` return null for every audit line, so
4804
+ * that comparison would go green with nothing in it on both sides. Agreement
4805
+ * by both sides reporting nothing is the vacuous shape #398 built it to
4806
+ * avoid.
4807
+ *
4808
+ * Square brackets rather than parentheses on purpose: most action lines
4809
+ * already end in a parenthetical (`(security template)`, `(rungate devDep)`),
4810
+ * and a marker that looks like one more of those is one a reader skims past.
4811
+ *
4812
+ * One exported binding, so there is one thing to mutate and one string for a
4813
+ * consumer to grep.
4814
+ */
4815
+ export const REHEARSAL_MARKER = " [REHEARSAL — not applied]";
4816
+
4817
+ /**
4818
+ * ## Every line, because a line is the unit a reader consumes (#642)
4819
+ *
4820
+ * The mode was announced exactly once, by `rehearsalNotice`, at the top of
4821
+ * the run — and then no line of the report carried it. Measured on two
4822
+ * planted repositories: **all 56 of an audit's report lines were
4823
+ * byte-identical to the lines `--fix` printed for the same work.** So
4824
+ * `grep ci.yml`, `| tail -25`, a scrolled terminal, and an agent reading the
4825
+ * last N lines of a tool result all received `REPLACED: … (+114 lines)` with
4826
+ * no way to tell it from a write that landed. The issue's author read one
4827
+ * four times and filed a missing-write bug off it. The report never lied;
4828
+ * its unit of qualification was wider than its unit of consumption.
4829
+ *
4830
+ * `mode` is REQUIRED rather than defaulted. A default of `false` is a silent
4831
+ * default substitution (`.claude/rules/config-access.md`): a future call site
4832
+ * that forgets to say which mode it is in would print unqualified lines and
4833
+ * look exactly like one that meant to.
4834
+ *
4835
+ * **Not sufficient: marking the `Total:` line, or the first line.** That is
4836
+ * the cheapest repair and it leaves every grep/tail/scrolled consumer in
4837
+ * precisely the position the issue is about. The `Total:` line is marked as
4838
+ * well, but after the per-line marking, not instead of it.
4839
+ */
4840
+ export function reportScaffoldActions(actions: string[], mode: { rehearsed: boolean }): number {
4841
+ const qualify = (line: string) => (mode.rehearsed ? `${line}${REHEARSAL_MARKER}` : line);
3284
4842
  console.log("\n=== Scaffold Report ===");
3285
- for (const action of actions) console.log(` ${action}`);
4843
+ for (const action of actions) console.log(` ${qualify(action)}`);
3286
4844
  const count = (verb: string) => actions.filter(a => a.startsWith(verb)).length;
3287
4845
  // AUTO-FIXED is reported separately from AUDITED on purpose (#42 SC-3).
3288
4846
  // What the scaffold CHANGED and what it merely NOTICED are different facts,
3289
4847
  // and a reader who cannot tell them apart has to diff the tree to find out
3290
4848
  // which of the reported gaps are still gaps.
3291
- console.log(`\nTotal: ${count("CREATED")} created, ${count("REPLACED")} replaced, ${count("AUTO-FIXED")} auto-fixed, ${count("SKIP")} skipped, ${count("REFUSED")} refused`);
4849
+ // The marker goes on the END of this line rather than into the `Total:`
4850
+ // token: `test/scaffold-auto-fix.test.ts` finds it with
4851
+ // `startsWith("\nTotal:")`, and a reader's eye finds it the same way.
4852
+ console.log(qualify(`\nTotal: ${count("CREATED")} created, ${count("REPLACED")} replaced, ${count("AUTO-FIXED")} auto-fixed, ${count("SKIP")} skipped, ${count("REFUSED")} refused`));
3292
4853
  return count("REFUSED");
3293
4854
  }
3294
4855