@feigi/fleet-ctl 3.140.0 → 3.141.1

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.
@@ -269,8 +269,10 @@ cause `other`, with both runs — the mutant's and the unmutated tree's — as
269
269
  evidence; label nothing. A kill's evidence line goes in your report.
270
270
 
271
271
  **Duty 3 is one script, and its exit code is your verdict.**
272
- `~/.omp/plugins/node_modules/@feigi/fleet-ctl/scripts/fleet-run finisher-label.mjs --pr <M> --pin <your dispatch pin>`
273
- (the full SHA). It confirms exactly one of `patch`/`minor`/`major` is on the
272
+ `~/.omp/plugins/node_modules/@feigi/fleet-ctl/scripts/fleet-run finisher-label.mjs --pr <M> --pin <your dispatch pin> --kill '<evidence line>'`
273
+ (the full SHA; `--kill` carries your kill's evidence line as one quoted
274
+ argument, and a PR whose mutation you skipped — an Inert diff or a Ticketless
275
+ PR — omits it). It confirms exactly one of `patch`/`minor`/`major` is on the
274
276
  PR — a Ticketless PR with none gets `patch` added first — records the head you
275
277
  audited, adds `ready-to-merge`, and reads the labels
276
278
  back. Exit 0 is the only code that means the label is on. Exit 3 means the PR
@@ -280,7 +282,9 @@ before the label, and the receipt names which it found. Exit 4 means the
280
282
  read-back does not carry the label, written or not. Exit 5 means the PR is a
281
283
  Ticketless PR whose diff is not inert, or whose Inert diff verdict could not
282
284
  look: the script posted the head record and added no label, and you are halted
283
- with cause `human`. Exit 2 means a `gh` call or the invocation itself failed:
285
+ with cause `human`. Exit 6 means a ticket PR whose diff is not inert, or whose
286
+ Inert diff verdict could not look, came without a `--kill` in the
287
+ `red: … ; baseline: …` grammar: the script wrote nothing. Exit 2 means a `gh` call or the invocation itself failed:
284
288
  report the stderr it printed. Every non-zero exit halts you, with cause `other`
285
289
  unless it is exit 5, with the receipt as evidence, and you do not run any of
286
290
  its steps by hand to get past it. A repo whose label list defines none of the
@@ -31,34 +31,27 @@ was given for, and the label no longer covers it.
31
31
 
32
32
  ## The labelled head
33
33
 
34
- `ready-to-merge` is a finisher's verdict on one tree, and it does not expire when that tree does. **A GitHub label does not follow the branch** — one merged PR's timeline shows it, read with the timeline query below: `labeled ready-to-merge`, then commits and a `head_ref_force_pushed`, then `merged`, with no `unlabeled` anywhere between. The label stayed put while the head moved out from under it. Every other guard in this chain — the finisher's dispatch pin, the halt on a moved head, the worktree audit — runs *before* the label exists, so none of them is watching this window. You are the last gate, and **re-deriving the head is a requirement here, not bot discretion**: merge only a head that still carries the audit the label stands for.
34
+ `ready-to-merge` is a finisher's verdict on one tree, and it does not expire when that tree does. **A GitHub label does not follow the branch** — one merged PR's timeline shows it, which the `timeline` route below reads: `labeled ready-to-merge`, then commits and a `head_ref_force_pushed`, then `merged`, with no `unlabeled` anywhere between. The label stayed put while the head moved out from under it. Every other guard in this chain — the finisher's dispatch pin, the halt on a moved head, the worktree audit — runs *before* the label exists, so none of them is watching this window. You are the last gate, and **re-deriving the head is a requirement here, not bot discretion**: merge only a head that still carries the audit the label stands for.
35
35
 
36
- **The labelled head is the head its labeller recorded.** Whoever adds `ready-to-merge` — a finisher, or `review-and-fix` run standalone — posts a PR comment whose whole body is `ready-to-merge-head: <sha>`, naming the head it audited, immediately before the label. The prefix `ready-to-merge-head:` is not a label: type it as written, whatever string the Label map gives `ready-to-merge`. Read the newest one before `gh pr update-branch` and before anything else that can move the head:
36
+ **The labelled head is the head its labeller recorded.** Whoever adds `ready-to-merge` — a finisher, or `review-and-fix` run standalone — posts a PR comment whose whole body is `ready-to-merge-head: <sha>`, naming the head it audited, immediately before the label. The prefix `ready-to-merge-head:` is not a label: type it as written, whatever string the Label map gives `ready-to-merge`. Read the newest one before `gh pr update-branch` and before anything else that can move the head, with one read-only command that decides the route — you never compare the SHAs yourself:
37
37
 
