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,612 @@
1
+ /**
2
+ * The `rungate/run-<issue>` branch: is it safe to delete, and did the run
3
+ * leave the shared checkout somewhere it did not find it (#640).
4
+ *
5
+ * ## What actually happens today
6
+ *
7
+ * A ship run checks `rungate/run-<issue>` out **in the shared primary**,
8
+ * commits each wave onto it there, and then ends. Nothing puts the checkout
9
+ * back and nothing deletes the branch. Measured on the primary on 2026-10-09
10
+ * it was sitting on `rungate/run-597` with `run-621` and `run-627` left over
11
+ * from runs that had finished hours earlier; measured again on 2026-10-19 it
12
+ * was on `rungate/run-631`, eleven days later, same defect.
13
+ *
14
+ * Three costs, in increasing order:
15
+ *
16
+ * 1. The primary lies about where it is. `git -C <primary> …` is the
17
+ * documented way to avoid `cd` in this repo, and it answers with a run
18
+ * branch.
19
+ * 2. The refs accumulate. The name is keyed on the ISSUE, not the run, so
20
+ * a leftover from a previous run of the same issue is indistinguishable
21
+ * by name from the current one.
22
+ * 3. A stale ref has already cost a run an IMPLEMENT failure.
23
+ *
24
+ * ## Why containment is a BLOB comparison and never an ancestry one
25
+ *
26
+ * This is the part that decides whether the cleanup is usable at all.
27
+ *
28
+ * Every branch this repo creates is **squash-merged**, and a squash merge
29
+ * destroys ancestry: the merged content has no commit in common with the
30
+ * branch that produced it. `git merge-base --is-ancestor` therefore reports
31
+ * ORPHANED for content that is fully present on main — measured on the six
32
+ * commits #511 and #512 recovered, all six reported orphaned, all six fully
33
+ * landed. A cleanup built on ancestry would refuse to delete **every branch
34
+ * it ever created**, which is a refusal nobody can act on and everybody
35
+ * learns to click past.
36
+ *
37
+ * So the question asked here is the one `scripts/verify-merge-content.ts`
38
+ * asks at merge time, pointed at a branch instead of a merge commit: of the
39
+ * paths this branch CHANGED, does the base hold the same bytes, mode and
40
+ * type? The blob reading comes from `lib/tree-entries.ts`, which both files
41
+ * import, so there is one binding to mutate rather than two that agree.
42
+ *
43
+ * ## The direction this is allowed to be wrong in
44
+ *
45
+ * Toward NOT deleting. A branch whose work landed and whose files the base
46
+ * has since modified reads `NOT_CONTAINED`, and the cleanup leaves it alone.
47
+ * That costs a stale ref somebody deletes by hand. The other direction
48
+ * destroys unmerged work, so `UNMEASURED` — an unreadable repo, an
49
+ * unresolvable ref — refuses too, and is reported rather than treated as a
50
+ * clean branch with nothing in it.
51
+ */
52
+ import { treeEntries, gitRead } from "./tree-entries";
53
+
54
+ /** The branch a ship run commits its waves onto. Keyed on the issue. */
55
+ export function runBranchName(issue: number | string): string {
56
+ return `rungate/run-${issue}`;
57
+ }
58
+
59
+ /**
60
+ * The shell that puts the checkout on this run's branch (#702).
61
+ *
62
+ * **Extracted so it can be EXECUTED, which is the whole point.** #702 asks
63
+ * for the resume-or-refuse property to be "asserted by driving a run against
64
+ * a planted repo in that state, not by reading the branch-setup code" — and
65
+ * while this lived inside an agent prompt's template literal in
66
+ * `workflows/ship.js`, reading it was the only thing anyone could do. The
67
+ * behaviour was correct; nothing held it, so an edit to the `case` arms
68
+ * could reintroduce the discard with every test still green.
69
+ *
70
+ * ## What the two arms mean, because they are easy to read backwards
71
+ *
72
+ * - `git switch -c <ref>` **fails** when the branch already exists. That
73
+ * failure is the load-bearing part: `|| git switch <ref>` then ADOPTS the
74
+ * existing branch, so a run re-entering an issue commits onto the work
75
+ * already there instead of a fresh branch cut from the base. Measured on a
76
+ * planted repo carrying six commits: HEAD after is the prior tip.
77
+ * - The `case` guard means a checkout already on some other branch is left
78
+ * alone entirely. A run must not move a shared checkout off work somebody
79
+ * else is doing.
80
+ *
81
+ * ## The cheapest wrong fix, named here because this is where it would go
82
+ *
83
+ * **Drop the `-c` and always `git switch <ref>`.** It "obviously" resumes,
84
+ * and it breaks every run of an issue whose branch does not exist yet —
85
+ * which is most of them — because there is nothing to switch to. The pair of
86
+ * cases over this binding is what makes that visible: the resume case passes
87
+ * under it and the first-run case does not.
88
+ *
89
+ * `ref` arrives ALREADY SHELL-QUOTED. Quoting is the caller's, because
90
+ * `workflows/ship.js` owns `shellQuote` and a second quoter here would be a
91
+ * second decider for how a branch name reaches a command line.
92
+ */
93
+ export function runBranchSetupScript(quotedRef: string): string {
94
+ return `case "$branch" in
95
+ ""|main|master)
96
+ git switch -c ${quotedRef} 2>/dev/null || git switch ${quotedRef} ;;
97
+ esac`;
98
+ }
99
+
100
+ /**
101
+ * What a branch-setup actually did, from the two HEADs and the two branches.
102
+ *
103
+ * `leftoverRunBranch` says what was THERE before the run; this says what the
104
+ * run DID about it. They are different questions — a leftover can be present
105
+ * and resumed, present and discarded, or present and never reached — and
106
+ * #702's AC-2 is that the three outcomes are distinguishable in the
107
+ * artefact rather than all reading as a branch name.
108
+ *
109
+ * An unreadable input is `UNMEASURED` and never `NO_PRIOR_BRANCH`. Those are
110
+ * the two that must not collapse: "there was no prior work" and "nobody
111
+ * looked" are the byte-identical pair #702 is about.
112
+ */
113
+ export type RunBranchStart =
114
+ | "NO_PRIOR_BRANCH"
115
+ | "PRIOR_BRANCH_RESUMED"
116
+ | "PRIOR_BRANCH_DISCARDED"
117
+ | "UNMEASURED";
118
+
119
+ export interface RunBranchStartInput {
120
+ /** The branch the checkout was on before, `""` for a detached HEAD. */
121
+ branchBefore: string;
122
+ /** The branch it is on after. */
123
+ branchAfter: string;
124
+ /** The tip the run's branch is now at. */
125
+ headAfter: string;
126
+ /**
127
+ * The tip the run's branch held BEFORE setup, or `null` when it did not
128
+ * exist. `undefined` means nobody read it — which is not the same thing.
129
+ */
130
+ priorTip: string | null | undefined;
131
+ }
132
+
133
+ export function runBranchStart(input: RunBranchStartInput): RunBranchStart {
134
+ const { branchAfter, headAfter, priorTip } = input;
135
+ if (priorTip === undefined) return "UNMEASURED";
136
+ if (!branchAfter || !headAfter) return "UNMEASURED";
137
+ if (priorTip === null) return "NO_PRIOR_BRANCH";
138
+ return priorTip === headAfter ? "PRIOR_BRANCH_RESUMED" : "PRIOR_BRANCH_DISCARDED";
139
+ }
140
+
141
+ /** The sentence a run logs for a start that lost work, or `null`. */
142
+ export function runBranchStartRefusal(
143
+ reading: RunBranchStart,
144
+ branch: string,
145
+ discarded: string[] = [],
146
+ ): string | null {
147
+ if (reading === "PRIOR_BRANCH_DISCARDED") {
148
+ return (
149
+ `${branch} already existed with ${discarded.length} commit(s) that are not on this run's ` +
150
+ `base, and this run started somewhere else — ${discarded.join(", ")}. Starting from the ` +
151
+ `base is a reasonable default and taking it SILENTLY makes "there was no prior work" and ` +
152
+ `"there was prior work and it was dropped" identical from the outside (#702).`
153
+ );
154
+ }
155
+ if (reading === "UNMEASURED") {
156
+ return (
157
+ `the branch this run started on could not be read, so whether it discarded prior work on ` +
158
+ `${branch} is unknown. That is not "there was no prior branch" (#702).`
159
+ );
160
+ }
161
+ return null;
162
+ }
163
+
164
+ /** A path the branch changed, and what each side holds there. */
165
+ export interface ContainmentDivergence {
166
+ path: string;
167
+ /** `<mode> <type> <oid>` the branch holds, or `ABSENT`. */
168
+ branch: string;
169
+ /** `<mode> <type> <oid>` the base holds, or `ABSENT`. */
170
+ base: string;
171
+ }
172
+
173
+ export type ContainmentReading =
174
+ /** Every path the branch changed is present on the base, byte for byte. */
175
+ | { reading: "CONTAINED"; branch: string; base: string; comparedPaths: number }
176
+ /** The branch holds something the base does not. Refuse to delete it. */
177
+ | {
178
+ reading: "NOT_CONTAINED";
179
+ branch: string;
180
+ base: string;
181
+ comparedPaths: number;
182
+ divergent: ContainmentDivergence[];
183
+ refusal: string;
184
+ }
185
+ /** The question could not be asked. Not the same as a clean answer. */
186
+ | { reading: "UNMEASURED"; branch: string; base: string; refusal: string };
187
+
188
+ const MAX_NAMED = 8;
189
+
190
+ function refusalSuffix(d: ContainmentDivergence[]): string {
191
+ const named = d.slice(0, MAX_NAMED).map(x => x.path).join(", ");
192
+ return d.length > MAX_NAMED ? `${named}, … (${d.length} total)` : named;
193
+ }
194
+
195
+ /**
196
+ * Whether every change on `branch` is already present on `base`.
197
+ *
198
+ * `comparedPaths` is on the reading rather than derived by the caller,
199
+ * because a comparison over ZERO paths is the thing that reads exactly like
200
+ * a clean one: an empty divergence list is produced both by a branch that is
201
+ * genuinely contained and by a scope that failed to resolve. A caller that
202
+ * wants to refuse a vacuous CONTAINED can see the number.
203
+ */
204
+ export function branchContainment(repo: string, branch: string, base: string): ContainmentReading {
205
+ const named = { branch, base };
206
+
207
+ if (!String(repo || "").trim()) {
208
+ return { ...named, reading: "UNMEASURED", refusal: "no repository was named, so nothing was read" };
209
+ }
210
+ for (const [label, ref] of [["branch", branch], ["base", base]] as const) {
211
+ if (!String(ref || "").trim()) {
212
+ return { ...named, reading: "UNMEASURED", refusal: `no ${label} ref was named, so nothing was read` };
213
+ }
214
+ }
215
+
216
+ // Self-comparison, refused by identity before any tree is read. The
217
+ // names can differ and still be one commit — `rungate/run-640` and a
218
+ // base that was fast-forwarded onto it — so the SHAs are compared, not
219
+ // the strings. `scripts/verify-merge-content.ts` refuses the same shape.
220
+ try {
221
+ const bSha = gitRead(repo, ["rev-parse", "--verify", `${branch}^{commit}`]).out.trim();
222
+ const oSha = gitRead(repo, ["rev-parse", "--verify", `${base}^{commit}`]).out.trim();
223
+ if (bSha && bSha === oSha) {
224
+ return {
225
+ ...named,
226
+ reading: "UNMEASURED",
227
+ refusal:
228
+ `${branch} and ${base} are the same commit (${bSha.slice(0, 12)}), so the containment ` +
229
+ "check would be comparing a ref against itself and could only say yes",
230
+ };
231
+ }
232
+ } catch (e: any) {
233
+ return {
234
+ ...named,
235
+ reading: "UNMEASURED",
236
+ refusal:
237
+ `${branch} or ${base} could not be resolved to a commit ` +
238
+ `(${String(e?.message || e).split("\n")[0]}), and unresolvable is not contained`,
239
+ };
240
+ }
241
+
242
+ let branchTree: Map<string, string>;
243
+ let baseTree: Map<string, string>;
244
+ let mergeBaseTree: Map<string, string>;
245
+ try {
246
+ branchTree = treeEntries(repo, branch);
247
+ baseTree = treeEntries(repo, base);
248
+ // The scope is what the BRANCH changed, which is the diff against where
249
+ // it left the base — not the whole tree. Comparing whole trees would
250
+ // call every branch divergent the moment the base moved on for any
251
+ // unrelated reason, which is the same unusable refusal as ancestry.
252
+ //
253
+ // `merge-base` EXITS 1 when there is none, which is the same shape as
254
+ // any other git failure and must not be read as one: unrelated
255
+ // histories have no scope at all, and an empty scope compares clean.
256
+ // So it is asked separately and its own non-zero is a named reading,
257
+ // not a generic "could not be read".
258
+ let mergeBase = "";
259
+ try {
260
+ mergeBase = gitRead(repo, ["merge-base", branch, base]).out.trim();
261
+ } catch {
262
+ mergeBase = "";
263
+ }
264
+ if (!mergeBase) {
265
+ return {
266
+ ...named,
267
+ reading: "UNMEASURED",
268
+ refusal:
269
+ `${branch} and ${base} have no merge base, so there is no scope to compare — ` +
270
+ "unrelated histories are not an empty diff, and an empty diff is what this would " +
271
+ "otherwise report",
272
+ };
273
+ }
274
+ mergeBaseTree = treeEntries(repo, mergeBase);
275
+ } catch (e: any) {
276
+ return {
277
+ ...named,
278
+ reading: "UNMEASURED",
279
+ refusal:
280
+ `the trees for ${branch} and ${base} could not be read (${String(e?.message || e).split("\n")[0]}), ` +
281
+ "and unreadable is not contained",
282
+ };
283
+ }
284
+
285
+ const scope = new Set<string>();
286
+ for (const [path, entry] of branchTree) {
287
+ if (mergeBaseTree.get(path) !== entry) scope.add(path);
288
+ }
289
+ for (const path of mergeBaseTree.keys()) {
290
+ if (!branchTree.has(path)) scope.add(path);
291
+ }
292
+
293
+ const divergent: ContainmentDivergence[] = [];
294
+ for (const path of [...scope].sort()) {
295
+ const b = branchTree.get(path) ?? "ABSENT";
296
+ const o = baseTree.get(path) ?? "ABSENT";
297
+ if (b !== o) divergent.push({ path, branch: b, base: o });
298
+ }
299
+
300
+ // A comparison over ZERO paths is not a verdict. It is produced by a
301
+ // branch that is genuinely identical to its base AND by a scope that
302
+ // resolved nothing, and the second is what `--base <the branch itself>`
303
+ // produces: merge-base of a ref with itself is that ref, every entry
304
+ // matches, scope is empty, CONTAINED, delete. The reading has carried
305
+ // `comparedPaths` since it was written and nothing looked at it, which
306
+ // is the #602 shape — an available reading nobody reads.
307
+ if (scope.size === 0) {
308
+ return {
309
+ ...named,
310
+ reading: "UNMEASURED",
311
+ refusal:
312
+ `${branch} and ${base} differ at no path at all, so the containment check witnessed ` +
313
+ "nothing — a comparison over zero paths is not a verdict to delete on. This is what " +
314
+ "comparing a ref against itself looks like.",
315
+ };
316
+ }
317
+
318
+ if (divergent.length > 0) {
319
+ return {
320
+ ...named,
321
+ reading: "NOT_CONTAINED",
322
+ comparedPaths: scope.size,
323
+ divergent,
324
+ refusal:
325
+ `${branch} holds ${divergent.length} of its ${scope.size} changed path(s) that ${base} does not ` +
326
+ `match: ${refusalSuffix(divergent)}. Deleting it would destroy that work.`,
327
+ };
328
+ }
329
+
330
+ return { ...named, reading: "CONTAINED", comparedPaths: scope.size };
331
+ }
332
+
333
+ /** The one sentence a caller prints, or null when there is nothing to say. */
334
+ export function containmentRefusal(r: ContainmentReading): string | null {
335
+ return r.reading === "CONTAINED" ? null : r.refusal;
336
+ }
337
+
338
+ /**
339
+ * The shared checkout's HEAD, before and after, as one comparison.
340
+ *
341
+ * A run that leaves the primary somewhere else is cost 1 above, and the only
342
+ * honest way to assert it is to read the branch at both ends and compare —
343
+ * not to describe the intent, and not to assert that a restore step exists.
344
+ */
345
+ export type CheckoutDrift =
346
+ | { reading: "UNCHANGED"; before: string; after: string }
347
+ | { reading: "MOVED"; before: string; after: string; refusal: string }
348
+ | { reading: "UNMEASURED"; before: string; after: string; refusal: string };
349
+
350
+ export function checkoutDrift(before: unknown, after: unknown): CheckoutDrift {
351
+ const b = String(before ?? "").trim();
352
+ const a = String(after ?? "").trim();
353
+ // An unread end is not an unchanged one. A run that failed to report where
354
+ // the checkout ended up has not proven it put it back — and an empty
355
+ // string compared with an empty string is equality, which is how this
356
+ // would otherwise pass by never having looked.
357
+ if (!b || !a) {
358
+ return {
359
+ reading: "UNMEASURED",
360
+ before: b,
361
+ after: a,
362
+ refusal:
363
+ `the shared checkout's branch was not read at ${!b ? "the start" : "the end"} of the run, ` +
364
+ "so whether the run moved it is unknown — and unknown is not unchanged (#640)",
365
+ };
366
+ }
367
+ if (b === a) return { reading: "UNCHANGED", before: b, after: a };
368
+ return {
369
+ reading: "MOVED",
370
+ before: b,
371
+ after: a,
372
+ refusal:
373
+ `the run left the shared checkout on ${a}; it was on ${b} when the run started. ` +
374
+ "Every other session reading that checkout now gets a run branch (#640)",
375
+ };
376
+ }
377
+
378
+ /** The one sentence a caller prints, or null when the checkout came back. */
379
+ export function checkoutDriftRefusal(d: CheckoutDrift): string | null {
380
+ return d.reading === "UNCHANGED" ? null : d.refusal;
381
+ }
382
+
383
+ /**
384
+ * WHICH commit `rungate/run-<issue>` names, asked of both refs that can hold
385
+ * it (#640).
386
+ *
387
+ * The first cut of this module asked `git for-each-ref refs/heads/<branch>`
388
+ * and nothing else. No remote ref was consulted anywhere, there was no
389
+ * argument that accepted one, and no output said which ref an answer was
390
+ * about. Measured on the real pair on 2026-10-19: `rungate/run-631` is
391
+ * `4acc0a17` through `refs/heads` and `92eb88cf` through
392
+ * `refs/remotes/origin` — 2 commits one way and 6 the other. Both error
393
+ * directions are live, and they are not symmetric in cost:
394
+ *
395
+ * - the local ref BEHIND the push → containment reports CONTAINED about a
396
+ * commit the run never pushed, and `--mode delete` destroys the commits
397
+ * that exist only under the remote name;
398
+ * - the local ref AHEAD → the check refuses, correctly, and the refusal is
399
+ * then attributed to the run whose work it is not.
400
+ *
401
+ * **The cheapest wrong fix, named here because this is the function it would
402
+ * be applied to: match `refs/remotes/origin/<branch>` as well and take
403
+ * whichever `for-each-ref` returns first.** It makes the remote-only symptom
404
+ * disappear and silently picks one of two commits whenever both exist, which
405
+ * is precisely the state the real pair is in. So a disagreement is its own
406
+ * reading here: this function resolves BOTH and, when they differ, refuses to
407
+ * be the thing that chose.
408
+ */
409
+ export type RunBranchRefsReading =
410
+ /** Neither ref exists. The ordinary start-of-run state. */
411
+ | { reading: "ABSENT"; branch: string; local: null; remote: null; resolvedRef: null; resolvedSha: null }
412
+ /** Exactly one ref exists, or both exist at one commit. `resolvedRef` names it. */
413
+ | {
414
+ reading: "LOCAL_ONLY" | "REMOTE_ONLY" | "AGREED";
415
+ branch: string;
416
+ local: string | null;
417
+ remote: string | null;
418
+ resolvedRef: string;
419
+ resolvedSha: string;
420
+ }
421
+ /** Both exist, at different commits. Nothing is resolved; the caller is told. */
422
+ | {
423
+ reading: "DIVERGED";
424
+ branch: string;
425
+ local: string;
426
+ remote: string;
427
+ resolvedRef: null;
428
+ resolvedSha: null;
429
+ refusal: string;
430
+ }
431
+ /** The question could not be asked. Not the same as a clean answer. */
432
+ | {
433
+ reading: "UNMEASURED";
434
+ branch: string;
435
+ local: null;
436
+ remote: null;
437
+ resolvedRef: null;
438
+ resolvedSha: null;
439
+ refusal: string;
440
+ };
441
+
442
+ const NOTHING = { local: null, remote: null, resolvedRef: null, resolvedSha: null } as const;
443
+
444
+ /**
445
+ * Both refs that can carry the run branch, and what each names.
446
+ *
447
+ * ONE `for-each-ref` over two patterns rather than two calls: two calls are
448
+ * two readings taken at two moments, and a fetch landing between them would
449
+ * produce a pair that was never simultaneously true.
450
+ *
451
+ * `%(refname)` is the FULL ref, deliberately. `%(refname:short)` abbreviates
452
+ * `refs/remotes/origin/rungate/run-631` to `origin/rungate/run-631` and
453
+ * `refs/heads/rungate/run-631` to `rungate/run-631` — two spellings a reader
454
+ * has to know the rules for, where the whole complaint on #640 is that the
455
+ * output never said which ref it read.
456
+ */
457
+ export function runBranchRefs(repo: string, branch: string, remoteName = "origin"): RunBranchRefsReading {
458
+ const named = { branch, ...NOTHING };
459
+ if (!String(repo || "").trim() || !String(branch || "").trim()) {
460
+ return {
461
+ ...named,
462
+ reading: "UNMEASURED",
463
+ refusal:
464
+ `could not ask for ${branch || "an unnamed branch"} without both a repository and a branch name — ` +
465
+ "unknown is not absent (#640)",
466
+ };
467
+ }
468
+
469
+ const localRef = `refs/heads/${branch}`;
470
+ const remoteRef = `refs/remotes/${remoteName}/${branch}`;
471
+ let lines: string[];
472
+ try {
473
+ const { out } = gitRead(repo, ["for-each-ref", "--format=%(refname) %(objectname)", localRef, remoteRef]);
474
+ lines = out.split("\n").map(l => l.trim()).filter(Boolean);
475
+ } catch (e: any) {
476
+ return {
477
+ ...named,
478
+ reading: "UNMEASURED",
479
+ refusal:
480
+ `could not ask ${repo} which commit ${branch} names ` +
481
+ `(${String(e?.message || e).split("\n")[0]}) — unknown is not absent (#640)`,
482
+ };
483
+ }
484
+
485
+ let local: string | null = null;
486
+ let remote: string | null = null;
487
+ for (const line of lines) {
488
+ const space = line.indexOf(" ");
489
+ if (space === -1) continue;
490
+ const ref = line.slice(0, space);
491
+ const sha = line.slice(space + 1).trim();
492
+ if (ref === localRef) local = sha;
493
+ else if (ref === remoteRef) remote = sha;
494
+ }
495
+
496
+ if (local === null && remote === null) return { ...named, reading: "ABSENT" };
497
+ if (local !== null && remote === null) {
498
+ return { branch, local, remote: null, reading: "LOCAL_ONLY", resolvedRef: localRef, resolvedSha: local };
499
+ }
500
+ if (local === null && remote !== null) {
501
+ return { branch, local: null, remote, reading: "REMOTE_ONLY", resolvedRef: remoteRef, resolvedSha: remote };
502
+ }
503
+ if (local === remote) {
504
+ return { branch, local, remote, reading: "AGREED", resolvedRef: localRef, resolvedSha: local! };
505
+ }
506
+ return {
507
+ branch,
508
+ local: local!,
509
+ remote: remote!,
510
+ reading: "DIVERGED",
511
+ resolvedRef: null,
512
+ resolvedSha: null,
513
+ refusal:
514
+ `${branch} names two different commits: ${localRef} is ${local!.slice(0, 12)} and ${remoteRef} is ` +
515
+ `${remote!.slice(0, 12)}. Nothing here chooses between them — an answer about one of them would be ` +
516
+ "confident about a commit the run may never have pushed, in either direction (#640)",
517
+ };
518
+ }
519
+
520
+ export type LeftoverReading =
521
+ /** No branch of that name, under either ref. The ordinary start-of-run state. */
522
+ | { reading: "ABSENT"; branch: string }
523
+ /** A branch exists, and it is safe to reuse or remove. */
524
+ | { reading: "LEFTOVER_CONTAINED"; branch: string; notice: string; resolvedRef: string; resolvedSha: string }
525
+ /** A branch exists and holds work. Reusing it silently would bury it. */
526
+ | {
527
+ reading: "LEFTOVER_UNCONTAINED";
528
+ branch: string;
529
+ notice: string;
530
+ divergent: ContainmentDivergence[];
531
+ resolvedRef: string;
532
+ resolvedSha: string;
533
+ }
534
+ /**
535
+ * The name resolves to two commits. Reported as its own reading rather than
536
+ * folded into UNMEASURED: "I could not look" and "I looked and the answer
537
+ * is two different things" are different facts, and only the second names
538
+ * two commits somebody has to reconcile.
539
+ */
540
+ | { reading: "LEFTOVER_DIVERGED"; branch: string; notice: string; local: string; remote: string }
541
+ | { reading: "UNMEASURED"; branch: string; notice: string };
542
+
543
+ /**
544
+ * Whether a run is about to reuse a branch somebody else left behind.
545
+ *
546
+ * The name is keyed on the issue, so a second run of the same issue finds
547
+ * the first run's branch and commits onto it as if it were its own. That is
548
+ * not hypothetical — it is the only state the primary has been observed in,
549
+ * and nothing today distinguishes it from a fresh start.
550
+ *
551
+ * This REPORTS. It does not refuse: an interrupted run's branch is usually
552
+ * exactly what you want to resume onto, and a gate that stopped every re-run
553
+ * is one that gets switched off.
554
+ */
555
+ export function leftoverRunBranch(repo: string, issue: number | string, base: string): LeftoverReading {
556
+ const branch = runBranchName(issue);
557
+ // Resolution is `runBranchRefs`'s, not a second `for-each-ref` here. A
558
+ // local-heads read beside it would be two deciders for one question, and
559
+ // the one this file shipped with was the local-only one
560
+ // (`.claude/rules/checks-must-be-able-to-fail.md`, the fourth shape).
561
+ const refs = runBranchRefs(repo, branch);
562
+ if (refs.reading === "UNMEASURED") {
563
+ return { reading: "UNMEASURED", branch, notice: refs.refusal };
564
+ }
565
+ if (refs.reading === "ABSENT") return { reading: "ABSENT", branch };
566
+ if (refs.reading === "DIVERGED") {
567
+ return {
568
+ reading: "LEFTOVER_DIVERGED",
569
+ branch,
570
+ local: refs.local,
571
+ remote: refs.remote,
572
+ notice:
573
+ `${refs.refusal} This run will commit onto the LOCAL one. Fetch and reconcile the two before ` +
574
+ "treating either as this issue's work (#640)",
575
+ };
576
+ }
577
+
578
+ // The resolved ref, not the bare name: the bare name resolves to the local
579
+ // head by git's own rules, which is the reading this function used to take
580
+ // and the one that can be about the wrong commit.
581
+ const ref = refs.resolvedRef;
582
+ const where = `${ref} (${refs.resolvedSha.slice(0, 12)})`;
583
+ const containment = branchContainment(repo, ref, base);
584
+ if (containment.reading === "UNMEASURED") {
585
+ return {
586
+ reading: "UNMEASURED",
587
+ branch,
588
+ notice: `${branch} already exists as ${where} and ${containment.refusal}`,
589
+ };
590
+ }
591
+ if (containment.reading === "CONTAINED") {
592
+ return {
593
+ reading: "LEFTOVER_CONTAINED",
594
+ branch,
595
+ resolvedRef: ref,
596
+ resolvedSha: refs.resolvedSha,
597
+ notice:
598
+ `${branch} already exists as ${where} and everything on it is already on ${base} — ` +
599
+ "a leftover from an earlier run of this issue, not work in progress (#640)",
600
+ };
601
+ }
602
+ return {
603
+ reading: "LEFTOVER_UNCONTAINED",
604
+ branch,
605
+ resolvedRef: ref,
606
+ resolvedSha: refs.resolvedSha,
607
+ divergent: containment.divergent,
608
+ notice:
609
+ `${branch} already exists as ${where} and ${containment.refusal} This run will commit onto it. ` +
610
+ "If that is not an interrupted run of this issue, stop and look (#640)",
611
+ };
612
+ }
@@ -138,6 +138,13 @@ const CeremonyTierOverrideSchema = z.object({
138
138
  agents: z.record(z.union([z.boolean(), z.string()])).optional(),
139
139
  }).passthrough();
