@feigi/fleet-ctl 3.133.3 → 3.134.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.
@@ -153,16 +153,32 @@ ordering is detectable afterwards from the diff — a restore lands on the
153
153
  uncommitted clause and destroys it silently, or the mutant is still in the
154
154
  tree when the fix-applier commits and a deliberately broken guard ships as
155
155
  the fix, in a commit nothing re-reviews. So take your own:
156
- `git worktree add --detach <scratch>/pr<N>/finish-<your member name> <your dispatch pin>`,
157
- mutate and run `<testCmd>` in there, then
156
+ `~/.fleet/bin/fleet-run finisher-tree.mjs --worktree <abs-path> --pin <your dispatch pin> --pr <N> --member <your member name> --scratch <scratch>`
157
+ adds `git worktree add --detach <scratch>/pr<N>/finish-<your member name> <your dispatch pin>`
158
+ and runs the Install step in it, as a claim does: a detached worktree holds
159
+ tracked files only, so without that step a suite whose dependencies are
160
+ ignored cannot start. Mutate and run `<testCmd>` in that tree, then
158
161
  `git worktree remove --force <scratch>/pr<N>/finish-<your member name>`.
159
162
  **At your dispatch pin, never at the fetched branch tip** — duty 1 just
160
163
  proved the owned worktree sits at that pin, and `PR headRefOid` may carry
161
164
  commits no reviewer read, the substitution the halt block's head-equality
162
165
  check rejects for the same reason. `<scratch>` is the absolute root your dispatch prompt names. The member name is in the path because
163
166
  the scratch root is shared with every sibling, so `<scratch>/pr<N>` alone
164
- collides whenever a PR gets a second finisher, and `worktree add` on an
165
- occupied path fails closed into a halt with a purely mechanical cause.
167
+ collides whenever a PR gets a second finisher, and the script fails closed on
168
+ an occupied path.
169
+
170
+ **The script's exit code is your verdict on the tree, and its one JSON line is
171
+ the receipt.** Only exit 0 means a tree at your pin with its dependencies
172
+ installed and the tree clean; the receipt's `tree` is the path to work in.
173
+ Any other exit is a halt at duty 2: cause `other`, the receipt as the
174
+ evidence, no label, and you run none of the script's steps by hand to get past
175
+ it. The codes are distinct: 1 no usable tree (an occupied path, a failed add,
176
+ a head that is not your pin, a Recipe that could not be read, a tree dirty
177
+ before the Install step), 3 the Install step did not run (exit 126 or 127, a
178
+ broken Recipe), 4 the Install step failed, 5 the Install step changed the
179
+ tree or left its state unreadable; exit 2 is a refusal with no receipt, a
180
+ refused invocation or a receipt the script could not write. The script
181
+ removes nothing, so a tree it left behind is removed like any other below.
166
182
 
167
183
  **Remove it on every path, the failing ones included** — a mutant that comes
168
184
  back green, a suite that will not start, your own halt at any duty. `--force`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feigi/fleet-ctl",