38
38
  ```bash
39
- gh pr view <pr> --json comments \
40
- -q '[.comments[] | {createdAt, sha: (.body | capture("\\Aready-to-merge-head: (?<sha>[0-9a-f]{40})\\s*\\z").sha)}]
41
- | sort_by(.createdAt) | last | .sha // ""'
39
+ ~/.omp/plugins/node_modules/@feigi/fleet-ctl/scripts/fleet-run labelled-head.mjs --pr <pr>
42
40
  ```
43
41
 
44
- Nothing else names that head. A commit's dates are when it was made, not when it was pushed, so a commit made before the label and pushed after it carries no date after the label; and a plain push that a force-push then orphans leaves no line on the PR's timeline at all.
42
+ It prints one JSON line, `{pr, record, head, route, timeline, exit}`: `record` is the newest record's SHA (`null` when no comment is a record), `head` the PR's current head, and `route` one of `current`, `gate` or `timeline`. **The route is the command's answer, not yours to re-derive:** a `record` that differs from `head` is route `gate`, never `timeline` — the `timeline` route is reached only when `record` is `null`. Exit 2 means a read failed (its `step` is `read-pr`, `label-map` or `read-timeline`, its `error` what `gh` said): skip the PR and report `<step>-#<pr>`, the way any other gate refusal is reported.
45
43
 
46
- **A recorded head that is the current head (`gh pr view <pr> --json headRefOid -q .headRefOid`) is the normal case, and it proceeds untouched** — label applied, head unchanged, merge goes ahead exactly as it did before this gate existed.
44
+ Nothing else names that head. A commit's dates are when it was made, not when it was pushed, so a commit made before the label and pushed after it carries no date after the label; and a plain push that a force-push then orphans leaves no line on the PR's timeline at all.
47
45
 
48
- **A recorded head that is not the current head is not refused on sight — it may be a rebase-carry, and the merge gate decides.** The label binds to the change the finisher audited, not to one SHA: a rewrite that leaves the PR's net change byte-identical — a conflict-free rebase onto a newer `main` — keeps it, and anything a push adds, drops or edits does not, whenever it was pushed and however its commits are dated. So, in the main checkout after a plain `git fetch origin`, run step 3's gate now, before step 1, with `--pre <labelled head>` and no `--post`. **`rebaseCarry` null → refuse:** report `head-moved-after-label-#<pr>` and stop on that PR. Leave the label where it is — you audited nothing and removing another member's verdict is not yours to do. What clears it is a **fresh** finisher against the new head; the first audit does not transfer, because it verified a different tree. Non-null → the current head carries the labelled head's change: `--pre` stays the labelled head on every later gate run, step 1's `pre` must read `rebaseCarry.accepted` (any other head is a push since the proof — refuse with `head-moved-after-label-#<pr>`), and your report names the carry as `rebase-carry-#<pr>` with both SHAs.
46
+ **Route `current` — the recorded head is the current head — is the normal case, and it proceeds untouched** — label applied, head unchanged, merge goes ahead exactly as it did before this gate existed.
49
47
 
50
- **No record — a hand-added label, or one applied before its labeller recorded a head — falls back to the timeline, which can refuse a moved head but never name the labelled one.** Read it before `gh pr update-branch` too: your own rebase lands commits after the label by construction, so once you have rebased this read can no longer tell your commits from someone else's:
48
+ **Route `gate` — the recorded head is not the current head — is not refused on sight: it may be a rebase-carry, and the merge gate decides.** The label binds to the change the finisher audited, not to one SHA: a rewrite that leaves the PR's net change byte-identical — a conflict-free rebase onto a newer `main` — keeps it, and anything a push adds, drops or edits does not, whenever it was pushed and however its commits are dated. So, in the main checkout after a plain `git fetch origin`, run step 3's gate now, before step 1, with `--pre <record>` and no `--post`. **`rebaseCarry` null → refuse:** report `head-moved-after-label-#<pr>` and stop on that PR. Leave the label where it is — you audited nothing and removing another member's verdict is not yours to do. What clears it is a **fresh** finisher against the new head; the first audit does not transfer, because it verified a different tree. Non-null → the current head carries the labelled head's change: `--pre` stays the labelled head on every later gate run, step 1's `pre` must read `rebaseCarry.accepted` (any other head is a push since the proof — refuse with `head-moved-after-label-#<pr>`), and your report names the carry as `rebase-carry-#<pr>` with both SHAs.
51
49
 
