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
@@ -43,32 +43,19 @@
43
43
  * replaced build, and `--force` is the only thing that overrides it. A refusal
44
44
  * a consumer has to read is cheap; a deleted deploy job is not.
45
45
  */
46
- import { createHash } from "crypto";
47
-
48
- /** Prefix of the single line recording what the harness authored. */
49
- export const MANAGED_MARKER_PREFIX = "# rungate-managed-sha256: ";
50
-
51
46
  /** A top-level YAML key at column zero. Block scalars are always indented. */
52
47
  const TOP_LEVEL_KEY = /^([A-Za-z_][A-Za-z0-9_.\-]*):(?:\s|$)/;
53
48
 
54
- export type ManagedWriteVerb = "CREATED" | "UPDATED" | "REPLACED" | "SKIP" | "REFUSED";
55
-
56
- export interface ManagedWritePlan {
57
- verb: ManagedWriteVerb;
58
- /** Bytes to write. Meaningless for SKIP and REFUSED — nothing is written. */
59
- content: string;
60
- /** Lines in the proposed content minus lines in the file on disk. 0 for a new file. */
61
- lineDelta: number;
62
- /** Jobs in the file on disk holding content the write would lose. */
63
- atRiskJobs: string[];
64
- /** Non-blank lines the write would lose and the harness cannot prove it wrote. */
65
- lostLines: string[];
66
- /** Populated only when verb === "REFUSED". Names the jobs and the line delta. */
67
- refusal: string | null;
68
- }
69
-
70
49
  interface Section {
71
50
  key: string;
51
+ /**
52
+ * The contiguous comment block introducing this key, held apart from the
53
+ * section it precedes so it can travel with the key (#941).
54
+ *
55
+ * Empty for the leading preamble and for any key with nothing above it.
56
+ * `[...intro, ...lines]` is always the section as it appeared in the file.
57
+ */
58
+ intro: string[];
72
59
  lines: string[];
73
60
  }
74
61
 
@@ -79,19 +66,62 @@ interface JobBlock {
79
66
 
80
67
  // ── reading the shape of a workflow file ───────────────────────────────────
81
68
 
69
+ /**
70
+ * Split the comment block introducing the NEXT top-level key off the end of a
71
+ * section (#941).
72
+ *
73
+ * The same rule `parseSubKeys` applies one level down, and deliberately so:
74
+ * a run of comments immediately above a key belongs to that key, because the
75
+ * whole reason to read this structure is to carry a generated key into a
76
+ * consumer's file and a key carried without its reason is a key the next
77
+ * person deletes. Two mechanisms for associating comments with keys would be
78
+ * worse than the bug, so `isIntroLine` is the one place that decides.
79
+ *
80
+ * Column zero only. A top-level key's comment is never indented, and an
81
+ * indented one is commentary inside the mapping above — `permissions:` carries
82
+ * eight lines of it, and moving those onto the next key would be the #482
83
+ * incident with the harness holding the pen.
84
+ *
85
+ * Blank lines leading the block stay behind: they separate it from the section
86
+ * above rather than introducing the key below. A suffix of nothing but blanks
87
+ * is layout, and is left alone.
88
+ */
89
+ function splitIntroducingComment(lines: string[]): [string[], string[]] {
90
+ const isIntroLine = (l: string) => l.trim() === "" || l.startsWith("#");
91
+ let at = lines.length;
92
+ while (at > 0 && isIntroLine(lines[at - 1])) at--;
93
+ while (at < lines.length && lines[at].trim() === "") at++;
94
+ if (at >= lines.length || !lines[at].startsWith("#")) return [lines, []];
95
+ return [lines.slice(0, at), lines.slice(at)];
96
+ }
97
+
82
98
  function splitTopLevel(text: string): Section[] {
83
99
  const out: Section[] = [];
84
- let cur: Section = { key: "", lines: [] };
100
+ let cur: Section = { key: "", intro: [], lines: [] };
85
101
  for (const line of text.split("\n")) {
86
102
  const m = TOP_LEVEL_KEY.exec(line);
87
103
  if (m) {
88
104
  if (cur.key !== "" || cur.lines.length > 0) out.push(cur);
89
- cur = { key: m[1], lines: [line] };
105
+ cur = { key: m[1], intro: [], lines: [line] };
90
106
  } else {
91
107
  cur.lines.push(line);
92
108
  }
93
109
  }
94
110
  out.push(cur);
111
+
112
+ // Move each introducing comment block onto the key it introduces (#941).
113
+ //
114
+ // The leading preamble is exempt. It is the managed banner — the one part of
115
+ // the file the harness authors outright, replaced whole by the merge — and
116
+ // reading it as an introduction to `name:` would hand the banner to a
117
+ // consumer section and lose it the moment the consumer already had one.
118
+ for (let i = 1; i < out.length; i++) {
119
+ const above = out[i - 1];
120
+ if (above.key === "") continue;
121
+ const [kept, intro] = splitIntroducingComment(above.lines);
122
+ above.lines = kept;
123
+ out[i].intro = intro;
124
+ }
95
125
  return out;
96
126
  }
97
127
 
@@ -136,6 +166,339 @@ function parseJobsSection(lines: string[]): { head: string[]; jobs: JobBlock[] }
136
166
  return { head, jobs };
137
167
  }
138
168
 
