rungate 0.8.24 → 0.8.26

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.
@@ -0,0 +1,186 @@
1
+ /**
2
+ * A merged pull request's CI time, broken into parts (#2271, the computation half of #1046).
3
+ *
4
+ * The harness times agents and suite runs and, before this, nothing about CI.
5
+ * #1046 measured by hand that roughly 14 of every 19.8 merge-minutes were
6
+ * neither a check nor a queue, and nothing in the tree could say what they
7
+ * were. This turns API-shaped data into a reading that can: each check's
8
+ * duration, each run's queue time, the critical path, the re-run count, and
9
+ * the three spans open → first check start → last check end → merge.
10
+ *
11
+ * A value nobody measured is UNMEASURED with the reason, never `0`: a skipped
12
+ * required check reported as 0 ms would read as the fastest check in the suite
13
+ * (.claude/rules/config-access.md, Silent Default Substitution). A run still in
14
+ * progress has no duration, so it makes the whole reading UNMEASURED rather
15
+ * than reporting elapsed-so-far.
16
+ *
17
+ * Pure: no network and no clock. The shapes are the GitHub REST API's pull
18
+ * request, workflow run and job objects, narrowed to the fields read here.
19
+ */
20
+
21
+ export interface PullRequestShape {
22
+ number: number;
23
+ created_at: string;
24
+ merged_at: string | null;
25
+ }
26
+
27
+ /** One attempt of a workflow run. A re-run is a second entry with the same id. */
28
+ export interface WorkflowRunShape {
29
+ id: number;
30
+ name: string;
31
+ run_attempt: number;
32
+ status: string;
33
+ created_at: string;
34
+ run_started_at?: string | null;
35
+ }
36
+
37
+ /** A job of one run attempt — the unit a required check reports. */
38
+ export interface JobShape {
39
+ name: string;
40
+ run_id: number;
41
+ run_attempt: number;
42
+ status: string;
43
+ conclusion: string | null;
44
+ started_at: string | null;
45
+ completed_at: string | null;
46
+ }
47
+
48
+ export type Reading = { status: "MEASURED"; ms: number } | { status: "UNMEASURED"; reason: string };
49
+
50
+ export interface CheckReading {
51
+ /** The job's name, as a required check reports it. */
52
+ name: string;
53
+ /** The workflow it ran in, or `run <id>` when the run is not in the input. */
54
+ workflow: string;
55
+ runId: number;
56
+ /** The attempt that counted: the last one. */
57
+ duration: Reading;
58
+ /** Every attempt, in order. A re-run never overwrites the first. */
59
+ attempts: Array<{ attempt: number; conclusion: string | null; duration: Reading }>;
60
+ }
61
+
62
+ export type CiReading =
63
+ | {
64
+ status: "MEASURED";
65
+ pr: number;
66
+ checks: CheckReading[];
67
+ queue: Array<{ runId: number; name: string; attempt: number; wait: Reading }>;
68
+ criticalPath: { checks: string[]; duration: Reading };
69
+ reruns: number;
70
+ spans: { openToFirstCheck: Reading; firstToLastCheck: Reading; lastCheckToMerge: Reading };
71
+ }
72
+ | { status: "UNMEASURED"; pr: number; reason: string };
73
+
74
+ const unmeasured = (reason: string): Reading => ({ status: "UNMEASURED", reason });
75
+
76
+ function between(from: string | null | undefined, to: string | null | undefined, what: string): Reading {
77
+ if (!from) return unmeasured(`${what}: no start time`);
78
+ if (!to) return unmeasured(`${what}: no end time`);
79
+ const ms = Date.parse(to) - Date.parse(from);
80
+ if (Number.isNaN(ms)) return unmeasured(`${what}: a time that does not parse`);
81
+ if (ms < 0) return unmeasured(`${what}: ends before it starts`);
82
+ return { status: "MEASURED", ms };
83
+ }
84
+
85
+ function jobDuration(job: JobShape): Reading {
86
+ if (job.conclusion === "skipped") return unmeasured("did not run (skipped)");
87
+ if (!job.started_at) return unmeasured("no started_at — it never started");
88
+ if (!job.completed_at) return unmeasured(`no completed_at — it ended ${job.conclusion ?? "without a conclusion"}`);
89
+ return between(job.started_at, job.completed_at, job.name);
90
+ }
91
+
92
+ type Timed = { name: string; start: number; end: number };
93
+
94
+ /**
95
+ * The longest chain of checks that ran one after another (#2271). A check
96
+ * follows another when it started at or after that one ended; checks that
97
+ * overlap ran in parallel, and parallel time is not added. The one place this
98
+ * is decided, so a mutation of it reddens every reader.
99
+ */
100
+ function criticalPath(checks: Timed[]): { checks: string[]; duration: Reading } {
101
+ if (checks.length === 0) return { checks: [], duration: unmeasured("no check ran to completion") };
102
+ const sorted = [...checks].sort((a, b) => a.start - b.start || a.end - b.end);
103
+ const best: number[] = [];
104
+ const prev: number[] = [];
105
+ sorted.forEach((c, i) => {
106
+ best[i] = c.end - c.start;
107
+ prev[i] = -1;
108
+ for (let j = 0; j < i; j++) {
109
+ if (sorted[j]!.end <= c.start && best[j]! + (c.end - c.start) > best[i]!) {
110
+ best[i] = best[j]! + (c.end - c.start);
111
+ prev[i] = j;
112
+ }
113
+ }
114
+ });
115
+ let tip = 0;
116
+ best.forEach((b, i) => { if (b > best[tip]!) tip = i; });
117
+ const chain: string[] = [];
118
+ for (let i = tip; i !== -1; i = prev[i]!) chain.unshift(sorted[i]!.name);
119
+ return { checks: chain, duration: { status: "MEASURED", ms: best[tip]! } };
120
+ }
121
+
122
+ export function ciReadingFor(input: { pr: PullRequestShape; runs: WorkflowRunShape[]; jobs: JobShape[] }): CiReading {
123
+ const { pr, runs, jobs } = input;
124
+ if (!pr.merged_at) return { status: "UNMEASURED", pr: pr.number, reason: "the pull request is not merged" };
125
+ if (runs.length === 0) return { status: "UNMEASURED", pr: pr.number, reason: "no workflow run for its commits" };
126
+ const open = runs.find(r => r.status !== "completed");
127
+ if (open) {
128
+ return { status: "UNMEASURED", pr: pr.number, reason: `run ${open.id} attempt ${open.run_attempt} is ${open.status}` };
129
+ }
130
+
131
+ const queue = [...runs]
132
+ .sort((a, b) => a.id - b.id || a.run_attempt - b.run_attempt)
133
+ .map(r => ({ runId: r.id, name: r.name, attempt: r.run_attempt, wait: between(r.created_at, r.run_started_at, `run ${r.id} attempt ${r.run_attempt} queue`) }));
134
+
135
+ // A check is a job within ONE workflow run: its attempts share the run id.
136
+ // Two workflows on the same push may each have a job named "build", and
137
+ // grouped by name alone one of them was dropped (review round 1, PR #2272).
138
+ const workflowOf = new Map(runs.map(r => [r.id, r.name]));
139
+ const byCheck = new Map<string, JobShape[]>();
140
+ for (const j of jobs) {
141
+ const key = `${j.run_id}\u0000${j.name}`;
142
+ byCheck.set(key, [...(byCheck.get(key) ?? []), j]);
143
+ }
144
+ const label = (j: JobShape) => `${workflowOf.get(j.run_id) ?? `run ${j.run_id}`} / ${j.name}`;
145
+ const checks: CheckReading[] = [...byCheck.values()].map(attempts => {
146
+ const ordered = [...attempts].sort((a, b) => a.run_attempt - b.run_attempt);
147
+ const read = ordered.map(j => ({ attempt: j.run_attempt, conclusion: j.conclusion, duration: jobDuration(j) }));
148
+ const first = ordered[0]!;
149
+ return {
150
+ name: first.name, workflow: workflowOf.get(first.run_id) ?? `run ${first.run_id}`, runId: first.run_id,
151
+ duration: read[read.length - 1]!.duration, attempts: read,
152
+ };
153
+ });
154
+
155
+ const maxAttempt = new Map<number, number>();
156
+ for (const r of runs) maxAttempt.set(r.id, Math.max(maxAttempt.get(r.id) ?? 0, r.run_attempt));
157
+ const reruns = [...maxAttempt.values()].reduce((n, a) => n + (a - 1), 0);
158
+
159
+ // Every attempt that ran counts toward the spans: a failed first attempt is
160
+ // CI time the pull request spent. Only the attempt that counted is a link
161
+ // in the critical path.
162
+ const ran = jobs.filter(j => jobDuration(j).status === "MEASURED");
163
+ const counted: Timed[] = [];
164
+ for (const attempts of byCheck.values()) {
165
+ const last = [...attempts].sort((a, b) => a.run_attempt - b.run_attempt).pop()!;
166
+ if (jobDuration(last).status === "MEASURED") {
167
+ counted.push({ name: label(last), start: Date.parse(last.started_at!), end: Date.parse(last.completed_at!) });
168
+ }
169
+ }
170
+
171
+ let spans: { openToFirstCheck: Reading; firstToLastCheck: Reading; lastCheckToMerge: Reading };
172
+ if (ran.length === 0) {
173
+ const none = unmeasured("no check ran to completion");
174
+ spans = { openToFirstCheck: none, firstToLastCheck: none, lastCheckToMerge: none };
175
+ } else {
176
+ const first = new Date(Math.min(...ran.map(j => Date.parse(j.started_at!)))).toISOString();
177
+ const last = new Date(Math.max(...ran.map(j => Date.parse(j.completed_at!)))).toISOString();
178
+ spans = {
179
+ openToFirstCheck: between(pr.created_at, first, "open to first check"),
180
+ firstToLastCheck: between(first, last, "first check to last check"),
181
+ lastCheckToMerge: between(last, pr.merged_at, "last check to merge"),
182
+ };
183
+ }
184
+
185
+ return { status: "MEASURED", pr: pr.number, checks, queue, criticalPath: criticalPath(counted), reruns, spans };
186
+ }
@@ -282,6 +282,14 @@ export const CLI_COMMANDS: Record<string, CliCommand> = {
282
282
  summary: "Print the board's node id from config",
283
283
  usage: "rungate board-id [--project-root <dir>] (UNMEASURED and exit 2 when the config names no board)",
284
284
  },