52
- ```bash
53
- label="<ready-to-merge string>" gh api "repos/{owner}/{repo}/issues/<pr>/timeline?per_page=100" --paginate \
54
- -q '.[] | select((.event == "labeled" and .label.name == env.label)
55
- or .event == "committed" or .event == "head_ref_force_pushed")
56
- | .event + " " + (.sha // .label.name // "")'
57
- ```
50
+ **Route `timeline` — no record, a hand-added label or one applied before its labeller recorded a head — falls back to the timeline, which can refuse a moved head but never name the labelled one.** The command has already read it, `gh api repos/{owner}/{repo}/issues/<pr>/timeline?per_page=100 --paginate`, and printed the verdict as `timeline: {label, verdict, after}`, `label` the Label map's string for `ready-to-merge`. Run the command before `gh pr update-branch`, on this route too: your own rebase lands commits after the label by construction, so once you have rebased this read can no longer tell your commits from someone else's.
58
51
 
59
- A `committed` or `head_ref_force_pushed` line after the last `labeled ready-to-merge` means the head moved after the audit. **With no record, refuse:** report `head-moved-after-label-#<pr>` and stop on that PR, the label left where it is — nothing names a head the label was applied to, so no carry can be proven. **Nothing after that label line is the normal case, and it proceeds untouched.**
52
+ `verdict` is `moved` when a `committed` or `head_ref_force_pushed` event follows the last `labeled` event for that string, `after` listing those events as `<event> <sha>`; otherwise `clean`. **`moved` with no record → refuse:** report `head-moved-after-label-#<pr>` and stop on that PR, the label left where it is — nothing names a head the label was applied to, so no carry can be proven. **`clean` is the normal case, and it proceeds untouched.** A timeline with no `labeled` event for that string has no verdict: the label is on the PR, so a read that never saw it applied came back empty or wrong, and the command exits 2 with `step` `read-timeline`.
60
53
 
61
- Record the head before you rebase — `gh pr view <pr> --json headRefOid -q .headRefOid` — because step 3 hands it to the merge gate as `--pre` and nothing later can reconstruct it. Where step 1 runs, that is its `pre`; on an already-current PR it is simply the head you merge. After a carry, `--pre` is the labelled head instead.
54
+ Record the head before you rebase — the `head` the command printed, read before anything moved it — because step 3 hands it to the merge gate as `--pre` and nothing later can reconstruct it. Where step 1 runs, that is its `pre`; on an already-current PR it is simply the head you merge. After a carry, `--pre` is the labelled head instead.
62
55
 
63
56
  What this gate deliberately does not answer. It does not ask *who* audited — a hand-added `ready-to-merge` with no finisher behind it reads clean here, and the reviewer-only rule in `run-team/SKILL.md` is what owns that — nor who posted the record or who force-pushed. A head rebased after the label by an **earlier, abandoned pass of this command** is judged like any other moved head: with a record, carried when its net change is the labelled head's, refused when it is not; without one, refused.
64
57
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feigi/fleet-ctl",
3
- "version": "3.140.0",
3
+ "version": "3.141.1",
4
4
  "description": "Agent fleet: run-team controller, merge bot, PR reviewer, and the ticket pipeline they share",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -3,12 +3,13 @@
3
3
  // read as one: the release-label check is a precondition, and a finisher that
4
4
  // stopped after it reported `labelled` on a PR that never got the label.
5
5
  //
6
- // finisher-label.mjs --pr <M> --pin <sha> [--repo <dir>]
6
+ // finisher-label.mjs --pr <M> --pin <sha> [--kill <evidence line>] [--repo <dir>]
7
7
  //
8
8
  // `--pin` is the full 40-hex head the finisher audited; `--repo` is the
9
9
  // directory `gh` runs in (it resolves the repository from there), the cwd when
10
- // omitted. Reached through the Resolver: `~/.omp/plugins/node_modules/@feigi/fleet-ctl/scripts/fleet-run
11
- // finisher-label.mjs ...`.
10
+ // omitted. `--kill` is the evidence line of the acceptance mutation's kill,
11
+ // read only at step 1b. Reached through the Resolver:
12
+ // `~/.omp/plugins/node_modules/@feigi/fleet-ctl/scripts/fleet-run finisher-label.mjs ...`.
12
13
  //
13
14
  // Steps, in this order, each one only if every earlier one held:
14
15
  //
@@ -24,10 +25,14 @@
24
25
  // list is read only when the PR carries none of them — one on the PR
25
26
  // proves it is defined — and a list that fills the limit it was read with
