rungate 0.8.2 → 0.8.4

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 (74) hide show
  1. package/bin/rungate.ts +11 -6
  2. package/config/prove-evidence.schema.json +21 -3
  3. package/gates/.gate-salt +1 -1
  4. package/gates/gate-executor.ts +153 -1
  5. package/gates/prove.test.ts +12 -6
  6. package/gates/schema.ts +69 -6
  7. package/gates/workflow.test.ts +12 -5
  8. package/hooks/BunTestPathGuard.hook.ts +106 -0
  9. package/hooks/DocHygiene.hook.ts +2 -1
  10. package/hooks/GateResultProtection.hook.ts +28 -7
  11. package/hooks/HookCurrency.hook.ts +48 -1
  12. package/hooks/TopLevelCdGuard.hook.ts +38 -6
  13. package/hooks/VerifyPhaseLock.hook.ts +25 -8
  14. package/hooks/WorkflowStateGuard.hook.ts +24 -7
  15. package/lib/ai-review-jury.ts +725 -0
  16. package/lib/ai-review-rounds.ts +791 -4
  17. package/lib/ai-review-unmeasured.ts +361 -0
  18. package/lib/bash-write-guard.ts +1235 -102
  19. package/lib/bun-test-paths.ts +253 -0
  20. package/lib/cli-commands.ts +252 -11
  21. package/lib/closing-reference-audit.ts +163 -0
  22. package/lib/conformity.ts +17 -1
  23. package/lib/create-sc.ts +45 -12
  24. package/lib/derived-spec.ts +206 -0
  25. package/lib/file-claims.ts +335 -0
  26. package/lib/finding-arbiter.ts +502 -28
  27. package/lib/finding-jury.ts +61 -5
  28. package/lib/finding-pr-routing.ts +333 -0
  29. package/lib/frontmatter.ts +16 -0
  30. package/lib/gate-check-audit.ts +646 -0
  31. package/lib/generators/agents-md.ts +29 -0
  32. package/lib/github.ts +112 -7
  33. package/lib/hook-tree-currency.ts +494 -0
  34. package/lib/issue-closure-audit.ts +161 -14
  35. package/lib/issue-create-override.ts +53 -3
  36. package/lib/issue-filing-gate.ts +1073 -76
  37. package/lib/local-review-rounds.ts +523 -0
  38. package/lib/organize.ts +21 -1
  39. package/lib/project-state-shape.ts +56 -5
  40. package/lib/release-preflight.ts +90 -1
  41. package/lib/repo-path.ts +94 -0
  42. package/lib/report-provenance.ts +218 -3
  43. package/lib/risk-tier.ts +302 -0
  44. package/lib/rounds-to-pass.ts +274 -0
  45. package/lib/rule-row-drift.ts +199 -0
  46. package/lib/sc-claim-forms.ts +33 -5
  47. package/lib/sc-guard.ts +11 -1
  48. package/lib/sc-id-cross-tree.ts +17 -2
  49. package/lib/sc-ids.ts +71 -6
  50. package/lib/sc-reservations.ts +158 -14
  51. package/lib/scaffold/ai-review-findings.ts +1369 -27
  52. package/lib/scaffold/ai-review-step.ts +4095 -119
  53. package/lib/scaffold/ai-review-unmeasured-workflow.ts +243 -0
  54. package/lib/scaffold/owned-files.ts +14 -0
  55. package/lib/scaffold/steps.ts +100 -9
  56. package/lib/scratch-roots.ts +93 -3
  57. package/lib/spec-updater.ts +22 -2
  58. package/lib/spec-write-ast.ts +728 -0
  59. package/lib/spec-write-sweep.ts +470 -0
  60. package/lib/test-suite-lock.ts +127 -13
  61. package/lib/ts-ast.ts +26 -0
  62. package/lib/validators/spec-validators.ts +36 -7
  63. package/lib/write-spec.ts +138 -0
  64. package/package.json +2 -1
  65. package/scripts/ai-review-findings.ts +41 -1
  66. package/scripts/arbitrate-finding.ts +330 -12
  67. package/scripts/audit-specs.ts +225 -24
  68. package/scripts/convert-spec.ts +7 -2
  69. package/scripts/create-sc.ts +14 -2
  70. package/scripts/create-spec.ts +5 -2
  71. package/scripts/detect-sc-drift.ts +10 -2
  72. package/scripts/record-ai-review-unmeasured.ts +370 -0
  73. package/scripts/split-spec.ts +17 -4
  74. package/scripts/sync-sc-status.ts +14 -2
