@feigi/fleet-ctl 0.0.0 → 3.16.3

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 (153) hide show
  1. package/agents/{fleet-implementer.agent.md → fleet-implementer-slow-high.agent.md} +23 -2
  2. package/agents/fleet-implementer-slow-medium.agent.md +231 -0
  3. package/agents/fleet-implementer-smol-high.agent.md +231 -0
  4. package/agents/{fleet-implementer-alt.agent.md → fleet-implementer-task-high.agent.md} +23 -2
  5. package/agents/fleet-implementer-task-max.agent.md +231 -0
  6. package/agents/fleet-review-comments.agent.md +4 -2
  7. package/agents/fleet-review-correctness.agent.md +2 -1
  8. package/agents/fleet-review-runner.agent.md +14 -10
  9. package/agents/fleet-review-silent-failure.agent.md +4 -3
  10. package/agents/fleet-review-simplify.agent.md +2 -1
  11. package/agents/fleet-review-snapshot.agent.md +2 -1
  12. package/agents/fleet-review-test-run.agent.md +29 -0
  13. package/agents/fleet-review-tests.agent.md +10 -5
  14. package/agents/fleet-review-types.agent.md +4 -2
  15. package/agents/fleet-review-verifier.agent.md +4 -3
  16. package/commands/review-and-fix.md +7 -6
  17. package/commands/run-merge-bot.md +14 -4
  18. package/package.json +4 -2
  19. package/scripts/agent-test.test.mjs +36 -32
  20. package/scripts/ambient-git-vars-mjs-prose.test.mjs +23 -13
  21. package/scripts/apply-ruleset.test.mjs +4 -3
  22. package/scripts/arg-header-probes-prose.test.mjs +1 -0
  23. package/scripts/arg.test.mjs +18 -18
  24. package/scripts/board-cli.test.mjs +18 -21
  25. package/scripts/board-identity.test.mjs +9 -9
  26. package/scripts/board-liveness-banner.test.mjs +6 -6
  27. package/scripts/board-prev-shape.test.mjs +12 -13
  28. package/scripts/board-tryparse-null.test.mjs +7 -7
  29. package/scripts/board.mjs +4 -7
  30. package/scripts/board.test.mjs +57 -61
  31. package/scripts/candidates.test.mjs +228 -17
  32. package/scripts/ci-completes-premise-prose.test.mjs +1 -1
  33. package/scripts/ci-state-prose.test.mjs +2 -2
  34. package/scripts/ci-state.mjs +389 -187
  35. package/scripts/ci-state.test.mjs +458 -165
  36. package/scripts/citation-sweep-prose.test.mjs +59 -1
  37. package/scripts/claim-lifecycle.test.mjs +2 -1
  38. package/scripts/claim-ticket.test.mjs +35 -34
  39. package/scripts/closing-keyword-prose.test.mjs +1 -1
  40. package/scripts/cockpit-tick-nonblocking.test.mjs +8 -8
  41. package/scripts/compute-board.mjs +13 -3
  42. package/scripts/compute-board.test.mjs +64 -1
  43. package/scripts/compute-spend.mjs +46 -8
  44. package/scripts/compute-spend.test.mjs +64 -10
  45. package/scripts/cross-repo-citation-prose.test.mjs +18 -19
  46. package/scripts/delete-merged-branch.sh +218 -0
  47. package/scripts/delete-merged-branch.test.mjs +576 -0
  48. package/scripts/derive-testcmd.sh +18 -7
  49. package/scripts/derive-testcmd.test.mjs +9 -8
  50. package/scripts/diff-stats.mjs +2 -2
  51. package/scripts/diff-stats.test.mjs +7 -11
  52. package/scripts/dispatch-block-golden-prose.test.mjs +111 -6
  53. package/scripts/dispatch-block-pins-prose.test.mjs +5 -5
  54. package/scripts/dispositions-check.mjs +507 -0
  55. package/scripts/dispositions-check.test.mjs +843 -0
  56. package/scripts/dispositions-gate-prose.test.mjs +114 -0
  57. package/scripts/drop-merged-label.test.mjs +3 -4
  58. package/scripts/exec-stub.mjs +93 -0
  59. package/scripts/exec-stub.test.mjs +69 -0
  60. package/scripts/filing-bar-seat-prose.test.mjs +1 -1
  61. package/scripts/finisher-test-verdict-prose.test.mjs +102 -0
  62. package/scripts/fix-applier-correction-rules-prose.test.mjs +11 -10
  63. package/scripts/fleet-bootstrap +5 -20
  64. package/scripts/fleet-bootstrap.test.mjs +75 -0
  65. package/scripts/fleet-heartbeat.mjs +2 -2
  66. package/scripts/fleet-provenance +15 -24
  67. package/scripts/fleet-provenance.test.mjs +86 -12
  68. package/scripts/fleet-run.test.mjs +5 -5
  69. package/scripts/fleet-state.mjs +33 -11
  70. package/scripts/fleet-state.test.mjs +90 -3
  71. package/scripts/fleet-tick.mjs +346 -70
  72. package/scripts/fleet-tick.test.mjs +566 -16
  73. package/scripts/force-with-lease-reason-prose.test.mjs +1 -1
  74. package/scripts/frontmatter-check.mjs +3 -2
  75. package/scripts/frontmatter-check.test.mjs +6 -6
  76. package/scripts/immutable-body-claim-prose.test.mjs +53 -262
  77. package/scripts/implementer-model-tier.test.mjs +98 -506
  78. package/scripts/inflight.test.mjs +18 -127
  79. package/scripts/is-cli.mjs +26 -0
  80. package/scripts/is-cli.test.mjs +99 -0
  81. package/scripts/json.test.mjs +3 -3
  82. package/scripts/ledger-dispatch.test.mjs +368 -7
  83. package/scripts/ledger-grammar.mjs +85 -1
  84. package/scripts/ledger-grammar.test.mjs +86 -1
  85. package/scripts/ledger-read-require-file.test.mjs +7 -7
  86. package/scripts/ledger-rotate.test.mjs +142 -0
  87. package/scripts/ledger.mjs +181 -17
  88. package/scripts/ledger.test.mjs +12 -130
  89. package/scripts/main-checkout.mjs +312 -0
  90. package/scripts/main-checkout.test.mjs +332 -0
  91. package/scripts/member-outcomes-header.test.mjs +3 -3
  92. package/scripts/member-outcomes.mjs +4 -5
  93. package/scripts/member-outcomes.test.mjs +92 -18
  94. package/scripts/member-prompt-prose.test.mjs +17 -13
  95. package/scripts/member-record.mjs +8 -3
  96. package/scripts/member-record.test.mjs +5 -5
  97. package/scripts/member-write-guard.mjs +5 -5
  98. package/scripts/member-write-guard.test.mjs +6 -3
  99. package/scripts/no-undo-audit.sh +24 -21
  100. package/scripts/no-undo-audit.test.mjs +9 -13
  101. package/scripts/pointer-target-prose.test.mjs +1 -1
  102. package/scripts/pr-overlap.test.mjs +6 -9
  103. package/scripts/prompt-renderer.mjs +10 -9
  104. package/scripts/prose-pin.mjs +10 -11
  105. package/scripts/prove-merge.test.mjs +3 -3
  106. package/scripts/quiet-payload-prose.test.mjs +1 -1
  107. package/scripts/reap.test.mjs +3 -4
  108. package/scripts/release-label-split-prose.test.mjs +17 -2
  109. package/scripts/release-ticket.test.mjs +35 -44
  110. package/scripts/review-core-cwd-isolation.test.mjs +7 -6
  111. package/scripts/review-core-reads.test.mjs +1 -1
  112. package/scripts/review-core-scratch-refusal.test.mjs +64 -0
  113. package/scripts/review-core-shared-test-run.test.mjs +238 -0
  114. package/scripts/review-core-snapshot-path.test.mjs +59 -12
  115. package/scripts/review-core-specialist-scratch.test.mjs +12 -10
  116. package/scripts/review-core-testcmd.test.mjs +76 -45
  117. package/scripts/review-core-unrun.test.mjs +154 -168
  118. package/scripts/review-core.mjs +250 -56
  119. package/scripts/review-eval.mjs +11 -4
  120. package/scripts/review-host-fixture.mjs +12 -3
  121. package/scripts/review-in-run-retry.test.mjs +27 -3
  122. package/scripts/review-runner-spawns.test.mjs +5 -3
  123. package/scripts/review-runner.test.mjs +14 -3
  124. package/scripts/review-tier-audit.test.mjs +1 -1
  125. package/scripts/run-merge-bot-prose.test.mjs +29 -6
  126. package/scripts/scratch-partition-invariant-prose.test.mjs +1 -1
  127. package/scripts/section-between-guard-prose.test.mjs +4 -3
  128. package/scripts/select-dimensions.test.mjs +1 -1
  129. package/scripts/shell-traps-prose.test.mjs +6 -9
  130. package/scripts/shortlist.mjs +4 -1
  131. package/scripts/shortlist.test.mjs +30 -16
  132. package/scripts/snapshot-repo.test.mjs +177 -4
  133. package/scripts/stash-prohibition-prose.test.mjs +1 -1
  134. package/scripts/temp-dir.mjs +47 -0
  135. package/scripts/tier-check.mjs +95 -28
  136. package/scripts/tier-check.test.mjs +131 -29
  137. package/scripts/tier-outcomes-header.test.mjs +11 -54
  138. package/scripts/tier-outcomes.mjs +34 -12
  139. package/scripts/tier-outcomes.test.mjs +157 -4
  140. package/scripts/tier-roles.mjs +118 -29
  141. package/scripts/tier-roles.test.mjs +226 -61
  142. package/scripts/tracker-block-copy-prose.test.mjs +3 -3
  143. package/scripts/verify-sha.test.mjs +4 -5
  144. package/scripts/watcher-degraded-block.test.mjs +5 -8
  145. package/scripts/within-run-pair-prose.test.mjs +43 -75
  146. package/scripts/worktree-audit.test.mjs +2 -1
  147. package/skills/next-ticket/SKILL.md +2 -2
  148. package/skills/run-team/SKILL.md +433 -303
  149. package/skills/run-team/references/ci-and-staleness.md +7 -6
  150. package/skills/run-team/references/correction-tickets.md +3 -3
  151. package/skills/run-team/references/isolation.md +1 -1
  152. package/skills/sizing-a-ticket/SKILL.md +8 -8
  153. package/scripts/tier-guard-gate-prose.test.mjs +0 -216