26
27
  // proves nothing, so it is exit 2 rather than a skipped count.
27
- // 1b on a Ticketless PR, finisher-scope.mjs's Inert diff verdict at `--pin`,
28
- // run in-process. A diff that is not inert, or a verdict that could not
29
- // look, stops after step 2: the head record is posted, the label is not
30
- // added, and the exit is 5.
28
+ // 1b finisher-scope.mjs's Inert diff verdict at `--pin`, run in-process on
29
+ // every PR. On a Ticketless PR a diff that is not inert, or a verdict
30
+ // that could not look, stops after step 2: the head record is posted,
31
+ // the label is not added, and the exit is 5. On a ticket PR either one
32
+ // needs a `--kill` claim — non-empty and in the finisher's evidence-line
33
+ // grammar, `red: … ; baseline: …` — and without one the exit is 6 and
34
+ // nothing is written. The claim is taken on its word: the script cannot
35
+ // rerun the mutation. An inert diff, or a Ticketless PR, ignores `--kill`.
31
36
  // 2 comment `ready-to-merge-head: <pin>`, the record the merge bot reads as
32
37
  // the head the label was applied to — skipped when the newest such
33
38
  // comment already names this pin.
@@ -48,8 +53,8 @@
48
53
  //
49
54
  // Stdout is always one JSON line, the receipt:
50
55
  //
51
- // {pr, pin, ticketless, releaseLabels, patchAdded, inert, commented, added,
52
- // readBack, exit, firstRead [, step, error]}
56
+ // {pr, pin, ticketless, releaseLabels, patchAdded, inert, kill, commented,
57
+ // added, readBack, exit, firstRead [, step, error] [, killGiven]}
53
58
  //
54
59
  // ticketless the Ticketless test's answer, null when it never got one
55
60
  // releaseLabels the release labels the PR carried (`patch` once added to a
@@ -57,6 +62,7 @@
57
62
  // never got an answer
58
63
  // patchAdded this run added `patch`
59
64
  // inert the Inert diff verdict object, null when it never ran
65
+ // kill the `--kill` claim step 1b accepted, null when it took none
60
66
  // commented this run posted the head record
61
67
  // added this run wrote the label
62
68
  // readBack every label name the step 4 read carried, null if it never ran
@@ -64,6 +70,8 @@
64
70
  // step on exit 2 only, the step that failed: `pin`, `repo`,
65
71
  // `label-map`, or the step whose `gh` call failed
66
72
  // error on exit 2 only, what `gh` (or the invocation) said
73
+ // killGiven on exit 6 only, what `--kill` carried, null when it was
74
+ // not given
67
75
  //
68
76
  // A usage error that never reaches `gh` — a missing or unknown flag — is a
69
77
  // refusal on stderr with no receipt, as in every other script's `die()`.
@@ -80,6 +88,8 @@
80
88
  // 5 a Ticketless PR whose diff is not inert, or whose verdict could not
81
89
  // look: the head record is posted and the label is not added, so the
82
90
  // maintainer's `ready-to-merge` is the merge
91
+ // 6 a ticket PR whose diff is not inert, or whose verdict could not look,
92
+ // with no well-formed `--kill` claim — nothing was written
83
93
 
84
94
  import { spawnSync } from "node:child_process";
85
95
  import { statSync } from "node:fs";
@@ -89,16 +99,17 @@ import { inertVerdict } from "./finisher-scope.mjs";
89
99
  import { gitEnv } from "./git-env.mjs";
90
100
  import { LABEL_LIST_ARGS, LABEL_LIST_LIMIT, releaseLabelsDefined, releaseLabelsIn } from "./release-labels.mjs";
91
101
  import { readLabelMap } from "./label-map.mjs";
102
+ import { headRecordBody, newestHeadRecord } from "./ready-to-merge-head.mjs";
92
103
  import { ticketlessVerdict } from "./ticketless.mjs";
93
104
 
94
105
  const NAME = "finisher-label";
95
106
 
96
107
  const die = makeDie(NAME);
97
108
  const { arg, numArg, sweep, stray } = defineFlags(die, {
98
- flags: { pr: "value", pin: "value", repo: "value" },
109
+ flags: { pr: "value", pin: "value", repo: "value", kill: "value" },
99
110
  });
100
111
 
101
- const USAGE = "usage: finisher-label.mjs --pr <M> --pin <sha> [--repo <dir>]";
112
+ const USAGE = "usage: finisher-label.mjs --pr <M> --pin <sha> [--kill <evidence line>] [--repo <dir>]";
102
113
 