285
+ // #2273, the command half of #1046: a merged PR's CI breakdown. Ships before
286
+ // #1046's generated job-summary step, which calls it through `bunx`. Reads
287
+ // the API only, so no `projectRootFlag`.
288
+ "ci-reading": {
289
+ script: "scripts/ci-reading.ts",
290
+ summary: "Print a merged pull request's CI breakdown — per-check time, queue, critical path, re-runs",
291
+ usage: "rungate ci-reading --pr <N> [--repo <owner/name>] [--format text|markdown] (a reading always exits 0, UNMEASURED naming why; a bad command line exits 2)",
292
+ },
285
293
  // #2193 (part 1 of #2183): the board-intake move step as a tested command.
286
294
  // `board-intake.yml` switches to it in #2183, once a release carries it.
287
295
  "board-intake-move": {
@@ -805,6 +805,63 @@ export function placementCount(specText: string): { deferred: boolean; criteria:
805
805
  return { deferred: declaresDeferred(specText), criteria: placementReading(specText).criteria.length };
806
806
  }
807
807
 
808
+ /**
809
+ * The deferral bank after a writer that is not a promotion appends to a spec.
810
+ *
811
+ * `create-sc` is the other writer of criteria. It appended to a deferred spec
812
+ * and left `.claude/spec-deferral-ratchet.json` at the old count, so the next
813
+ * pull request's SC-2734 and stage item E1 went red until someone edited the
814
+ * bank by hand. The rule is `bankWithPromotion`'s: the bank moves only from
815
+ * the count the spec stated before the append. `text: null` means there is
816
+ * nothing to write, because the spec is not deferred or its count did not
817
+ * change. A deferred spec with no readable bank refuses, never passes.
818
+ */
819
+ export function bankAfterAppend(
820
+ bankText: string | null,
821
+ specPath: string,
822
+ before: string,
823
+ after: string,
824
+ ): { ok: true; text: string | null } | { ok: false; refusal: PromotionRefusal; why: string } {
825
+ const was = placementCount(before);
826
+ const now = placementCount(after);
827
+ if (!was.deferred || now.criteria === was.criteria) return { ok: true, text: null };
828
+ if (bankText === null) {
829
+ return { ok: false, refusal: "BANK_DRIFT", why: `${specPath} is deferred and the deferral bank could not be read` };
830
+ }
831
+ return bankWithPromotion(bankText, specPath, was.criteria, now.criteria);
832
+ }
833
+
834
+ /** The writer `writeSpecWithBank` writes through: `writeSpec`, or a stand-in in a test. */
835
+ export type SpecWriter = (path: string, content: string) => { written: boolean; refusal?: string | null };
836
+
837
+ /**
838
+ * Write the spec and then the bank, both or neither (review of #2298).
839
+ *
840
+ * A bank write that fails after the spec write landed would leave the bank one
841
+ * behind, and `create-sc` cannot repair that on a retry the way
842
+ * `bankForRetry` does for a promotion: it mints a fresh id every run, so a
843
+ * bank one behind looks exactly like somebody else's unbanked criterion. So
844
+ * the spec is put back. `restored: false` is the one state left that needs a
845
+ * person, and it says so.
846
+ */
847
+ export function writeSpecWithBank(
848
+ write: SpecWriter,
849
+ spec: { path: string; before: string; after: string },
850
+ bank: { path: string; text: string | null },
851
+ ): { ok: true } | { ok: false; why: string; restored: boolean } {
852
+ const specWrite = write(spec.path, spec.after);
853
+ if (!specWrite.written) return { ok: false, why: `the spec was not written (${specWrite.refusal ?? "no reason given"})`, restored: true };
854
+ if (bank.text === null) return { ok: true };
855
+ const bankWrite = write(bank.path, bank.text);
856
+ if (bankWrite.written) return { ok: true };
857
+ const undo = write(spec.path, spec.before);
858
+ return {
859
+ ok: false,
860
+ why: `the deferral bank could not be written (${bankWrite.refusal ?? "no reason given"})`,
861
+ restored: undo.written,
862
+ };
863
+ }
864
+
808
865
  /**
809
866
  * ## Declining — the router's other outcome
810
867
  *
@@ -31,7 +31,9 @@
31
31
  * `AGENTS.md` rule 7 asks us to watch.
32
32
  */
33
33
 
34
+ import { criterionAnswer } from "./board-mirror";
34
35
  import { headingOccurrencesOf } from "./issue-shape";
36
+ import { PHASE_VALUE, phaseInFamily } from "./spec-placement";
35
37
  import type { MilestoneAction } from "./spec-placement";
36
38
 
37
39
  /** The section a repaired body carries. One spelling, by fiat. */
@@ -304,3 +306,125 @@ export function rowPlacement(
304
306
  }
305
307
  return { kind: "place", milestone: target.existing.title, phase: target.phase };
306
308
  }