@@ -50,6 +50,7 @@
50
50
  */
51
51
 
52
52
  import type { Finding } from "./finding-arbiter";
53
+ import { SEVERITY_RANK, type Severity } from "./scaffold/ai-review-step";
53
54
 
54
55
  // ── Cardinalities ────────────────────────────────────────────────────────
55
56
 
@@ -214,11 +215,19 @@ export function classifyCategory(finding: Pick<Finding, "title" | "body">): Find
214
215
  * `Pre-existing` is the one that matters most here and the one we had no way
215
216
  * to say: a finding about code the change never touched is not the author's
216
217
  * defect and should not be priced like one.
218
+ *
219
+ * **Declared in `./scaffold/ai-review-step` and re-exported here**, not
220
+ * declared twice. That module is the one the deployed CI path can import —
221
+ * it has no relative imports of its own, which is what lets the mutation
222
+ * batteries carry it — and until CRC-B7 this vocabulary lived here, where
223
+ * nothing reachable from CI could name it. Its docblock there carries the
224
+ * input on which this and `AI_REVIEW_SEVERITIES` must disagree.
225
+ *
226
+ * Re-exported rather than moved outright so `severityOf`, the arbiter, the
227
+ * filing gate and `hooks/VerifyPhaseLock.hook.ts` keep naming it here.
217
228
  */
218
- export type Severity = "Important" | "Nit" | "Pre-existing";
219
-
220
- /** Sort order for the posted comments. A pre-existing bug is still a bug. */
221
- export const SEVERITY_RANK: Record<Severity, number> = { Important: 0, "Pre-existing": 1, Nit: 2 };
229
+ export { SEVERITY_RANK };
230
+ export type { Severity };
222
231
 
223
232
  // ── The vote ─────────────────────────────────────────────────────────────
224
233
 
@@ -370,6 +379,43 @@ export interface JuryReading {
370
379
  agree: number;
371
380
  quorum: number;
372
381
  groupSize: number;
382
+ /**
383
+ * Every verifier's vote, as cast, in ballot order (#1467, CRC-B4).
384
+ *
385
+ * **The counts above are a summary and this is the record.** Before this
386
+ * field existed, `juryReading` was handed `VerifierVote[]` and returned two
387
+ * integers, so a reading saying *2 of 3* could not say which two agreed or
388
+ * what the third's objection was — and a ledger row built from it carried
389
+ * the same hole. CRC-B4 asks for the individual votes specifically because
390
+ * *"re-running to recover the votes re-samples the thing being measured"*: a
391
+ * verifier is a sampled instrument, so the second ballot is a second draw
392
+ * and not a recovery of the first.
393
+ *
394
+ * Carried on an UNMEASURED reading too. A ballot that could not be counted
395
+ * is still a ballot that was cast, and the votes on it are the only record
396
+ * that a group was convened at all.
397
+ *
398
+ * What it is NOT: evidence the verifiers were independent. Three agent runs
399
+ * behind three ids look exactly like three agents — see this module's
400
+ * header.
401
+ */
402
+ ballot: readonly VerifierVote[];
403
+ /**
404
+ * Did any verifier dissent from any other?
405
+ *
406
+ * **Arithmetically derivable from `agree` and `votes`, and a field anyway**,
407
+ * which is worth stating plainly rather than overselling: it carries no
408
+ * information those two do not. It is first-class for two reasons. CRC-B4
409
+ * names it as one, at decision time — and a consumer computing
410
+ * `agree > 0 && agree < votes` for itself is a second decider over one
411
+ * question, which is the fourth shape in
412
+ * `.claude/rules/checks-must-be-able-to-fail.md`: two deciders that agree
413
+ * are behaviourally one, and nothing can tell which of them is dead.
414
+ *
415
+ * The half that genuinely cannot be recovered from the counts is `ballot`
416
+ * above — *which* verifier dissented, and on what reasoning.
417
+ */
418
+ disagreed: boolean;
373
419
  unmeasuredReasons: string[];
374
420
  }