103
114
  // The sweep runs before the required-flag check so a misspelt flag is named
104
115
  // as that, not buried under a missing-flag usage line.
@@ -107,6 +118,12 @@ stray();
107
118
  const pr = numArg("pr");
108
119
  const pinArg = arg("pin");
109
120
  const repo = arg("repo");
121
+ // Read by hand past arg(), which refuses an empty value as a usage error: an
122
+ // empty claim is a malformed kill, refused at exit 6 like a missing one, and
123
+ // only where the verdict needs a claim. arg() still reads the absent case, so
124
+ // a `--kill=` form is refused by name rather than read as no claim.
125
+ const killAt = process.argv.indexOf("--kill");
126
+ const killArg = killAt === -1 ? arg("kill") : (process.argv[killAt + 1] ?? "");
110
127
  if (pr === null || pinArg === null) die(USAGE);
111
128
 
112
129
  const receipt = {
@@ -116,6 +133,7 @@ const receipt = {
116
133
  releaseLabels: null,
117
134
  patchAdded: false,
118
135
  inert: null,
136
+ kill: null,
119
137
  commented: false,
120
138
  added: false,
121
139
  readBack: null,
@@ -224,30 +242,43 @@ if (found.length === 0) {
224
242
  receipt.releaseLabels = found;
225
243
  }
226
244
 
227
- // --- 1b: the Inert diff verdict, on a Ticketless PR ------------------------
245
+ // --- 1b: the Inert diff verdict ---------------------------------------------
228
246
  // No ticket gives a Ticketless PR its ruling or its acceptance mutation, so it
229
247
  // merges unattended only when its whole diff is inert; otherwise the head is
230
- // recorded and the maintainer's label is the merge.
231
- if (ticketless) receipt.inert = inertVerdict({ worktree: resolve(repo ?? "."), pin });
248
+ // recorded and the maintainer's label is the merge. A ticket PR whose diff is
249
+ // not inert merges on its acceptance mutation's kill, so it is labelled only
250
+ // with that kill's evidence line in hand.
251
+ receipt.inert = inertVerdict({ worktree: resolve(repo ?? "."), pin });
252
+ const why = receipt.inert.verdict === "unknown" ? `its diff could not be read (${receipt.inert.reason})` : "its diff is not inert";
253
+
254
+ // The finisher's evidence-line grammar,
255
+ // `red: <cmd> → exit N, fail K incl <test>; baseline: <cmd> → exit 0, <test> pass`,
256
+ // checked for its two halves, each non-blank, on one line (`.` stops at a newline).
257
+ const EVIDENCE = /^red:(.*?); baseline:(.*)$/;
258
+ const evidence = (s) => {
259
+ const m = EVIDENCE.exec(s ?? "");
260
+ return m !== null && m[1].trim() !== "" && m[2].trim() !== "";
261
+ };
262
+ if (!ticketless && receipt.inert.exit !== 0) {
263
+ if (!evidence(killArg)) {
264
+ const claim = killArg === null ? "no --kill claim was given" : `the --kill claim is not an evidence line (red: … ; baseline: …): ${JSON.stringify(killArg)}`;
265
+ finish(6, { killGiven: killArg }, `the PR is a ticket PR and ${why}, and ${claim}; nothing was written`);
266
+ }
267
+ receipt.kill = killArg;
268
+ }
232
269
 
233
270
  // --- 2: the head record ----------------------------------------------------
234
271
  // The newest record wins, the way the merge bot reads it: a matching record
235
272
  // older than one naming another head is not the record the bot will act on.
236
- const RECORD = /^ready-to-merge-head: ([0-9a-f]{40})\s*$/;
237
- const records = first.comments
238
- .map((c, i) => ({ i, at: c.createdAt, m: RECORD.exec(c.body) }))
239
- .filter((c) => c.m !== null)
240
- .sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : a.i - b.i));
241
- const recorded = records.length > 0 && records[records.length - 1].m[1] === pin;
273
+ const recorded = newestHeadRecord(first.comments) === pin;
242
274
  const labelled = firstLabels.includes(LABEL);
243
275
 
244
276
  if (!recorded) {
245
- gh("comment", ["pr", "comment", String(pr), "--body", `ready-to-merge-head: ${pin}`]);
277
+ gh("comment", ["pr", "comment", String(pr), "--body", headRecordBody(pin)]);
246
278
  receipt.commented = true;
247
279
  }
248
280
 
