rungate 0.6.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 (113) 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 +81 -16
  5. package/lib/behavioral-cache.ts +150 -2
  6. package/lib/branch-protection.ts +790 -0
  7. package/lib/brief-ac-alignment.ts +104 -0
  8. package/lib/brief-references.ts +205 -0
  9. package/lib/bun-version.ts +93 -14
  10. package/lib/check-remedy.ts +140 -0
  11. package/lib/ci-checkout.ts +17 -0
  12. package/lib/ci-history-depth.ts +159 -0
  13. package/lib/ci-setup-step.ts +96 -0
  14. package/lib/claude-code-action.ts +85 -0
  15. package/lib/claude-tool-vocabulary.ts +188 -0
  16. package/lib/cli-commands.ts +15 -0
  17. package/lib/commit-sha.ts +42 -0
  18. package/lib/commit-subject.ts +90 -0
  19. package/lib/compliance-report.ts +377 -45
  20. package/lib/compliance.ts +191 -17
  21. package/lib/config-loader.ts +39 -1
  22. package/lib/config-trackable.ts +391 -0
  23. package/lib/conformity.ts +1087 -100
  24. package/lib/containment.ts +238 -0
  25. package/lib/content-hash.ts +24 -0
  26. package/lib/create-sc.ts +249 -16
  27. package/lib/dev-liveness.ts +180 -0
  28. package/lib/discovery-branch-points.ts +432 -0
  29. package/lib/discovery-stability.ts +481 -0
  30. package/lib/distribution-currency.ts +186 -0
  31. package/lib/doc-routing.ts +157 -0
  32. package/lib/evidence-prevalidator.ts +224 -2
  33. package/lib/evidence-satisfiability.ts +534 -12
  34. package/lib/failure-intake.ts +317 -0
  35. package/lib/fallow-availability.ts +157 -0
  36. package/lib/fs-write-capabilities.ts +232 -0
  37. package/lib/gate-run-split.ts +147 -0
  38. package/lib/generators/agents-md.ts +140 -32
  39. package/lib/git-isolation.ts +140 -0
  40. package/lib/github.ts +15 -0
  41. package/lib/google-auth-action.ts +93 -0
  42. package/lib/harness-project.ts +48 -0
  43. package/lib/harness-provenance.ts +255 -0
  44. package/lib/hook-evidence.ts +235 -0
  45. package/lib/hook-scopes.ts +386 -0
  46. package/lib/hook-target-tree.ts +398 -0
  47. package/lib/hook-trees.ts +447 -0
  48. package/lib/js-top-level-code.ts +78 -10
  49. package/lib/junit-checks.ts +52 -0
  50. package/lib/launch-base.ts +253 -0
  51. package/lib/line-citation.ts +372 -0
  52. package/lib/orphan-reaper.ts +468 -0
  53. package/lib/parity-binding.ts +205 -0
  54. package/lib/per-test-timeouts.ts +219 -0
  55. package/lib/plan-coverage.ts +151 -0
  56. package/lib/prior-branch.ts +201 -8
  57. package/lib/process-table.ts +146 -0
  58. package/lib/project-state-derivation.ts +219 -0
  59. package/lib/project-state-root.ts +258 -0
  60. package/lib/published-artifact.ts +525 -0
  61. package/lib/readdir-sorted.ts +45 -0
  62. package/lib/review-execution-reading.ts +206 -0
  63. package/lib/review-tool-agreement.ts +433 -0
  64. package/lib/rule-promotion.ts +234 -0
  65. package/lib/rule-retirement.ts +525 -0
  66. package/lib/run-branch.ts +612 -0
  67. package/lib/rungate-schema.ts +19 -0
  68. package/lib/runner-home.ts +274 -0
  69. package/lib/sc-id-cross-tree.ts +19 -7
  70. package/lib/sc-ids.ts +121 -13
  71. package/lib/sc-reservations.ts +289 -0
  72. package/lib/scaffold/ai-review-findings.ts +403 -0
  73. package/lib/scaffold/ai-review-step.ts +4661 -64
  74. package/lib/scaffold/managed-workflow.ts +587 -192
  75. package/lib/scaffold/owned-files.ts +152 -45
  76. package/lib/scaffold/pre-push-hook.ts +49 -5
  77. package/lib/scaffold/steps.ts +1413 -244
  78. package/lib/scaffold/workflow-census.ts +217 -0
  79. package/lib/scaffold/workflow-drift.ts +217 -0
  80. package/lib/scaffold/write-steps.ts +4 -0
  81. package/lib/scan-budget.ts +247 -0
  82. package/lib/scanner.ts +43 -51
  83. package/lib/scratch-roots.ts +50 -5
  84. package/lib/screenshot-discovery.ts +121 -0
  85. package/lib/screenshot-upload.ts +41 -1
  86. package/lib/secret-patterns.ts +511 -8
  87. package/lib/ship-mode.ts +219 -0
  88. package/lib/source-slice.ts +294 -0
  89. package/lib/stale-cleanup.ts +37 -3
  90. package/lib/suite-flake.ts +278 -0
  91. package/lib/suite-measurement.ts +23 -4
  92. package/lib/suite-run-reading.ts +241 -1
  93. package/lib/suite-timeout-margin.ts +193 -0
  94. package/lib/test-case-bodies.ts +883 -0
  95. package/lib/test-case-deletion.ts +653 -0
  96. package/lib/test-census.ts +97 -29
  97. package/lib/test-command-positions.ts +274 -0
  98. package/lib/test-suite-lock.ts +159 -16
  99. package/lib/tool-probe.ts +31 -9
  100. package/lib/top-level-cd.ts +393 -0
  101. package/lib/tree-entries.ts +89 -0
  102. package/lib/ts-ast.ts +200 -0
  103. package/lib/walk-test-files.ts +97 -0
  104. package/lib/workflow-actions.ts +263 -0
  105. package/lib/worktree-collect.ts +177 -5
  106. package/lib/worktree-repo.ts +36 -1
  107. package/package.json +2 -1
  108. package/scripts/ai-review-findings.ts +45 -0
  109. package/scripts/create-sc.ts +21 -1
  110. package/scripts/extract-constraints.ts +107 -7
  111. package/scripts/generate-code-map.ts +23 -30
  112. package/scripts/scaffold-project.ts +8 -1
  113. package/scripts/sync-sc-status.ts +77 -16
