@feigi/fleet-ctl 3.140.0 → 3.141.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.
@@ -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.0",
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": {
@@ -89,6 +89,7 @@ import { inertVerdict } from "./finisher-scope.mjs";
89
89
  import { gitEnv } from "./git-env.mjs";
90
90
  import { LABEL_LIST_ARGS, LABEL_LIST_LIMIT, releaseLabelsDefined, releaseLabelsIn } from "./release-labels.mjs";
91
91
  import { readLabelMap } from "./label-map.mjs";
92
+ import { headRecordBody, newestHeadRecord } from "./ready-to-merge-head.mjs";
92
93
  import { ticketlessVerdict } from "./ticketless.mjs";
93
94
 
94
95
  const NAME = "finisher-label";
@@ -233,16 +234,11 @@ if (ticketless) receipt.inert = inertVerdict({ worktree: resolve(repo ?? "."), p
233
234
  // --- 2: the head record ----------------------------------------------------
234
235
  // The newest record wins, the way the merge bot reads it: a matching record
235
236
  // 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;
237
+ const recorded = newestHeadRecord(first.comments) === pin;
242
238
  const labelled = firstLabels.includes(LABEL);
243
239
 
244
240
  if (!recorded) {
245
- gh("comment", ["pr", "comment", String(pr), "--body", `ready-to-merge-head: ${pin}`]);
241
+ gh("comment", ["pr", "comment", String(pr), "--body", headRecordBody(pin)]);
246
242
  receipt.commented = true;
247
243
  }
248
244
 
@@ -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
+ }