169
+ interface SubBlock {
170
+ key: string;
171
+ lines: string[];
172
+ }
173
+
174
+ /**
175
+ * Split a non-`jobs` top-level section into its key line and one block per
176
+ * sub-key (#839).
177
+ *
178
+ * The same shape `parseJobsSection` reads, with two deliberate differences.
179
+ * A sub-key here may carry a value on its own line (`contents: read`), which a
180
+ * job name never does. And a run of comments immediately above a sub-key
181
+ * belongs to that sub-key rather than to the one before it, because the whole
182
+ * point of reading this structure is to carry a generated sub-key into a
183
+ * consumer's file and the generated `merge_group:` is eleven lines of comment
184
+ * explaining why it has no `branches:` filter. Carrying the key without its
185
+ * reason is how the next person deletes it.
186
+ *
187
+ * That is the opposite of the rule for TOP-LEVEL keys, where a comment stays
188
+ * with the key above it (#482) — top-level sections are never relocated, so
189
+ * nothing there needs to travel.
190
+ */
191
+ function parseSubKeys(lines: string[]): { head: string[]; blocks: SubBlock[] } {
192
+ const body = lines.slice(1);
193
+ let base = -1;
194
+ for (const l of body) {
195
+ if (l.trim() === "") continue;
196
+ if (l.trimStart().startsWith("#")) continue;
197
+ const indent = l.length - l.trimStart().length;
198
+ // A column-zero line inside a section is a trailing comment or stray text,
199
+ // never a sub-key. Letting it set `base` to 0 is the bug
200
+ // `parseJobsSection` records for comments; here the guard is structural.
201
+ if (indent === 0) continue;
202
+ if (base < 0 || indent < base) base = indent;
203
+ }
204
+ const isSubKey = (l: string) =>
205
+ base > 0 &&
206
+ l.length - l.trimStart().length === base &&
207
+ /^[A-Za-z0-9_.\-]+:(\s|$)/.test(l.trim());
208
+
209
+ const head = [lines[0]];
210
+ const blocks: SubBlock[] = [];
211
+ /** Comments and blanks held back until we know what they introduce. */
212
+ let pending: string[] = [];
213
+ const open = () => (blocks.length === 0 ? head : blocks[blocks.length - 1].lines);
214
+ for (const l of body) {
215
+ if (isSubKey(l)) {
216
+ blocks.push({ key: l.trim().replace(/:.*$/, ""), lines: [...pending, l] });
217
+ pending = [];
218
+ continue;
219
+ }
220
+ if (l.trim() === "" || l.trimStart().startsWith("#")) {
221
+ pending.push(l);
222
+ continue;
223
+ }
224
+ open().push(...pending, l);
225
+ pending = [];
226
+ }
227
+ // Whatever is left introduces nothing; it stays where the consumer put it.
228
+ open().push(...pending);
229
+ return { head, blocks };
230
+ }
231
+
232
+ /**
233
+ * The consumer's section with the generated sub-keys it does not have appended
234
+ * (#839).
235
+ *
236
+ * Only the sub-keys it does NOT have. A sub-key both sides declare is a local
237
+ * knob — a branch list, a runner label, a permission the consumer widened —
238
+ * and the consumer's value stands. What the harness takes back is the
239
+ * STRUCTURE: a trigger or a permission the generator learned since this file
240
+ * was written, which under the previous rule could never reach an already
241
+ * scaffolded repo at all because every non-`jobs` key the consumer had was
242
+ * the consumer's whichever side the merge was walking.
243
+ *
244
+ * Appended rather than interleaved, for the reason the whole of #482 exists:
245
+ * a key that moves away from the comment introducing it reads as a deletion.
246
+ */
247
+ /**
248
+ * The consumer's sub-keys that this generator computes and has stopped
249
+ * emitting (#923).
250
+ *
251
+ * Read off the SAME `parseSubKeys` both sides of the merge read, so the thing
252
+ * removed and the thing reported removed cannot be two different readings.
253
+ * The scalar guard is the same one `mergeTopLevelSection` opens with and for
254
+ * the same reason: `permissions: read-all` has no sub-keys to withdraw.
255
+ */
256
+ function revokedSubKeys(
257
+ section: string,
258
+ before: Section,
259
+ generated: Section,
260
+ computed: ComputedSubKeys,
261
+ ): RevokedSubKey[] {
262
+ const owned = computed.get(section);
263
+ if (owned === undefined) return [];
264
+ if (!/^[A-Za-z_][A-Za-z0-9_.\-]*:\s*(#.*)?$/.test(before.lines[0])) return [];
265
+ const emitted = new Set(parseSubKeys(generated.lines).blocks.map(s => s.key));
266
+ return parseSubKeys(before.lines)
267
+ .blocks.filter(s => owned.has(s.key) && !emitted.has(s.key))
268
+ .map(s => ({ section, key: s.key, lines: s.lines }));
269
+ }
270
+
271
+ /**
272
+ * The consumer's section with the revoked sub-keys taken out (#923).
273
+ *
274
+ * Reassembled from `parseSubKeys` rather than filtered by line value: a
275
+ * revoked block carries the blank line and the comment block that introduce
276
+ * it, and dropping those by value would take every other blank in the section
277
+ * with them. `parseSubKeys` places every body line in exactly one block in
278
+ * file order, so head followed by the surviving blocks IS the section minus
279
+ * what was withdrawn — and with nothing to withdraw it is the section
280
+ * unchanged, which is why the caller still runs the untouched merge after it.
281
+ */
282
+ function withoutRevoked(before: Section, revoked: readonly RevokedSubKey[]): Section {
283
+ if (revoked.length === 0) return before;
284
+ const gone = new Set(revoked.map(r => r.key));
285
+ const parsed = parseSubKeys(before.lines);
286
+ return {
287
+ ...before,
288
+ lines: [...parsed.head, ...parsed.blocks.filter(s => !gone.has(s.key)).flatMap(s => s.lines)],
289
+ };
290
+ }
291
+
292
+ function mergeTopLevelSection(before: Section, generated: Section): string[] {
293
+ // A scalar on the consumer's side (`permissions: read-all`, `on: [push]`)
294
+ // has nowhere to put a sub-key, and appending one produces YAML that does
295
+ // not parse. The consumer's spelling stands.
296
+ //
297
+ // Read off the KEY LINE and not off "the consumer declared no sub-keys":
298
+ // a bare `permissions:` with nothing under it is an empty mapping, not a
299
+ // scalar, and it is exactly the shape an older generator leaves behind when
300
+ // the only sub-key it knew has since been renamed. Treating the two the
301
+ // same is how `permissions.contents` failed to converge — caught by #840's
302
+ // skew loop, which rewinds every sub-key rather than the one that was on
303
+ // somebody's mind.
304
+ if (!/^[A-Za-z_][A-Za-z0-9_.\-]*:\s*(#.*)?$/.test(before.lines[0])) return before.lines;
305
+
306
+ const b = parseSubKeys(before.lines);
307
+ const have = new Set(b.blocks.map(s => s.key));
308
+ const extra = parseSubKeys(generated.lines).blocks.filter(s => !have.has(s.key));
309
+ if (extra.length === 0) return before.lines;
310
+
311
+ const [kept, trailing] = splitTrailingBlanks(before.lines);
312
+ return [...kept, ...extra.flatMap(s => splitTrailingBlanks(s.lines)[0]), ...trailing];
313
+ }
314
+
315
+ /**
316
+ * The sub-keys one generated workflow COMPUTES, by the top-level key they sit
317
+ * under (#923).
318
+ *
319
+ * Declared by the caller, never here. `HARNESS_COMPUTED_SUBKEYS` in
320
+ * `lib/scaffold/steps.ts` names it per FILE, because the scope is the whole
321
+ * risk: this merge runs over every managed workflow, and a map keyed by
322
+ * section alone makes `permissions.id-token` revocable in files whose
323
+ * generator never emits it under any config. A consumer with a deploy job of
324
+ * their own and `id-token: write` in that workflow's `permissions:` would
325
+ * have it withdrawn by a feature that was not reasoning about their file.
326
+ *
327
+ * Which is #923's own defect wearing the other hat: the issue is about a
328
+ * grant outliving its reason, and an unscoped revoker is a WITHDRAWAL
329
+ * outliving its reason. The symmetry is the argument for scoping it tightly.
330
+ *
331
+ * Empty is the default at every seam, so a caller that declares nothing
332
+ * revokes nothing.
333
+ */
334
+ export type ComputedSubKeys = ReadonlyMap<string, ReadonlySet<string>>;
335
+
336
+ const NO_COMPUTED_SUBKEYS: ComputedSubKeys = new Map();
337
+
338
+ /** A sub-key the merge withdrew because the generator stopped emitting it (#923). */
339
+ export interface RevokedSubKey {
340
+ /** The top-level key it sat under. */
341
+ section: string;
342
+ /** The sub-key itself. */
343
+ key: string;
344
+ /** Its lines as they stood in the consumer's file, comment block included. */
345
+ lines: string[];
346
+ }
347
+
348
+ /**
349
+ * Opening of the line the merge writes where a consumer has declined a
350
+ * generated key (#839).
351
+ *
352
+ * Stable prefix, because it is matched to strip the previous run's copy before
353
+ * the current one is written — the comment has to disappear when the config
354
+ * entry does, or a consumer who opts back in keeps reading that they have not.
355
+ * `resolveManagedWrite` knows this prefix for the same reason it knows the
356
+ * managed banner: a refusal is only useful when it is about somebody else's
357
+ * work, and this line is the harness's.
358
+ */
359
+ export const WORKFLOW_OVERRIDE_COMMENT =
360
+ "# rungate: ci.workflowOverrides in .claude/rungate/config.json declares this key the consumer's";
361
+
362
+ /** The harness's note on a declined key, naming the key and the config path. */
363
+ function overrideNotice(key: string, indent: string): string {
364
+ return `${indent}${WORKFLOW_OVERRIDE_COMMENT} — the generated \`${key}:\` is not merged into it.`;
365
+ }
366
+
367
+ /**
368
+ * Top-level workflow keys this consumer has taken back from the generator
369
+ * (#839).
370
+ *
371
+ * The escape hatch that makes the key-wise merge safe to turn on. Structural
372
+ * keys are the harness's by default; a consumer who needs a different CI —
373
+ * self-hosted runners declared in `on:`, a permission model the generator
374
+ * cannot know about — names the key here and the merge leaves it alone and
375
+ * says so in the file.
376
+ *
377
+ * `jobs` is refused rather than honoured. Job ownership already has a
378
+ * mechanism (`HARNESS_OWNED_JOBS` and the job merge), and a second one that
379
+ * silently freezes `test` and `gates` would leave a consumer with a required
380
+ * check nothing regenerates. Read through the same `harness?.ci` binding as
381
+ * `shardCount` and `globalToolInstallStep`; a malformed value yields no
382
+ * overrides, which is the direction that keeps the harness in charge rather
383
+ * than the one that quietly hands everything over.
384
+ *
385
+ * Declared here rather than in `steps.ts`, which re-exports it unchanged, so
386
+ * that `lib/conformity.ts` can ask the same question (#915) without importing
387
+ * the generator.
388
+ */
389
+ export function workflowOverrides(ci: unknown): string[] {
390
+ const raw = (ci as { workflowOverrides?: unknown } | null | undefined)?.workflowOverrides;
391
+ if (!Array.isArray(raw)) return [];
392
+ return raw.filter(
393
+ (k): k is string => typeof k === "string" && k !== "jobs" && OVERRIDE_KEY.test(k),
394
+ );
395
+ }
396
+
397
+ const OVERRIDE_KEY = /^[A-Za-z_][A-Za-z0-9_.\-]*$/;
398
+
399
+ /*
400
+ * There was an `overrideNoticeKeys` parser here (#915), reading the notices
401
+ * back out of a workflow so `workflow-drift.ts` could treat them as a second
402
+ * source of ownership beside `ci.workflowOverrides`. #958 deleted its only
403
+ * caller: a notice is a comment anybody can type, so reading it back let a
404
+ * hand-edited workflow exempt itself from the drift check. The notice is
405
+ * written FOR A HUMAN READING THE FILE — it says why a key they edited was
406
+ * left alone — and it is not evidence of anything on the way back in.
407
+ *
408
+ * `stripOverrideNotices` below still matches on the prefix, because removing
409
+ * last run's notices before re-merging is a different job from believing
410
+ * them.
411
+ */
412
+
413
+ /**
414
+ * Drop every previous run's override notice, wherever in the file it sits.
415
+ *
416
+ * Over the whole document rather than per section, and before anything is
417
+ * parsed. A notice written at column zero for a key the consumer did not have
418
+ * lands in whatever section follows it on the next read — including `jobs:`,
419
+ * where it would ride along with a preserved consumer job while a fresh copy
420
+ * was appended, one more line every run.
421
+ */
422
+ function stripOverrideNotices(text: string): string {
423
+ return text
424
+ .split("\n")
425
+ .filter(l => !l.trim().startsWith(WORKFLOW_OVERRIDE_COMMENT))
426
+ .join("\n");
427
+ }
428
+
429
+ /**
430
+ * What the CALLER was able to prove about the file on disk (#957).
431
+ *
432
+ * `VERIFIED` means the bytes handed in as `before` still hash to the digest a
433
+ * previous harness run stamped on them, so the harness wrote every one of
434
+ * them. `UNPROVEN` is every other reading — no marker, a marker that no longer
435
+ * matches, or a caller that did not look — and they are deliberately one
436
+ * value: a reading nobody took and a reading that came back negative are both
437
+ * "the harness cannot prove this", which is the only distinction the merge
438
+ * acts on.
439
+ *
440
+ * The merge cannot compute this itself. The marker is stripped one layer up,
441
+ * before anything is parsed, because `resolveManagedWrite` treats every line
442
+ * outside a job as the consumer's and the marker line would otherwise refuse
443
+ * its own update (#722/#767). So the proof has to arrive as an argument, which
444
+ * is why #957 was filed rather than bundled into #941.
445
+ */
446
+ export type MergeProvenance = "VERIFIED" | "UNPROVEN";
447
+
448
+ /**
449
+ * The generated comment block to write above a key the consumer ALREADY has,
450
+ * or nothing (#957).
451
+ *
452
+ * #941 made a section the merge ADDS arrive with its introducing comment, and
453
+ * deliberately left a section the consumer already has alone — comments
454
+ * included. That is right, and it leaves a residue: a consumer who took the
455
+ * bare key through the defect holds it for ever, because the key is present
456
+ * from then on and nothing ever puts the reasoning back. **This repository was
457
+ * one of them.**
458
+ *
459
+ * Two conditions, and the second is what makes the first safe to act on.
460
+ *
461
+ * - **The harness can prove it wrote these bytes.** Presence is the wrong
462
+ * discriminator: "the consumer wrote this section bare" and "the harness
463
+ * wrote it bare, through the bug" look identical, and repairing on absence
464
+ * re-imposes a comment on every consumer who deliberately DELETED one, every
465
+ * run, with no way to opt out short of `ci.workflowOverrides`. A harness that
466
+ * cannot be disagreed with is the thing the refusal path exists to avoid.
467
+ * - **The consumer has written no commentary of their own.** #917's precedent
468
+ * one level up: where both sides have said something about the same thing,
469
+ * the consumer's stands. A comment is the consumer's statement about their
470
+ * own file and replacing one is the data loss #216 exists to prevent.
471
+ *
472
+ * Idempotent by the same condition that gates it. After one run the key has a
473
+ * block, so `consumerIntro` is non-empty on every run after, and the inverse
474
+ * defect — a copy appended per upgrade, with nothing stripping the last one —
475
+ * cannot arise.
476
+ *
477
+ * **What this does NOT claim**, said here rather than left as an omission. A
478
+ * verified marker proves the harness WROTE the bytes, not that it AUTHORED
479
+ * them: the merge carries a consumer's sub-key values forward and re-stamps,
480
+ * so a consumer who set `cancel-in-progress: true` by hand and re-scaffolded
481
+ * will receive the generator's explanation of why it is an expression. That is
482
+ * the generator explaining its own default above a value the consumer chose —
483
+ * a comment they can delete, after which this never fires again — and it is a
484
+ * better outcome than the file staying silent. Narrowing it further, to a
485
+ * section byte-identical to the generated one, would make the repair
486
+ * unreachable for every consumer the moment the generator changes a value.
487
+ *
488
+ * One exported binding, so there is one thing to mutate. It takes plain data
489
+ * rather than a `Section`, so a case can drive it without constructing the
490
+ * parser's internals.
491
+ */
492
+ export function restorableIntro(args: {
493
+ provenance: MergeProvenance;
494
+ consumerIntro: readonly string[];
495
+ generatedIntro: readonly string[];
496
+ }): string[] {
497
+ if (args.provenance !== "VERIFIED") return [];
498
+ if (args.consumerIntro.length > 0) return [];
499
+ return [...args.generatedIntro];
500
+ }
501
+
139
502
  /** Split trailing blank lines off a block. */
140
503
  function splitTrailingBlanks(lines: string[]): [string[], string[]] {
141
504
  let end = lines.length;
@@ -147,6 +510,46 @@ function jobsSectionOf(sections: Section[]): Section | undefined {
147
510
  return sections.find(s => s.key === "jobs");
148
511
  }
149
512
 
513
+ /**
514
+ * Opening of the banner every harness-generated workflow carries.
515
+ *
516
+ * Deliberately the stable prefix and not the whole sentence: the rest of it
517
+ * names the config path, and that is exactly the part that changed and caused
518
+ * the harness to refuse to update its own file.
519
+ */
520
+ export const MANAGED_BANNER_PREFIX = "# Managed by rungate";
521
+
522
+ /**
523
+ * The part of the leading preamble `mergeManagedWorkflow` replaces (#834).
524
+ *
525
+ * The merge states its own ownership rule at the preamble: *"the consumer's
526
+ * leading preamble is replaced by the generated one, which carries the
527
+ * managed banner — it is the one part of the file the harness does author."*
528
+ * The write's loss set did not agree. It whitelisted only the banner LINE, so
529
+ * the prose underneath it read as the consumer's, and a consumer that added
530
+ * `ci.vertex` had its whole re-scaffold REFUSED over three lines of the
531
+ * harness's own "no credential is configured" paragraph — the paragraph the
532
+ * new header, the one saying a federation now exists, is there to replace.
533
+ *
534
+ * Two deciders about the same bytes, disagreeing, and the merge is the one
535
+ * that was right: it computed the correct file and the write declined to put
536
+ * it on disk. That is what kept `id-token: write` off every already
537
+ * scaffolded consumer, and it is why #839's sub-key merge — which adds a
538
+ * generated sub-key the consumer lacks, `id-token` included — could not reach
539
+ * `ai-review.yml` either. One refusal, two features.
540
+ *
541
+ * It starts AT the banner, not at line one. A comment a consumer wrote above
542
+ * the banner is still theirs, is still dropped by the merge, and must still
543
+ * make the write refuse — widening this to the whole preamble would turn that
544
+ * refusal into a silent deletion.
545
+ */
546
+ export function managedPreamble(text: string): string[] {
547
+ const head = splitTopLevel(text).find(s => s.key === "");
548
+ if (!head) return [];
549
+ const start = head.lines.findIndex(l => l.startsWith(MANAGED_BANNER_PREFIX));
550
+ return start < 0 ? [] : head.lines.slice(start);
551
+ }
552
+
150
553
  /** Every top-level key a workflow declares, in file order (#482). */
151
554
  export function topLevelKeyOrder(text: string): string[] {
152
555
  return splitTopLevel(text).map(s => s.key).filter(k => k !== "");
@@ -227,11 +630,29 @@ export function jobNames(text: string): string[] {
227
630
 
228
631
  // ── the merge ──────────────────────────────────────────────────────────────
229
632
 
633
+ /**
634
+ * Job names the harness owns whether or not it emitted one this run (#728).
635
+ *
636
+ * `mergeJobsSection` decides ownership by asking whether the GENERATED file
637
+ * contains a job of that name, which is correct for every job the harness
638
+ * always emits and wrong for one it emits conditionally. `test-shard` exists
639
+ * only when `ci.shards > 1`: turn sharding back off and the previous run's
640
+ * matrix is absent from the generated side, so it reads as a consumer job
641
+ * and is carried forward — leaving an orphan that runs the whole suite once
642
+ * per leg, forever, with nothing in the diff explaining where it came from.
643
+ *
644
+ * A name here is removed when it is not regenerated. Add a conditionally
645
+ * emitted job to this set in the same commit that makes it conditional.
646
+ */
647
+ const HARNESS_OWNED_JOBS = new Set(["test", "test-shard", "gates"]);
648
+
230
649
  function mergeJobsSection(before: Section, generated: Section): string[] {
231
650
  const g = parseJobsSection(generated.lines);
232
651
  const b = parseJobsSection(before.lines);
233
652
  const generatedNames = new Set(g.jobs.map(j => j.name));
234
- const extra = b.jobs.filter(j => !generatedNames.has(j.name));
653
+ const extra = b.jobs.filter(
654
+ j => !generatedNames.has(j.name) && !HARNESS_OWNED_JOBS.has(j.name),
655
+ );
235
656
  if (extra.length === 0) return generated.lines;
236
657
 
237
658
  const [content, trailing] = splitTrailingBlanks(g.jobs.flatMap(j => j.lines));
@@ -243,12 +664,60 @@ function mergeJobsSection(before: Section, generated: Section): string[] {
243
664
  * The newly generated file with everything the harness did not author carried
244
665
  * across: consumer-only jobs appended to the jobs mapping, consumer-only
245
666
  * top-level keys appended to the file.
667
+ *
668
+ * `overrides` names top-level keys the consumer has claimed through
669
+ * `ci.workflowOverrides`. A claimed key is left exactly as the consumer wrote
670
+ * it and carries a comment saying so — deviation is explicit, never implicit,
671
+ * which is the half of #839 that makes the other half safe to ship.
672
+ *
673
+ * `provenance` is what the caller could prove about `before` (#957). It
674
+ * defaults to `UNPROVEN`, which is the fail-closed direction and the
675
+ * pre-#957 behaviour exactly: a caller that has not looked changes nothing.
246
676
  */
247
- export function mergeManagedWorkflow(before: string, generated: string): string {
248
- const b = splitTopLevel(before);
677
+ export function mergeManagedWorkflow(
678
+ before: string,
679
+ generated: string,
680
+ overrides: readonly string[] = [],
681
+ provenance: MergeProvenance = "UNPROVEN",
682
+ computed: ComputedSubKeys = NO_COMPUTED_SUBKEYS,
683
+ ): string {
684
+ return mergeManagedWorkflowRecording(before, generated, overrides, provenance, computed).content;
685
+ }
686
+
687
+ /**
688
+ * `mergeManagedWorkflow`, plus the derived grants it withdrew (#923).
689
+ *
690
+ * The recording form exists because the write has to agree with the merge
691
+ * about the revocation, and the cheap way to make it agree is the wrong one.
692
+ * Withdrawing `id-token: write` puts that line and the comment introducing it
693
+ * into `resolveManagedWrite`'s loss set — outside any job, outside the
694
+ * leading preamble, nothing covering them — and the whole re-scaffold REFUSES
695
+ * over two lines the harness wrote itself. That is #834's failure reached
696
+ * from the other direction.
697
+ *
698
+ * The fix is not a second computation in the write of which lines ought to be
699
+ * revoked. Two deciders about the same bytes is what #834 actually was, and
700
+ * the merge was the one that was right. So the merge reports the lines it
701
+ * removed and the write whitelists THOSE, which is why this returns blocks
702
+ * rather than a count.
703
+ *
704
+ * `mergeManagedWorkflow` is the thin wrapper and not the other way round:
705
+ * there is one merge, and a caller that does not need the record reads
706
+ * `.content`.
707
+ */
708
+ export function mergeManagedWorkflowRecording(
709
+ before: string,
710
+ generated: string,
711
+ overrides: readonly string[] = [],
712
+ provenance: MergeProvenance = "UNPROVEN",
713
+ computed: ComputedSubKeys = NO_COMPUTED_SUBKEYS,
714
+ ): { content: string; revoked: RevokedSubKey[] } {
715
+ const revoked: RevokedSubKey[] = [];
716
+ const b = splitTopLevel(stripOverrideNotices(before));
249
717
  const g = splitTopLevel(generated);
250
718
  const generatedKeys = new Set(g.map(s => s.key));
251
719
  const beforeJobs = jobsSectionOf(b);
720
+ const declined = new Set(overrides);
252
721
  const beforeByKey = new Map(b.filter(s => s.key !== "").map(s => [s.key, s] as const));
253
722
 
254
723
  // Walk the CONSUMER's sections, not the generated ones (#482).
@@ -272,11 +741,49 @@ export function mergeManagedWorkflow(before: string, generated: string): string
272
741
  const generatedJobs = generatedByKey.get("jobs");
273
742
  return generatedJobs ? mergeJobsSection(beforeJobs, generatedJobs) : section.lines;
274
743
  }
275
- // Every non-jobs key the consumer already has is the consumer's, whichever
276
- // side we are walking. The generated `on:` is a default for a file that
277
- // does not exist yet, not a claim on one that does.
278
- if (section.key !== "" && beforeByKey.has(section.key)) return beforeByKey.get(section.key)!.lines;
279
- return section.lines;
744
+ // Every non-jobs key the consumer already has is merged SUB-KEY BY
745
+ // SUB-KEY (#839).
746
+ //
747
+ // It used to be returned whole, on the reasoning that the generated `on:`
748
+ // is a default for a file that does not exist yet and not a claim on one
749
+ // that does. True of a one-time default, and wrong for a fleet: it made
750
+ // scaffold ORDER decide ownership, so no CI improvement the harness ever
751
+ // made could reach a repo it had already scaffolded. Measured 2026-10-20 —
752
+ // a consumer scaffolded before the generator learned `merge_group:` could
753
+ // not be given it by any number of re-scaffolds, and enabling a merge
754
+ // queue there would hang every entry on a check that never reports.
755
+ //
756
+ // What replaced it keeps the part that was right. The consumer's value for
757
+ // a sub-key both sides declare still wins, and the consumer's top-level
758
+ // order is untouched; only a sub-key the consumer does not have at all is
759
+ // added.
760
+ const consumer = beforeByKey.get(section.key);
761
+ if (section.key === "" || consumer === undefined) return section.lines;
762
+ const gen = generatedByKey.get(section.key);
763
+ // A derived grant the generator has stopped computing is withdrawn before
764
+ // the sub-key merge runs, never after: the merge's job is to carry what
765
+ // the generator newly emits INTO the consumer's section, and running it
766
+ // over a section that still holds a withdrawn key would have it decide
767
+ // ownership of a line that is on its way out (#923).
768
+ //
769
+ // Inside the `!declined` arm, deliberately. A consumer who has named this
770
+ // top-level key in `ci.workflowOverrides` has taken the whole block back,
771
+ // and revoking a sub-key out of a block the harness has just declared not
772
+ // its own is the deletion-without-a-route that #839's escape hatch exists
773
+ // to make impossible.
774
+ let merged: string[];
775
+ if (gen !== undefined && !declined.has(section.key)) {
776
+ const withdrawn = revokedSubKeys(section.key, consumer, gen, computed);
777
+ revoked.push(...withdrawn);
778
+ merged = mergeTopLevelSection(withoutRevoked(consumer, withdrawn), gen);
779
+ } else {
780
+ merged = consumer.lines;
781
+ }
782
+ // The notice is re-made from the current config every run — never carried
783
+ // — so a consumer who opts back in stops being told they have opted out.
784
+ return declined.has(section.key)
785
+ ? [merged[0], overrideNotice(section.key, " "), ...merged.slice(1)]
786
+ : merged;
280
787
  };
281
788
 
282
789
  const ordered: string[] = [];
@@ -289,15 +796,55 @@ export function mergeManagedWorkflow(before: string, generated: string): string
289
796
  if (genHead) ordered.push(...genHead.lines);
290
797
  continue;
291
798
  }
292
- ordered.push(...sectionFor(section));
799
+ // The consumer's own introducing comment, emitted unchanged (#941). A key
800
+ // the consumer already has keeps whatever they wrote above it, and the
801
+ // generator's block for that key is not merged in beside it — the same
802
+ // rule #839 applies to a sub-key both sides declare, one level up.
803
+ //
804
+ // Unless the consumer wrote nothing above it AND the harness can prove it
805
+ // wrote the section itself, in which case the block it dropped through
806
+ // #941 is put back (#957). `restorableIntro` returns nothing whenever
807
+ // `section.intro` is non-empty, so this expression is `section.intro`
808
+ // in every case but that one — including a declined key, whose generated
809
+ // counterpart is not consulted at all.
810
+ const genForIntro = declined.has(section.key) ? undefined : generatedByKey.get(section.key);
811
+ ordered.push(
812
+ ...section.intro,
813
+ ...restorableIntro({
814
+ provenance,
815
+ consumerIntro: section.intro,
816
+ generatedIntro: genForIntro?.intro ?? [],
817
+ }),
818
+ ...sectionFor(section),
819
+ );
293
820
  emitted.add(section.key);
294
821
  }
295
822
  // Generated keys the consumer does not have, appended in generated order.
296
823
  // Preserving the consumer's layout must not mean refusing to take anything
297
824
  // new.
825
+ //
826
+ // With the comment block that introduces each of them (#941). It used to
827
+ // arrive without one: a comment above a top-level key was read as the tail
828
+ // of the section ABOVE it, so the key travelled and its reasoning stayed
829
+ // behind in a section the consumer already had. What landed on every
830
+ // already-scaffolded consumer was a bare
831
+ // `cancel-in-progress: ${{ github.event_name == 'pull_request' }}` in a file
832
+ // headed "do not edit", with nothing anywhere saying why it is an expression
833
+ // rather than `true` — and simplifying it to `true` is what made one
834
+ // consumer cancel its own main-branch CI on every merge. Only brand-new
835
+ // consumers, who get the generated file verbatim, ever saw the reason.
298
836
  for (const section of g) {
299
837
  if (section.key === "" || emitted.has(section.key)) continue;
300
- ordered.push(...splitTrailingBlanks(section.lines)[0]);
838
+ if (declined.has(section.key)) {
839
+ // Declining a key the consumer does not have means not writing it. The
840
+ // notice is still written, at column zero where the key would have
841
+ // gone: an omission nothing records is indistinguishable from a
842
+ // generator that never emitted the key.
843
+ ordered.push(overrideNotice(section.key, ""));
844
+ ordered.push("");
845
+ continue;
846
+ }
847
+ ordered.push(...section.intro, ...splitTrailingBlanks(section.lines)[0]);
301
848
  ordered.push("");
302
849
  }
303
850
  // A `before` with no top-level key at all — empty, or something that is not
@@ -306,163 +853,11 @@ export function mergeManagedWorkflow(before: string, generated: string): string
306
853
  // second merge loop: two code paths producing the same bytes for the same
307
854
  // input is one decider too many, and the dead one is the one no mutation
308
855
  // can reach.
309
- return b.some(s => s.key !== "") ? ordered.join("\n") : generated;
310
- }
311
-
312
- /**
313
- * Reconstruct, out of the file on disk, the region a previous harness run
314
- * wrote — the exact inverse of `mergeManagedWorkflow`. Consumer-only jobs and
315
- * consumer-only top-level keys are dropped; nothing else is touched.
316
- */
317
- export function harnessRegion(before: string, generated: string): string {
318
- const b = splitTopLevel(before);
319
- const g = splitTopLevel(generated);
320
- const generatedKeys = new Set(g.map(s => s.key));
321
- const generatedJobNames = new Set(jobNames(generated));
322
-
323
- const out: string[] = [];
324
- for (const section of b) {
325
- if (section.key !== "" && !generatedKeys.has(section.key)) continue;
326
- if (section.key !== "jobs") {
327
- out.push(...section.lines);
328
- continue;
329
- }
330
- const parsed = parseJobsSection(section.lines);
331
- const [, trailing] = splitTrailingBlanks(parsed.jobs.flatMap(j => j.lines));
332
- const kept = parsed.jobs
333
- .filter(j => generatedJobNames.has(j.name))
334
- .flatMap(j => splitTrailingBlanks(j.lines)[0]);
335
- out.push(...parsed.head, ...kept, ...trailing);
336
- }
337
- return out.join("\n");
338
- }
339
-
340
- // ── the marker ─────────────────────────────────────────────────────────────
341
-
342
- function stripMarker(text: string): { body: string; marker: string | null } {
343
- const lines = text.split("\n");
344
- const at = lines.findIndex(l => l.startsWith(MANAGED_MARKER_PREFIX));
345
- if (at < 0) return { body: text, marker: null };
346
- const marker = lines[at].slice(MANAGED_MARKER_PREFIX.length).trim();
347
- lines.splice(at, 1);
348
- return { body: lines.join("\n"), marker };
349
- }
350
-
351
- function stampMarker(body: string, authored: string): string {
352
- const sha = createHash("sha256").update(authored).digest("hex");
353
- return `${MANAGED_MARKER_PREFIX}${sha}\n${body}`;
354
- }
355
-
356
- // ── measuring what a write would lose ──────────────────────────────────────
357
-
358
- function nonBlank(text: string): string[] {
359
- return text.split("\n").map(l => l.trim()).filter(l => l !== "");
360
- }
361
-
362
- /** Lines of `from` that `minus` does not account for, counting duplicates. */
363
- function multisetSubtract(from: string[], minus: string[]): string[] {
364
- const counts = new Map<string, number>();
365
- for (const l of minus) counts.set(l, (counts.get(l) ?? 0) + 1);
366
- const out: string[] = [];
367
- for (const l of from) {
368
- const n = counts.get(l) ?? 0;
369
- if (n > 0) counts.set(l, n - 1);
370
- else out.push(l);
371
- }
372
- return out;
373
- }
374
-
375
- /** Which jobs in `text` contain any of `lines`. */
376
- function jobsHolding(text: string, lines: string[]): string[] {
377
- const wanted = new Set(lines);
378
- const jobs = jobsSectionOf(splitTopLevel(text));
379
- if (!jobs) return [];
380
- return parseJobsSection(jobs.lines)
381
- .jobs.filter(j => j.lines.some(l => wanted.has(l.trim())))
382
- .map(j => j.name);
383
- }
384
-
385
- // ── the decision ───────────────────────────────────────────────────────────
386
-
387
- /**
388
- * Decide what writing `generated` over `before` should do.
389
- *
390
- * `before` is the file on disk, or null when there is none. Nothing here
391
- * touches the filesystem: the caller writes `plan.content` and reports
392
- * `plan.verb`, which is why the verb is a measurement of the two contents
393
- * rather than a guess from whether the path existed.
394
- */
395
- export function planManagedWrite(
396
- before: string | null,
397
- generated: string,
398
- opts: { force?: boolean } = {},
399
- ): ManagedWritePlan {
400
- const clean = stripMarker(generated).body;
401
-
402
- if (before === null) {
403
- return {
404
- verb: "CREATED",
405
- content: stampMarker(clean, clean),
406
- lineDelta: 0,
407
- atRiskJobs: [],
408
- lostLines: [],
409
- refusal: null,
410
- };
411
- }
412
-
413
- const { body: beforeBody, marker } = stripMarker(before);
414
- const force = opts.force === true;
415
- const merged = force ? clean : mergeManagedWorkflow(beforeBody, clean);
416
- const content = stampMarker(merged, clean);
417
- const lineDelta = content.split("\n").length - before.split("\n").length;
418
-
419
- if (content === before) {
420
- return { verb: "SKIP", content, lineDelta: 0, atRiskJobs: [], lostLines: [], refusal: null };
421
- }
422
-
423
- // Lines the harness can prove it wrote are free to change. Everything else
424
- // that the write would drop belongs to the consumer.
425
- //
426
- // Scoping the whitelist to the REGION rather than to the whole file is not
427
- // independently observable today, and saying so is cheaper than implying a
428
- // guard that is not there (.claude/rules/checks-must-be-able-to-fail.md):
429
- // widening it to `nonBlank(beforeBody)` leaves all 39 tests green, because a
430
- // verified marker means the merge carried every consumer line, so
431
- // `before \ merged` holds nothing but harness lines anyway. The narrow form
432
- // is what stays correct if the merge ever stops carrying something, and the
433
- // extraction it depends on IS pinned — mutating `harnessRegion` to return
434
- // its input turns 3 red.
435
- const region = harnessRegion(beforeBody, clean);
436
- const provable =
437
- marker !== null && createHash("sha256").update(region).digest("hex") === marker ? nonBlank(region) : [];
438
- const lostLines = multisetSubtract(
439
- multisetSubtract(nonBlank(beforeBody), nonBlank(merged)),
440
- provable,
441
- );
442
- const atRiskJobs = jobsHolding(beforeBody, lostLines);
443
-
444
- if (lostLines.length > 0 && !force) {
445
- const where = atRiskJobs.length > 0 ? `job(s) ${atRiskJobs.join(", ")}` : "content outside any job";
446
- return {
447
- verb: "REFUSED",
448
- content,
449
- lineDelta,
450
- atRiskJobs,
451
- lostLines,
452
- refusal:
453
- `${lostLines.length} line(s) the harness did not author would be lost from ${where} ` +
454
- `(${before.split("\n").length} -> ${content.split("\n").length} lines, ${lineDelta >= 0 ? "+" : ""}${lineDelta}). ` +
455
- `Re-run with --force to overwrite, or move the content into a job the harness does not generate.`,
456
- };
457
- }
458
-
459
- const removing = lostLines.length > 0 || lineDelta < 0;
460
- return {
461
- verb: removing ? "REPLACED" : "UPDATED",
462
- content,
463
- lineDelta,
464
- atRiskJobs,
465
- lostLines,
466
- refusal: null,
467
- };
856
+ // A `before` with nothing to merge takes the generated file whole, so
857
+ // nothing of the consumer's was withdrawn and the record has to say so —
858
+ // reporting a revocation for a file that was replaced outright would have
859
+ // the scaffold claim it removed a grant it never read.
860
+ return b.some(s => s.key !== "")
861
+ ? { content: ordered.join("\n"), revoked }
862
+ : { content: generated, revoked: [] };
468
863
  }