140
140
 
141
+ /** See `ship:` below and `lib/ship-mode.ts` for why `mode` is not an enum. */
142
+ const ShipSchema = z.object({
143
+ mode: z.string(),
144
+ since: z.string().optional(),
145
+ reason: z.string().optional(),
146
+ }).passthrough();
147
+
141
148
  export const ProjectHarnessSchema = z.object({
142
149
  project: z.string(),
143
150
  repo: z.string(),
@@ -188,6 +195,18 @@ export const ProjectHarnessSchema = z.object({
188
195
  mcp: z.array(McpServerSchema).optional(),
189
196
  research: z.array(ResearchToolSchema).optional(),
190
197
  roles: z.record(RoleSchema).optional(),
198
+ /**
199
+ * Whether this project ships through the harness or directly (#911).
200
+ *
201
+ * `mode` is a plain string here, NOT `z.enum(["harness","direct"])`, and
202
+ * that is deliberate: `lib/scanner.ts`'s config read is wrapped in
203
+ * `catch {}`, so a zod throw on a typo'd mode would be swallowed and read
204
+ * as an absent config — which resolves to `"harness"`. A typo that
205
+ * silently reinstates the harness is the defect #911 exists to stop, so
206
+ * the refusal lives in `resolveShipPolicy` (`lib/ship-mode.ts`), which is
207
+ * reached on the generator path and names the offending value.
208
+ */
209
+ ship: ShipSchema.optional(),
191
210
  stalenessThreshold: z.number().optional(),
192
211
  ceremonyOverrides: z.record(CeremonyTierOverrideSchema).optional(),
193
212
  schemaVersion: z.number().default(1),