309
+
310
+ /** One opted-in family, as the placing run reads it — SC-2779. */
311
+ export interface PlacingFamily {
312
+ /** The `board: { prefix }` its spec declares. */
313
+ prefix: string;
314
+ /** Every criterion the family's spec states, placed in a phase or not. */
315
+ stated: readonly string[];
316
+ /** Each placed criterion's value in the spec's table (`placementsById`). */
317
+ placements: ReadonlyMap<string, string>;
318
+ /** The live milestone for each phase the table places. A phase with none is absent. */
319
+ milestones: ReadonlyMap<number, string>;
320
+ }
321
+
322
+ /**
323
+ * What the placing run does with one open issue — SC-2779.
324
+ *
325
+ * - `move`: into `milestone`, the family's milestone for the phase.
326
+ * - `stay`: it already sits there.
327
+ * - `left`: the rule leaves it where it is, and the run says why by name.
328
+ * - `none`: it names no criterion an opted-in spec states; nothing to say.
329
+ * - `refuse`: the phase it belongs in has no milestone. The run writes nothing,
330
+ * because `plan-spec` makes milestones and this never does.
331
+ */
332
+ export type IssueMove =
333
+ | { kind: "move"; milestone: string; why: string }
334
+ | { kind: "stay"; why: string }
335
+ | { kind: "left"; why: string }
336
+ | { kind: "none" }
337
+ | { kind: "refuse"; why: string };
338
+
339
+ /**
340
+ * Which milestone an open issue belongs in, read from the opted-in specs —
341
+ * SC-2779, ADR-018 Decision 4 as ADR-019 Decision 3 narrowed it.
342
+ *
343
+ * THE one decider. `plan-issues --place` asks it about every open issue, and
344
+ * nothing else moves an issue between phases.
345
+ *
346
+ * - Criteria in ONE phase of ONE family: the issue moves to that phase's
347
+ * milestone, whether it has no milestone or a different one of that family.
348
+ * - No milestone, criteria in several phases of one family: the lowest, since
349
+ * the issue cannot finish before its earliest phase does.
350
+ * - A milestone, criteria in several phases: never moved.
351
+ * - Criteria from two families: left where it is and named, because phase
352
+ * numbers do not compare across specs.
353
+ * - A milestone that is not one of the family's phases: never moved.
354
+ *
355
+ * Two readings this adds, both in the direction of not moving anything:
356
+ *
357
+ * - **"Serves no criterion" is believed.** The same {@link criterionAnswer}
358
+ * the `needs-criterion` label reads. An issue saying it serves none names
359
+ * criteria only in passing: on 2026-11-17 #2307 cited SC-2734 and SC-2776
360
+ * that way, and reading them as served would have moved it into the
361
+ * finished Engine Phase 6, where the phase order then holds every later
362
+ * phase behind it.
363
+ * - **A criterion placed outside every phase stops the move.** `Done`,
364
+ * `Blocked` and the other non-phase values, or no placement at all, mean
365
+ * the issue does not sit wholly in a phase, so no phase is named for it.
366
+ *
367
+ * Only criteria an opted-in spec states are read. An id from a spec that is
368
+ * not on the board has no phase, so it cannot place the issue or contradict
369
+ * a placement (the reading ADR-019 measured its 39 issues with).
370
+ */
371
+ export function issuePlacement(
372
+ issue: { readonly title: string; readonly body?: string | null; readonly milestone: string | null },
373
+ families: readonly PlacingFamily[],
374
+ ): IssueMove {
375
+ const answers = families
376
+ .map(f => ({ f, answer: criterionAnswer(issue, f.stated) }))
377
+ .filter(a => a.answer.names.length > 0);
378
+ if (answers.length === 0) return { kind: "none" };
379
+ if (answers.some(a => a.answer.servesNone)) {
380
+ return {
381
+ kind: "left",
382
+ why: `says it serves no criterion, so the ids it mentions (${answers.flatMap(a => a.answer.names).join(", ")}) do not place it`,
383
+ };
384
+ }
385
+ if (answers.length > 1) {
386
+ return {
387
+ kind: "left",
388
+ why:
389
+ `names ${answers.map(a => `${a.f.prefix}'s ${a.answer.names.join(", ")}`).join(" and ")} — ` +
390
+ "phase numbers do not compare across specs",
391
+ };
392
+ }
393
+ const { f, answer } = answers[0]!;
394
+ const unphased = answer.names.filter(id => !PHASE_VALUE.test(f.placements.get(id) ?? ""));
395
+ if (unphased.length > 0) {
396
+ return {
397
+ kind: "left",
398
+ why:
399
+ `${unphased.map(id => `${id} is ${f.placements.has(id) ? `placed ${f.placements.get(id)}` : "placed nowhere"}`).join(", ")} ` +
400
+ `in ${f.prefix}'s table, so the issue does not sit wholly in a phase`,
401
+ };
402
+ }
403
+ const current = issue.milestone === null ? null : phaseInFamily(issue.milestone, f.prefix);
404
+ if (issue.milestone !== null && current === null) {
405
+ return { kind: "left", why: `is in "${issue.milestone}", which is not a ${f.prefix} phase — that is never moved` };
406
+ }
407
+ const phases = [...new Set(answer.names.map(id => Number(f.placements.get(id)!.match(PHASE_VALUE)![1])))].sort((a, b) => a - b);
408
+ if (phases.length > 1 && issue.milestone !== null) {
409
+ return {
410
+ kind: "left",
411
+ why: `names criteria in ${phases.map(p => `Phase ${p}`).join(" and ")} and already has a milestone — that is never moved`,
412
+ };
413
+ }
414
+ const target = phases[0]!;
415
+ if (current === target) return { kind: "stay", why: `already in "${issue.milestone}"` };
416
+ const milestone = f.milestones.get(target);
417
+ if (milestone === undefined) {
418
+ return {
419
+ kind: "refuse",
420
+ why: `belongs in ${f.prefix} Phase ${target}, which has no milestone — run plan-spec first; this never creates one`,
421
+ };
422
+ }
423
+ return {
424
+ kind: "move",
425
+ milestone,
426
+ why:
427
+ `${issue.milestone === null ? "no milestone" : `"${issue.milestone}"`} → "${milestone}" ` +
428
+ `(${answer.names.join(", ")}${phases.length > 1 ? `; the lowest of ${phases.map(p => `Phase ${p}`).join(", ")}` : ""})`,
429
+ };
430
+ }
@@ -53,6 +53,7 @@
53
53
  * direction costs 197 lines of a rule nobody noticed was gone.