249
281
  if (ticketless && receipt.inert.exit !== 0) {
250
- const why = receipt.inert.verdict === "unknown" ? `its diff could not be read (${receipt.inert.reason})` : "its diff is not inert";
251
282
  finish(5, {}, `the PR is a Ticketless PR and ${why}: the head is recorded and ${LABEL} is left to the maintainer`);
252
283
  }
253
284
 
@@ -0,0 +1,189 @@
1
+ #!/usr/bin/env node
2
+ // The merge bot's "labelled head" step as one read-only command, so the bot
3
+ // never compares two SHAs by eye: a recorded head printed beside a different
4
+ // current head was read as "no record" and sent down the timeline fallback,
5
+ // which refuses a moved head without ever calling merge-gate.mjs.
6
+ //
7
+ // labelled-head.mjs --pr <N> [--repo <dir>]
8
+ //
9
+ // `--repo` is the directory `gh` runs in (it resolves the repository from
10
+ // there), the cwd when omitted. Reached through the Resolver:
11
+ // `~/.omp/plugins/node_modules/@feigi/fleet-ctl/scripts/fleet-run labelled-head.mjs ...`.
12
+ //
13
+ // One `gh pr view <N> --json comments,headRefOid` read gives the newest head
14
+ // record (ready-to-merge-head.mjs owns its grammar, the one finisher-label.mjs
15
+ // writes) and the current head together. The route follows from those two
16
+ // alone:
17
+ //
18
+ // current a record exists and names the current head: proceed untouched.
19
+ // gate a record exists and names another head: not refused on sight, it
20
+ // may be a rebase-carry. Run merge-gate.mjs with `--pre <record>`
21
+ // and no `--post`; its `rebaseCarry` decides.
22
+ // timeline no record: a hand-added label, or one applied before its labeller
23
+ // recorded a head. The timeline is read here and its verdict
24
+ // printed. A recorded head is never routed to `timeline`.
25
+ //
26
+ // The timeline read is the only one that needs the Label map's string for
27
+ // `ready-to-merge`, so the map is read only on that route. The `timeline`
28
+ // object holds `verdict`, `moved` when a `committed` or `head_ref_force_pushed`
29
+ // event follows the last `labeled` event for that string, else `clean`; and
30
+ // `after`, those events as `<event> <sha>`. A timeline with no `labeled` event
31
+ // for that string has no verdict: the label is on the PR, so a read that never
32
+ // saw it applied came back empty or wrong, and it fails as `read-timeline`.
33
+ // The label is left where it is on every verdict: this command writes nothing.
34
+ //
35
+ // Stdout is one JSON line on every run that gets past its flags (a flag
36
+ // refusal, and a receipt that cannot be written, print none):
37
+ //
38
+ // {pr, record, head, route, timeline [, step, error], exit}
39
+ //
40
+ // record the newest record's SHA, null when none
41
+ // head the PR's current head
42
+ // route `current`, `gate` or `timeline`; null on exit 2
43
+ // timeline null off the `timeline` route, else {label, verdict, after}
44
+ // step on exit 2 only, the read that failed: `read-pr`, `label-map`,
45
+ // or `read-timeline`
46
+ // error on exit 2 only, what `gh` (or the invocation) said
47
+ //
48
+ // Exit vocabulary:
49
+ //
50
+ // 0 a route was decided
51
+ // 2 the invocation or a read failed — a missing or unknown flag, or a
52
+ // receipt stdout would not take, is a refusal on stderr with no receipt,
53
+ // as in every other script's `die()`
54
+
55
+ import { spawnSync } from "node:child_process";
56
+ import { statSync } from "node:fs";
57
+ import { resolve } from "node:path";
58
+ import { makeDie, defineFlags, writeAll } from "./arg.mjs";
59
+ import { gitEnv } from "./git-env.mjs";
60
+ import { readLabelMap } from "./label-map.mjs";
61
+ import { newestHeadRecord } from "./ready-to-merge-head.mjs";
62
+
63
+ const NAME = "labelled-head";
64
+ const USAGE = "usage: labelled-head.mjs --pr <N> [--repo <dir>]";
65
+
66
+ const MOVING = new Set(["committed", "head_ref_force_pushed"]);
67
+
68
+ const die = makeDie(NAME);
69
+ const { arg, numArg, sweep, stray } = defineFlags(die, {
70
+ flags: { pr: "value", repo: "value" },
71
+ });
72
+
73
+ // The sweep runs before the required-flag check so a misspelt flag is named
74
+ // as that, not buried under a missing-flag usage line.
75
+ sweep();
76
+ stray();
77
+ const pr = numArg("pr");
78
+ const repo = arg("repo");
79
+ if (pr === null) die(USAGE);
80
+
81
+ const receipt = { pr, record: null, head: null, route: null, timeline: null, exit: 0 };
82
+
83
+ function finish(exit, extra = {}, message = null) {
84
+ Object.assign(receipt, extra, { exit });
85
+ const written = writeAll(1, `${JSON.stringify(receipt)}\n`);
86
+ if (message !== null) writeAll(2, `${NAME}: ${message}\n`);
87
+ // The receipt is the only carrier of the route: a lost write is exit 2, never
88
+ // a decided route with nothing printed.
89
+ if (!written) die("the receipt could not be written to stdout");
90
+ process.exit(exit);
91
+ }
92
+
93
+ function fail(step, error) {
94
+ finish(2, { step, error }, `${step}: ${error}`);
95
+ }
96
+
97
+ if (repo !== null) {
98
+ // `throwIfNoEntry` covers ENOENT alone: an unreadable path (EACCES, ELOOP)
99
+ // still throws, and must take the receipt path rather than a stack trace.
100
+ let stat;
101
+ try {
102
+ stat = statSync(repo, { throwIfNoEntry: false });
103
+ } catch (e) {
104
+ fail("read-pr", `--repo cannot be read: ${repo} (${e.code ?? e.message})`);
105
+ }
106
+ if (!stat?.isDirectory()) fail("read-pr", `--repo is not a directory: ${repo}`);
107
+ }
108
+
109
+ // `gh` resolves its repository from the cwd's git remotes, so an ambient
110
+ // GIT_DIR would retarget every call at another repository.
111
+ const GH_ENV = gitEnv();
112
+
113
+ function gh(step, args) {
114
+ const r = spawnSync("gh", args, { encoding: "utf8", env: GH_ENV, stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024, ...(repo === null ? {} : { cwd: repo }) });
115
+ if (r.error) fail(step, `could not run gh: ${r.error.message}`);
116
+ if (r.signal) fail(step, `gh was killed by ${r.signal}`);
117
+ if (r.status !== 0) fail(step, (r.stderr ?? "").trim() || `gh exited ${r.status}`);
118
+ return r.stdout;
119
+ }
120
+
121
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
122
+
123
+ // The route the record and the head decide. A record is never routed to
124
+ // `timeline`: that is the whole of this function.
125
+ function routeOf(record, head) {
126
+ if (record === null) return "timeline";
127
+ return record === head ? "current" : "gate";
128
+ }
129
+
130
+ // The verdict the timeline events give, `events` as `{event, sha, label}` in
131
+ // timeline order, `label` the string the `ready-to-merge` role maps to; null
132
+ // when no `labeled` event names `label`, since nothing is after a line never
133
+ // seen.
134
+ function timelineVerdict(events, label) {
135
+ const last = events.findLastIndex((e) => e.event === "labeled" && e.label === label);
136
+ if (last === -1) return null;
137
+ const after = events.slice(last + 1).filter((e) => MOVING.has(e.event)).map((e) => `${e.event} ${e.sha ?? ""}`.trimEnd());
138
+ return { label, verdict: after.length > 0 ? "moved" : "clean", after };
139
+ }
140
+
141
+ const out = gh("read-pr", ["pr", "view", String(pr), "--json", "comments,headRefOid"]);
142
+ let view;
143
+ try {
144
+ view = JSON.parse(out);
145
+ } catch {
146
+ fail("read-pr", `gh printed no JSON: ${out.slice(0, 200)}`);
147
+ }
148
+ if (
149
+ !isObject(view) ||
150
+ !/^[0-9a-f]{40}$/.test(view.headRefOid) ||
151
+ !Array.isArray(view.comments) ||
152
+ !view.comments.every((c) => isObject(c) && typeof c.body === "string" && typeof c.createdAt === "string")
153
+ ) {
154
+ fail("read-pr", `gh printed an unexpected shape: ${out.slice(0, 200)}`);
155
+ }
156
+
157
+ const record = newestHeadRecord(view.comments);
158
+ const head = view.headRefOid;
159
+ const route = routeOf(record, head);
160
+ receipt.record = record;
161
+ receipt.head = head;
162
+ if (route !== "timeline") finish(0, { route });
163
+
164
+ let label;
165
+ try {
166
+ label = readLabelMap({ cwd: resolve(repo ?? ".") })["ready-to-merge"];
167
+ } catch (e) {
168
+ fail("label-map", e.message);
169
+ }
170
+ // `-q` runs per page, so a paginated timeline answers one JSON value per
171
+ // line however many pages it took.
172
+ // A `head_ref_force_pushed` event carries its SHA in `commit_id`, `sha` null.
173
+ const lines = gh("read-timeline", [
174
+ "api",
175
+ `repos/{owner}/{repo}/issues/${pr}/timeline?per_page=100`,
176
+ "--paginate",
177
+ "-q",
178
+ '.[] | select(.event == "labeled" or .event == "committed" or .event == "head_ref_force_pushed") | {event, sha: (.sha // .commit_id), label: .label.name} | tojson',
179
+ ]);
180
+ let events;
181
+ try {
182
+ events = lines.split("\n").filter((l) => l !== "").map((l) => JSON.parse(l));
183
+ } catch {
184
+ fail("read-timeline", `gh printed no JSON: ${lines.slice(0, 200)}`);
185
+ }
186
+ if (!events.every(isObject)) fail("read-timeline", `gh printed an unexpected shape: ${lines.slice(0, 200)}`);
187
+ const timeline = timelineVerdict(events, label);
188
+ if (timeline === null) fail("read-timeline", `no labeled event for ${label} in the timeline`);
189
+ finish(0, { route, timeline });
@@ -0,0 +1,29 @@
1
+ // The head record, as its writer posts it and its reader reads it back: a PR
2
+ // comment whose whole body is `ready-to-merge-head: <sha>`, naming the head
3
+ // the labeller audited, posted immediately before the `ready-to-merge` label.
4
+ // Shared by finisher-label.mjs, which writes it, and labelled-head.mjs, which
5
+ // the merge bot runs to read it, so the grammar is stated once. The prefix is
6
+ // not a label: it is `ready-to-merge-head:` whatever string the Label map
7
+ // gives `ready-to-merge`.
8
+
9
+ // The whole body: 40 lowercase hex after the prefix, and nothing else but
10
+ // trailing whitespace (a newline, CRLF, blank lines). A prefix before the
11
+ // keyword, a suffix after the SHA, a second line, a short or uppercase SHA is
12
+ // not a record.
13
+ const HEAD_RECORD = /^ready-to-merge-head: ([0-9a-f]{40})\s*$/;
14
+
15
+ // The body the writer posts for `sha`.
16
+ export const headRecordBody = (sha) => `ready-to-merge-head: ${sha}`;
17
+
18
+ // The newest record among `comments` (`{body, createdAt}` as `gh pr view --json
19
+ // comments` prints them): newest by `createdAt`, the later array position
20
+ // winning a tie, since the sort is stable. A comment that is not a record,
21
+ // however new, hides nothing. Answers the SHA, or null when no comment is a
22
+ // record.
23
+ export function newestHeadRecord(comments) {
24
+ const records = comments
25
+ .map((c) => ({ at: c.createdAt, m: HEAD_RECORD.exec(c.body) }))
26
+ .filter((c) => c.m !== null)
27
+ .sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));
28
+ return records.length === 0 ? null : records[records.length - 1].m[1];
29
+ }
@@ -244,6 +244,8 @@ head is not part of it, and duty 1 audits that head separately.
244
244
 