@@ -1,7 +1,7 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { classifyRole, computeSpend, attributeTools, mergeTools } from "./compute-spend.mjs";
4
- import { foldOmpTranscript } from "./member-record.mjs";
3
+ import { classifyRole, computeSpend, attributeTools, mergeTools, canonicalMemberName, CANONICAL_MEMBER_NAME_PREFIXES } from "./compute-spend.mjs";
4
+ import { foldOmpTranscript, parseMemberName } from "./member-record.mjs";
5
5
 
6
6
  const agent = (o) => ({ label: "x", role: "other", cacheWrite: 0, output: 0, cacheRead: 0, ...o });
7
7
 
@@ -286,6 +286,56 @@ test("implementers classify off the member NAME, which is where `impl-` actually
286
286
  assert.equal(classifyRole({ spawnDepth: 0, agentDefinition: "impl-332", description: "whatever" }), "other");
287
287
  });
288
288
 
289
+ test("a member family spelled PascalCase or without hyphens classifies off the name like its kebab form (#2396)", () => {
290
+ // omp task names are free-form, and controllers have dispatched the same
291
+ // families as `Impl327`, `FixPr774`, `Fix-pr-766`, `ReviewPR77`. The
292
+ // descriptions carry no role word, so only the name can carry the match.
293
+ const role = (memberName) => classifyRole({ spawnDepth: 0, memberName, description: "whatever" });
294
+ assert.equal(role("Impl327"), "implementer");
295
+ assert.equal(role("FixPr774"), "reviewer");
296
+ assert.equal(role("Fix-pr-766"), "reviewer");
297
+ assert.equal(role("ReviewPR77"), "reviewer");
298
+ assert.equal(role("ResolvePr1232"), "reviewer");
299
+ assert.equal(role("FinisherPr1567b"), "finisher");
300
+ assert.equal(role("Finish436"), "finisher");
301
+ assert.equal(role("MergeBot12"), "merge-bot");
302
+ // What it must still REFUSE: a generated word pair that merely starts with a
303
+ // family word is not that family. Kebab-casing these wholesale would turn
304
+ // `FinishSetupDocs` into `finish-setup-docs`, which `^finish-` books.
305
+ assert.equal(role("FinishSetupDocs"), "other");
306
+ assert.equal(role("Implementer5"), "other");
307
+ assert.equal(role("ImplPlan"), "other");
308
+ });
309
+
310
+ test("canonicalMemberName rewrites only a whole family-number name (#2396)", () => {
311
+ // The start anchor: a name that merely ENDS in a family spelling is not one.
312
+ assert.equal(canonicalMemberName("Xfix-pr-5"), "Xfix-pr-5");
313
+ assert.equal(canonicalMemberName("Setup-Impl3"), "Setup-Impl3");
314
+ // The number is required: a bare family word has no ticket to name.
315
+ for (const bare of ["Impl", "FixPr", "ReviewPr", "MergeBot"]) {
316
+ assert.equal(canonicalMemberName(bare), bare);
317
+ assert.equal(classifyRole({ spawnDepth: 0, memberName: bare, description: "whatever" }), "other");
318
+ }
319
+ // Surrounding whitespace is dropped before matching, for the join key and the role alike.
320
+ assert.equal(canonicalMemberName(" Impl327 "), "impl-327");
321
+ assert.equal(parseMemberName(" Impl327 ").ticket, "327");
322
+ assert.equal(parseMemberName(" impl-327 ").ticket, "327");
323
+ assert.equal(classifyRole({ spawnDepth: 0, memberName: " impl-327 ", description: "whatever" }), "implementer");
324
+ });
325
+
326
+ test("every canonical member-name prefix round-trips from its PascalCase and hyphenless spellings (#2396)", () => {
327
+ // A family added to the prefix list that the spelling pattern does not cover
328
+ // would be a stem member-record accepts but this rewrite leaves blank.
329
+ const stems = CANONICAL_MEMBER_NAME_PREFIXES.replace("finish(?:er)?", "finish|finisher").split("|");
330
+ assert.ok(stems.includes("fix-pr") && stems.includes("finisher"), "the expansion above must still yield the stems it is checked against");
331
+ for (const stem of stems) {
332
+ const pascal = stem.split("-").map((w) => w[0].toUpperCase() + w.slice(1)).join("");
333
+ for (const spelling of [`${pascal}12`, `${stem.replaceAll("-", "")}12`, `${stem}-12`]) {
334
+ assert.equal(canonicalMemberName(spelling), `${stem}-12`, spelling);
335
+ }
336
+ }
337
+ });
338
+
289
339
  test("the omp review fan-out classifies off its agent DEFINITION — depth cannot reach it there", () => {
290
340
  // The depth check above books a nested fan-out whose specialists are the
291
341
  // reviewer's grandchildren under that shape. omp has no such nesting: its
@@ -336,7 +386,7 @@ test("a definition name in the dispatch PROSE is not a dispatch — the fleet br
336
386
  });
337
387
 
338
388
  test("the fleet implementer definitions classify as implementer, independent of the `^impl-` name pattern", () => {
339
- // `agentDefinition`-based classification (`fleet-implementer(-alt)`) is
389
+ // `agentDefinition`-based classification (`fleet-implementer-<cell>`) is
340
390
  // checked BEFORE the `^impl-` name/description pattern below it, so it must
341
391
  // not depend on a canonically-shaped member name to fire — this pin
342
392
  // exercises classifyRole directly, on `agentDefinition` alone, so it stays
@@ -353,12 +403,16 @@ test("the fleet implementer definitions classify as implementer, independent of
353
403
  // split 73 other, 7 merge-bot, 5 finisher, 5 reviewer, none of them
354
404
  // implementer — the gap was in what omp handed classifyRole, not in the
355
405
  // classifier's own patterns.
356
- assert.equal(classifyRole({ spawnDepth: 0, agentDefinition: "fleet-implementer", description: "Ticket #1486. Worktree: .worktrees/1486-classify" }), "implementer");
357
- assert.equal(classifyRole({ spawnDepth: 0, agentDefinition: "fleet-implementer-alt", description: "Ticket #1486. Worktree: .worktrees/1486-classify" }), "implementer");
358
- // EXACT, unlike the review prefix above: the alternate-tier pairing is closed
359
- // at these two names, so a third `fleet-implementer-`-prefixed definition is a
360
- // deliberate addition and not something to classify in advance.
361
- assert.equal(classifyRole({ spawnDepth: 0, agentDefinition: "fleet-implementer-probe", description: "whatever" }), "other");
406
+ // Every cell, and the pre-cell pair #2129 retired: recorded history still
407
+ // carries rows dispatched under those two, and books them by definition.
408
+ for (const def of ["fleet-implementer-slow-high", "fleet-implementer-slow-medium", "fleet-implementer-task-high", "fleet-implementer-task-max", "fleet-implementer-smol-high", "fleet-implementer", "fleet-implementer-alt"]) {
409
+ assert.equal(classifyRole({ spawnDepth: 0, agentDefinition: def, description: "Ticket #1486. Worktree: .worktrees/1486-classify" }), "implementer", def);
410
+ }
411
+ // EXACT, unlike the review prefix above: a `fleet-implementer-`-prefixed
412
+ // name outside the `CELL` grammar is not an implementer definition.
413
+ for (const def of ["fleet-implementer-probe", "fleet-implementer-slow-ultra", "fleet-implementer-alt-2"]) {
414
+ assert.equal(classifyRole({ spawnDepth: 0, agentDefinition: def, description: "whatever" }), "other", def);
415
+ }
362
416
  });
363
417
 
364
418
  test("depth still outranks the definition — a fleet member's own fan-out is not another implementer", () => {
@@ -366,7 +420,7 @@ test("depth still outranks the definition — a fleet member's own fan-out is no
366
420
  // implementer dispatched is the specialist it structurally is rather than
367
421
  // inheriting its parent's definition. Move either branch above the depth
368
422
  // check and this goes red.
369
- assert.equal(classifyRole({ spawnDepth: 1, agentDefinition: "fleet-implementer", description: "whatever" }), "specialist");
423
+ assert.equal(classifyRole({ spawnDepth: 1, agentDefinition: "fleet-implementer-slow-high", description: "whatever" }), "specialist");
370
424
  // And memory still outranks both, which is the rule that keeps memory-system
371
425
  // work out of review spend.
372
426
  assert.equal(classifyRole({ spawnDepth: 0, agentDefinition: "memory-proxy", description: "Review PR 1353 correctness" }), "memory");
@@ -8,22 +8,21 @@ import { join } from "node:path";
8
8
  // human and to an agent. Not a broken link (a repo's own markdown files link
9
9
  // nothing); a reader defect, which is why counts-not-numbers was the only
10
10
  // workaround the file had. The convention that closes it is host-split, and
11
- // both halves need pinning: the rule in the Reviewers section, which the
12
- // controller relays to a hand-dispatched fallback reviewer, and the applied
13
- // instance where the foreign evidence sits.
11
+ // both halves need pinning: the rule in the claim-discipline block every
12
+ // implementer agent body carries, and the applied instance where the foreign
13
+ // evidence sits.
14
14
  const REPO = join(import.meta.dirname, "..");
15
- const RUN_TEAM = readFileSync(join(REPO, "skills", "run-team", "SKILL.md"), "utf8");
15
+ const AGENT = readFileSync(join(REPO, "agents", "fleet-implementer-slow-high.agent.md"), "utf8");
16
16
  const CORRECTIONS = readFileSync(
17
17
  join(REPO, "skills", "run-team", "references", "correction-tickets.md"),
18
18
  "utf8",
19
19
  );
20
20
 
21
- // Slice-scoped, not whole-file: SKILL.md is 1200+ lines and a bare presence
22
- // check anywhere in it stays green when the text lands somewhere its reader
23
- // never reaches (measured before in this repo — member-prompt-prose.test.mjs
24
- // #172). The correction-ticket rule block sits under `### Reviewers`, and its
25
- // own closing clause names the reader the controller has to relay it to: a
26
- // hand-dispatched fallback reviewer.
21
+ // Slice-scoped, not whole-file: a bare presence check anywhere in a long file
22
+ // stays green when the text lands somewhere its reader never reaches (measured
23
+ // before in this repo — member-prompt-prose.test.mjs #172). The claim-discipline
24
+ // block is what the harness injects into every implementer, so the rule has to
25
+ // sit inside it.
27
26
  function slice(text, startAnchor, endAnchor, what, { endsFile = false } = {}) {
28
27
  const at = text.indexOf(startAnchor);
29
28
  assert.notEqual(at, -1, `${what} start anchor ('${startAnchor}') moved — update this test`);
@@ -39,13 +38,13 @@ function slice(text, startAnchor, endAnchor, what, { endsFile = false } = {}) {
39
38
  // matches need the wrap invisible.
40
39
  const flat = (s) => s.replace(/\s+/g, " ");
41
40
 
42
- const correctionRuleBlock = () =>
41
+ const disciplineBlock = () =>
43
42
  flat(
44
43
  slice(
45
- RUN_TEAM,
46
- "**Correction tickets ship new wrong claims",
47
- "#### Fallback: hand-dispatched reviewer member",
48
- "the correction-ticket rule block",
44
+ AGENT,
45
+ "**Claim discipline, on every ticket:**",
46
+ "Commit incrementally as you go",
47
+ "the agent body's claim-discipline block",
49
48
  ),
50
49
  );
51
50
 
@@ -59,17 +58,17 @@ const conventionSection = () =>
59
58
  const secondRunSection = () =>
60
59
  flat(slice(CORRECTIONS, "## Second mechanism", "## The clause-by-clause duty", "the second-run evidence"));
61
60
 
62
- test("the cross-repo citation rule reaches the reviewer, in the rule block the controller relays to a fallback reviewer", () => {
63
- const block = correctionRuleBlock();
61
+ test("the cross-repo citation rule reaches every implementer, in the agent body's claim-discipline block", () => {
62
+ const block = disciplineBlock();
64
63
  assert.match(
65
64
  block,
66
65
  /another repo/i,
67
- "the correction-ticket rule block no longer says anything about evidence from another repo — a fallback reviewer relayed only this block stops catching a bare `#N` written for foreign evidence",
66
+ "the claim-discipline block no longer says anything about evidence from another repo — an implementer stops being told not to write a bare `#N` for foreign evidence",
68
67
  );
69
68
  assert.match(
70
69
  block,
71
70
  /owner\/repo#N/,
72
- "the github.com half of the citation rule is gone from the block the controller relays",
71
+ "the github.com half of the citation rule is gone from the agent body",
73
72
  );
74
73
  assert.match(
75
74
  block,
@@ -0,0 +1,218 @@
1
+ #!/bin/sh
2
+ # Delete a merged PR's head branch from `origin` (#2196). The merge bot owns
3
+ # this step: run-merge-bot.md's step 4 calls it after the merge is confirmed.
4
+ # Until #2196 nothing did — the fleet leaned on the repo setting "Automatically
5
+ # delete head branches", which nothing here enforced or checked, so a repo with
6
+ # it off accumulated every merged branch, and reap.sh (which reaps only a local
7
+ # branch whose upstream is `[gone]`) never saw one to reap.
8
+ #
9
+ # REMOTE ONLY, on purpose — never `gh pr merge --delete-branch`. That flag's
10
+ # post-merge LOCAL cleanup dies with `fatal: 'main' is already used by worktree
11
+ # at <path>` whenever the head branch is checked out in a git worktree, and every
12
+ # fleet-claimed ticket's branch is, by construction
13
+ # (`.worktrees/<issue>-<slug>`, docs/requirements.md §3.2). This script runs no
14
+ # local branch or worktree command at all: it deletes the ref on `origin`, which
15
+ # leaves the local branch `[gone]` with its worktree still on disk — exactly the
16
+ # state reap.sh already reaps, worktree first and branch second. So the local
17
+ # half stays reap.sh's, with its dirty-worktree and unpushed-work refusals
18
+ # intact, and a worktree holding the branch cannot make this step fail.
19
+ #
20
+ # The delete is LEASED to the head GitHub merged (`--force-with-lease=<ref>:
21
+ # <headRefOid>`), so the check and the act are one ref update on the server: a
22
+ # push that landed on the branch after the merge makes the delete refuse instead
23
+ # of destroying commits `main` never received. A separate "is the tip still the
24
+ # merged head" read followed by a plain delete would leave a window between the
25
+ # two; the lease closes it at delete time.
26
+ #
27
+ # Success is READ BACK, never inferred from the push's exit status: after the
28
+ # push, `ls-remote` must show the ref absent. A branch already absent before the
29
+ # push — the repo still has auto-delete on, or a re-run — is the same success:
30
+ # the outcome this step exists for already holds.
31
+ #
32
+ # KEPT while another open PR uses the branch (#2295). Deleting a branch closes
33
+ # every open PR headed by it, and may close rather than retarget every open PR
34
+ # based on it — GitHub retargets stacked PRs when IT deletes a merged head, and
35
+ # nobody has observed whether a push-delete triggers the same. So just before
36
+ # the push the script asks for both, and deletes nothing when either answers.
37
+ # The merged PR is not open, so it never matches. A fork PR whose own branch
38
+ # shares the name does not count as headed by it: that branch lives in the fork.
39
+ # The lookups run only when there is a delete to guard — a branch already gone
40
+ # has none, and is exit 0 whatever they would say.
41
+ #
42
+ # Exit 0: the branch is gone from origin (deleted here, already gone, or a fork
43
+ # PR's branch, which lives in another repository and is not ours to
44
+ # delete — `"skipped":"cross-repository"`).
45
+ # Exit 1: the branch is STILL on origin — the lease refused (the tip moved after
46
+ # the merge) or the push failed. REPORT IT as
47
+ # `branch-delete-failed-#<pr>`, never swallow it.
48
+ # Exit 2: could not even tell what to delete — bad usage, the PR is not merged,
49
+ # a `gh`/`ls-remote` call failed, the head names the base branch, or an
50
+ # open-PR lookup failed, answered with something that is not a list
51
+ # of PR numbers, or could not be checked for that (nothing is deleted;
52
+ # the lookup is named on stderr).
53
+ # Exit 3: KEPT on purpose — another open PR uses the branch as its head or its
54
+ # base. Nothing was pushed. Stdout is one `branch-kept-#<pr>` line per
55
+ # such PR (that PR's number, not the merged one's) instead of the JSON
56
+ # payload; stderr says which role each plays. A deliberate keep, not a
57
+ # failure: report the lines, never retry.
58
+ set -eu
59
+
60
+ # Ambient GIT_DIR/GIT_WORK_TREE would point `ls-remote origin` and the push at
61
+ # whatever repository they name rather than the one this runs in — the same
62
+ # misdirection reap.sh's header records for its own calls.
63
+ unset GIT_DIR GIT_WORK_TREE
64
+
65
+ NAME=delete-merged-branch
66
+ die() { printf '%s: %s\n' "$NAME" "$1" >&2; exit 2; }
67
+
68
+ json_lib="$(dirname "$0")/json.sh"
69
+ [ -r "$json_lib" ] || die "cannot read $json_lib — refusing to run without the JSON escaping helpers"
70
+ # shellcheck source-path=SCRIPTDIR
71
+ # shellcheck source=json.sh
72
+ . "$json_lib" || die "$json_lib failed to load"
73
+
74
+ net_lib="$(dirname "$0")/net.sh"
75
+ [ -r "$net_lib" ] || die "cannot read $net_lib — refusing to run without the bounded git transport"
76
+ # shellcheck source-path=SCRIPTDIR
77
+ # shellcheck source=net.sh
78
+ . "$net_lib" || die "$net_lib failed to load"
79
+
80
+ [ $# -eq 1 ] || die "usage: delete-merged-branch.sh <pr>"
81
+ pr=$1
82
+ case "$pr" in ''|*[!0-9]*|0?*) die "pr must be a number, got '$pr'";; esac
83
+
84
+ # One read, so state, head and fork-ness all describe the same moment. Fields
85
+ # are joined on \037 (unit separator), not @tsv's tab: a tab is IFS whitespace,
86
+ # so `read` collapses a run of them and an empty field shifts every later field
87
+ # left — an empty headRefName read the base branch as the head commit. A
88
+ # non-whitespace IFS keeps an empty field in its place. No field can carry the
89
+ # separator: git refnames cannot hold a control character (git-check-ref-format).
90
+ echo "\$ gh pr view $pr --json state,isCrossRepository,headRefName,headRefOid,baseRefName" >&2
91
+ if ! fields=$(gh pr view "$pr" --json state,isCrossRepository,headRefName,headRefOid,baseRefName \
92
+ --jq '[.state, (.isCrossRepository | tostring), .headRefName, .headRefOid, .baseRefName] | map(. // "") | join("\u001f")'); then
93
+ die "gh pr view $pr failed — cannot tell whether it merged or what its head branch is"
94
+ fi
95
+ us=$(printf '\037')
96
+ IFS=$us read -r state cross branch oid base <<EOF
97
+ $fields
98
+ EOF
99
+
100
+ # MERGED, not just closed: a PR closed unmerged still holds work nowhere else.
101
+ [ "$state" = "MERGED" ] || die "PR #$pr is not merged (state=$state) — refusing to delete its branch"
102
+ [ -n "$branch" ] && [ -n "$oid" ] || die "gh pr view $pr returned no head branch or head commit"
103
+ case "$oid" in *[!0-9a-f]*) die "gh pr view $pr returned a head commit that is not a hex SHA: '$oid'";; esac
104
+ [ "$branch" != "$base" ] || die "PR #$pr's head branch is its base branch '$base' — refusing to delete it"
105
+
106
+ if ! jbranch=$(jstr "$branch"); then
107
+ die "could not JSON-escape branch name '$branch'"
108
+ fi
109
+
110
+ # A fork PR's head lives in the fork. A same-named branch on OUR origin is a
111
+ # different branch that happens to share the name, and the lease alone would be
112
+ # the only thing standing between it and this delete.
113
+ if [ "$cross" = "true" ]; then
114
+ printf '{"pr":%s,"branch":"%s","deleted":false,"skipped":"cross-repository"}\n' "$pr" "$jbranch"
115
+ exit 0
116
+ fi
117
+
118
+ # 30s, the budget every fleet `ls-remote` gets: it moves refs, no objects. The
119
+ # ref-only `push --delete` below moves no objects either, so it shares it.
120
+ # `FLEET_NET_TIMEOUT` shortens it, never lengthens — net_budget's rule.
121
+ ref_budget=$(net_budget 30 "${FLEET_NET_TIMEOUT:-}")
122
+
123
+ # Prints the tip of refs/heads/$branch on origin, or nothing when it is absent.
124
+ # An exact field match rather than trusting ls-remote's pattern, which matches
125
+ # any ref ENDING in the pattern on a `/` boundary.
126
+ remote_tip() {
127
+ rt_rc=0
128
+ rt_out=$(net_git "" "$ref_budget" ls-remote --heads origin "refs/heads/$branch") || rt_rc=$?
129
+ if [ "$rt_rc" -ne 0 ]; then
130
+ if net_stalled "$rt_rc"; then
131
+ die "git ls-remote did not finish within ${ref_budget}s and was killed, so whether $branch is on origin is unknown"
132
+ fi
133
+ die "git ls-remote failed, so whether $branch is on origin is unknown"
134
+ fi
135
+ printf '%s\n' "$rt_out" | awk -F '\t' -v ref="refs/heads/$branch" '$2 == ref { print $1 }'
136
+ }
137
+
138
+ echo "\$ git ls-remote --heads origin refs/heads/$branch" >&2
139
+ before=$(remote_tip)
140
+ if [ -z "$before" ]; then
141
+ printf '{"pr":%s,"branch":"%s","deleted":false,"alreadyGone":true}\n' "$pr" "$jbranch"
142
+ exit 0
143
+ fi
144
+
145
+ # Dies unless $2 is empty or one PR number per line: a `gh` that exits 0 has
146
+ # not answered if what it printed cannot be read as that. grep's exit 1 is the
147
+ # only "valid list" answer; anything past it (2 and up) means grep itself
148
+ # failed, and reading that as valid would let the delete through unchecked.
149
+ pr_numbers() {
150
+ pn_rc=0
151
+ printf '%s\n' "$2" | grep -Eqv '^([1-9][0-9]*)?$' || pn_rc=$?
152
+ case "$pn_rc" in
153
+ 0) die "the open-PR lookup \`gh pr list --$1 $branch\` answered with something that is not a list of PR numbers: '$2' — not deleting it" ;;
154
+ 1) ;;
155
+ *) die "grep exited $pn_rc, so whether the open-PR lookup \`gh pr list --$1 $branch\` answered with a list of PR numbers is unknown — not deleting it" ;;
156
+ esac
157
+ }
158
+
159
+ # Asked here, after the branch is known to be on origin and just before the
160
+ # push, so a keep is only ever reported for a branch that is really still
161
+ # there. `--limit` sits far past any real count: a truncated list would still
162
+ # keep the branch, but would drop a `branch-kept-#` line.
163
+ echo "\$ gh pr list --head $branch --state open --json number,isCrossRepository" >&2
164
+ if ! headed=$(gh pr list --head "$branch" --state open --limit 1000 --json number,isCrossRepository \
165
+ --jq '.[] | select(.isCrossRepository | not) | .number'); then
166
+ die "the open-PR lookup \`gh pr list --head $branch\` failed — cannot tell whether deleting it would close another PR; not deleting it"
167
+ fi
168
+ pr_numbers head "$headed"
169
+ echo "\$ gh pr list --base $branch --state open --json number" >&2
170
+ if ! based=$(gh pr list --base "$branch" --state open --limit 1000 --json number --jq '.[].number'); then
171
+ die "the open-PR lookup \`gh pr list --base $branch\` failed — cannot tell whether deleting it would close another PR; not deleting it"
172
+ fi
173
+ pr_numbers base "$based"
174
+
175
+ # Both lists hold only validated PR numbers, so splitting them is safe — and
176
+ # command substitution strips trailing newlines, so a list is non-empty only
177
+ # when it names a PR.
178
+ for n in $headed; do
179
+ printf '%s: open PR #%s uses %s as its head — deleting the branch would close it; keeping the branch\n' "$NAME" "$n" "$branch" >&2
180
+ done
181
+ for n in $based; do
182
+ printf '%s: open PR #%s uses %s as its base — deleting the branch may close it rather than retarget it; keeping the branch\n' "$NAME" "$n" "$branch" >&2
183
+ done
184
+ if [ -n "$headed$based" ]; then
185
+ printf '%s\n%s\n' "$headed" "$based" | grep . | sort -nu | sed 's/^/branch-kept-#/'
186
+ exit 3
187
+ fi
188
+
189
+ echo "\$ git push --force-with-lease=refs/heads/$branch:$oid origin --delete refs/heads/$branch" >&2
190
+ push_rc=0
191
+ net_git "" "$ref_budget" push --force-with-lease="refs/heads/$branch:$oid" origin --delete "refs/heads/$branch" >&2 || push_rc=$?
192
+
193
+ echo "\$ git ls-remote --heads origin refs/heads/$branch" >&2
194
+ after=$(remote_tip)
195
+ if [ -n "$after" ]; then
196
+ # The branch survived. Say which of the three causes this run can tell apart.
197
+ if [ "$after" != "$oid" ]; then
198
+ reason="branch tip $after is not the merged head $oid — a push landed after the merge; not deleting it"
199
+ elif net_stalled "$push_rc"; then
200
+ reason="git push --delete did not finish within ${ref_budget}s and was killed; the branch was still on origin when read back"
201
+ else
202
+ reason="git push --delete exited $push_rc and the branch is still on origin"
203
+ fi
204
+ if ! jreason=$(jstr "$reason"); then jreason="unrenderable reason"; fi
205
+ printf '%s: %s\n' "$NAME" "$reason" >&2
206
+ printf '{"pr":%s,"branch":"%s","deleted":false,"tip":"%s","reason":"%s"}\n' "$pr" "$jbranch" "$after" "$jreason"
207
+ exit 1
208
+ fi
209
+
210
+ # Absent now. If the push itself failed, something else removed the branch
211
+ # between the two reads (auto-delete racing this run) — still the outcome
212
+ # this step exists for, so it is reported as already gone rather than deleted.
213
+ if [ "$push_rc" -ne 0 ]; then
214
+ printf '{"pr":%s,"branch":"%s","deleted":false,"alreadyGone":true}\n' "$pr" "$jbranch"
215
+ exit 0
216
+ fi
217
+ printf '{"pr":%s,"branch":"%s","deleted":true}\n' "$pr" "$jbranch"
218
+ exit 0