@@ -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
+ }
@@ -9,6 +9,7 @@
9
9
 
10
10
  import { readdirSync, readFileSync, statSync, unlinkSync, existsSync, rmdirSync, renameSync, mkdirSync } from 'fs';
11
11
  import { join, dirname } from 'path';
12
+ import { workRootOwnership, workRootRefusalLine, type WorkRootVerdict } from './runner-home';
12
13
 
13
14
  /**
14
15
  * Recursively find files by name under a directory.
@@ -32,6 +33,13 @@ function findFiles(dir: string, name: string): string[] {
32
33
  export interface CleanupResult {
33
34
  deleted: number;
34
35
  logs: string[];
36
+ /**
37
+ * Whether the sweep declined to touch this root (#904).
38
+ *
39
+ * `deleted: 0` is what a refusal and a clean root both produce, so the
40
+ * counts cannot carry this. See `lib/runner-home.ts`.
41
+ */
42
+ refused: boolean;
35
43
  }
36
44
 
37
45
  export interface ArchiveResult {
@@ -39,6 +47,8 @@ export interface ArchiveResult {
39
47
  purged: number;
40
48
  skipped: number;
41
49
  logs: string[];
50
+ /** Whether the sweep declined to touch this root (#904). */
51
+ refused: boolean;
42
52
  }
43
53
 
44
54
  /**
@@ -52,7 +62,22 @@ export function archiveAndPurge(
52
62
  workDir: string,
53
63
  archiveTtlMs: number,
54
64
  purgeTtlMs: number,
65
+ env: NodeJS.ProcessEnv = process.env,
55
66
  ): ArchiveResult {
67
+ // Guarded here as well as in `cleanStaleFiles` because this is exported and
68
+ // destructive. A refusal reachable only through the caller is a side door,
69
+ // and the next caller walks through it (#904).
70
+ const verdict = workRootOwnership(workDir, env);
71
+ if (!verdict.sweep) {
72
+ return {
73
+ archived: 0,
74
+ purged: 0,
75
+ skipped: 0,
76
+ logs: [workRootRefusalLine(workDir, verdict)],
77
+ refused: true,
78
+ };
79
+ }
80
+
56
81
  const now = Date.now();
57
82
  let archived = 0;
58
83
  let purged = 0;
@@ -185,7 +210,7 @@ export function archiveAndPurge(
185
210
  } catch {}
186
211
  }
187
212
 
188
- return { archived, purged, skipped, logs };
213
+ return { archived, purged, skipped, logs, refused: false };
189
214
  }
190
215
 
191
216
  /**
@@ -196,7 +221,16 @@ export function cleanStaleFiles(
196
221
  workDir: string,
197
222
  fourHoursMs: number,
198
223
  sevenDaysMs: number,
224
+ env: NodeJS.ProcessEnv = process.env,
199
225
  ): CleanupResult {
226
+ // Decided before the `.ship-active` walk, not just before the archive pass:
227
+ // a sibling runner's `.ship-active` is state it is relying on, and deleting
228
+ // it is the same harm one function lower down (#904).
229
+ const verdict: WorkRootVerdict = workRootOwnership(workDir, env);
230
+ if (!verdict.sweep) {
231
+ return { deleted: 0, logs: [workRootRefusalLine(workDir, verdict)], refused: true };
232
+ }
233
+
200
234
  const now = Date.now();
201
235
  let deleted = 0;
202
236
  const logs: string[] = [];
@@ -215,10 +249,10 @@ export function cleanStaleFiles(
215
249
 
216
250
  // Archive and purge work directories
217
251
  const thirtyDaysMs = 30 * 24 * 60 * 60 * 1000;
218
- const archiveResult = archiveAndPurge(workDir, fourHoursMs, thirtyDaysMs);
252
+ const archiveResult = archiveAndPurge(workDir, fourHoursMs, thirtyDaysMs, env);
219
253
 
220
254
  // Merge logs
221
255
  logs.push(...archiveResult.logs);
222
256
 
223
- return { deleted, logs };
257
+ return { deleted, logs, refused: archiveResult.refused };
224
258
  }