3
- "version": "3.133.3",
3
+ "version": "3.134.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": {
@@ -16,6 +16,9 @@
16
16
  // rowDispatch, the function `route` itself calls), and on the evidence-favours
17
17
  // side the same for the Preview fit's table (`.fleet/router-preview.json`, which
18
18
  // metrics-refresh.mjs writes beside the guard), marked where its Cell differs.
19
+ // The receipts' newest `metrics` step, which the guard section quotes when there
20
+ // is no guard, also feeds the evidence-favours side: a refit that step says
21
+ // failed, with no fit written after it, is said in that side's heading.
19
22
  // Figures show only from a guard `readCostGuard` (fleet-tick.mjs, the reader
20
23
  // the tick judges the file by) accepts; `guard` here is that reader's own
21
24
  // answer, `{ status: "ok", guard }` or
@@ -108,13 +111,22 @@ function tierRoute(role, level, generation, modelRoles) {
108
111
  }
109
112
 
110
113
  // ---------------------------------------------------------------------------
111
- // No guard: the newest `metrics` step of the phase 0 and close-out receipts.
114
+ // The newest `metrics` step of the phase 0 and close-out receipts: the guard
115
+ // section quotes it when there is no guard, and evidence favours reads a failed refit off it.
112
116
  // ---------------------------------------------------------------------------
113
117
 
114
118
  // `step` is `{ status, at, output }` or null. A step that has not run carries no
115
119
  // refresh to quote.
116
120
  const ran = (step) => step != null && step.status !== "pending" && Number.isFinite(Date.parse(step.at));
117
121
 
122
+ // The newest `metrics` step of the two receipts that has run, by `at`; on equal
123
+ // times, phase 0's. Null when neither receipt has run one.
124
+ function newestStep(receipts) {
125
+ const steps = [receipts?.phase0, receipts?.closeout].filter(ran);
126
+ if (steps.length === 0) return null;
127
+ return steps.reduce((a, b) => (Date.parse(b.at) > Date.parse(a.at) ? b : a));
128
+ }
129
+
118
130
  // metrics-refresh's own line from a step's output: the cost-guard duty's, else
119
131
  // the last of its lines, else the output's first line. Its own prefix, the
120
132
  // "skipped," and the note that the file was left as it was are dropped; the rest
@@ -128,17 +140,23 @@ function refreshLine(output) {
128
140
  return line.trim().replace(/; \S*cost-guard\.json left as it is$/, "");
129
141
  }
130
142
 
131
- // The newest `metrics` step of the two receipts, with the verb its status and
132
- // line give it: `{ verb, at, why }`, or null when neither receipt has run one.
133
- function newestRefresh(receipts) {
134
- const steps = [receipts?.phase0, receipts?.closeout].filter(ran);
135
- if (steps.length === 0) return null;
136
- const step = steps.reduce((a, b) => (Date.parse(b.at) > Date.parse(a.at) ? b : a));
143
+ // The newest `metrics` step, with the verb its status and line give it:
144
+ // `{ verb, at, why }`, or null when neither receipt has run one.
145
+ function newestRefresh(step) {
146
+ if (step === null) return null;
137
147
  const why = refreshLine(step.output);
138
148
  const verb = step.status === "failed" ? "failed" : /metrics-refresh: cost guard: skipped,/.test(step.output ?? "") ? "skipped" : "ran";
139
149
  return { verb, at: step.at, why };
140
150
  }
141
151
 
152
+ // Why the Preview fit's refit failed, off a `metrics` step's output: the rest of
153
+ // metrics-refresh's `preview: failed — ` line, trimmed, or null when the output
154
+ // has none. Found anywhere in a line, as refreshLine finds its own.
155
+ export function refitFailure(output) {
156
+ const m = /metrics-refresh: preview: failed — ([^\n]*)/.exec(String(output ?? ""));
157
+ return m === null ? null : m[1].trim();
158
+ }
159
+
142
160
  // ---------------------------------------------------------------------------
143
161
  // The guard section.
144
162
  // ---------------------------------------------------------------------------
@@ -352,9 +370,10 @@ function booked(entry, pulls) {
352
370
  // The Cells drawn: the five, then any the guard holds or a card names beyond them.
353
371
  const drawOrder = (held, pulls) => [...new Set([...CELLS, ...held, ...pulls.flatMap((p) => p.targets.map((t) => t.cell)).filter((c) => CELL.test(c))])];
354
372
 
355
- function guardSection(read, receipts, modelRoles, pulls, recordsNote = null) {
373
+ // `step` is the receipts' newest `metrics` step, newestStep's pick.
374
+ function guardSection(read, receipts, step, modelRoles, pulls, recordsNote = null) {
356
375
  const label = readLabel(modelRoles);
357
- const refresh = newestRefresh(receipts);
376
+ const refresh = newestRefresh(step);
358
377
  const notes = [];
359
378
  const footnotes = [];
360
379
 
@@ -601,10 +620,24 @@ const FAVOURS = "evidence favours";
601
620
 
602
621
  // The evidence-favours side with no Preview fit to lay out: its heading says
603
622
  // why, and its column is empty — nothing is unknown there, there is nothing to show.
604
- const noFit = (heading) => ({
605
- title: FAVOURS, source: { text: "Preview fit", check: null }, heading, labels: [], footnotes: [], rows: null, unread: null,
623
+ const noFit = (heading, labels = []) => ({
624
+ title: FAVOURS, source: { text: "Preview fit", check: null }, heading, labels, footnotes: [], rows: null, unread: null,
606
625
  });
607
626
 
627
+ // The newest refit failed: `step` is the receipts' newest `metrics` step, `p`
628
+ // the Preview fit read, null when none was. Said while that step's output holds
629
+ // the failed line and no fit was written after it — a `computed_at` before the
630
+ // step's `at`, or one that is no time. A later step, a fit written after this
631
+ // one, or the receipt no longer read clears it.
632
+ function refitLabel(step, p) {
633
+ if (step === null) return [];
634
+ const why = refitFailure(step.output);
635
+ if (why === null) return [];
636
+ const computed = p === null ? NaN : Date.parse(p.computed_at);
637
+ if (Number.isFinite(computed) && computed >= Date.parse(step.at)) return [];
638
+ return [`the newest refit failed at ${when(step.at)}: ${why}`];
639
+ }
640
+
608
641
  // The Preview fit's heading labels, against `raw`, the guard on disk, `routed`,
609
642
  // readGuard's answer for it, `table`, the installed one, and `records`, whether
610
643
  // the fit read the guard's files: fitted beside another guard, on other records,
@@ -650,12 +683,13 @@ function nDiffers(p, raw, records) {
650
683
  // Cell marked where it differs from the Cell routes now gives that row. `preview`
651
684
  // is gather's read, `{ status: "ok", preview } | { status: "missing" } | {
652
685
  // status: "unreadable", why }`; `guard` readCostGuard's answer and `routed`
653
- // readGuard's for the same file, null when the router reads none; `mark` the
654
- // footnote mark its n footnote takes.
655
- function evidenceFavours({ preview, guard, routed, table, modelRoles, mark }) {
686
+ // readGuard's for the same file, null when the router reads none; `step` the
687
+ // receipts' newest `metrics` step, newestStep's pick; `mark` the footnote mark
688
+ // its n footnote takes.
689
+ function evidenceFavours({ preview, guard, routed, table, modelRoles, step, mark }) {
656
690
  if (routed === null) return noFit("no Preview fit: it is written only beside a cost guard");
657
- if (preview?.status === "unreadable") return noFit(`no Preview fit read: ${preview.why}`);
658
- if (preview?.status !== "ok") return noFit("no Preview fit yet: the next phase 0 writes one");
691
+ if (preview?.status === "unreadable") return noFit(`no Preview fit read: ${preview.why}`, refitLabel(step, null));
692
+ if (preview?.status !== "ok") return noFit("no Preview fit yet: the next phase 0 writes one", refitLabel(step, null));
659
693
  const p = preview.preview;
660
694
  const fit = p.table;
661
695
  const raw = guard.guard;
@@ -676,7 +710,7 @@ function evidenceFavours({ preview, guard, routed, table, modelRoles, mark }) {
676
710
  title: FAVOURS,
677
711
  source: { text: ["Preview fit", "this repository's runs", `computed ${when(p.computed_at)}`, plural(fit.n_rows, "Pull")].join(" · "), check: null },
678
712
  heading: fit.burn_in ? `stage ${fit.stage}: ${shortWords(fit, "present") ?? "every Cell has its merged PRs"}` : null,
679
- labels: previewLabels(p, raw, routed, table, records),
713
+ labels: [...refitLabel(step, p), ...previewLabels(p, raw, routed, table, records)],
680
714
  footnotes: differ.length === 0 ? [] : [{ mark, text: `${list(differ)}: the guard counts merges by GitHub's state, the fit by Rulings, and the fit admits only drawn or rule-sized Pulls` }],
681
715
  rows: Object.fromEntries(OBJECTIVES.map((o) => [o,
682
716
  Object.fromEntries(["*", ...STRATA].filter((s) => Object.hasOwn(fit.rows[o], s)).map((s) => [s, entry(o, s)])),
@@ -904,12 +938,13 @@ export function computeCellEvidence({ guard, receipts, agents, modelRoles = null
904
938
  guardJson = null, mainMetrics = null, closeoutPr = null, openPrs = null, checkoutTable = null }) {
905
939
  const routed = guard?.status === "ok" ? readGuard(guard.guard) : null;
906
940
  const routes = routesNow({ table, guard: routed, modelRoles, install, repoUrl, checkout: checkoutTable });
907
- const favours = evidenceFavours({ preview, guard, routed, table, modelRoles, mark: superscript(routes.footnotes.length + 1) });
941
+ const step = newestStep(receipts);
942
+ const favours = evidenceFavours({ preview, guard, routed, table, modelRoles, step, mark: superscript(routes.footnotes.length + 1) });
908
943
  const records = recordsAgainstMain({ read: guard, preview, main: mainMetrics, closeoutPr, openPrs });
909
944
  return {
910
945
  alerts: [records.alert, noRulingAlert(guard), readersAlert(guardJson)].filter((a) => a !== null),
911
946
  policy: policyRowsView({ sides: [routes, favours], objective }),
912
- guard: guardSection(guard, receipts, modelRoles, pulls, records.note),
947
+ guard: guardSection(guard, receipts, step, modelRoles, pulls, records.note),
913
948
  declared: declaredSection(agents, modelRoles),
914
949
  };
915
950
  }
package/scripts/evict.mjs CHANGED
@@ -75,6 +75,10 @@
75
75
  // there is nothing to restore. Without `--apply` it runs nothing and prints
76
76
  // the command it would run. Prints
77
77
  // `{"applied","worktree","install"}`; exit 0 restored (or would), 2 refused.
78
+ //
79
+ // That install sequence is `installIn()`, exported: finisher-tree.mjs runs the
80
+ // same read, the same checks and the same words in the tree it builds for the
81
+ // acceptance mutation, so there is one copy of it.
78
82
 
79
83
  import { spawnSync } from "node:child_process";
80
84
  import { readFileSync, realpathSync, statSync, unlinkSync, writeFileSync } from "node:fs";
@@ -380,6 +384,57 @@ function sweep({ afterRotate, apply }) {
380
384
  writeAll(1, `${JSON.stringify({ applied: apply, ledger: found.file, evicted, kept, failed })}\n`);
381
385
  }
382
386
 
387
+ /**
388
+ * The Install step in `tree`, read and, with `apply`, run as claim-ticket.sh
389
+ * runs it: the one sequence a restore and the finisher's tree share. `{install}`
390
+ * when it ran and left the tree clean (or, without `apply`, would run); else
391
+ * `{refusal: {kind, message, install, exit}}`, `message` the claim's own words
392
+ * and `exit` the Install step's exit status, null when it never produced one.
393
+ * `kind` is one of:
394
+ * derive derive-testcmd.sh would not name the Install step
395
+ * status-before the tree state could not be read before the Install step
396
+ * dirty-before the tree was not clean before it: nothing ran
397
+ * not-run the Install step could not be started, or exited 126 or 127
398
+ * failed it was killed by a signal, or exited non-zero
399
+ * status-after the tree state could not be read after it
400
+ * dirtied it left the tree changed
401
+ * `verb` names the operation in the dirty-before refusal, and `retry` whether
402
+ * that refusal tells its reader to clear the change and run the operation again:
403
+ * a restore's caller may, the finisher may not. `install` is null in a refusal
404
+ * that came before the command was read. Nothing here writes a mark or a
405
+ * restore time, and it never exits the process.
406
+ */
407
+ export function installIn(tree, apply, { verb = "restore", retry = true } = {}) {
408
+ const refuse = (kind, message, install = null, exit = null) => ({ refusal: { kind, message, install, exit } });
409
+ const derived = run("sh", [join(SCRIPT_DIR, "derive-testcmd.sh"), tree, "install", "--at", "origin/main"]);
410
+ const install = String(derived.stdout ?? "").replace(/\n$/, "");
411
+ if (derived.error || derived.status !== 0 || install === "") {
412
+ return refuse("derive", String(derived.stderr ?? "").trim() || `derive-testcmd.sh ${tree} install failed (${how(derived)})`);
413
+ }
414
+ // Dirty before anything runs is no Install step's doing: said in its own
415
+ // words, so the dirty-after refusal below never blames the Recipe for it.
416
+ const before = git(tree, ["status", "--porcelain", "-uall"]);
417
+ if (before.error || before.status !== 0) return refuse("status-before", `could not read the tree state in ${tree} before the Install step (${how(before)})`, install);
418
+ if (before.stdout !== "") {
419
+ const then = retry ? `; clear that change, then ${verb} again` : "";
420
+ return refuse("dirty-before", `${tree} is not clean before the ${verb} (first: ${before.stdout.split("\n")[0]}) — the Install step did not run${then}`, install);
421
+ }
422
+ if (!apply) return { install };
423
+ // Through `sh -c` with `CI` unset and the output dropped, as claim-ticket.sh
424
+ // runs it; no timeout, as there.
425
+ const r = run("sh", ["-c", install], { cwd: tree, drop: ["CI"], stdio: "ignore", timeout: 0 });
426
+ if (r.error) return refuse("not-run", `the Install step '${install}' did not run in ${tree} (${how(r)}) — ${REDERIVE}`, install);
427
+ if (r.signal) return refuse("failed", `install failed in ${tree} (${how(r)})`, install);
428
+ if (r.status === 126 || r.status === 127) {
429
+ return refuse("not-run", `the Install step '${install}' did not run in ${tree} (exit ${r.status}: not executable or not found) — ${REDERIVE}`, install, r.status);
430
+ }
431
+ if (r.status !== 0) return refuse("failed", `install failed in ${tree} (exit ${r.status})`, install, r.status);
432
+ const status = git(tree, ["status", "--porcelain", "-uall"]);
433
+ if (status.error || status.status !== 0) return refuse("status-after", `could not verify the tree state in ${tree} after the Install step`, install, 0);
434
+ if (status.stdout !== "") return refuse("dirtied", `the Install step '${install}' changed the tree in ${tree} (first: ${status.stdout.split("\n")[0]}) — ${REDERIVE}`, install, 0);
435
+ return { install };
436
+ }
437
+
383
438
  function restore(tree, apply) {
384
439
  try {
385
440
  if (!statSync(tree).isDirectory()) die(`--restore ${tree} is not a directory`);
@@ -389,29 +444,10 @@ function restore(tree, apply) {
389
444
  const mark = evictionMark(tree);
390
445
  if (mark.unknown !== undefined) die(`cannot tell whether ${tree} is evicted: ${mark.unknown}`);
391
446
  if (!mark.marked) die(`${tree} is not evicted (no ${join(mark.dir, EVICTED)}) — nothing to restore`);
392
- const derived = run("sh", [join(SCRIPT_DIR, "derive-testcmd.sh"), tree, "install", "--at", "origin/main"]);
393
- const install = String(derived.stdout ?? "").replace(/\n$/, "");
394
- if (derived.error || derived.status !== 0 || install === "") {
395
- die(`${String(derived.stderr ?? "").trim() || `derive-testcmd.sh ${tree} install failed (${how(derived)})`}`);
396
- }
397
- // Dirty before anything runs is no Install step's doing: said in its own
398
- // words, so the dirty-after refusal below never blames the Recipe for it.
399
- const before = git(tree, ["status", "--porcelain", "-uall"]);
400
- if (before.error || before.status !== 0) die(`could not read the tree state in ${tree} before the Install step (${how(before)})`);
401
- if (before.stdout !== "") die(`${tree} is not clean before the restore (first: ${before.stdout.split("\n")[0]}) — the Install step did not run; clear that change, then restore again`);
447
+ const done = installIn(tree, apply);
448
+ if (done.refusal) die(done.refusal.message);
449
+ const { install } = done;
402
450
  if (apply) {
403
- // Through `sh -c` with `CI` unset and the output dropped, as claim-ticket.sh
404
- // runs it; no timeout, as there.
405
- const r = run("sh", ["-c", install], { cwd: tree, drop: ["CI"], stdio: "ignore", timeout: 0 });
406
- if (r.error) die(`the Install step '${install}' did not run in ${tree} (${how(r)}) — ${REDERIVE}`);
407
- if (r.signal) die(`install failed in ${tree} (${how(r)})`);
408
- if (r.status === 126 || r.status === 127) {
409
- die(`the Install step '${install}' did not run in ${tree} (exit ${r.status}: not executable or not found) — ${REDERIVE}`);
410
- }
411
- if (r.status !== 0) die(`install failed in ${tree} (exit ${r.status})`);
412
- const status = git(tree, ["status", "--porcelain", "-uall"]);
413
- if (status.error || status.status !== 0) die(`could not verify the tree state in ${tree} after the Install step`);
414
- if (status.stdout !== "") die(`the Install step '${install}' changed the tree in ${tree} (first: ${status.stdout.split("\n")[0]}) — ${REDERIVE}`);
415
451
  // The restore time first: a mark removed with no time beside it would read
416
452
  // the tree idle by its HEAD alone and evict it again at once.
417
453
  const restored = join(mark.dir, RESTORED);
@@ -0,0 +1,163 @@
1
+ #!/usr/bin/env node
2
+ // The finisher's verification tree as one command: the detached worktree duty 2
3
+ // runs the acceptance mutation in, with the Install step already run in it, so
4
+ // the suite can start on a consumer whose dependencies are untracked.
5
+ //
6
+ // finisher-tree.mjs --worktree <abs> --pin <sha> --pr <N> --member <name> --scratch <abs>
7
+ //
8
+ // `--worktree` is the path the finisher was dispatched with: git runs there, and
9
+ // every worktree of that repository shares its refs and Recipe cache. `--pin` is
10
+ // the full 40-hex head it was dispatched against. `--scratch` is the absolute
11
+ // scratch root the dispatch prompt names. The tree is
12
+ // `<scratch>/pr<N>/finish-<member>`: the member name is in the path because the
13
+ // scratch root is shared with every sibling, so `pr<N>` alone collides whenever
14
+ // a PR gets a second finisher. Reached through the Resolver:
15
+ // `~/.fleet/bin/fleet-run finisher-tree.mjs ...`.
16
+ //
17
+ // In order, each step only once every earlier one held:
18
+ //
19
+ // 1 The path. Anything already at it - a tree, a file, an empty directory -
20
+ // fails closed: git alone would accept an empty directory, and a tree
21
+ // built over somebody's leftover is not the pin's.
22
+ // 2 `git worktree add --detach <tree> <pin>`, then `HEAD` read back: it must
23
+ // equal the pin, never the PR's pushed tip.
24
+ // 3 The Install step, by evict.mjs's `installIn()`: read with
25
+ // `derive-testcmd.sh <tree> install --at origin/main`, run in the tree
26
+ // through `sh -c` with `CI` unset, no timeout, under no suite slot, with a
27
+ // clean `git status --porcelain -uall` required before it and after it. 126
28
+ // or 127 is a Recipe that no longer runs, any other non-zero exit a failed
29
+ // install, and a change to the tree an Install step that changed it.
30
+ //
31
+ // Stdout is one JSON line, the receipt, whatever happened after the arguments
32
+ // parsed:
33
+ //
34
+ // {tree, member, pr, pin, head, install, kind, exit, message}
35
+ //
36
+ // tree the path the tree was, or would have been, built at
37
+ // head `git -C <tree> rev-parse HEAD`, null when never read
38
+ // install the Install step's command, null when never read
39
+ // kind `installed`, or what stopped the build: `occupied`, `unreadable`,
40
+ // `add-failed`, `head-unreadable`, `head-mismatch`, or one of
41
+ // evict.mjs's `installIn()` kinds: `derive`, `status-before`,
42
+ // `dirty-before`, `not-run`, `failed`, `status-after`, `dirtied`
43
+ // exit the Install step's own exit status, null when it produced none
44
+ // message null when installed, else the refusal in words
45
+ //
46
+ // Exit vocabulary, each its own code so the receipt's `kind` is not needed to
47
+ // tell the three install failures apart:
48
+ //
49
+ // 0 installed and clean: the tree is at the pin with its dependencies in it
50
+ // 1 no usable tree, nothing the Install step did: an occupied path, a failed
51
+ // add, a head that is not the pin, a Recipe that could not be read, a
52
+ // status that could not be read before the Install step, or a tree dirty
53
+ // before it
54
+ // 2 a refusal on stderr with no receipt: a usage refusal, as in every other
55
+ // script, or a receipt that could not be written to stdout
56
+ // 3 the Install step did not run: exit 126 or 127, or it could not be started
57
+ // 4 the Install step failed: another non-zero exit, or a signal
58
+ // 5 the Install step ran and left the tree changed, or left its state
59
+ // unreadable
60
+ //
61
+ // Any non-zero exit leaves the tree where it stands, and the finisher removes
62
+ // it with `git worktree remove --force` on every path as it always did: this
63
+ // script removes nothing. Where the exit is 1 on an occupied path, nothing was
64
+ // built at all.
65
+
66
+ import { spawnSync } from "node:child_process";
67
+ import { lstatSync } from "node:fs";
68
+ import { isAbsolute, join } from "node:path";
69
+ import { defineFlags, makeDie, writeAll } from "./arg.mjs";
70
+ import { how } from "./evict-mark.mjs";
71
+ import { installIn } from "./evict.mjs";
72
+ import { gitEnv } from "./git-env.mjs";
73
+ import { isCLI } from "./is-cli.mjs";
74
+
75
+ const NAME = "finisher-tree";
76
+ const die = makeDie(NAME);
77
+ const USAGE = "usage: finisher-tree.mjs --worktree <abs> --pin <sha> --pr <N> --member <name> --scratch <abs>";
78
+ const SHA = /^[0-9a-f]{40}$/;
79
+ // A member name is one path segment: dispatch names (`finisher-pr-12`,
80
+ // `finisher-pr-12-b`) and nothing that could climb out of `pr<N>/`. The
81
+ // alphanumeric first character is what rules out `.` and `..`.
82
+ const MEMBER = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
83
+ const GIT_TIMEOUT_MS = 5 * 60_000;
84
+ const MAX_BUFFER = 64 * 1024 * 1024;
85
+
86
+ // The installIn() refusal kinds an Install step that ran or tried to run
87
+ // answers for; every other refusal is exit 1.
88
+ const EXIT = {
89
+ "not-run": 3,
90
+ failed: 4,
91
+ "status-after": 5,
92
+ dirtied: 5,
93
+ };
94
+
95
+ const git = (dir, args) =>
96
+ spawnSync("git", ["-C", dir, ...args], { encoding: "utf8", maxBuffer: MAX_BUFFER, env: gitEnv(), timeout: GIT_TIMEOUT_MS });
97
+
98
+ function main() {
99
+ const { arg, sweep, stray } = defineFlags(die, {
100
+ flags: { worktree: "value", pin: "value", pr: "value", member: "value", scratch: "value" },
101
+ });
102
+ // The sweep runs before the required-flag check so a misspelled flag is
103
+ // named as that, not buried under a missing-flag usage line.
104
+ sweep();
105
+ stray();
106
+ const worktree = arg("worktree");
107
+ const pinArg = arg("pin");
108
+ const pr = arg("pr");
109
+ const member = arg("member");
110
+ const scratch = arg("scratch");
111
+ if ([worktree, pinArg, pr, member, scratch].includes(null)) die(USAGE);
112
+ if (!isAbsolute(worktree)) die(`--worktree needs an absolute path, got ${worktree}`);
113
+ if (!isAbsolute(scratch)) die(`--scratch needs an absolute path, got ${scratch}`);
114
+ const pin = pinArg.toLowerCase();
115
+ if (!SHA.test(pin)) die(`--pin needs a full 40-character commit SHA, got ${pinArg}`);
116
+ if (!/^[1-9][0-9]*$/.test(pr)) die(`--pr needs a PR number, got ${pr}`);
117
+ if (!MEMBER.test(member)) die(`--member needs one path segment of letters, digits, '.', '_' and '-', got ${JSON.stringify(member)}`);
118
+
119
+ const tree = join(scratch, `pr${pr}`, `finish-${member}`);
120
+ const receipt = { tree, member, pr: Number(pr), pin, head: null, install: null, kind: null, exit: null, message: null };
121
+ const finish = (code, kind, message = null) => {
122
+ receipt.kind = kind;
123
+ receipt.message = message;
124
+ // A receipt lost on its way to stdout must not leave its exit standing: an
125
+ // exit 0 with no receipt names no tree to work in, so a lost write is the
126
+ // no-receipt exit.
127
+ if (!writeAll(1, `${JSON.stringify(receipt)}\n`)) die("the receipt could not be written to stdout");
128
+ process.exitCode = code;
129
+ };
130
+
131
+ // 1: the path. An entry of any kind, a dangling symlink included, is an
132
+ // occupied path; only ENOENT is free.
133
+ try {
134
+ lstatSync(tree);
135
+ return finish(1, "occupied", `${tree} already exists — a tree built over it would not be the pin's`);
136
+ } catch (e) {
137
+ if (e.code !== "ENOENT") return finish(1, "unreadable", `cannot look at ${tree} (${e.code ?? e.message})`);
138
+ }
139
+
140
+ // 2: the tree, at the pin.
141
+ const added = git(worktree, ["worktree", "add", "--detach", tree, pin]);
142
+ if (added.error || added.status !== 0) return finish(1, "add-failed", `git worktree add --detach ${tree} ${pin} failed (${how(added)})`);
143
+ const head = git(tree, ["rev-parse", "HEAD"]);
144
+ const at = String(head.stdout ?? "").trim();
145
+ if (head.error || head.status !== 0 || at === "") return finish(1, "head-unreadable", `could not read HEAD in ${tree} (${how(head)})`);
146
+ receipt.head = at;
147
+ if (at !== pin) return finish(1, "head-mismatch", `HEAD in ${tree} is ${at}, not the pin ${pin}`);
148
+
149
+ // 3: the Install step. No retry in a dirty-before refusal: the finisher runs
150
+ // none of this script's steps by hand to get past one.
151
+ const done = installIn(tree, true, { verb: "install", retry: false });
152
+ if (done.refusal) {
153
+ const { kind, message, install, exit } = done.refusal;
154
+ receipt.install = install;
155
+ receipt.exit = exit;
156
+ return finish(EXIT[kind] ?? 1, kind, message);
157
+ }
158
+ receipt.install = done.install;
159
+ receipt.exit = 0;
160
+ finish(0, "installed");
161
+ }
162
+
163
+ if (isCLI(import.meta.url)) main();
@@ -70,7 +70,9 @@
70
70
  // in-process because a fit has no verdict for an exit status to carry, and the
71
71
  // `fit` CLI reads the TSVs only as committed. It never fails the run: an error
72
72
  // prints `metrics-refresh: preview: failed — <why>`, leaves the old file in
73
- // place and leaves the exit status as the other duties set it.
73
+ // place and leaves the exit status as the other duties set it. That line stays
74
+ // on stdout: the cockpit reads it off the receipts' `metrics` step, and
75
+ // close-out's receipt keeps only stdout from a run that exits 0.
74
76
  //
75
77
  // One `metrics-refresh: <duty>: …` line per duty on stdout. Exit 0 when no
76
78
  // duty failed; 1 when one failed — named on stderr, and the duties after
@@ -253,16 +253,32 @@ ordering is detectable afterwards from the diff — a restore lands on the
253
253
  uncommitted clause and destroys it silently, or the mutant is still in the
254
254
  tree when the fix-applier commits and a deliberately broken guard ships as
255
255
  the fix, in a commit nothing re-reviews. So take your own:
256
- `git worktree add --detach <scratch>/pr<N>/finish-<your member name> <your dispatch pin>`,
257
- mutate and run `<testCmd>` in there, then
256
+ `~/.fleet/bin/fleet-run finisher-tree.mjs --worktree <abs-path> --pin <your dispatch pin> --pr <N> --member <your member name> --scratch <scratch>`
257
+ adds `git worktree add --detach <scratch>/pr<N>/finish-<your member name> <your dispatch pin>`
258
+ and runs the Install step in it, as a claim does: a detached worktree holds
259
+ tracked files only, so without that step a suite whose dependencies are
260
+ ignored cannot start. Mutate and run `<testCmd>` in that tree, then
258
261
  `git worktree remove --force <scratch>/pr<N>/finish-<your member name>`.
259
262
  **At your dispatch pin, never at the fetched branch tip** — duty 1 just
260
263
  proved the owned worktree sits at that pin, and `PR headRefOid` may carry
261
264
  commits no reviewer read, the substitution the halt block's head-equality
262
265
  check rejects for the same reason. `<scratch>` is the absolute root your dispatch prompt names. The member name is in the path because
263
266
  the scratch root is shared with every sibling, so `<scratch>/pr<N>` alone
264
- collides whenever a PR gets a second finisher, and `worktree add` on an
265
- occupied path fails closed into a halt with a purely mechanical cause.
267
+ collides whenever a PR gets a second finisher, and the script fails closed on
268
+ an occupied path.
269
+
270
+ **The script's exit code is your verdict on the tree, and its one JSON line is
271
+ the receipt.** Only exit 0 means a tree at your pin with its dependencies
272
+ installed and the tree clean; the receipt's `tree` is the path to work in.
273
+ Any other exit is a halt at duty 2: cause `other`, the receipt as the
274
+ evidence, no label, and you run none of the script's steps by hand to get past
275
+ it. The codes are distinct: 1 no usable tree (an occupied path, a failed add,
276
+ a head that is not your pin, a Recipe that could not be read, a tree dirty
277
+ before the Install step), 3 the Install step did not run (exit 126 or 127, a
278
+ broken Recipe), 4 the Install step failed, 5 the Install step changed the
279
+ tree or left its state unreadable; exit 2 is a refusal with no receipt, a
280
+ refused invocation or a receipt the script could not write. The script
281
+ removes nothing, so a tree it left behind is removed like any other below.
266
282
 
267
283
  ## Remove the verification worktree on every path
268
284