245
245
  **Duty 3 holds a Ticketless PR whose diff is not inert.** `finisher-label.mjs` adds `patch` to a Ticketless PR that carries no release label, then runs the Inert diff verdict in-process at your pin. A diff that is not inert, or a verdict that could not look, gets the `ready-to-merge-head:` record and no `ready-to-merge`, and the script exits 5: halt with cause `human`. No ticket gives that PR a ruling or a mutation, so the maintainer's `ready-to-merge` is the merge. The merge bot merges it off the record at the pinned head, and a head that moved after the record is merged by hand.
246
246
 
247
+ **Duty 3 holds a ticket PR whose diff is not inert until it is handed the kill.** `finisher-label.mjs` runs the same Inert diff verdict on a ticket PR. A diff that is not inert, or a verdict that could not look, is labelled only when the call carries `--kill '<evidence line>'`, the kill's evidence line in the `red: … ; baseline: …` grammar, which the receipt records as `kill`. Without one, or with one not in that grammar, the script writes nothing — no head record, no label — and exits 6: halt with cause `other` and the receipt as evidence. The script takes the claim on its word; it cannot rerun the mutation. An Inert diff and a Ticketless PR ran no mutation, so they omit `--kill`, and the script ignores one they pass.
248
+
247
249
  ## Whatever you verify by running, run in a tree nobody else owns
248
250
 
249
251
  **Whatever you verify by RUNNING, run in a tree nobody else owns.**