rungate 0.5.0 → 0.7.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 (142) hide show
  1. package/lib/affected-tests.ts +398 -0
  2. package/lib/agent-audit.ts +2 -3
  3. package/lib/agent-worktree.ts +287 -0
  4. package/lib/agents-md-sections.ts +209 -0
  5. package/lib/behavioral-cache.ts +150 -2
  6. package/lib/branch-diff.ts +139 -0
  7. package/lib/branch-protection.ts +790 -0
  8. package/lib/brief-ac-alignment.ts +104 -0
  9. package/lib/brief-references.ts +205 -0
  10. package/lib/bun-version.ts +347 -0
  11. package/lib/check-remedy.ts +140 -0
  12. package/lib/ci-checkout.ts +18 -1
  13. package/lib/ci-history-depth.ts +159 -0
  14. package/lib/ci-setup-step.ts +96 -0
  15. package/lib/claude-code-action.ts +85 -0
  16. package/lib/claude-tool-vocabulary.ts +188 -0
  17. package/lib/cli-commands.ts +15 -0
  18. package/lib/commit-sha.ts +42 -0
  19. package/lib/commit-subject.ts +90 -0
  20. package/lib/compliance-report.ts +377 -45
  21. package/lib/compliance.ts +196 -20
  22. package/lib/config-loader.ts +51 -1
  23. package/lib/config-trackable.ts +391 -0
  24. package/lib/conformity.ts +1272 -189
  25. package/lib/containment.ts +238 -0
  26. package/lib/content-hash.ts +24 -0
  27. package/lib/context-docs.ts +143 -28
  28. package/lib/create-brief.ts +2 -1
  29. package/lib/create-sc.ts +323 -4
  30. package/lib/dev-liveness.ts +180 -0
  31. package/lib/discovery-branch-points.ts +432 -0
  32. package/lib/discovery-stability.ts +481 -0
  33. package/lib/distribution-currency.ts +186 -0
  34. package/lib/doc-routing.ts +157 -0
  35. package/lib/doc-scan-targets.ts +9 -0
  36. package/lib/evidence-command-transport.ts +160 -0
  37. package/lib/evidence-prevalidator.ts +246 -2
  38. package/lib/evidence-satisfiability.ts +534 -12
  39. package/lib/failure-intake.ts +317 -0
  40. package/lib/fallow-availability.ts +286 -0
  41. package/lib/fs-write-capabilities.ts +232 -0
  42. package/lib/gate-refusal-currency.ts +112 -0
  43. package/lib/gate-run-split.ts +147 -0
  44. package/lib/gate-timeouts.ts +82 -0
  45. package/lib/generators/agent-briefs.ts +4 -1
  46. package/lib/generators/agents-md.ts +204 -48
  47. package/lib/generators/code-map.ts +2 -1
  48. package/lib/generators/types.ts +8 -0
  49. package/lib/git-dates.ts +55 -0
  50. package/lib/git-isolation.ts +140 -0
  51. package/lib/github.ts +15 -0
  52. package/lib/google-auth-action.ts +93 -0
  53. package/lib/harness-project.ts +48 -0
  54. package/lib/harness-provenance.ts +255 -0
  55. package/lib/hook-evidence.ts +235 -0
  56. package/lib/hook-scopes.ts +386 -0
  57. package/lib/hook-target-tree.ts +398 -0
  58. package/lib/hook-trees.ts +447 -0
  59. package/lib/js-top-level-code.ts +78 -10
  60. package/lib/junit-checks.ts +536 -0
  61. package/lib/launch-base.ts +253 -0
  62. package/lib/line-citation.ts +372 -0
  63. package/lib/local-calendar-day.ts +78 -0
  64. package/lib/orphan-reaper.ts +468 -0
  65. package/lib/parity-binding.ts +205 -0
  66. package/lib/per-test-timeouts.ts +219 -0
  67. package/lib/plan-coverage.ts +151 -0
  68. package/lib/prior-branch.ts +201 -8
  69. package/lib/process-table.ts +146 -0
  70. package/lib/project-state-derivation.ts +219 -0
  71. package/lib/project-state-root.ts +258 -0
  72. package/lib/project-state-shape.ts +59 -0
  73. package/lib/promote-outputs.ts +6 -2
  74. package/lib/published-artifact.ts +525 -0
  75. package/lib/readdir-sorted.ts +45 -0
  76. package/lib/report-provenance.ts +156 -0
  77. package/lib/review-execution-reading.ts +206 -0
  78. package/lib/review-tool-agreement.ts +433 -0
  79. package/lib/rule-promotion.ts +234 -0
  80. package/lib/rule-retirement.ts +525 -0
  81. package/lib/run-branch.ts +612 -0
  82. package/lib/rungate-schema.ts +19 -0
  83. package/lib/runner-home.ts +274 -0
  84. package/lib/sc-claim-forms.ts +75 -0
  85. package/lib/sc-id-cross-tree.ts +323 -0
  86. package/lib/sc-ids.ts +121 -13
  87. package/lib/sc-reservations.ts +289 -0
  88. package/lib/scaffold/ai-review-findings.ts +403 -0
  89. package/lib/scaffold/ai-review-step.ts +4777 -0
  90. package/lib/scaffold/managed-workflow.ts +587 -192
  91. package/lib/scaffold/owned-files.ts +186 -39
  92. package/lib/scaffold/pre-push-hook.ts +49 -5
  93. package/lib/scaffold/rehearsal.ts +205 -71
  94. package/lib/scaffold/steps.ts +1517 -293
  95. package/lib/scaffold/workflow-census.ts +217 -0
  96. package/lib/scaffold/workflow-drift.ts +217 -0
  97. package/lib/scaffold/write-steps.ts +10 -4
  98. package/lib/scan-budget.ts +247 -0
  99. package/lib/scanner.ts +80 -62
  100. package/lib/scratch-roots.ts +50 -5
  101. package/lib/screenshot-discovery.ts +121 -0
  102. package/lib/screenshot-upload.ts +41 -1
  103. package/lib/secret-patterns.ts +511 -8
  104. package/lib/ship-mode.ts +219 -0
  105. package/lib/source-slice.ts +294 -0
  106. package/lib/spec-listing.ts +148 -0
  107. package/lib/spec-requirements.ts +209 -0
  108. package/lib/stale-cleanup.ts +37 -3
  109. package/lib/suite-flake.ts +278 -0
  110. package/lib/suite-measurement.ts +23 -4
  111. package/lib/suite-run-reading.ts +411 -1
  112. package/lib/suite-timeout-margin.ts +193 -0
  113. package/lib/test-case-bodies.ts +883 -0
  114. package/lib/test-case-deletion.ts +653 -0
  115. package/lib/test-census.ts +97 -29
  116. package/lib/test-command-positions.ts +274 -0
  117. package/lib/test-command.ts +133 -0
  118. package/lib/test-suite-lock.ts +325 -26
  119. package/lib/tool-probe.ts +142 -0
  120. package/lib/top-level-cd.ts +393 -0
  121. package/lib/tracked-vs-ignored.ts +234 -0
  122. package/lib/tree-entries.ts +89 -0
  123. package/lib/ts-ast.ts +200 -0
  124. package/lib/validators/spec-validators.ts +3 -2
  125. package/lib/walk-test-files.ts +97 -0
  126. package/lib/workflow-actions.ts +263 -0
  127. package/lib/worktree-collect.ts +177 -5
  128. package/lib/worktree-repo.ts +36 -1
  129. package/package.json +2 -1
  130. package/scripts/ai-review-findings.ts +45 -0
  131. package/scripts/audit-specs.ts +247 -12
  132. package/scripts/audit-transcript.ts +2 -1
  133. package/scripts/convert-spec.ts +2 -1
  134. package/scripts/create-sc.ts +37 -7
  135. package/scripts/create-spec.ts +2 -1
  136. package/scripts/create-success.ts +2 -1
  137. package/scripts/extract-constraints.ts +197 -26
  138. package/scripts/generate-code-map.ts +62 -28
  139. package/scripts/scaffold-project.ts +12 -2
  140. package/scripts/split-spec.ts +2 -1
  141. package/scripts/sync-sc-status.ts +127 -14
  142. package/scripts/sync-spec-tests.ts +2 -1
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Whether this project ships through the harness, and the rule that says so (#911).
3
+ *
4
+ * `.claude/rules/ship-workflow.md` is generated, and until this module existed
5
+ * its text was a constant: *"All implementation work must go through the ship
6
+ * workflow — never spawn agents directly."* Jason decided on 2026-10-19,
7
+ * reconfirmed on 2026-10-21, to bypass the harness until RunGate is stable —
8
+ * so every agent working under that decision read a repo rule contradicting
9
+ * its instructions, and had no way to tell a live policy from a stale one.
10
+ * One did exactly the right thing: it shipped as instructed and closed its
11
+ * report flagging the conflict, because nothing in the tree could resolve it.
12
+ *
13
+ * Editing the consumer's copy is not a fix. The file carries a
14
+ * `generated-sha` and `decideRuleWrite` rewrites it on the next re-scaffold,
15
+ * so the decision has to be declared where the generator reads it.
16
+ *
17
+ * ## Why the refusal lives here and not in the zod schema
18
+ *
19
+ * The obvious place to reject `"mode": "dierct"` is `ProjectHarnessSchema`,
20
+ * as `z.enum(["harness", "direct"])`. That is the wrong place, and the reason
21
+ * is the one `.claude/rules/config-access.md` names: `lib/scanner.ts`'s
22
+ * `loadHarnessConfig` wraps its read in `catch {}` and returns `null`. A zod
23
+ * throw from a typo'd mode would be swallowed there and read as *no config*,
24
+ * which resolves to `"harness"` — **a typo that silently reinstates the
25
+ * harness is precisely the failure #911 exists to stop.** So `ShipSchema`
26
+ * takes `mode` as a plain string and this module is the single decider, with
27
+ * a message that names the offending value and the modes that exist.
28
+ */
29
+
30
+ import { RUNGATE_CONFIG_RELATIVE_PATH } from "./config-loader";
31
+
32
+ /** The declared ship modes. There is no third, and no silent fallback. */
33
+ export const SHIP_MODES = ["harness", "direct"] as const;
34
+
35
+ export type ShipMode = (typeof SHIP_MODES)[number];
36
+
37
+ /**
38
+ * What a project with no `ship` block gets.
39
+ *
40
+ * Absent means `"harness"` so every consumer scaffolded before #911 is
41
+ * byte-identical after it. That is asserted, not asserted-by-comment — see
42
+ * `test/ship-mode.test.ts`.
43
+ */
44
+ export const DEFAULT_SHIP_MODE: ShipMode = "harness";
45
+
46
+ export interface ShipPolicy {
47
+ mode: ShipMode;
48
+ /** The day the project went direct, `YYYY-MM-DD`. Present iff `direct`. */
49
+ since?: string;
50
+ /** Why, in the project's own words. Present iff `direct`. */
51
+ reason?: string;
52
+ }
53
+
54
+ /** Thrown rather than defaulted. A config that says something unreadable is not a config that says nothing. */
55
+ export class ShipModeError extends Error {
56
+ constructor(message: string) {
57
+ super(message);
58
+ this.name = "ShipModeError";
59
+ }
60
+ }
61
+
62
+ /**
63
+ * The config file NAMED, never read — every refusal and the generated rule
64
+ * tell the reader where to go and fix it. Taken from `lib/config-loader.ts`
65
+ * rather than written as a literal, per `.claude/rules/config-access.md`:
66
+ * that constant is exported for exactly this, and a literal here is a
67
+ * CONFIG-1 violation whether or not anything opens the file.
68
+ */
69
+ const CONFIG_PATH = RUNGATE_CONFIG_RELATIVE_PATH;
70
+ const SINCE_FORMAT = /^\d{4}-\d{2}-\d{2}$/;
71
+
72
+ function refuse(detail: string): never {
73
+ throw new ShipModeError(`REFUSED: ${CONFIG_PATH} declares an unusable \`ship\` block — ${detail}`);
74
+ }
75
+
76
+ function nonEmptyString(value: unknown): value is string {
77
+ return typeof value === "string" && value.trim().length > 0;
78
+ }
79
+
80
+ /**
81
+ * Resolve the project's ship policy from its loaded harness config.
82
+ *
83
+ * Takes the already-loaded config rather than a project root, because
84
+ * `.claude/rules/config-access.md` puts every read of the config file behind
85
+ * `lib/config-loader.ts` and the scan has already done it.
86
+ *
87
+ * A `ship` block that is present and unreadable REFUSES. Absent is the only
88
+ * thing that defaults, and it defaults to the behaviour that existed before
89
+ * this module.
90
+ */
91
+ export function resolveShipPolicy(harnessConfig: Record<string, unknown> | null | undefined): ShipPolicy {
92
+ const raw = harnessConfig?.ship;
93
+ if (raw === undefined || raw === null) return { mode: DEFAULT_SHIP_MODE };
94
+
95
+ if (typeof raw !== "object" || Array.isArray(raw)) {
96
+ refuse(`\`ship\` must be an object, got ${Array.isArray(raw) ? "an array" : typeof raw}`);
97
+ }
98
+
99
+ const block = raw as Record<string, unknown>;
100
+ const mode = block.mode;
101
+
102
+ if (mode === undefined) {
103
+ refuse(
104
+ `it declares no \`mode\`. Write one of ${SHIP_MODES.map(m => `"${m}"`).join(", ")}, ` +
105
+ `or delete the block to get "${DEFAULT_SHIP_MODE}"`,
106
+ );
107
+ }
108
+
109
+ if (!(SHIP_MODES as readonly unknown[]).includes(mode)) {
110
+ refuse(
111
+ `\`ship.mode\` is ${JSON.stringify(mode)}, which is not a ship mode. ` +
112
+ `Valid modes: ${SHIP_MODES.map(m => `"${m}"`).join(", ")}. ` +
113
+ `This is NOT defaulted to "${DEFAULT_SHIP_MODE}" on purpose — a typo that silently ` +
114
+ `reinstates the harness is the defect #911 exists to stop`,
115
+ );
116
+ }
117
+
118
+ if (mode === "harness") return { mode: "harness" };
119
+
120
+ // "direct" without a date and a reason is the bare permission #911 says the
121
+ // next agent re-litigates. The whole defect being fixed is an agent unable
122
+ // to tell a current decision from a stale one, so the two facts that make
123
+ // it current are required rather than optional.
124
+ const { since, reason } = block;
125
+ if (!nonEmptyString(since)) {
126
+ refuse(
127
+ `\`ship.mode\` is "direct" but \`ship.since\` is ${JSON.stringify(since ?? null)}. ` +
128
+ `A direct-ship declaration must say when it was taken, as "YYYY-MM-DD" — ` +
129
+ `a rule with no date reads as sloppiness and gets re-litigated`,
130
+ );
131
+ }
132
+ if (!SINCE_FORMAT.test(since)) {
133
+ refuse(`\`ship.since\` is ${JSON.stringify(since)}, which is not a "YYYY-MM-DD" date`);
134
+ }
135
+ if (!nonEmptyString(reason)) {
136
+ refuse(
137
+ `\`ship.mode\` is "direct" but \`ship.reason\` is ${JSON.stringify(reason ?? null)}. ` +
138
+ `A direct-ship declaration must say why, so the next agent can tell a current ` +
139
+ `decision from a stale one`,
140
+ );
141
+ }
142
+
143
+ return { mode: "direct", since, reason };
144
+ }
145
+
146
+ /**
147
+ * The generated body of `.claude/rules/ship-workflow.md`.
148
+ *
149
+ * One binding, so there is one thing to mutate and the two modes cannot drift
150
+ * into two renderers. The `"harness"` arm is byte-identical to what the
151
+ * generator emitted before #911 — `test/ship-mode.test.ts` asserts that
152
+ * against the file in this repository rather than against a copy of the
153
+ * string, so a reformat here is caught.
154
+ */
155
+ export function shipWorkflowRule(policy: ShipPolicy): string {
156
+ if (policy.mode === "harness") {
157
+ return `---
158
+ description: All implementation work must go through the ship workflow — never spawn agents directly
159
+ ---
160
+
161
+ ## Ship Workflow Required
162
+
163
+ When shipping an issue or implementing code changes, use the ship workflow:
164
+
165
+ \`\`\`
166
+ Skill("ship") → Workflow({ scriptPath: "workflows/ship.js" })
167
+ \`\`\`
168
+
169
+ **NEVER spawn Marcus, Quinn, or Rook directly with the Agent tool.** The ship workflow captures transcripts, runs compliance grading, and enforces gates. Spawning agents directly bypasses all measurement.
170
+
171
+ If Skill("harness") or Skill("goal") fails, fall back to Skill("ship") with the issue number.
172
+ `;
173
+ }
174
+
175
+ return `---
176
+ description: This project ships DIRECTLY as of ${policy.since} — do not route work through the ship workflow
177
+ ---
178
+
179
+ ## Direct-ship mode, since ${policy.since}
180
+
181
+ **This project is in direct-ship mode as of ${policy.since}: ${policy.reason}.**
182
+
183
+ Shipping an issue without the ship workflow is the current, declared policy of
184
+ this project. Do not call \`Skill("ship")\` and do not invoke
185
+ \`Workflow({ scriptPath: "workflows/ship.js" })\`. If another document tells you
186
+ to, that document is out of date and this one is not: the mode is declared in
187
+ \`${CONFIG_PATH}\` under \`ship\`, and this file is generated from it, so a
188
+ re-scaffold restates it rather than reverting it.
189
+
190
+ You do not need to escalate to ask whether the bypass is legitimate. The date
191
+ and the reason above are the answer.
192
+
193
+ ## What to do instead
194
+
195
+ "Do not use the harness" is not an instruction you can follow. This is:
196
+
197
+ 1. **Claim the issue on the tracker first** — \`gh issue edit <N> --add-assignee @me\`.
198
+ An unclaimed issue is indistinguishable from an unstarted one.
199
+ 2. **Work from a worktree cut off \`origin/main\`**, never from the project's
200
+ primary checkout — another session is usually in it.
201
+ 3. **Write the regression test first, and prove it can fail** before writing
202
+ the fix. See \`.claude/rules/checks-must-be-able-to-fail.md\`.
203
+ 4. **Run targeted tests**, not the whole suite — name the files your change
204
+ touches.
205
+ 5. **Open a PR and enable auto-merge.** Review happens there, where it is
206
+ durable and where CI already runs.
207
+ 6. **Let the PR close the issue. Do not run \`gh issue close\` yourself.** Put
208
+ \`Fixes #<N>\` in the PR BODY, naming the issue you claimed in step 1, and
209
+ the merge closes it. A hand-typed close is attributed to nobody, so
210
+ \`issue-audit.yml\` records the issue as closed with no ship record — the
211
+ lane's own output becomes the audit's finding (#925).
212
+
213
+ ## This is temporary, and reversible in one line
214
+
215
+ Set \`ship.mode\` back to \`"harness"\` in \`${CONFIG_PATH}\` and re-scaffold.
216
+ Nothing about the harness has been removed — \`Skill("ship")\` and
217
+ \`workflows/ship.js\` are unchanged and still work.
218
+ `;
219
+ }
@@ -0,0 +1,294 @@
1
+ /**
2
+ * Cut the region a claim is about, by where the CONSTRUCT ends (#664).
3
+ *
4
+ * `.claude/rules/checks-must-be-able-to-fail.md` says to cut the region out of
5
+ * the string first, assert on the cut, and assert the cut is non-empty. Ten
6
+ * guards in `test/` satisfy the letter of that with `slice(at, at + 6000)` and
7
+ * miss the point: a region ends where its construct ends, and a character
8
+ * count is a guess about how long the construct will stay that size. The guess
9
+ * decays silently and the day it fails it accuses the wrong code.
10
+ *
11
+ * Measured on `test/worktree-repo.test.ts` SC-1446: 650 characters of
12
+ * headroom, and a 2,119-character insertion in the branch ABOVE the one it
13
+ * guards pushed both target strings 1,469 characters past the boundary. The
14
+ * case is named "the Verify BUILD regression has an else, and it is terminal",
15
+ * the `else` is still there and still terminal, and the case went red.
16
+ *
17
+ * So this module has **no numeric-length parameter anywhere in its API**. A
18
+ * window cannot decay if there is no window to pass. A cut ends at a matching
19
+ * bracket or at a named end anchor, and nothing else is offered.
20
+ *
21
+ * ## The refusals, and why each is its own name
22
+ *
23
+ * | refusal | the input only it reaches |
24
+ * |---|---|
25
+ * | `AnchorNotFoundError` | an anchor, start anchor or end anchor absent from the document |
26
+ * | `AmbiguousAnchorError` | a subject or start anchor occurring more than once |
27
+ * | `UnbalancedCutError` | a bracket with no matching close, or no opener after the anchor |
28
+ * | `EmptyCutError` | an end landing where the anchor ends, so the cut holds only the anchor |
29
+ * | `AnchorOutsideCutError` | a two-sided region that does not contain the anchor it is about |
30
+ *
31
+ * **`AmbiguousAnchorError` is the one this module shipped without (#668).**
32
+ * `structuralCut` used `indexOf` and `structuralCutAround` used
33
+ * `lastIndexOf`, and neither counted: a duplicated anchor produced a
34
+ * well-formed cut about whichever occurrence the direction of the search
35
+ * happened to reach. That is worse than the four refusals above, because
36
+ * those return nothing and this returns something — a confident answer about
37
+ * the wrong region, which is the failure line numbers already had (#514).
38
+ * `lib/source-anchor.ts`, named here as this module's model, has said
39
+ * *"not found and found-twice are both refusals"* since it was written;
40
+ * this module was the sibling that did not.
41
+ *
42
+ * **The END anchor is deliberately NOT counted**, and that is not an
43
+ * oversight carried forward. An end anchor is a boundary searched forward
44
+ * from a known start, and the nearest one is the correct one by
45
+ * construction: `"\n}"` closes hundreds of functions in any file worth
46
+ * cutting, and refusing it as ambiguous would make the end-anchor form
47
+ * unusable. A subject or start anchor is a claim about WHICH construct, and
48
+ * there the second occurrence is the whole problem.
49
+ *
50
+ * The last two of the original four are the ones that matter most, because the thing they prevent
51
+ * reads as a pass. A caller that runs `expect(cut).toContain(x)` over a cut
52
+ * that is nothing but the anchor is asserting against text it typed itself,
53
+ * and a two-sided region that misses its subject answers confidently about the
54
+ * wrong code — which is the failure line numbers already had (#514).
55
+ *
56
+ * This is a sibling of `lib/source-anchor.ts`, not a replacement for it. That
57
+ * module answers *where does this citation point*; this one answers *what is
58
+ * the region this claim is about*. Its exports are untouched.
59
+ *
60
+ * ## Scope, stated rather than implied
61
+ *
62
+ * The bracket scan is a raw text scan, the same one already written by hand in
63
+ * `test/ship-remediation-commits.test.ts` and `test/liveness-contradiction.test.ts`.
64
+ * It does not know about strings, comments or regex literals, so it is for
65
+ * cutting a block out of source whose brackets balance across the region —
66
+ * which is what every call site here does. An unbalanced region refuses by
67
+ * name rather than running to the end of the document.
68
+ */
69
+
70
+ /** The bracket kinds a cut can close on. */
71
+ export type Bracket = "{" | "[" | "(";
72
+
73
+ const CLOSER: Record<Bracket, string> = { "{": "}", "[": "]", "(": ")" };
74
+
75
+ /**
76
+ * Where a cut stops: at the close of a balanced bracket, or at a named anchor.
77
+ *
78
+ * Both ends are structural. Neither is a length — that is the whole point of
79
+ * the module and the reason this type has no third member.
80
+ */
81
+ export type CutEnd = { balanced: Bracket } | { endAnchor: string };
82
+
83
+ /** The bounds of a two-sided cut: a named start, and either structural end. */
84
+ export interface CutBounds {
85
+ startAnchor: string;
86
+ end: CutEnd;
87
+ }
88
+
89
+ /** An anchor — leading, trailing or the subject itself — is not in the document. */
90
+ export class AnchorNotFoundError extends Error {
91
+ readonly anchor: string;
92
+ constructor(anchor: string, role: string) {
93
+ super(`the ${role} ${JSON.stringify(anchor)} does not appear in the document, so the cut reads nothing`);
94
+ this.name = "AnchorNotFoundError";
95
+ this.anchor = anchor;
96
+ Object.setPrototypeOf(this, AnchorNotFoundError.prototype);
97
+ }
98
+ }
99
+
100
+ /** A bracket cut found no opener, or an opener that never closes. */
101
+ export class UnbalancedCutError extends Error {
102
+ readonly anchor: string;
103
+ readonly bracket: Bracket;
104
+ constructor(anchor: string, bracket: Bracket, detail: string) {
105
+ super(`the cut from ${JSON.stringify(anchor)} cannot close its ${bracket} — ${detail}`);
106
+ this.name = "UnbalancedCutError";
107
+ this.anchor = anchor;
108
+ this.bracket = bracket;
109
+ Object.setPrototypeOf(this, UnbalancedCutError.prototype);
110
+ }
111
+ }
112
+
113
+ /**
114
+ * The cut holds nothing but the anchor the caller typed.
115
+ *
116
+ * Not literally zero bytes — a cut always carries its own anchor — but zero
117
+ * bytes BEYOND it, which is the same thing for every purpose a cut has. An
118
+ * assertion over it can only confirm the anchor, and an assertion that can
119
+ * only confirm its own input is this repository's most common defect.
120
+ */
121
+ export class EmptyCutError extends Error {
122
+ readonly anchor: string;
123
+ constructor(anchor: string) {
124
+ super(
125
+ `the cut from ${JSON.stringify(anchor)} holds nothing beyond the anchor itself, ` +
126
+ `so anything asserted against it is being asserted against the anchor`,
127
+ );
128
+ this.name = "EmptyCutError";
129
+ this.anchor = anchor;
130
+ Object.setPrototypeOf(this, EmptyCutError.prototype);
131
+ }
132
+ }
133
+
134
+ /**
135
+ * The anchor names more than one place, so the cut is about whichever one
136
+ * the search direction reached first.
137
+ *
138
+ * The count is in the message on purpose. A refusal that says only
139
+ * "ambiguous" sends the reader back to count occurrences by hand, which is
140
+ * the work the refusal just did.
141
+ */
142
+ export class AmbiguousAnchorError extends Error {
143
+ readonly anchor: string;
144
+ readonly occurrences: number;
145
+ constructor(anchor: string, role: string, occurrences: number) {
146
+ super(
147
+ `the ${role} ${JSON.stringify(anchor)} appears ${occurrences} times in the document, ` +
148
+ `so the cut would be about whichever one the search reached first — ` +
149
+ `not found and found-twice are both refusals`,
150
+ );
151
+ this.name = "AmbiguousAnchorError";
152
+ this.anchor = anchor;
153
+ this.occurrences = occurrences;
154
+ Object.setPrototypeOf(this, AmbiguousAnchorError.prototype);
155
+ }
156
+ }
157
+
158
+ /** A two-sided region closed before it reached the anchor it is about. */
159
+ export class AnchorOutsideCutError extends Error {
160
+ readonly anchor: string;
161
+ constructor(anchor: string, startAnchor: string) {
162
+ super(
163
+ `the region from ${JSON.stringify(startAnchor)} does not contain ${JSON.stringify(anchor)} — ` +
164
+ `it closed before reaching the anchor, so it is about other code`,
165
+ );
166
+ this.name = "AnchorOutsideCutError";
167
+ this.anchor = anchor;
168
+ Object.setPrototypeOf(this, AnchorOutsideCutError.prototype);
169
+ }
170
+ }
171
+
172
+ /**
173
+ * How many times `anchor` occurs in `doc`.
174
+ *
175
+ * Exported so the duplicate-anchor scan and every caller that wants to know
176
+ * ask ONE binding. `test/worktree-repo.test.ts` wrote
177
+ * `source.split(ELSE_SITE).length - 1` by hand, which is a second decider
178
+ * for the same question: mutating either would leave the other counting
179
+ * correctly, and no behavioural test could tell them apart
180
+ * (`.claude/rules/checks-must-be-able-to-fail.md`, the fourth shape).
181
+ *
182
+ * An EMPTY anchor counts as zero rather than as `doc.length + 1`. Splitting
183
+ * on "" returns one element per character, which would report a huge number
184
+ * for an anchor that names nothing; and `indexOf("")` is 0, so without this
185
+ * an empty anchor silently cuts from the top of the file.
186
+ */
187
+ export function anchorOccurrences(doc: string, anchor: string): number {
188
+ if (anchor === "") return 0;
189
+ return doc.split(anchor).length - 1;
190
+ }
191
+
192
+ /**
193
+ * The single index of `anchor`, refusing both zero and more than one.
194
+ *
195
+ * One binding for both functions and both anchor roles, so there is one
196
+ * thing to mutate. `structuralCut` reaching for `indexOf` and
197
+ * `structuralCutAround` reaching for `lastIndexOf` is exactly how the two
198
+ * ended up disagreeing about a question neither of them was asking.
199
+ */
200
+ function locateUnique(doc: string, anchor: string, role: string): number {
201
+ const n = anchorOccurrences(doc, anchor);
202
+ if (n === 0) throw new AnchorNotFoundError(anchor, role);
203
+ if (n > 1) throw new AmbiguousAnchorError(anchor, role, n);
204
+ return doc.indexOf(anchor);
205
+ }
206
+
207
+ /**
208
+ * The index one past the matching close of the first `bracket` at or after
209
+ * `from`. Refuses rather than returning a sentinel: `-1` and "the end of the
210
+ * document" are both indistinguishable from a correct answer at the call site.
211
+ */
212
+ function balancedEnd(doc: string, from: number, anchor: string, bracket: Bracket): number {
213
+ const open = doc.indexOf(bracket, from);
214
+ if (open < 0) {
215
+ throw new UnbalancedCutError(anchor, bracket, `no ${bracket} follows the anchor`);
216
+ }
217
+ const closer = CLOSER[bracket];
218
+ let depth = 0;
219
+ for (let i = open; i < doc.length; i++) {
220
+ if (doc[i] === bracket) depth++;
221
+ else if (doc[i] === closer && --depth === 0) return i + 1;
222
+ }
223
+ throw new UnbalancedCutError(anchor, bracket, `the ${bracket} at offset ${open} is never closed`);
224
+ }
225
+
226
+ /** The exclusive end index for one `CutEnd`, measured forward from `from`. */
227
+ function endIndex(doc: string, from: number, anchor: string, end: CutEnd): number {
228
+ if ("balanced" in end) return balancedEnd(doc, from, anchor, end.balanced);
229
+ // Searched past the anchor, and EXCLUSIVE of the end anchor — which is how
230
+ // `slice(at, src.indexOf("\n}", at))` is already written in this tree.
231
+ const at = doc.indexOf(end.endAnchor, from + anchor.length);
232
+ if (at < 0) throw new AnchorNotFoundError(end.endAnchor, "end anchor");
233
+ return at;
234
+ }
235
+
236
+ /** Refuse a cut that carries nothing the caller did not already type. */
237
+ function refuseEmpty(doc: string, from: number, anchor: string, to: number): void {
238
+ if (doc.slice(from + anchor.length, to).trim().length === 0) throw new EmptyCutError(anchor);
239
+ }
240
+
241
+ /**
242
+ * The text from `anchor` to a structural end.
243
+ *
244
+ * ```ts
245
+ * structuralCut(shipSource, "Verify CODE regression #${regressionCount}", { balanced: "{" })
246
+ * structuralCut(shipSource, "function collectAgentWork(", { endAnchor: "\n}" })
247
+ * ```
248
+ *
249
+ * A balanced end is inclusive of its closing bracket; a named end anchor is
250
+ * exclusive of the anchor text, both matching the hand-written forms already
251
+ * in `test/`. Throws `AnchorNotFoundError`, `UnbalancedCutError` or
252
+ * `EmptyCutError` — never a short cut and never an empty string.
253
+ */
254
+ export function structuralCut(doc: string, anchor: string, end: CutEnd): string {
255
+ const at = locateUnique(doc, anchor, "anchor");
256
+ const to = endIndex(doc, at, anchor, end);
257
+ refuseEmpty(doc, at, anchor, to);
258
+ return doc.slice(at, to);
259
+ }
260
+
261
+ /**
262
+ * The region around `anchor`, bounded structurally on BOTH sides.
263
+ *
264
+ * The before-and-after shape — `slice(at - 1_500, at + 1_500)` at
265
+ * `test/agent-timings-queued.test.ts:292` — is fragile at two ends rather than
266
+ * one. Replacing it needs a start that is a construct too, so the start is a
267
+ * named anchor found by searching BACKWARD from the subject, and the end is
268
+ * resolved forward from that start:
269
+ *
270
+ * ```ts
271
+ * structuralCutAround(shipSource, "TIMING: ${t.agent}", {
272
+ * startAnchor: "for (const t of gradeResult.timing)",
273
+ * end: { balanced: "{" },
274
+ * })
275
+ * ```
276
+ *
277
+ * The region must contain the anchor, and that is checked rather than assumed:
278
+ * an end anchor sitting between the start and the subject produces a region
279
+ * that is well-formed, non-empty, and about something else.
280
+ */
281
+ export function structuralCutAround(doc: string, anchor: string, bounds: CutBounds): string {
282
+ const at = locateUnique(doc, anchor, "anchor");
283
+ const { startAnchor, end } = bounds;
284
+ // Counted, not `lastIndexOf`. Searching backward from the subject makes a
285
+ // duplicated start anchor look resolved — it picks the nearest preceding
286
+ // one, which is a plausible region and not necessarily the right one.
287
+ const from = locateUnique(doc, startAnchor, "start anchor");
288
+
289
+ const to = endIndex(doc, from, startAnchor, end);
290
+ refuseEmpty(doc, from, startAnchor, to);
291
+ const cut = doc.slice(from, to);
292
+ if (!cut.includes(anchor)) throw new AnchorOutsideCutError(anchor, startAnchor);
293
+ return cut;
294
+ }
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Where a spec may be listed, and what counts as a spec (#382, #552).
3
+ *
4
+ * `refreshAgentsMd` warns when a file in `specs/` is not named in
5
+ * `AGENTS.md`. D-15 capped AGENTS.md at 100 lines and moved the specs table
6
+ * and the doc-routing table into `.claude/rules/`, and neither check
7
+ * followed. So both have warned on every `--fix` run since: 23 spec
8
+ * filenames on this repo, plus `CODE-MAP.md exists but not referenced`,
9
+ * every single time.
10
+ *
11
+ * **Both are unfixable from the document's side**, which is what makes them
12
+ * worse than noise. Satisfying `UNLISTED specs` means pasting 23 filenames
13
+ * back into AGENTS.md, which breaks the line cap D-15 moved them out to
14
+ * respect — the detector asking for the thing the architecture forbids. A
15
+ * consumer who adds the table by hand gets it deleted by the next
16
+ * `REGENERATED: AGENTS.md`, so the warning cannot be cleared at all.
17
+ *
18
+ * A standing false positive trains readers past the whole class. #380
19
+ * measured the neighbouring check at a true-positive rate of **zero** for
20
+ * the same underlying reason, and nobody had noticed in months because the
21
+ * output was always noisy.
22
+ *
23
+ * ## Is `SPEC-TEMPLATE.md` a spec?
24
+ *
25
+ * **No, and this module is where that is decided.** It is the file
26
+ * `create-spec` copies to start a new spec; it governs nothing and a reader
27
+ * sent to it by a routing table learns nothing about the project. The
28
+ * scanner has always excluded it from `specs-routing.md`, and the audit has
29
+ * always included it — which is how it ended up in the warning list as the
30
+ * one entry that was never going to be listed anywhere.
31
+ *
32
+ * It is a decision rather than a lookup, so it lives in one named constant
33
+ * that both sides import, rather than being absorbed by whichever file a
34
+ * check happens to read.
35
+ *
36
+ * ## Why the surfaces are a directory and not a filename
37
+ *
38
+ * `listingSurfaces` searches AGENTS.md and every `.claude/rules/*.md`, not
39
+ * `.claude/rules/specs-routing.md` by name. The generator chooses that
40
+ * filename and a check that hard-codes it is a second decider for the same
41
+ * question — the shape that put this defect here. A rule file renamed by the
42
+ * generator stays covered; a spec listed in no agent-facing document at all
43
+ * is still reported, which is the half that has to keep working.
44
+ */
45
+ import { existsSync, readFileSync, readdirSync } from "fs";
46
+ import { join } from "path";
47
+
48
+ /**
49
+ * Files that live in `specs/` and are not specs. See the module docstring —
50
+ * this is a judgement, and it is deliberately a list of exact names rather
51
+ * than a pattern, so adding to it is a visible decision.
52
+ */
53
+ export const NON_SPEC_FILES: readonly string[] = ["SPEC-TEMPLATE.md"];
54
+
55
+ export function isSpecFile(name: string): boolean {
56
+ return name.endsWith(".md") && !NON_SPEC_FILES.includes(name);
57
+ }
58
+
59
+ /** Top-level spec files in `root/specs`, or `[]` when there is no `specs/`. */
60
+ export function specFilesIn(root: string): string[] {
61
+ const dir = join(root, "specs");
62
+ if (!existsSync(dir)) return [];
63
+ try {
64
+ return readdirSync(dir).filter(isSpecFile);
65
+ } catch {
66
+ return [];
67
+ }
68
+ }
69
+
70
+ export interface Surface {
71
+ /** Project-relative, so a report can name it. */
72
+ path: string;
73
+ content: string;
74
+ }
75
+
76
+ /**
77
+ * Every agent-facing document in which a spec or a doc may be listed.
78
+ *
79
+ * AGENTS.md first because a consumer may still list specs there; then
80
+ * `.claude/rules/*.md`, which is where this project's generator puts the
81
+ * tables and where D-15 moved them.
82
+ */
83
+ export function listingSurfaces(root: string): Surface[] {
84
+ const out: Surface[] = [];
85
+ const agents = join(root, "AGENTS.md");
86
+ if (existsSync(agents)) {
87
+ try { out.push({ path: "AGENTS.md", content: readFileSync(agents, "utf-8") }); } catch { /* unreadable */ }
88
+ }
89
+ const rulesDir = join(root, ".claude", "rules");
90
+ if (!existsSync(rulesDir)) return out;
91
+ let names: string[];
92
+ try { names = readdirSync(rulesDir).filter(f => f.endsWith(".md")).sort(); } catch { return out; }
93
+ for (const n of names) {
94
+ try {
95
+ out.push({ path: `.claude/rules/${n}`, content: readFileSync(join(rulesDir, n), "utf-8") });
96
+ } catch { /* unreadable */ }
97
+ }
98
+ return out;
99
+ }
100
+
101
+ /**
102
+ * A line that puts a reader somewhere: a table row, or a list item.
103
+ *
104
+ * **A mention is not a listing**, and the difference is measurable here.
105
+ * `.claude/rules/checks-must-be-able-to-fail.md:407` discusses
106
+ * `specs/SPEC-TEMPLATE.md` in a paragraph about #484. A whole-document
107
+ * `includes` counts that as the template being listed — so the mutation
108
+ * that makes `SPEC-TEMPLATE.md` a spec again measured 1 red where 2 were
109
+ * predicted, and the one that did not fire was the live-tree case. Any spec
110
+ * any rule file happens to name in prose would have been waved through the
111
+ * same way.
112
+ *
113
+ * That is `.claude/rules/checks-must-be-able-to-fail.md`'s own *"search the
114
+ * slice, not the document"*, met in a function whose job is to decide
115
+ * whether a document points somewhere. The boundary is asserted in both
116
+ * directions rather than left to this comment, because narrowing a detector
117
+ * is the change most likely to buy green with blindness.
118
+ *
119
+ * Deliberately permissive about WHICH list: the generator writes table rows,
120
+ * a consumer may well write bullets, and the direction this is allowed to be
121
+ * wrong in is toward reporting a spec that is in fact listed — which costs a
122
+ * line in a table — rather than toward silence.
123
+ */
124
+ const LISTING_LINE = /^\s*(\||[-*+]\s|\d+\.\s)/;
125
+
126
+ export function listsFile(content: string, name: string): boolean {
127
+ return content.split("\n").some(l => l.includes(name) && LISTING_LINE.test(l));
128
+ }
129
+
130
+ /** Spec files listed by no surface. Empty when every spec is listed somewhere. */
131
+ export function unlistedSpecs(root: string): string[] {
132
+ const specs = specFilesIn(root);
133
+ if (specs.length === 0) return [];
134
+ const surfaces = listingSurfaces(root);
135
+ return specs.filter(f => !surfaces.some(s => listsFile(s.content, f)));
136
+ }
137
+
138
+ /**
139
+ * `CODE-MAP.md` exists but no surface points at it.
140
+ *
141
+ * Matched on `CODE-MAP` rather than on the filename, because the routing
142
+ * table writes it in backticks and the key-files table writes it bare, and
143
+ * the question is whether a reader is sent there at all.
144
+ */
145
+ export function codeMapUnreferenced(root: string): boolean {
146
+ if (!existsSync(join(root, "CODE-MAP.md"))) return false;
147
+ return !listingSurfaces(root).some(s => listsFile(s.content, "CODE-MAP"));
148
+ }