375
421
 
@@ -400,7 +446,17 @@ export function juryReading(votes: readonly VerifierVote[], config: JuryConfig =
400
446
  const groupSize = config.groupSize ?? VERIFIER_GROUP_SIZE;
401
447
  const quorum = config.quorum ?? VERIFIER_QUORUM;
402
448
  const agree = votes.filter(v => v.real).length;
403
- const base = { votes: votes.length, agree, quorum, groupSize };
449
+ // Written here and on every return below, so there is no path out of this
450
+ // function that produces a reading without the ballot that made it. A
451
+ // refused reading needs it most: it is the only record the group met.
452
+ const base = {
453
+ votes: votes.length,
454
+ agree,
455
+ quorum,
456
+ groupSize,
457
+ ballot: [...votes],
458
+ disagreed: agree > 0 && agree < votes.length,
459
+ };
404
460
  const unmeasuredReasons: string[] = [];
405
461
 
406
462
  if (quorum * 2 <= groupSize || quorum < 1) {
@@ -0,0 +1,333 @@
1
+ /**
2
+ * Which open pull request a finding belongs on (#1343).
3
+ *
4
+ * ## The hand-routing this replaces
5
+ *
6
+ * Measured while working #1261: about 45% of filings named a file an open PR
7
+ * was already changing, and a finding routed to the tracker in that situation
8
+ * is a race — the PR lands and the issue describes code that no longer exists.
9
+ * The same shape arrives from the other direction on the review path, because
10
+ * `ai-review` reads the MERGE REF: a defect that lives on `main` is attributed
11
+ * to whichever pull request is standing closest, and a `high` naming a file
12
+ * that PR never opened is a red no author can clear from their branch. Both
13
+ * were being resolved by hand, one finding at a time, by reading the finding
14
+ * and then reading diffs until one of them contained the file.
15
+ *
16
+ * That lookup is mechanical and this module is it.
17
+ *
18
+ * ## What a match claims, and what it does not
19
+ *
20
+ * #1343 is right that file-level matching is the cheap signal: a finding that
21
+ * names a file an open PR touches may have nothing to do with that PR's
22
+ * change. So the reading here is deliberately narrower than "these are about
23
+ * the same thing". **It is a claim about a race, not about a topic**: somebody
24
+ * is editing this file right now, so a tracker row about it will be stale
25
+ * before anybody reads it, and the person holding the file is the person who
26
+ * can act. That claim is true whether or not the finding and the PR share a
27
+ * subject, which is why the cheap signal is the right one for THIS question.
28
+ *
29
+ * The paths come from the arbiter's own `symptomKeys` — the `file:` half —
30
+ * rather than from a second path extractor written here. One extractor, so a
31
+ * mutation of it cannot be covered by a duplicate that nobody mutated
32
+ * (`.claude/rules/checks-must-be-able-to-fail.md`, fourth shape).
33
+ *
34
+ * ## No imports, on purpose
35
+ *
36
+ * `test/finding-pr-routing.test.ts` mutates a copy of this file in a temp
37
+ * directory and runs the suite against it. A relative import would die on
38
+ * module resolution there and read as the mutation being rejected on the
39
+ * merits. So the key-to-path step takes `symptomKeys(finding)` output as a
40
+ * string array instead of importing the function that produced it.
41
+ */
42
+
43
+ /** The prefix `symptomKeys` puts on a repository path. */
44
+ export const FILE_KEY_PREFIX = "file:";
45
+
46
+ /** An open pull request, as little of one as routing needs. */
47
+ export interface OpenPullRequest {
48
+ number: number;
49
+ /** Repo-relative paths in its diff, as the API listed them. */
50
+ files: readonly string[];
51
+ /**
52
+ * GitHub's OWN count of the changed files.
53
+ *
54
+ * Carried so a short `files` array is detectable. `gh pr list --json files`
55
+ * fetches one page, and a list cut off at the page size is indistinguishable
56
+ * from a complete one — a PR whose diff was truncated can hold the cited
57
+ * path and never match, which turns a positive answer into a silent
58
+ * `TRACKER`. Comparing the two numbers is a truncation detector that needs
59
+ * no constant and so cannot be wrong about a page size nobody re-read.
60
+ */
61
+ declaredFileCount: number;
62
+ }
63
+
64
+ /**
65
+ * The open pull requests, or the reason there is no reading of them.
66
+ *
67
+ * A corpus that could not be fetched is **not** a corpus with no matches.
68
+ * That conflation is the fail-open `lib/github.ts` closed for the issue list
69
+ * in #1374, and it is worse here: "no open PR touches this file" is the
70
+ * reading that sends the finding to the tracker.
71
+ */
72
+ export type OpenPrCorpus =
73
+ | { status: "measured"; prs: readonly OpenPullRequest[] }
74
+ | { status: "unmeasured"; why: string };
75
+
76
+ /**
77
+ * Where the finding goes.
78
+ *
79
+ * Six values and not fewer. Each one is a different instruction to whoever is
80
+ * holding the finding, and the two that look collapsible are the two that must
81
+ * not be: `TRACKER` says the question was asked and no open PR owns the file,
82
+ * `UNMEASURED` says it was not asked. `NO_CITED_PATH` is a third state again —
83
+ * the question does not apply, because this instrument routes by path and the
84
+ * finding named none.
85
+ */
86
+ export type Route =
87
+ /** The PR under review changes a cited file. It belongs where it is. */
88
+ | "THIS_PR"
89
+ /** Exactly one other open PR changes a cited file. `prs` names it. */
90
+ | "OTHER_PR"
91
+ /** Several do, and picking one would be a guess. `prs` names them all. */
92
+ | "AMBIGUOUS"
93
+ /** No open PR changes any cited file. The tracker is the right home. */
94
+ | "TRACKER"
95
+ /** The finding cites no repository path, so this instrument says nothing. */
96
+ | "NO_CITED_PATH"
97
+ /** The corpus could not be read, or was read incompletely. */
98
+ | "UNMEASURED";
99
+
100
+ export interface Routing {
101
+ route: Route;
102
+ /** Every path the finding cites — the population the rest is drawn from. */
103
+ citedPaths: string[];
104
+ /** The pull requests this route names. Empty unless `OTHER_PR`/`AMBIGUOUS`. */
105
+ prs: number[];
106
+ /** The cited paths that produced the match. Empty when there was none. */
107
+ matchedPaths: string[];
108
+ /** How many open PRs were considered. `null` when there was no corpus. */
109
+ consideredPrs: number | null;
110
+ /** Why, in a sentence a reader can act on without re-running anything. */
111
+ reason: string;
112
+ }
113
+
114
+ export interface RouteOptions {
115
+ corpus: OpenPrCorpus;
116
+ /**
117
+ * The pull request the finding arrived on, when it arrived on one.
118
+ *
119
+ * Never reported as an `OTHER_PR`: routing a finding away from the PR it is
120
+ * already on is not routing, it is a loop.
121
+ */
122
+ thisPr?: number;
123
+ /**
124
+ * That PR's changed files, when the caller knows them firsthand.
125
+ *
126
+ * The caller's own diff beats the corpus row for the same PR, because the
127
+ * caller read it from the tree it is standing in and the corpus row is a
128
+ * fetch that may already be stale — #1370 merged between two `gh pr list`
129
+ * calls thirty seconds apart while this was being written.
130
+ */
131
+ changedFiles?: readonly string[];
132
+ }
133
+
134
+ /**
135
+ * Paths, from `symptomKeys` output.
136
+ *
137
+ * Lower-cased already by the arbiter; normalised again here so a caller
138
+ * passing a raw path list (the `file` field of an `ai-review` payload, which
139
+ * is not a symptom key) gets the same treatment.
140
+ */
141
+ export function citedPathsFromKeys(keys: readonly string[]): string[] {
142
+ const out: string[] = [];
143
+ for (const key of keys) {
144
+ if (!key.startsWith(FILE_KEY_PREFIX)) continue;
145
+ const path = normalisePath(key.slice(FILE_KEY_PREFIX.length));
146
+ if (path !== "" && !out.includes(path)) out.push(path);
147
+ }
148
+ return out;
149
+ }
150
+
151
+ /** One spelling of a path: lower-case, no `./` and no leading slash. */
152
+ export function normalisePath(value: string): string {
153
+ let path = value.trim().toLowerCase().replace(/\\/g, "/");
154
+ while (path.startsWith("./")) path = path.slice(2);
155
+ while (path.startsWith("/")) path = path.slice(1);
156
+ return path;
157
+ }
158
+
159
+ /**
160
+ * Does `path` name the file `cited` names?
161
+ *
162
+ * Equality, or `cited` as a whole trailing SEGMENT of `path` — never a bare
163
+ * `endsWith`. A finding may cite `rungate.ts` where the diff says
164
+ * `bin/rungate.ts`, and a bare suffix test would make that cited path match
165
+ * `lib/my-rungate.ts` just as well, which manufactures an `AMBIGUOUS` out of
166
+ * two unrelated files.
167
+ */
168
+ export function pathMatches(cited: string, path: string): boolean {
169
+ return path === cited || path.endsWith("/" + cited);
170
+ }
171
+
172
+ /** Paths of `cited` this pull request's diff contains. */
173
+ function pathsIn(cited: readonly string[], files: readonly string[]): string[] {
174
+ const normalised = files.map(normalisePath);
175
+ return cited.filter(c => normalised.some(f => pathMatches(c, f)));
176
+ }
177
+
178
+ /**
179
+ * The single place that decides, over paths the caller already extracted.
180
+ *
181
+ * The order is load-bearing and each step is commented with why it sits where
182
+ * it does. The one that is easy to get backwards is `THIS_PR`: it is answered
183
+ * BEFORE the corpus is consulted at all, because it is decided from the
184
+ * caller's own diff and is therefore still correct when the corpus is
185
+ * unreadable. Demoting it below the corpus guard would turn an answerable
186
+ * question into `UNMEASURED` on every network hiccup.
187
+ */
188
+ export function routePaths(citedPaths: readonly string[], options: RouteOptions): Routing {
189
+ const cited = citedPaths.map(normalisePath).filter(p => p !== "");
190
+ const unique: string[] = [];
191
+ for (const p of cited) if (!unique.includes(p)) unique.push(p);
192
+ const corpus = options.corpus;
193
+ const considered = corpus.status === "measured" ? corpus.prs.length : null;
194
+ const base = { citedPaths: unique, prs: [] as number[], matchedPaths: [] as string[], consideredPrs: considered };
195
+
196
+ // ── 1. is there anything to route ON? ──
197
+ if (unique.length === 0) {
198
+ return {
199
+ ...base,
200
+ route: "NO_CITED_PATH",
201
+ reason: "the finding cites no repository path, so no pull request can be matched by file",
202
+ };
203
+ }
204
+
205
+ // ── 2. do we know which pull request is asking? ──
206
+ //
207
+ // #1427: with BOTH `thisPr` and `changedFiles` absent, this function used
208
+ // to carry on. Two things then went wrong together and in the same
209
+ // direction. Step 3 could not run, so "the diff at hand already owns this"
210
+ // was never asked; and step 6's `filter(p => p.number !== options.thisPr)`
211
+ // excluded nothing against `undefined`, so the pull request being
212
+ // arbitrated stayed in its OWN candidate corpus and could be returned as
213
+ // the other pull request to route to. `scripts/arbitrate-finding.ts` turns
214
+ // OTHER_PR into exit 4, which suppresses the filing — so a finding about
215
+ // the current pull request was routed away from it, to it.
216
+ //
217
+ // The absence of a reading is not a reading of absence. It is the same
218
+ // distinction this repository draws between `findings: null` and
219
+ // `findings: []`, and the docblock above already draws it for the corpus;
220
+ // it was simply never drawn for the caller's own identity.
221
+ //
222
+ // Either input answers, and they answer different questions: a number lets
223
+ // the corpus supply the diff, a diff needs no number. Requiring the number
224
+ // specifically would refuse a caller that has the better evidence.
225
+ // An EMPTY changed-files list is not a reading either, and that is not a
226
+ // theoretical door: `scripts/arbitrate-finding.ts` builds the list with
227
+ // `.split(",").filter(Boolean)`, so `--changed-files ""` arrives as `[]`
228
+ // rather than as absent. Found by the review on this pull request, which
229
+ // is the same fail-open one layer in — `[]` standing for "I looked and
230
+ // there was nothing" when nobody looked.
231
+ //
232
+ // With `thisPr` present an empty list is fine: the corpus supplies the
233
+ // diff and the self-exclusion in step 6 has a number to work with. It is
234
+ // only the combination that cannot answer.
235
+ const hasReading =
236
+ options.thisPr !== undefined ||
237
+ (options.changedFiles !== undefined && options.changedFiles.length > 0);
238
+ if (!hasReading) {
239
+ return {
240
+ ...base,
241
+ route: "UNMEASURED",
242
+ reason:
243
+ "neither the current pull request number nor its changed files were given, so which " +
244
+ "pull request is asking is UNMEASURED — and a router that does not know that can return " +
245
+ "the asker as the pull request to route to",
246
+ };
247
+ }
248
+
249
+ // ── 3. does the PR it arrived on already own it? ──
250
+ const ownRow =
251
+ corpus.status === "measured" && options.thisPr !== undefined
252
+ ? corpus.prs.find(p => p.number === options.thisPr)
253
+ : undefined;
254
+ // `??` would let an EMPTY explicit list shadow the corpus row, which is
255
+ // the same `[]`-is-not-a-reading confusion one layer in: a caller passing
256
+ // `--changed-files ""` alongside a real `--this-pr` would lose the diff
257
+ // GitHub already reported for that pull request. A list is preferred over
258
+ // the corpus only when it actually says something.
259
+ const ownFiles =
260
+ options.changedFiles !== undefined && options.changedFiles.length > 0
261
+ ? options.changedFiles
262
+ : ownRow?.files;
263
+ if (ownFiles !== undefined) {
264
+ const own = pathsIn(unique, ownFiles);
265
+ if (own.length > 0) {
266
+ return {
267
+ ...base,
268
+ route: "THIS_PR",
269
+ matchedPaths: own,
270
+ ...(options.thisPr !== undefined ? { prs: [options.thisPr] } : {}),
271
+ reason: `this change touches ${own.join(", ")}, so the finding is about the diff at hand`,
272
+ };
273
+ }
274
+ }
275
+
276
+ // ── 4. was the corpus read at all? ──
277
+ if (corpus.status !== "measured") {
278
+ return { ...base, route: "UNMEASURED", reason: `the open pull requests were not read: ${corpus.why}` };
279
+ }
280
+
281
+ // ── 5. was every diff read in full? ──
282
+ const truncated = corpus.prs.filter(p => p.files.length !== p.declaredFileCount);
283
+ if (truncated.length > 0) {
284
+ return {
285
+ ...base,
286
+ route: "UNMEASURED",
287
+ prs: truncated.map(p => p.number),
288
+ reason:
289
+ `${truncated.map(p => `#${p.number} listed ${p.files.length} of ${p.declaredFileCount} files`).join("; ")}` +
290
+ " — a diff read in part can hold the cited path and never match, so neither a hit nor a miss is a reading here",
291
+ };
292
+ }
293
+
294
+ // ── 6. who else is holding the file? ──
295
+ const scored = corpus.prs
296
+ .filter(p => p.number !== options.thisPr)
297
+ .map(p => ({ pr: p.number, matched: pathsIn(unique, p.files) }))
298
+ .filter(row => row.matched.length > 0)
299
+ .sort((a, b) => b.matched.length - a.matched.length || a.pr - b.pr);
300
+ if (scored.length === 0) {
301
+ return {
302
+ ...base,
303
+ route: "TRACKER",
304
+ reason: `none of the ${corpus.prs.length} open pull requests change ${unique.join(", ")}`,
305
+ };
306
+ }
307
+ const best = scored[0].matched.length;
308
+ const top = scored.filter(row => row.matched.length === best);
309
+ if (top.length > 1) {
310
+ return {
311
+ ...base,
312
+ route: "AMBIGUOUS",
313
+ prs: top.map(row => row.pr),
314
+ matchedPaths: top[0].matched,
315
+ reason:
316
+ `${top.map(row => `#${row.pr}`).join(" and ")} both change ${top[0].matched.join(", ")} — ` +
317
+ "picking one would be a guess, so the choice stays with whoever is holding the finding",
318
+ };
319
+ }
320
+ return {
321
+ ...base,
322
+ route: "OTHER_PR",
323
+ prs: [scored[0].pr],
324
+ matchedPaths: scored[0].matched,
325
+ reason: `#${scored[0].pr} changes ${scored[0].matched.join(", ")}, which this finding names`,
326
+ };
327
+ }
328
+
329
+ /** One line a caller can print without re-deriving any of the above. */
330
+ export function routingSummary(routing: Routing): string {
331
+ const where = routing.prs.length > 0 ? ` ${routing.prs.map(n => `#${n}`).join(",")}` : "";
332
+ return `ROUTE ${routing.route}${where}: ${routing.reason}`;
333
+ }
@@ -38,6 +38,7 @@
38
38
  * something smaller. A formatter that half-understands its input is how this
39
39
  * issue happened.
40
40
  */
41
+ import { mayWrite, readDerivedDeclaration, skipLine } from "./derived-spec";
41
42
 
42
43
  export interface FrontmatterEntry {
43
44
  key: string;
@@ -125,11 +126,26 @@ export function serialiseFrontmatter(parsed: ParsedFrontmatter): string {
125
126
  * - A block this module cannot parse is returned UNCHANGED, with `stamped`
126
127
  * empty and `refused` set. Leaving a file alone is always safe; rewriting
127
128
  * one you cannot read is what #299 was.
129
+ * - A document declaring `generated-by:` is returned UNCHANGED the same way
130
+ * (#1549). Same principle, one step further: do not rewrite one you do not
131
+ * OWN either. `DocHygiene.hook.ts` fires on every doc write, so without
132
+ * this it stamps `updated:` into a generated spec — discarded at the next
133
+ * regeneration, after breaking whatever pins the bytes.
134
+ *
135
+ * The check lives here rather than in the hook for two reasons. `refused`
136
+ * is already the channel for "left alone, and here is why", so the caller
137
+ * needs no new branch; and `specs/HOOK-ARCHITECTURE-SPEC.md` SC-371 caps a
138
+ * hook at 150 lines precisely so decisions land in `lib/` instead.
128
139
  */
129
140
  export function stampFrontmatter(
130
141
  content: string,
131
142
  fields: Record<string, string>,
132
143
  ): { content: string; stamped: string[]; refused: string | null } {
144
+ const derived = readDerivedDeclaration(content);
145
+ if (!mayWrite(derived)) {
146
+ return { content, stamped: [], refused: skipLine("this document", derived) };
147
+ }
148
+
133
149
  const hasOpen = OPEN.test(content);
134
150
  const parsed = hasOpen ? parseFrontmatter(content) : { entries: [], body: content };
135
151