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
@@ -0,0 +1,163 @@
1
+ /**
2
+ * A closing keyword GitHub will never act on (#1362).
3
+ *
4
+ * `.claude/rules/ship-workflow.md` says to put `Fixes #<N>` in the PR body and
5
+ * let the merge close the issue. What it cannot say, because nothing in the
6
+ * tree measured it until now, is that **a closing keyword inside a code span
7
+ * is inert**. GitHub parses the body as markdown and does not link a reference
8
+ * it finds inside backticks or a fenced block, so the PR merges, the author
9
+ * sees the sentence they wrote, and the issue stays open.
10
+ *
11
+ * Measured on `hornjason/pai-harness` at 2026-10-23T15:31Z: of **50** open
12
+ * issues, **27** carry at least one merged pull request cross-reference, from
13
+ * **65** distinct merged pull requests. Running this detector over all 65
14
+ * produced **one** report — PR #1208, naming #1148 and #1157. Its second line
15
+ * is the keyword and the number wrapped in backticks, the pull request says in
16
+ * prose that the work is done and verified, and `closingIssuesReferences` is
17
+ * empty. #1148 was rescued by the squash commit subject `fix(#1148): …`;
18
+ * #1157 was not in the title and is still open.
19
+ *
20
+ * ## Why this reports the INERT ones and not the live ones
21
+ *
22
+ * A function that decided which references DO close an issue would be a second
23
+ * decider competing with GitHub's own parser, and the two would agree on
24
+ * almost every input — `.claude/rules/checks-must-be-able-to-fail.md`'s fourth
25
+ * shape, where no behavioural test can tell a dead guard from a live one.
26
+ *
27
+ * This reports only what a caller can check against the API's own answer: the
28
+ * caller already knows `closingIssuesReferences`, and an empty one beside a
29
+ * keyword the author clearly meant is a disagreement worth refusing on. The
30
+ * question asked here is "did you write something that looks like it closes an
31
+ * issue and does not", which GitHub does not answer anywhere.
32
+ *
33
+ * ## Why the keyword must be ADJACENT to the number
34
+ *
35
+ * This repository writes negations constantly — `.claude/rules/` tells agents
36
+ * never to put a closing keyword next to an issue number they are not closing,
37
+ * and they comply by writing the denial in prose instead.
38
+ *
39
+ * The negative control, over the same 65 merged pull requests: loosening
40
+ * "adjacent" to "within 40 characters" produced **21** candidates, of which
41
+ * the same two were true and **19** were false. Three kinds of false, and only
42
+ * the first is a negation:
43
+ *
44
+ * - a denial — `Closes nothing — #523 stays open`, `Fixes nothing on its own —
45
+ * leaving #713 open`, `Neither issue is closed by this PR`;
46
+ * - prose about a DIFFERENT issue — `| #1281 | … | fixed, merged as #1288 |`;
47
+ * - a window artefact, where the 40 characters end mid-number and the
48
+ * candidate names an issue nobody wrote.
49
+ *
50
+ * So adjacency is not a convenience, it is the whole precision of the check,
51
+ * and widening it is the cheapest wrong fix available here: on the only corpus
52
+ * that exists, the loosened rule is wrong nineteen times out of twenty-one.
53
+ */
54
+
55
+ /**
56
+ * The verbs GitHub acts on, in one declaring position.
57
+ *
58
+ * Taken from GitHub's documented list rather than invented. Every form is
59
+ * spelled out instead of stemmed: `close|closes|closed` and not `close[sd]?`
60
+ * with a comment, because a reader checking this against the documentation
61
+ * compares a list to a list.
62
+ */
63
+ export const CLOSING_KEYWORDS: readonly string[] = [
64
+ "close",
65
+ "closes",
66
+ "closed",
67
+ "fix",
68
+ "fixes",
69
+ "fixed",
70
+ "resolve",
71
+ "resolves",
72
+ "resolved",
73
+ ];
74
+
75
+ /** One closing keyword that is present in the prose and inert in the markup. */
76
+ export interface InertClosingReference {
77
+ /** The issue number the author wrote. */
78
+ issue: number;
79
+ /** The keyword as they spelled it, case preserved, for the message. */
80
+ keyword: string;
81
+ /** Which markup swallowed it. */
82
+ reason: "code-span" | "fenced-block";
83
+ /** The matched text, so a message can quote what to change. */
84
+ text: string;
85
+ }
86
+
87
+ /**
88
+ * Byte ranges the GitHub markdown parser will not scan for references.
89
+ *
90
+ * Fenced blocks are taken first and their ranges removed from the input the
91
+ * span scanner sees, because a fence contains backticks by definition and a
92
+ * span scanner run over the raw body would pair the fence delimiters with each
93
+ * other and report nonsense.
94
+ */
95
+ function maskedRanges(body: string): { start: number; end: number; reason: InertClosingReference["reason"] }[] {
96
+ const out: { start: number; end: number; reason: InertClosingReference["reason"] }[] = [];
97
+ const fenced = /^[ \t]*(`{3,}|~{3,})[^\n]*\n[\s\S]*?^[ \t]*\1[ \t]*$/gm;
98
+ for (const m of body.matchAll(fenced)) {
99
+ out.push({ start: m.index!, end: m.index! + m[0].length, reason: "fenced-block" });
100
+ }
101
+ const inFence = (i: number) => out.some(r => i >= r.start && i < r.end);
102
+ // Single-line code spans. `[^`\n]+` keeps a span from spilling across a line,
103
+ // which is what an unmatched backtick in ordinary prose would otherwise do —
104
+ // and an unmatched backtick is common in a body that quotes shell.
105
+ for (const m of body.matchAll(/(`+)([^`\n]+?)\1/g)) {
106
+ if (inFence(m.index!)) continue;
107
+ out.push({ start: m.index!, end: m.index! + m[0].length, reason: "code-span" });
108
+ }
109
+ return out;
110
+ }
111
+
112
+ /**
113
+ * Closing keywords in `body` that name an issue and will not fire.
114
+ *
115
+ * Deduplicated by issue number: a body that names the same issue twice inside
116
+ * backticks is one mistake, not two, and a message listing it twice reads as
117
+ * two problems to fix.
118
+ */
119
+ export function inertClosingReferences(body: string): InertClosingReference[] {
120
+ if (!body) return [];
121
+ const ranges = maskedRanges(body);
122
+ const pattern = new RegExp(`\\b(${CLOSING_KEYWORDS.join("|")})\\b[ \\t]*:?[ \\t]*#(\\d+)\\b`, "gi");
123
+ const seen = new Set<number>();
124
+ const out: InertClosingReference[] = [];
125
+ for (const m of body.matchAll(pattern)) {
126
+ const hit = ranges.find(r => m.index! >= r.start && m.index! < r.end);
127
+ if (!hit) continue;
128
+ const issue = Number.parseInt(m[2]!, 10);
129
+ if (seen.has(issue)) continue;
130
+ seen.add(issue);
131
+ out.push({ issue, keyword: m[1]!, reason: hit.reason, text: m[0] });
132
+ }
133
+ return out;
134
+ }
135
+
136
+ /**
137
+ * The refusal text.
138
+ *
139
+ * It names the issue, the markup and the remedy, because
140
+ * `.claude/rules/self-referential-tests.md` is explicit that a check without a
141
+ * remedy is an obstacle. The remedy here is one character of punctuation, so
142
+ * the message says exactly which.
143
+ */
144
+ export function inertClosingMessage(refs: InertClosingReference[], prNumber: number): string {
145
+ const rows = refs
146
+ .map(r => ` ${r.text} — inside a ${r.reason}, so GitHub never linked it (issue #${r.issue})`)
147
+ .join("\n");
148
+ return (
149
+ `PR #${prNumber} has no closingIssuesReferences, and its body names ` +
150
+ `${refs.length === 1 ? "an issue" : "issues"} with a closing keyword that the markdown ` +
151
+ `parser cannot see:\n${rows}\n\n` +
152
+ `GitHub does not read a reference inside backticks or a fenced block, so this ` +
153
+ `pull request records no link to them and the merge will not close them. ` +
154
+ `Something else still might — PR #1208 carried two inert references and its squash ` +
155
+ `commit subject, "fix(#1148): …", closed that one anyway, while #1157 was not in ` +
156
+ `the title and stayed open after the body said in prose it was done. Do not rely ` +
157
+ `on that: it is a conventional-commit prefix that happens to be a closing keyword. ` +
158
+ `Remove the backticks from that line, then re-read the field rather than the body: ` +
159
+ `gh pr view ${prNumber} --json closingIssuesReferences. If the reference is ` +
160
+ `deliberately inert because you are quoting a keyword rather than using one, move ` +
161
+ `the quote so the number is not adjacent to the verb.`
162
+ );
163
+ }
package/lib/conformity.ts CHANGED
@@ -10,6 +10,8 @@ import { existsSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSyn
10
10
  import { tmpdir } from "os";
11
11
  import type { Dirent } from "fs";
12
12
  import { collectSpecFiles } from "./spec-files";
13
+ import { skipLine } from "./derived-spec";
14
+ import { maySpecBeWritten, writeSpec } from "./write-spec";
13
15
  import {
14
16
  ambiguousSpecNames,
15
17
  readSpecRequirements,
@@ -328,6 +330,20 @@ export function flipPassingCheckboxes(): number {
328
330
  for (const [specPath, ids] of byFile) {
329
331
  if (!existsSync(specPath)) continue;
330
332
  let content = readFileSync(specPath, "utf-8");
333
+
334
+ // #1286: the second checkbox flipper, asked BEFORE any counting. A tick
335
+ // on a spec a generator owns is discarded at the next regeneration,
336
+ // after breaking whatever pins the file — and a criterion counted as
337
+ // flipped in a file nobody wrote is a number that means nothing.
338
+ // #1552: the question is asked twice here and that is deliberate — once
339
+ // early so `flipped` does not count a file nobody wrote, and once inside
340
+ // `writeSpec`. Two consults of ONE decider, both landing on `mayWrite`.
341
+ const early = maySpecBeWritten(content);
342
+ if (!early.allowed) {
343
+ console.warn(skipLine(specPath, early.reading));
344
+ continue;
345
+ }
346
+
331
347
  let changed = false;
332
348
  for (const id of ids) {
333
349
  const unchecked = `- [ ] ${id}:`;
@@ -337,7 +353,7 @@ export function flipPassingCheckboxes(): number {
337
353
  flipped++;
338
354
  }
339
355
  }
340
- if (changed) writeFileSync(specPath, content);
356
+ if (changed) writeSpec(specPath, content);
341
357
  }
342
358
  return flipped;
343
359
  }
package/lib/create-sc.ts CHANGED
@@ -14,10 +14,12 @@ import type { ScNamespaceReading, SourceReading } from "./sc-id-cross-tree";
14
14
  import { readScNamespace } from "./sc-id-cross-tree";
15
15
  import type { ScReservation, ScReservationReading } from "./sc-reservations";
16
16
  import {
17
+ blocksInNamespace,
17
18
  lowestFreeInBlock,
18
19
  readScReservations,
20
+ SC_NAMESPACE,
19
21
  RESERVATION_REFUSAL,
20
- reservationFor,
22
+ reservationsFor,
21
23
  reservedCeiling,
22
24
  reservedIdCount,
23
25
  SC_RESERVATIONS_PATH,
@@ -347,11 +349,16 @@ export function takenScNumbers(
347
349
  export function scReservationLeg(reading: ScReservationReading): SourceReading {
348
350
  const label = `SC reservation store (${SC_RESERVATIONS_PATH})`;
349
351
  if (reading.status === "read") {
352
+ // SC blocks only, on both numbers. `found` is documented as the size of
353
+ // the space the store removes from the allocator, and since #1363 an
354
+ // `FG`/`AR` block removes none of it — counting those would make the leg
355
+ // report a reading it did not take.
356
+ const sc = blocksInNamespace(reading.blocks, SC_NAMESPACE);
350
357
  return {
351
- label: `${label}: ${reading.blocks.length} block(s)`,
358
+ label: `${label}: ${sc.length} block(s)`,
352
359
  kind: "reservations",
353
360
  status: "read",
354
- found: reservedIdCount(reading.blocks),
361
+ found: reservedIdCount(sc),
355
362
  };
356
363
  }
357
364
  return {
@@ -386,16 +393,42 @@ export function allocateAgainstReservations(
386
393
  owner: string | null,
387
394
  taken: ReadonlySet<number>,
388
395
  ): number {
389
- const mine = reservationFor(blocks, owner);
390
- if (mine !== null) {
391
- const free = lowestFreeInBlock(mine, taken);
392
- if (free === null) {
393
- throw new ScReservationExhaustedError(
394
- `the SC block reserved to ${mine.owner} (${mine.from}-${mine.to}) is spent — ` +
395
- `widen it in ${SC_RESERVATIONS_PATH} rather than allocating outside it`,
396
- );
396
+ // SC blocks only, and the filter lives HERE rather than at the call site
397
+ // for the reason the docblock gives: this function is the single binding a
398
+ // mutation battery points at, and a filter applied by the caller would be a
399
+ // reservation-aware decision made somewhere this one cannot see.
400
+ //
401
+ // An `FG-45..60` block is not a claim on `SC-45..60`. Before #1363 it was
402
+ // read as one, which both pushed a stranger's allocation above 60 and
403
+ // answered the FG owner's next `create-sc` out of a block that describes
404
+ // different ids entirely.
405
+ blocks = blocksInNamespace(blocks, SC_NAMESPACE);
406
+ // EVERY block the owner holds, in declaration order, not the first one
407
+ // (#1541). Nothing has ever forbidden one owner from declaring two blocks
408
+ // and `overlapFault` does not refuse disjoint ones, so `find` was making a
409
+ // silent choice: with `100-102` spent and `200-299` empty under the same
410
+ // owner, the allocator refused and told the reader to WIDEN `100-102` — the
411
+ // one repair that cannot work, pointed at a block the owner had already
412
+ // moved past.
413
+ //
414
+ // Declaration order rather than lowest-first, because the order is a thing
415
+ // the person writing the store chose and `readScReservations` preserves it.
416
+ // Sorting here would relocate where existing owners allocate, which is a
417
+ // change to every block in the store dressed up as a bug fix.
418
+ const mine = reservationsFor(blocks, owner);
419
+ if (mine.length > 0) {
420
+ for (const block of mine) {
421
+ const free = lowestFreeInBlock(block, taken);
422
+ if (free !== null) return free;
397
423
  }
398
- return free;
424
+ // Only now is the owner out of room. The message names every block,
425
+ // because naming one invites widening it while another sits empty — and
426
+ // after #1541 that is no longer a hypothetical reader error.
427
+ const spent = mine.map(b => `${b.from}-${b.to}`).join(", ");
428
+ throw new ScReservationExhaustedError(
429
+ `every SC block reserved to ${mine[0].owner} (${spent}) is spent — ` +
430
+ `widen one in ${SC_RESERVATIONS_PATH} rather than allocating outside it`,
431
+ );
399
432
  }
400
433
  // No block of your own. The floor is still correct about what is WRITTEN;
401
434
  // it knows nothing about what is DECLARED, so it is raised past every block
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Whether a spec file's bytes are authored by a person or produced by a
3
+ * generator — and therefore whether any rungate write path may touch them
4
+ * (#1286).
5
+ *
6
+ * On 2026-10-22 `bunx rungate audit-specs --fix` injected 39 lines of
7
+ * `<!-- REVIEW: unmatched (...) -->` into a consumer's `specs/POV-SPEC.md`.
8
+ * That file is produced by the consumer's own `scripts/sync-spec.ts` and
9
+ * hash-pinned by its `test/spec-drift.test.ts`, so the edit broke the
10
+ * recorded `body-sha256` and reddened their suite — and the next
11
+ * `sync-spec.ts` run would have discarded it regardless. The write was
12
+ * simultaneously destructive and futile.
13
+ *
14
+ * The file said so, in English, on line 12: `<!-- DERIVED FILE — do not edit
15
+ * here.` `--fix` edited it on line 355. **A consumer who does the right thing
16
+ * and labels a derived file got nothing for it**, because the label had no
17
+ * reader. That is the gap this module closes.
18
+ *
19
+ * ## Why a frontmatter key and not the English sentence
20
+ *
21
+ * Matching the prose is the cheapest wrong fix, and it is wrong in the
22
+ * direction nobody sees. The sentence has no spelling: `DERIVED FILE`,
23
+ * `Managed by X — do not edit`, `DO NOT EDIT`, the same words reflowed across
24
+ * a line break, the same words in another language. You cannot enumerate it,
25
+ * and every widening of the pattern buys a false positive — at which point
26
+ * `--fix` silently stops working on a spec somebody wrote by hand, which is
27
+ * the same class of silent failure in the other direction.
28
+ *
29
+ * rungate's own tree already holds both traps:
30
+ *
31
+ * - `specs/bootstrap-data-flow/consumer-requirements.md` carries
32
+ * `# Managed by rungate — do not edit.` **twice, inside fenced code
33
+ * blocks**, quoting generated CI as an illustration.
34
+ * - `specs/SPEC-TEMPLATE.md` carries `<!-- BEGIN GENERATED PATTERNS -->`,
35
+ * which delimits a *region* and says nothing about the file.
36
+ *
37
+ * A loose `do not edit` grep stops fixing both of those and reports nothing.
38
+ *
39
+ * ## Why not `generated-sha`, which already exists
40
+ *
41
+ * Because it means the opposite thing. `generated-sha` is **rungate's own**
42
+ * provenance stamp, and `decideRuleWrite` (`lib/rule-provenance.ts`) reads a
43
+ * stamp matching the body as permission to **overwrite** — `action: "update"`,
44
+ * *"harness-written and untouched since"*. Reusing that key here would make
45
+ * one key authorise a write in the rules path and forbid one in the spec
46
+ * path.
47
+ *
48
+ * The fact being declared is different: **a generator that is not rungate
49
+ * owns these bytes.** Foreign ownership, not harness provenance. So it gets
50
+ * its own key, and the key's value names the generator, because a refusal
51
+ * that cannot say where to make the edit instead is a refusal nobody can act
52
+ * on.
53
+ *
54
+ * ## The three readings
55
+ *
56
+ * | reading | `mayWrite` | because |
57
+ * |---|---|---|
58
+ * | `derived` | no | `generated-by:` is declared; permanent and unambiguous |
59
+ * | `unprotected` | no | only a prose marker; caught, but by a detector that is deliberately too narrow to rely on |
60
+ * | `authored` | yes | nothing claims a generator owns it |
61
+ *
62
+ * `unprotected` is the honest middle. The prose detector below is scoped hard
63
+ * — an HTML comment, in the document head, outside code fences — precisely so
64
+ * it cannot eat the two authored specs named above. A detector that narrow
65
+ * **will** miss some real derived file, so a file it does catch is reported
66
+ * as UNPROTECTED and told to declare the key: we held the write this time,
67
+ * and that is not a guarantee you should build on.
68
+ *
69
+ * Refusing is the safe direction either way. A derived file wrongly preserved
70
+ * costs a line in a report. A derived file wrongly written costs the
71
+ * consumer's suite, and the edit is thrown away at the next regeneration.
72
+ *
73
+ * ## No relative imports, on purpose
74
+ *
75
+ * `test/derived-spec-guard.test.ts` builds a mutant copy of this file in an
76
+ * `mkdtemp` directory and runs the real write path against it. A relative
77
+ * import here would make that mutant die on module resolution, and a mutant
78
+ * that failed to load is indistinguishable from a guard that held —
79
+ * `.claude/rules/checks-must-be-able-to-fail.md`.
80
+ */
81
+
82
+ /** The frontmatter key by which a file declares which generator produces it. */
83
+ export const DERIVED_KEY = "generated-by";
84
+
85
+ export type DerivedStatus = "authored" | "derived" | "unprotected";
86
+
87
+ export interface DerivedReading {
88
+ status: DerivedStatus;
89
+ /** What regenerates the file. Present exactly when `status` is `derived`. */
90
+ generator?: string;
91
+ /** The prose that was read. Present exactly when `status` is `unprotected`. */
92
+ evidence?: string;
93
+ }
94
+
95
+ const FRONTMATTER = /^---\n([\s\S]*?)\n---\n/;
96
+
97
+ /**
98
+ * Phrases that declare a whole FILE produced, as opposed to a region of one.
99
+ *
100
+ * `generated file` and `generated by` are in; a bare `generated` is not —
101
+ * `<!-- BEGIN GENERATED PATTERNS -->` is a section delimiter and must not read
102
+ * as a declaration about the document.
103
+ */
104
+ const PROSE_DECLARATIONS = [
105
+ /\bdo\s+not\s+edit\b/i,
106
+ /\bdon'?t\s+edit\b/i,
107
+ /\bderived\s+file\b/i,
108
+ /\bgenerated\s+file\b/i,
109
+ /\bgenerated\s+by\b/i,
110
+ ];
111
+
112
+ /** Fenced blocks hold examples OF markers, never markers. */
113
+ function stripFences(text: string): string {
114
+ return text.replace(/^(```|~~~)[\s\S]*?^\1[^\n]*$/gm, "");
115
+ }
116
+
117
+ /**
118
+ * The part of the document a whole-file declaration can live in.
119
+ *
120
+ * Everything after the frontmatter, up to the first ATX heading or the first
121
+ * criterion line — whichever comes first. A marker below the first heading is
122
+ * talking about a section, which is the `SPEC-TEMPLATE.md` case.
123
+ *
124
+ * **Fences come out BEFORE the boundary is looked for, not after.** A fenced
125
+ * block quoting YAML, shell or Python holds lines beginning `# `, which is
126
+ * also an ATX heading — so searching the raw body ends the head inside the
127
+ * fence and a real marker below it is never read. That is a miss in the
128
+ * unsafe direction: the file reads as authored and `--fix` writes it.
129
+ *
130
+ * It also made the fenced-example case below pass for the wrong reason, which
131
+ * is the shape `.claude/rules/checks-must-be-able-to-fail.md` calls *green on
132
+ * the exit code, witnessing the wrong mechanism*: the fence was never
133
+ * stripped, the head simply stopped before it. Both cases in
134
+ * `test/derived-spec-guard.test.ts` now turn on this ordering.
135
+ */
136
+ function documentHead(content: string): string {
137
+ const body = stripFences(content.replace(FRONTMATTER, ""));
138
+ const lines = body.split("\n");
139
+ const end = lines.findIndex((l) => /^#{1,6}\s/.test(l) || /^\s*- \[[ xX]\]/.test(l));
140
+ return (end === -1 ? lines : lines.slice(0, end)).join("\n");
141
+ }
142
+
143
+ /** The first head HTML comment that declares the file produced, or null. */
144
+ function proseDerivedMarker(content: string): string | null {
145
+ const head = documentHead(content);
146
+ for (const [comment] of head.matchAll(/<!--[\s\S]*?-->/g)) {
147
+ if (PROSE_DECLARATIONS.some((re) => re.test(comment))) {
148
+ return comment.split("\n")[0].trim();
149
+ }
150
+ }
151
+ return null;
152
+ }
153
+
154
+ /** What the file claims about who produces it. */
155
+ export function readDerivedDeclaration(content: string): DerivedReading {
156
+ const fm = FRONTMATTER.exec(content);
157
+ if (fm) {
158
+ const declared = new RegExp(`^${DERIVED_KEY}:[ \\t]*(.*?)[ \\t]*$`, "m").exec(fm[1]);
159
+ if (declared) {
160
+ // A key present with no value still declares the file produced. It just
161
+ // cannot say by what, and the refusal says so rather than guessing.
162
+ const generator = declared[1].replace(/^["']|["']$/g, "").trim();
163
+ return { status: "derived", generator: generator || "(declared, unnamed)" };
164
+ }
165
+ }
166
+
167
+ const prose = proseDerivedMarker(content);
168
+ if (prose) return { status: "unprotected", evidence: prose };
169
+
170
+ return { status: "authored" };
171
+ }
172
+
173
+ /**
174
+ * THE decision. One site, one line, consulted by every rungate write path
175
+ * that edits a spec in place.
176
+ *
177
+ * Deliberately the only place the three readings turn into a yes or a no. A
178
+ * caller comparing `status` itself would be a second decider, which no
179
+ * mutation of this one could disable — the fourth shape in
180
+ * `.claude/rules/checks-must-be-able-to-fail.md`. `test/derived-spec-guard.test.ts`
181
+ * asserts the comparison below appears exactly once in this file, so the
182
+ * mutant it builds cannot be held up by a surviving copy.
183
+ */
184
+ export function mayWrite(reading: DerivedReading): boolean {
185
+ return reading.status === "authored";
186
+ }
187
+
188
+ /**
189
+ * Why a file was not written, in one line naming the file and the reason.
190
+ *
191
+ * A `--fix` that silently skips a file is the same defect as one that
192
+ * silently writes it, so there is no code path that refuses quietly.
193
+ */
194
+ export function skipLine(specFile: string, reading: DerivedReading): string {
195
+ if (reading.status === "derived") {
196
+ return (
197
+ `DERIVED: ${specFile} not written — frontmatter declares ` +
198
+ `\`${DERIVED_KEY}: ${reading.generator}\`. Edit the source and regenerate.`
199
+ );
200
+ }
201
+ return (
202
+ `UNPROTECTED: ${specFile} not written — read as derived from prose only ` +
203
+ `(${reading.evidence}). Prose is not a reliable declaration: add ` +
204
+ `\`${DERIVED_KEY}: <generator>\` to its frontmatter.`
205
+ );
206
+ }