54
54
  */
55
55
  import { createHash } from "crypto";
56
+ import { carryMarkedSection, normalizeTail, splitMarked, tailVariants } from "./scaffold/marked-section";
56
57
 
57
58
  export type RuleAction = "create" | "update" | "preserve";
58
59
 
@@ -115,6 +116,28 @@ export function stampProvenance(generated: string): string {
115
116
  return generated.replace(FRONTMATTER, block);
116
117
  }
117
118
 
119
+ /**
120
+ * Does the harness's stamp still cover this file — is everything it stamped
121
+ * untouched since? The one reading of that question (#370, #1553):
122
+ *
123
+ * - `{ section: null }`: no `## Project-owned` section, and the body is what
124
+ * was stamped;
125
+ * - `{ section }`: the text OUTSIDE the section is what was stamped, and the
126
+ * section (with its offset) is the project's;
127
+ * - `null`: no stamp, or something the stamp covers was edited.
128
+ *
129
+ * `decideRuleWrite` decides writes from it and `textOwner`
130
+ * (`lib/scaffold/steps.ts`) decides whose a line is, so the two cannot
131
+ * disagree about the same file (review, PR #2285).
132
+ */
133
+ export function stampCovers(text: string): { section: { start: number; text: string } | null } | null {
134
+ const stamp = declaredSha(text);
135
+ if (stamp === null) return null;
136
+ const marked = splitMarked(text);
137
+ if (marked === null) return stamp === bodySha(text) ? { section: null } : null;
138
+ return tailVariants(marked.outside).some(v => bodySha(v) === stamp) ? { section: { start: marked.start, text: marked.section } } : null;
139
+ }
140
+
118
141
  /**
119
142
  * The single place that decides whether a generated rule file may be written.
120
143
  *
@@ -127,6 +150,35 @@ export function decideRuleWrite(existing: string | null, generated: string): Rul
127
150
  const content = stampProvenance(generated);
128
151
  if (existing === null) return { action: "create", reason: "no such file", content };
129
152
 
153
+ // #1553 / SC-2769: a file carrying a `## Project-owned` section. The stamp
154
+ // covers the text OUTSIDE the section, so a project's edits under it never
155
+ // read as a hand edit of the file; an edit anywhere else still refuses, and
156
+ // the refusal names the lines rather than freezing the file silently.
157
+ const covered = stampCovers(existing);
158
+ const marked = splitMarked(existing);
159
+ if (marked !== null) {
160
+ const stamp = declaredSha(existing);
161
+ if (covered?.section) {
162
+ return {
163
+ action: "update",
164
+ reason: "harness-written outside ## Project-owned and untouched since; the section is carried forward verbatim",
165
+ content: carryMarkedSection(stampProvenance(normalizeTail(generated)), marked.section),
166
+ };
167
+ }
168
+ const written = new Set(normalizeTail(generated).split("\n").map(l => l.trim()).filter(l => l !== ""));
169
+ const edited = ruleBody(marked.outside).split("\n").map(l => l.trim()).filter(l => l !== "" && !written.has(l));
170
+ const named =
171
+ edited.length === 0
172
+ ? "the text outside it no longer matches the harness's stamp"
173
+ : `lines outside it the generator does not write: ${edited.slice(0, 3).map(l => JSON.stringify(l)).join(", ")}${edited.length > 3 ? ` and ${edited.length - 3} more` : ""}`;
174
+ return {
175
+ action: "preserve",
176
+ reason:
177
+ `${stamp === null ? "hand-authored, with a ## Project-owned section and no harness stamp" : "edited outside ## Project-owned"} — ${named}. ` +
178
+ "Move the edit under ## Project-owned, or delete the file and re-run",
179
+ };
180
+ }
181
+
130
182
  if (bodySha(existing) === bodySha(generated)) {
131
183
  // Unchanged from what the generator would write. Writing is a no-op on
132
184
  // the body and stamps the marker, which is how a pre-provenance tree
@@ -134,15 +186,14 @@ export function decideRuleWrite(existing: string | null, generated: string): Rul
134
186
  return { action: "update", reason: "identical to generator output", content };
135
187
  }
136
188
 
137
- const declared = declaredSha(existing);
138
- if (declared !== null && declared === bodySha(existing)) {
189
+ if (covered !== null) {
139
190
  return { action: "update", reason: "harness-written and untouched since", content };
140
191
  }
141
192
 
142
193
  return {
143
194
  action: "preserve",
144
195
  reason:
145
- declared === null
196
+ declaredSha(existing) === null
146
197
  ? "hand-authored — no harness provenance marker"
147
198
  : "hand-edited since the harness wrote it",
148
199
  };