@feigi/fleet-ctl 3.60.0 → 3.61.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feigi/fleet-ctl",
3
- "version": "3.60.0",
3
+ "version": "3.61.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": {
@@ -0,0 +1,977 @@
1
+ #!/usr/bin/env node
2
+ // A Pull as one resumable command: the mechanical steps in order, stopping at
3
+ // each judgement with a question the controller answers in one token.
4
+ //
5
+ // pull.mjs next [--head <N>]
6
+ // pull.mjs answer <N> <qid> <token> [--path <p>] [--] [<text>…]
7
+ //
8
+ // Reached through the Resolver and run from the MAIN checkout (a linked
9
+ // worktree refuses). `next` starts a Pull on the shortlist head — `--head`, else
10
+ // the first `.fleet/shortlist.json` entry with no `impl-` row, no live
11
+ // `excluded` row and no Pull of its own already ended in this phase-0 session — or resumes the
12
+ // one in progress for `--head`; `answer` records one answer and resumes. Both
13
+ // run until the next question or the end of the Pull, and both are safe to
14
+ // run again: the state is on disk after every step.
15
+ //
16
+ // EXITS
17
+ // 0 dispatched: `DISPATCH {"name","agent","brief"}` is printed. Running
18
+ // `next --head <N>` on a dispatched Pull prints it again.
19
+ // 1 the ticket left the Pull — taken, relabelled elsewhere, closed,
20
+ // relabelled by cause, excluded — with the reason printed; take the next
21
+ // entry. An empty shortlist is this exit too.
22
+ // 2 could not look, named on stderr: a probe that did not answer, a write
23
+ // that failed, a router that refused. `next --head <N>` runs a step that
24
+ // failed again; when the failure came from applying an answer, the
25
+ // question stands and the answer is given again. A router that refused
26
+ // has its claim released and the Pull is over, `next --head <N>` starting
27
+ // the ticket over; one whose claim could not be released leaves the Pull
28
+ // at the route step with the claim standing, and `next` routes again. An
29
+ // exclusion premise `gh` could not read is exit 2 when no other entry is
30
+ // left. An unknown flag is exit 2 as well, as for every script that holds
31
+ // a command line of its own.
32
+ // 3 usage: any other mistake in the command line, or an answer the pending
33
+ // question does not take. Nothing is recorded.
34
+ // 10 a question is pending: its `QUESTION <qid>:` block, with the tokens it
35
+ // takes, is printed.
36
+ //
37
+ // THE STEPS, in this order:
38
+ //
39
+ // 1 inflight `inflight.sh <N>`: anything but exit 0 is taken.
40
+ // 2 issue `gh issue view <N> --json title,body,comments,labels,createdAt`
41
+ // written to `<scratch>/impl-<N>/issue.json`. Without the
42
+ // `ready-for-agent` label the ticket is gone. The distilled
43
+ // brief and the paths the router's extractor finds in it are
44
+ // printed.
45
+ // 3 Q1 staleness `gone` / `present` (each with `--path <p>` and the string
46
+ // as the text) run `staleness.mjs --path <p> --gone|--present --
47
+ // <string>`; `none <why>` and `done` end the question. Exit 1
48
+ // from the probe with a JSON verdict naming a commit asks Q1b
49
+ // `close`: `yes` closes the issue with a comment citing the
50
+ // probe's commit and that commit's subject, `no <why>` asks Q1
51
+ // again. Exit 2, and exit 1 with no verdict JSON or no commit,
52
+ // are recorded as `could-not-check: <reason>` and carried into
53
+ // the brief.
54
+ // 4 Q2 decided `decided`, or a cause whose comment is posted and whose
55
+ // label replaces `ready-for-agent`.
56
+ // 5 Q3 collision `clear`, `behind-pr:#M`, `behind-issue:#M`. The script
57
+ // prints the brief's paths and the open PR numbers and runs no
58
+ // scan of its own. An exclusion is a ledger row.
59
+ // 6 claim `claim-ticket.sh <N> impl-<N> implementer --apply`.
60
+ // 7 route `ticket-router.mjs route …`; a router that refuses releases
61
+ // the claim, and a release that fails is exit 2 with the claim
62
+ // still standing. `--chain-head` is given when a ledger row reads
63
+ // `excluded · behind-issue:#<N>`: another open ticket
64
+ // sequences after this one.
65
+ // 8 row, render, dispatch `ledger.mjs row`, `dispatch-prompt.mjs render
66
+ // implementer --member impl-<N>`, `ledger.mjs dispatch`. The
67
+ // brief and the staleness text are given with `‹name›` for each
68
+ // `<name>` the implementer template declares: the renderer
69
+ // refuses a value that spells one.
70
+ //
71
+ // THE STATE is `<scratch>/impl-<N>/pull.json`: every command run (script, its
72
+ // arguments, exit status, bounded stdout, time), every question asked and every
73
+ // answer with its text and time, and where the Pull stands. A Pull that left
74
+ // the Pull (exit 1) or was refused by the router is held as `pull.previous.json`
75
+ // when `next` starts the ticket over, and so is a record from another phase-0
76
+ // session, whatever it says.
77
+ //
78
+ // No judgement lives here: the script offers evidence and takes a token.
79
+ //
80
+ // Zero deps: node builtins and sibling scripts only.
81
+
82
+ import { spawnSync } from "node:child_process";
83
+ import { mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from "node:fs";
84
+ import { dirname, join } from "node:path";
85
+ import { fileURLToPath } from "node:url";
86
+ import { isDigits, makeDie } from "./arg.mjs";
87
+ import { FleetDirUnresolvable, fleetFile } from "./fleet-dir.mjs";
88
+ import { gitEnv } from "./git-env.mjs";
89
+ import { isCLI } from "./is-cli.mjs";
90
+ import { memberTokens, premisesOf, tierValues } from "./ledger-grammar.mjs";
91
+ import { sessionFromReceipt } from "./phase0-receipt.mjs";
92
+ import { briefPaths, briefText } from "./ticket-router.mjs";
93
+
94
+ const NAME = "pull";
95
+ const SCRIPTS = dirname(fileURLToPath(import.meta.url));
96
+ const die = makeDie(NAME);
97
+ const MAX_BUFFER = 64 * 1024 * 1024;
98
+ const NETWORK_TIMEOUT_MS = 120_000;
99
+ const PR_LIMIT = 1000;
100
+ // A command's stdout and each of its arguments are kept to this many characters
101
+ // in the record, the tail kept: the end of a child's output says why it stopped.
102
+ const RECORD_MAX = 4000;
103
+ const STATE = "pull.json";
104
+ const PREVIOUS = "pull.previous.json";
105
+ const EXPLORE_EVERY = 5;
106
+ // The states that lift an exclusion's premise.
107
+ const LIFTED = new Set(["MERGED", "CLOSED"]);
108
+
109
+ const READY = "ready-for-agent";
110
+ const TRIAGE = "needs-triage";
111
+ const HUMAN = "ready-for-human";
112
+
113
+ const USAGE = `usage: ${NAME}.mjs next [--head <N>] | ${NAME}.mjs answer <N> <qid> <token> [--path <p>] [--] [<text>…]`;
114
+
115
+ // ── the comments the script posts ────────────────────────────────────────────
116
+
117
+ const RELABELLED = "*Relabelled by the fleet controller.* Pulled for implementation and returned:";
118
+
119
+ // What each `ready-for-human-hands` cause says in the comment.
120
+ const HANDS = Object.freeze({
121
+ "external access": "external access",
122
+ "manual testing": "manual testing",
123
+ judgment: "judgment during the work",
124
+ });
125
+
126
+ // `<cause> <line>`, the cause first: null cause when the text starts with none.
127
+ function handsParts(text) {
128
+ for (const cause of Object.keys(HANDS)) {
129
+ if (text === cause || text.startsWith(`${cause} `)) return { cause, line: text.slice(cause.length).trim() };
130
+ }
131
+ return { cause: null, line: "" };
132
+ }
133
+
134
+ /** The comment, and the label that replaces `ready-for-agent`, for a Q2 answer other than `decided`. */
135
+ export function relabel(token, text) {
136
+ if (token === "needs-triage") {
137
+ return {
138
+ label: TRIAGE,
139
+ comment: `${RELABELLED} the brief does not decide what to build. Missing decision: ${text}. Returning to /triage; \`${READY}\` restored once decided.`,
140
+ };
141
+ }
142
+ if (token === "ready-for-human-fork") {
143
+ return { label: HUMAN, comment: `${RELABELLED} the brief leaves a decision open. Open fork: ${text}.` };
144
+ }
145
+ const { cause, line } = handsParts(text);
146
+ return { label: HUMAN, comment: `${RELABELLED} needs human hands — ${HANDS[cause]}: ${line}.` };
147
+ }
148
+
149
+ /** The comment a `yes` to Q1b closes the issue with. */
150
+ export function closeComment(commit, subject) {
151
+ return `*Closed by the fleet controller.* Pulled for implementation and found already fixed by ${commit}: ${subject}.`;
152
+ }
153
+
154
+ // ── the ledger, read ─────────────────────────────────────────────────────────
155
+
156
+ const rowKey = (row) => row.split(/\s/)[0];
157
+ const isImplRow = (row) => memberTokens(row).some((t) => t.family === "impl");
158
+
159
+ /**
160
+ * The `--impl-row` the router is given: the row count the Pull creates — or,
161
+ * while an exploration assignment is rolling (the latest row 5k and every row
162
+ * after it carry no `tier=`), that row's number.
163
+ */
164
+ export function implRow(rows) {
165
+ const impl = rows.filter(isImplRow);
166
+ const n = impl.length;
167
+ const latest = n - (n % EXPLORE_EVERY);
168
+ if (latest >= EXPLORE_EVERY && impl.slice(latest - 1).every((r) => tierValues(r).length === 0)) return latest;
169
+ return n + 1;
170
+ }
171
+
172
+ /** Whether an `excluded · behind-issue:#<n>` row names ticket `n`: another open ticket sequences after it. */
173
+ export function chainHead(rows, n) {
174
+ return rows.some((r) => (premisesOf(r) ?? []).some((p) => p.kind === "issue" && p.target === String(n)));
175
+ }
176
+
177
+ // ── the brief ────────────────────────────────────────────────────────────────
178
+
179
+ /** The `Out of scope` section of `text`, heading to the next heading of its level or above; null when there is none. */
180
+ export function outOfScope(text) {
181
+ const all = text.split("\n");
182
+ const at = all.findIndex((l) => /^#{1,6}\s*out of scope\b/i.test(l));
183
+ if (at === -1) return null;
184
+ const level = /^#+/.exec(all[at])[0].length;
185
+ let end = all.length;
186
+ for (let i = at + 1; i < all.length; i++) {
187
+ const h = /^(#{1,6})\s/.exec(all[i]);
188
+ if (h !== null && h[1].length <= level) {
189
+ end = i;
190
+ break;
191
+ }
192
+ }
193
+ return all.slice(at, end).join("\n").trim();
194
+ }
195
+
196
+ // The placeholders the implementer's brief template declares. dispatch-prompt.mjs
197
+ // refuses a value that spells one, and a ticket's text is a value: one that
198
+ // names `<N>` would stop every render, with the claim standing.
199
+ const TEMPLATE = join(SCRIPTS, "..", "skills", "run-team", "briefs", "implementer.md");
200
+
201
+ function declaredPlaceholders() {
202
+ const lines = readFileSync(TEMPLATE, "utf8").split("\n");
203
+ if (lines[0] !== "---") return [];
204
+ const names = [];
205
+ for (const line of lines.slice(1)) {
206
+ if (line === "---") break;
207
+ const m = /^arg \S+ (.+)$/.exec(line);
208
+ if (m !== null) names.push(m[1]);
209
+ }
210
+ return names;
211
+ }
212
+
213
+ /** `text` with each declared placeholder's spelling `<name>` written `‹name›`, which the renderer does not read. */
214
+ export function defang(text, names) {
215
+ return names.reduce((t, n) => t.split(`<${n}>`).join(`‹${n}›`), text);
216
+ }
217
+
218
+ // ── children ─────────────────────────────────────────────────────────────────
219
+
220
+ const trimmed = (s) => String(s ?? "").trim();
221
+ const cap = (s) => (s.length > RECORD_MAX ? `…${s.slice(-(RECORD_MAX - 1))}` : s);
222
+ const now = () => new Date().toISOString();
223
+
224
+ function how(r) {
225
+ if (r.error) return r.error.code ?? r.error.message;
226
+ if (r.signal) return `killed by ${r.signal}`;
227
+ return `exit ${r.status}`;
228
+ }
229
+
230
+ /** `status` is the exit status, null when the child never ran or was killed (`how` says which). */
231
+ function spawn(cmd, args, { cwd, env, timeoutMs } = {}) {
232
+ const r = spawnSync(cmd, args, { cwd, encoding: "utf8", maxBuffer: MAX_BUFFER, env: gitEnv(env), timeout: timeoutMs });
233
+ const stdout = trimmed(r.stdout);
234
+ const stderr = trimmed(r.stderr);
235
+ return { status: r.error ? null : r.status, stdout, stderr, text: [stdout, stderr].filter(Boolean).join("\n"), how: how(r) };
236
+ }
237
+
238
+ const GH_ENV = { GH_REPO: "" };
239
+ const withText = (head, r) => (r.text ? `${head}\n${r.text}` : head);
240
+
241
+ // ── the state ────────────────────────────────────────────────────────────────
242
+
243
+ function fresh(ticket, session) {
244
+ return {
245
+ ticket,
246
+ member: `impl-${ticket}`,
247
+ started: now(),
248
+ status: "running",
249
+ stage: "inflight",
250
+ pending: null,
251
+ commands: [],
252
+ questions: [],
253
+ answers: [],
254
+ staleness: [],
255
+ close: null,
256
+ openPrs: null,
257
+ session,
258
+ commented: null,
259
+ route: null,
260
+ dispatch: null,
261
+ outcome: null,
262
+ };
263
+ }
264
+
265
+ // Null when there is no state; one that is there and cannot be used throws, naming it.
266
+ function readPull(path) {
267
+ let text;
268
+ try {
269
+ text = readFileSync(path, "utf8");
270
+ } catch (e) {
271
+ if (e.code === "ENOENT") return null;
272
+ throw new Refusal(`cannot read ${path} (${e.code ?? e.message}) — move it aside and run again`);
273
+ }
274
+ let s;
275
+ try {
276
+ s = JSON.parse(text);
277
+ } catch (e) {
278
+ throw new Refusal(`${path} is not JSON (${e.message}) — move it aside and run again`);
279
+ }
280
+ const ok = s !== null && typeof s === "object" && !Array.isArray(s)
281
+ && Number.isInteger(s.ticket) && typeof s.stage === "string" && typeof s.status === "string"
282
+ && Array.isArray(s.commands) && Array.isArray(s.questions) && Array.isArray(s.answers);
283
+ if (!ok) throw new Refusal(`${path} is not a Pull record — move it aside and run again`);
284
+ return s;
285
+ }
286
+
287
+ function writePull(path, st) {
288
+ const tmp = `${path}.${process.pid}.tmp`;
289
+ mkdirSync(dirname(path), { recursive: true });
290
+ writeFileSync(tmp, `${JSON.stringify(st, null, 2)}\n`);
291
+ renameSync(tmp, path);
292
+ }
293
+
294
+ /** A refusal the script reports at exit 2 in its own words. */
295
+ class Refusal extends Error {}
296
+
297
+ /** A command line or an answer the script refuses at exit 3. */
298
+ class Usage extends Error {}
299
+
300
+ // ── the questions ────────────────────────────────────────────────────────────
301
+
302
+ const STALENESS_TOKENS = [
303
+ "gone --path <p> [--] <string> the string the fix must remove from <p> on origin/main",
304
+ "present --path <p> [--] <string> the string the fix must add to <p> on origin/main",
305
+ "none <why> no string settles it; ends this question",
306
+ "done ends this question",
307
+ ];
308
+ const CLOSE_TOKENS = ["yes close the issue citing the commit and its subject", "no <why> keep the ticket"];
309
+ const DECIDED_TOKENS = [
310
+ "decided",
311
+ "needs-triage <the missing decision>",
312
+ "ready-for-human-fork <the options, verbatim from the brief>",
313
+ "ready-for-human-hands <external access|manual testing|judgment> <one line>",
314
+ ];
315
+ const COLLISION_TOKENS = ["clear", "behind-pr:#M", "behind-issue:#M"];
316
+
317
+ const TOKEN_LINES = { staleness: STALENESS_TOKENS, close: CLOSE_TOKENS, decided: DECIDED_TOKENS, collision: COLLISION_TOKENS };
318
+
319
+ // What each question's tokens take. `path`: a `--path <p>` is required; `text`: free text is required.
320
+ const SPECS = {
321
+ staleness: { gone: { path: true, text: true }, present: { path: true, text: true }, none: { text: true }, done: {} },
322
+ close: { yes: {}, no: { text: true } },
323
+ decided: { decided: {}, "needs-triage": { text: true }, "ready-for-human-fork": { text: true }, "ready-for-human-hands": { text: true } },
324
+ };
325
+
326
+ function block(qid, ticket, context) {
327
+ return [
328
+ `QUESTION ${qid}:`,
329
+ ...context.map((l) => ` ${l}`),
330
+ ` answer with: pull.mjs answer ${ticket} ${qid} <token> [<text>…] — the tokens:`,
331
+ ...TOKEN_LINES[qid].map((l) => ` ${l}`),
332
+ ];
333
+ }
334
+
335
+ /**
336
+ * The answer's parts, or a Usage refusal naming what the question takes. `rest`
337
+ * is what follows the token on the command line: `--path <p>` first where the
338
+ * token takes one, a `--` that ends the options, then the text.
339
+ */
340
+ export function parseAnswer(qid, token, rest) {
341
+ const takes = TOKEN_LINES[qid];
342
+ if (takes === undefined) throw new Usage(`${qid} is no question this script asks`);
343
+ const refuse = (why) => new Usage(`${why} — the tokens ${qid} takes:\n${takes.map((l) => ` ${l}`).join("\n")}`);
344
+ let spec = SPECS[qid]?.[token];
345
+ let said = token;
346
+ if (qid === "collision") {
347
+ const m = /^behind-(pr|issue):#?(\S+)$/.exec(token);
348
+ if (token === "clear") spec = {};
349
+ else if (m !== null && !m[2].startsWith("-") && (m[1] === "pr" || isDigits(m[2]))) {
350
+ spec = {};
351
+ said = `behind-${m[1]}:#${m[2]}`;
352
+ }
353
+ }
354
+ if (spec === undefined) throw refuse(`'${token}' is not a token of ${qid}`);
355
+ let path = null;
356
+ let args = rest;
357
+ if (args[0] === "--path") {
358
+ if (!spec.path) throw refuse(`${token} takes no --path`);
359
+ path = args[1];
360
+ if (path === undefined || path.trim() === "") throw refuse(`${token} needs a path after --path`);
361
+ args = args.slice(2);
362
+ } else if (spec.path) {
363
+ throw refuse(`${token} needs --path <p> before its text`);
364
+ }
365
+ if (args[0] === "--") args = args.slice(1);
366
+ const text = args.join(" ").trim();
367
+ if (spec.text && text === "") throw refuse(`${token} needs text`);
368
+ if (!spec.text && text !== "") throw refuse(`${token} takes no text, got: ${text}`);
369
+ if (token === "ready-for-human-hands" && handsParts(text).line === "") {
370
+ throw refuse("ready-for-human-hands needs one of external access|manual testing|judgment, then a line");
371
+ }
372
+ return { token: said, text, path };
373
+ }
374
+
375
+ // ── the Pull ─────────────────────────────────────────────────────────────────
376
+
377
+ // `{ exit, out, err }`: what a command prints and how it ends.
378
+ const result = (exit, out = [], err = []) => ({ exit, out, err });
379
+
380
+ class Pull {
381
+ constructor(st, p) {
382
+ this.st = st;
383
+ this.p = p;
384
+ // What the stages say on the way to their result, printed ahead of it.
385
+ this.log = [];
386
+ }
387
+
388
+ save() {
389
+ writePull(this.p.state, this.st);
390
+ }
391
+
392
+ // The Pull ends without a dispatch: exit 1, the ticket is not this run's.
393
+ leave(reason) {
394
+ this.st.status = "left";
395
+ this.st.pending = null;
396
+ this.st.outcome = { exit: 1, reason, at: now() };
397
+ return result(1, [`LEFT #${this.st.ticket}: ${reason} — next entry`]);
398
+ }
399
+
400
+ stop(why) {
401
+ return result(2, [], [`${NAME}: #${this.st.ticket}: ${why}`]);
402
+ }
403
+
404
+ // Runs a child and records it: `lead` is what the interpreter is given ahead
405
+ // of the arguments (the script's path), kept out of the record. `shown`
406
+ // computes the stdout the record keeps.
407
+ exec(step, name, cmd, lead, args, opts = {}, shown = null) {
408
+ const r = spawn(cmd, [...lead, ...args], { cwd: this.p.cwd, ...opts });
409
+ this.st.commands.push({
410
+ at: now(),
411
+ step,
412
+ cmd: [name, ...args.map((a) => cap(String(a)))],
413
+ exit: r.status,
414
+ ...(r.status === null ? { error: r.how } : {}),
415
+ stdout: cap(shown === null ? r.stdout : shown(r)),
416
+ });
417
+ this.save();
418
+ return r;
419
+ }
420
+
421
+ script(step, file, args, opts, shown) {
422
+ const cmd = file.endsWith(".sh") ? "sh" : process.execPath;
423
+ return this.exec(step, file, cmd, [join(SCRIPTS, file)], args, { env: GH_ENV, ...opts }, shown);
424
+ }
425
+
426
+ gh(step, args, shown) {
427
+ return this.exec(step, "gh", "gh", [], args, { env: GH_ENV, timeoutMs: NETWORK_TIMEOUT_MS }, shown);
428
+ }
429
+
430
+ ask(qid, context) {
431
+ this.st.pending = { qid, at: now() };
432
+ this.st.questions.push({ at: this.st.pending.at, qid });
433
+ this.save();
434
+ return result(10, block(qid, this.st.ticket, context));
435
+ }
436
+
437
+ ledgerRows() {
438
+ const r = this.script("ledger", "ledger.mjs", ["read"]);
439
+ if (r.status !== 0) throw new Refusal(withText(`ledger.mjs read ${r.how}`, r));
440
+ try {
441
+ const { rows } = JSON.parse(r.stdout);
442
+ if (Array.isArray(rows) && rows.every((x) => typeof x === "string")) return rows;
443
+ } catch {
444
+ // Falls through to the refusal below.
445
+ }
446
+ throw new Refusal("ledger.mjs read printed no {rows}");
447
+ }
448
+
449
+ // ── the ticket, as read ──
450
+ issue() {
451
+ return JSON.parse(readFileSync(this.p.issue, "utf8"));
452
+ }
453
+
454
+ brief() {
455
+ const issue = this.issue();
456
+ const text = briefText(issue).trim();
457
+ const found = outOfScope(text) ?? outOfScope(String(issue.body ?? ""));
458
+ const paths = briefPaths(text);
459
+ return [
460
+ `TICKET #${this.st.ticket}: ${issue.title}`,
461
+ "BRIEF:",
462
+ ...text.split("\n"),
463
+ "OUT OF SCOPE:",
464
+ ...(found === null ? ["(no Out of scope section found)"] : found.split("\n")),
465
+ `PATHS: ${paths.length === 0 ? "(none)" : paths.join(" ")}`,
466
+ ];
467
+ }
468
+
469
+ // What the dispatched member is told the ticket is: its title, its brief,
470
+ // and the Out of scope section when that sits outside the brief.
471
+ dispatchBrief() {
472
+ const issue = this.issue();
473
+ const text = briefText(issue).trim();
474
+ const outside = outOfScope(text) === null ? outOfScope(String(issue.body ?? "")) : null;
475
+ return [`Title: ${issue.title}`, text, ...(outside === null ? [] : [outside])].join("\n\n");
476
+ }
477
+
478
+ // ── the question standing, printed in full: what a Pull picked up again re-reads ──
479
+ describe() {
480
+ const { qid } = this.st.pending;
481
+ if (qid === "staleness") return [...this.brief(), ...block(qid, this.st.ticket, this.stalenessContext())];
482
+ if (qid === "close") return block(qid, this.st.ticket, this.closeContext());
483
+ if (qid === "decided") return [...this.brief(), ...block(qid, this.st.ticket, [])];
484
+ return [...this.brief(), ...block(qid, this.st.ticket, this.collisionContext())];
485
+ }
486
+
487
+ stalenessContext() {
488
+ return [`issue read: ${this.p.issue}`];
489
+ }
490
+
491
+ closeContext() {
492
+ const c = this.st.close;
493
+ return [
494
+ `staleness.mjs read --${c.mode} in ${c.path} as fixed by ${c.commit}`,
495
+ `subject: ${c.subject}`,
496
+ ];
497
+ }
498
+
499
+ collisionContext() {
500
+ const paths = briefPaths(briefText(this.issue()).trim());
501
+ const prs = this.st.openPrs;
502
+ return [
503
+ `paths the brief names: ${paths.length === 0 ? "(none)" : paths.join(" ")}`,
504
+ `open PRs: ${prs.length === 0 ? "(none)" : prs.map((n) => `#${n}`).join(" ")}`,
505
+ ];
506
+ }
507
+
508
+ // ── the stages: each returns null to go on to the stage `stage` now names, or a result ──
509
+ advance() {
510
+ const { st } = this;
511
+ for (;;) {
512
+ if (st.pending !== null) return result(10, this.describe());
513
+ const stage = this[`stage_${st.stage}`];
514
+ if (typeof stage !== "function") throw new Refusal(`${this.p.state} is at stage ${st.stage}, which this script does not know — move it aside and run again`);
515
+ const r = stage.call(this);
516
+ this.save();
517
+ if (r !== null) return r;
518
+ }
519
+ }
520
+
521
+ stage_inflight() {
522
+ const r = this.script("inflight", "inflight.sh", [String(this.st.ticket)]);
523
+ if (r.status === 0) {
524
+ this.st.stage = "issue";
525
+ return null;
526
+ }
527
+ return this.leave(r.status === 1 ? "taken" : `taken (the in-flight check could not answer: ${r.how})`);
528
+ }
529
+
530
+ stage_issue() {
531
+ const { st } = this;
532
+ const r = this.gh("issue", ["issue", "view", String(st.ticket), "--json", "title,body,comments,labels,createdAt"], (x) => `${Buffer.byteLength(x.stdout)} bytes, written to ${this.p.issue}`);
533
+ if (r.status !== 0) return this.stop(withText(`gh issue view failed (${r.how})`, r));
534
+ let issue;
535
+ try {
536
+ issue = JSON.parse(r.stdout);
537
+ } catch (e) {
538
+ return this.stop(`gh issue view printed no JSON: ${e.message}`);
539
+ }
540
+ const whole = issue !== null && typeof issue === "object" && typeof issue.title === "string"
541
+ && typeof issue.body === "string" && Array.isArray(issue.labels) && Array.isArray(issue.comments);
542
+ if (!whole) return this.stop("gh issue view printed no title, body, comments and labels");
543
+ try {
544
+ mkdirSync(dirname(this.p.issue), { recursive: true });
545
+ writeFileSync(this.p.issue, `${r.stdout}\n`);
546
+ } catch (e) {
547
+ return this.stop(`cannot write ${this.p.issue}: ${e.message}`);
548
+ }
549
+ if (!issue.labels.some((l) => l?.name === READY)) return this.leave("relabelled elsewhere");
550
+ this.log.push(...this.brief());
551
+ st.stage = "staleness";
552
+ return null;
553
+ }
554
+
555
+ stage_staleness() {
556
+ const { st } = this;
557
+ if (st.close === null) return this.ask("staleness", this.stalenessContext());
558
+ if (st.close.subject === null) {
559
+ const r = this.exec("close", "git", "git", [], ["log", "-1", "--format=%s", st.close.commit]);
560
+ const subject = r.stdout.split("\n")[0];
561
+ if (r.status !== 0 || subject === "") return this.stop(withText(`could not read the subject of ${st.close.commit} (${r.how})`, r));
562
+ st.close.subject = subject;
563
+ }
564
+ return this.ask("close", this.closeContext());
565
+ }
566
+
567
+ stage_decided() {
568
+ return this.ask("decided", []);
569
+ }
570
+
571
+ stage_collision() {
572
+ const { st } = this;
573
+ if (st.openPrs === null) {
574
+ const r = this.gh("collision", ["pr", "list", "--state", "open", "--json", "number", "--limit", String(PR_LIMIT)]);
575
+ if (r.status !== 0) return this.stop(withText(`gh pr list failed (${r.how})`, r));
576
+ let prs;
577
+ try {
578
+ prs = JSON.parse(r.stdout);
579
+ } catch (e) {
580
+ return this.stop(`could not parse gh pr list: ${e.message}`);
581
+ }
582
+ if (!Array.isArray(prs) || !prs.every((p) => Number.isInteger(p?.number))) return this.stop("gh pr list did not print a JSON array of numbered PRs");
583
+ if (prs.length >= PR_LIMIT) return this.stop(`gh pr list came back at its cap of ${PR_LIMIT} — it may hold more PRs than it showed`);
584
+ st.openPrs = prs.map((p) => p.number).sort((a, b) => a - b);
585
+ this.save();
586
+ }
587
+ return this.ask("collision", this.collisionContext());
588
+ }
589
+
590
+ stage_claim() {
591
+ const { st } = this;
592
+ // The session is the router's, and a claim made before it is known would
593
+ // have to be released again.
594
+ try {
595
+ st.session = sessionFromReceipt({ cwd: this.p.cwd });
596
+ } catch (e) {
597
+ return this.stop(e.message);
598
+ }
599
+ const r = this.script("claim", "claim-ticket.sh", [String(st.ticket), st.member, "implementer", "--apply"]);
600
+ if (r.status === 0) {
601
+ st.stage = "route";
602
+ return null;
603
+ }
604
+ if (r.status === 2) return this.leave(`taken (claim-ticket.sh refused the claim${r.text === "" ? "" : `: ${r.text.replace(/\s+/g, " ")}`})`);
605
+ return this.stop(withText(`claim-ticket.sh could not claim (${r.how})`, r));
606
+ }
607
+
608
+ stage_route() {
609
+ const { st } = this;
610
+ const rows = this.ledgerRows();
611
+ const k = implRow(rows);
612
+ const head = chainHead(rows, st.ticket);
613
+ const args = [
614
+ "route", "--session", st.session, "--ticket", String(st.ticket), "--arm", st.ticket % 2 === 0 ? "A" : "B",
615
+ "--impl-row", String(k), ...(head ? ["--chain-head"] : []), "--issue", this.p.issue, "--guard", this.p.guard,
616
+ ];
617
+ const r = this.script("route", "ticket-router.mjs", args);
618
+ const m = r.status === 0 ? /^POLICY=(\S+) CELL=(\S+) DRAW=(\S+) STRATUM=(\S+) REASON=(\S+)$/m.exec(r.stdout) : null;
619
+ if (m === null) {
620
+ const said = r.status === 0 ? `printed no routing line: ${r.stdout}` : withText(`refused (${r.how})`, r);
621
+ const rel = this.script("release", "release-ticket.sh", [String(st.ticket), st.member, "implementer", "--apply"]);
622
+ if (rel.status !== 0) {
623
+ // The claim stands, so the Pull is not over: it stays at this step, and running it again routes, or refuses and releases, again.
624
+ return this.stop(`ticket-router.mjs ${said}\n${withText(`its claim is STILL STANDING: release-ticket.sh failed (${rel.how})`, rel)}`);
625
+ }
626
+ st.status = "released";
627
+ st.outcome = { exit: 2, reason: `router ${said}`, at: now() };
628
+ return this.stop(`ticket-router.mjs ${said}\nits claim is released`);
629
+ }
630
+ st.route = { line: m[0], cell: m[2], draw: m[3], reason: m[5], implRow: k, chainHead: head };
631
+ st.stage = "row";
632
+ return null;
633
+ }
634
+
635
+ stage_row() {
636
+ const { st } = this;
637
+ const { cell, draw, reason } = st.route;
638
+ const text = `${st.member}${draw === "-" ? "" : ` · tier=${cell}`}${reason === "ok" ? "" : ` · route=${reason}`}`;
639
+ const r = this.script("row", "ledger.mjs", ["row", String(st.ticket), text]);
640
+ if (r.status !== 0) return this.stop(withText(`ledger.mjs row failed (${r.how})`, r));
641
+ st.stage = "render";
642
+ return null;
643
+ }
644
+
645
+ stage_render() {
646
+ const { st } = this;
647
+ const worktree = join(this.p.cwd, ".worktrees", `${st.ticket}-${st.member}`);
648
+ const staleness = st.staleness.length === 0 ? "no probe was run" : st.staleness.join("; ");
649
+ let names;
650
+ try {
651
+ names = declaredPlaceholders();
652
+ } catch (e) {
653
+ return this.stop(`cannot read the brief template ${TEMPLATE} (${e.code ?? e.message})`);
654
+ }
655
+ const r = this.script("render", "dispatch-prompt.mjs", [
656
+ "render", "implementer", "--member", st.member, "--ticket", String(st.ticket), "--worktree", worktree,
657
+ "--branch", `implementer/${st.ticket}-${st.member}`, "--scratch", this.p.scratch,
658
+ "--brief", defang(this.dispatchBrief(), names), "--staleness", defang(staleness, names),
659
+ ]);
660
+ if (r.status !== 0) return this.stop(withText(`dispatch-prompt.mjs render refused (${r.how}) — the claim stands`, r));
661
+ st.stage = "dispatch";
662
+ return null;
663
+ }
664
+
665
+ stage_dispatch() {
666
+ const { st } = this;
667
+ const r = this.script("dispatch", "ledger.mjs", ["dispatch", String(st.ticket), st.member]);
668
+ if (r.status !== 0) return this.stop(withText(`ledger.mjs dispatch refused (${r.how}) — the claim stands`, r));
669
+ let out;
670
+ try {
671
+ out = JSON.parse(r.stdout);
672
+ } catch (e) {
673
+ return this.stop(`ledger.mjs dispatch printed no JSON: ${e.message}`);
674
+ }
675
+ if (typeof out?.agent !== "string" || typeof out?.brief?.path !== "string") return this.stop("ledger.mjs dispatch printed no agent and brief path");
676
+ st.dispatch = { name: st.member, agent: out.agent, brief: out.brief.path };
677
+ st.status = "dispatched";
678
+ st.stage = "done";
679
+ st.outcome = { exit: 0, at: now() };
680
+ return this.dispatched();
681
+ }
682
+
683
+ stage_done() {
684
+ return this.dispatched();
685
+ }
686
+
687
+ dispatched() {
688
+ return result(0, [`DISPATCH ${JSON.stringify(this.st.dispatch)}`]);
689
+ }
690
+
691
+ // ── an answer's effect: null to ask on, or a result. Exit 2 is an effect that failed ──
692
+ answer(qid, { token, text, path }) {
693
+ const { st } = this;
694
+ const entry = { at: now(), qid, token, text, ...(path === null ? {} : { path }), applied: false };
695
+ st.answers.push(entry);
696
+ this.save();
697
+ const r = this[`answer_${qid}`](token, text, path);
698
+ // A failed effect leaves the question standing, to be answered again.
699
+ if (r !== null && r.exit === 2) return r;
700
+ entry.applied = true;
701
+ st.pending = null;
702
+ this.save();
703
+ return r;
704
+ }
705
+
706
+ answer_staleness(token, text, path) {
707
+ const { st } = this;
708
+ if (token === "done") {
709
+ st.stage = "decided";
710
+ return null;
711
+ }
712
+ if (token === "none") {
713
+ st.staleness.push(`could-not-check: no string settles it — ${text}`);
714
+ st.stage = "decided";
715
+ return null;
716
+ }
717
+ const r = this.script("staleness", "staleness.mjs", ["--path", path, `--${token}`, "--", text]);
718
+ if (r.status === 0) {
719
+ st.staleness.push(`${token} check at ${path}: still reproduces`);
720
+ return null;
721
+ }
722
+ let payload = null;
723
+ try {
724
+ payload = JSON.parse(r.stdout);
725
+ } catch {
726
+ // Not JSON: the reason below comes from its words.
727
+ }
728
+ if (r.status === 1 && typeof payload?.commit === "string" && payload.commit !== "") {
729
+ st.close = { mode: token, path, needle: text, commit: payload.commit, subject: null };
730
+ return null;
731
+ }
732
+ let reason;
733
+ if (r.status === 1) {
734
+ reason = payload !== null && typeof payload === "object"
735
+ ? "the probe read the ticket as fixed and named no commit"
736
+ : `the probe exited 1 with no verdict JSON, which is a crash and no verdict: ${(r.stderr || r.stdout || r.how).split("\n")[0]}`;
737
+ } else {
738
+ reason = typeof payload?.why === "string" ? payload.why : (r.stderr || r.stdout || r.how).split("\n")[0];
739
+ }
740
+ st.staleness.push(`could-not-check: ${reason}`);
741
+ return null;
742
+ }
743
+
744
+ answer_close(token, text) {
745
+ const { st } = this;
746
+ const c = st.close;
747
+ if (token === "no") {
748
+ st.staleness.push(`staleness probe read --${c.mode} in ${c.path} as fixed by ${c.commit}: ${c.subject}; kept by the controller: ${text}`);
749
+ st.close = null;
750
+ return null;
751
+ }
752
+ const r = this.gh("close", ["issue", "close", String(st.ticket), "--comment", closeComment(c.commit, c.subject)]);
753
+ if (r.status !== 0) return this.stop(withText(`gh issue close failed (${r.how})`, r));
754
+ return this.leave(`closed: fixed by ${c.commit}: ${c.subject}`);
755
+ }
756
+
757
+ answer_decided(token, text) {
758
+ const { st } = this;
759
+ if (token === "decided") {
760
+ st.stage = "collision";
761
+ return null;
762
+ }
763
+ const { label, comment } = relabel(token, text);
764
+ // One comment per cause: an edit that failed after its comment landed is
765
+ // answered again without a second comment.
766
+ if (st.commented !== comment) {
767
+ const c = this.gh("relabel", ["issue", "comment", String(st.ticket), "--body", comment]);
768
+ if (c.status !== 0) return this.stop(withText(`gh issue comment failed (${c.how})`, c));
769
+ st.commented = comment;
770
+ this.save();
771
+ }
772
+ const e = this.gh("relabel", ["issue", "edit", String(st.ticket), "--remove-label", READY, "--add-label", label]);
773
+ if (e.status !== 0) return this.stop(withText(`gh issue edit failed (${e.how}) — the comment is posted`, e));
774
+ return this.leave(`relabelled ${label}: ${token}`);
775
+ }
776
+
777
+ answer_collision(token) {
778
+ const { st } = this;
779
+ if (token === "clear") {
780
+ st.stage = "claim";
781
+ return null;
782
+ }
783
+ const r = this.script("exclude", "ledger.mjs", ["row", String(st.ticket), `excluded · ${token}`]);
784
+ if (r.status !== 0) return this.stop(withText(`ledger.mjs row failed (${r.how})`, r));
785
+ return this.leave(`excluded · ${token}`);
786
+ }
787
+ }
788
+
789
+ // ── the shortlist head ───────────────────────────────────────────────────────
790
+
791
+ // Whether an exclusion's premises still hold: a premise `gh` cannot be asked
792
+ // about, or whose state could not be read, stands, as the shortlist's refresh
793
+ // reads it. Each such premise is added to `unreadable`, so that a shortlist
794
+ // emptied by premises nobody could read is told apart from an empty one.
795
+ function exclusionLive(premises, cwd, unreadable) {
796
+ if (premises.length === 0) return true;
797
+ for (const { kind, target } of premises) {
798
+ if (target.startsWith("-") || !(kind === "pr" || isDigits(target))) return true;
799
+ const r = spawn("gh", [kind, "view", target, "--json", "state"], { cwd, env: GH_ENV, timeoutMs: NETWORK_TIMEOUT_MS });
800
+ if (r.status !== 0) {
801
+ unreadable.push(`gh ${kind} view ${target} (${r.how}${r.stderr === "" ? "" : `: ${r.stderr.split("\n")[0]}`})`);
802
+ return true;
803
+ }
804
+ let state;
805
+ try {
806
+ ({ state } = JSON.parse(r.stdout));
807
+ } catch {
808
+ unreadable.push(`gh ${kind} view ${target} (printed no JSON state)`);
809
+ return true;
810
+ }
811
+ if (!LIFTED.has(state)) return true;
812
+ }
813
+ return false;
814
+ }
815
+
816
+ // The phase-0 session names the run a Pull belongs to: the persistent scratch
817
+ // root holds every run's records, and only this run's are this run's. Null when
818
+ // the receipt names none, which the claim step refuses in its own words.
819
+ function currentRun(cwd) {
820
+ try {
821
+ return sessionFromReceipt({ cwd });
822
+ } catch {
823
+ return null;
824
+ }
825
+ }
826
+
827
+ /** The first shortlist entry still to be pulled, or null when the list holds none. */
828
+ function shortlistHead(p, run) {
829
+ let list;
830
+ try {
831
+ list = JSON.parse(readFileSync(p.shortlist, "utf8"));
832
+ } catch (e) {
833
+ throw new Refusal(`cannot read ${p.shortlist} (${e.code ?? e.message}) — run shortlist.mjs`);
834
+ }
835
+ if (!Array.isArray(list?.shortlist) || !list.shortlist.every((e) => Number.isInteger(e?.n))) {
836
+ throw new Refusal(`${p.shortlist} holds no shortlist[] of {n}`);
837
+ }
838
+ const led = spawn(process.execPath, [join(SCRIPTS, "ledger.mjs"), "read"], { cwd: p.cwd });
839
+ let rows;
840
+ try {
841
+ ({ rows } = JSON.parse(led.stdout));
842
+ } catch {
843
+ rows = null;
844
+ }
845
+ if (led.status !== 0 || !Array.isArray(rows) || !rows.every((r) => typeof r === "string")) {
846
+ throw new Refusal(withText(`ledger.mjs read did not answer (${led.how})`, led));
847
+ }
848
+ const unreadable = [];
849
+ for (const { n } of list.shortlist) {
850
+ const row = rows.find((r) => rowKey(r) === `#${n}`);
851
+ if (row !== undefined && isImplRow(row)) continue;
852
+ const premises = row === undefined ? null : premisesOf(row);
853
+ if (premises !== null && exclusionLive(premises, p.cwd, unreadable)) continue;
854
+ const ended = readPull(p.statePath(n));
855
+ if (ended !== null && (ended.status === "left" || ended.status === "released") && (run === null || ended.session === run)) continue;
856
+ return n;
857
+ }
858
+ if (unreadable.length > 0) {
859
+ throw new Refusal(`no entry to pull, and gh could not read the premise of an exclusion, which stands: ${unreadable.join("; ")} — run again once gh answers`);
860
+ }
861
+ return null;
862
+ }
863
+
864
+ // ── the commands ─────────────────────────────────────────────────────────────
865
+
866
+ function setup() {
867
+ let fleetDir;
868
+ try {
869
+ fleetDir = fleetFile(null);
870
+ } catch (e) {
871
+ if (!(e instanceof FleetDirUnresolvable)) throw e;
872
+ throw new Refusal(e.message);
873
+ }
874
+ const cwd = dirname(fleetDir);
875
+ const top = spawn("git", ["rev-parse", "--show-toplevel"], { cwd: process.cwd() });
876
+ if (top.status !== 0 || realpathSync(top.stdout) !== realpathSync(cwd)) {
877
+ throw new Usage(`run this from the main checkout ${cwd}${top.status === 0 ? `, not ${top.stdout}` : ""}`);
878
+ }
879
+ const root = spawn(process.execPath, [join(SCRIPTS, "scratch-root.mjs")], { cwd });
880
+ if (root.status !== 0) throw new Refusal(withText(`scratch-root.mjs ${root.how}`, root));
881
+ const scratch = root.stdout;
882
+ const dir = (n) => join(scratch, `impl-${n}`);
883
+ return {
884
+ cwd,
885
+ scratch,
886
+ shortlist: join(fleetDir, "shortlist.json"),
887
+ guard: join(fleetDir, "cost-guard.json"),
888
+ statePath: (n) => join(dir(n), STATE),
889
+ previousPath: (n) => join(dir(n), PREVIOUS),
890
+ issuePath: (n) => join(dir(n), "issue.json"),
891
+ };
892
+ }
893
+
894
+ const pullFor = (base, st) => new Pull(st, { ...base, state: base.statePath(st.ticket), issue: base.issuePath(st.ticket) });
895
+
896
+ function parseNext(args) {
897
+ if (args.length === 0) return null;
898
+ if (args.length !== 2 || args[0] !== "--head" || !isDigits(args[1]) || Number(args[1]) < 1) {
899
+ throw new Usage(`next takes only --head <N>, a ticket number — ${USAGE}`);
900
+ }
901
+ return Number(args[1]);
902
+ }
903
+
904
+ function next(args) {
905
+ const head = parseNext(args);
906
+ const base = setup();
907
+ const run = currentRun(base.cwd);
908
+ const n = head ?? shortlistHead(base, run);
909
+ if (n === null) return result(1, ["EMPTY: the shortlist holds no entry to pull — run shortlist.mjs once and Pull again; still empty, hold the slot idle until the next refresh trigger"]);
910
+ let st = readPull(base.statePath(n));
911
+ if (st !== null && (st.status === "left" || st.status === "released" || (run !== null && st.session !== run))) {
912
+ // Asked for by number, so asked for again: the ended Pull is kept beside the new one. A record from another
913
+ // run is ended too, whatever it says: the ledger rotated, and a dispatch it made is none of this run's.
914
+ renameSync(base.statePath(n), base.previousPath(n));
915
+ st = null;
916
+ }
917
+ const first = st === null;
918
+ if (first) st = fresh(n, run);
919
+ const pull = pullFor(base, st);
920
+ if (first) pull.save();
921
+ const r = pull.advance();
922
+ return { ...r, out: [first ? `PULL #${n}: started, state in ${base.statePath(n)}` : `PULL #${n}: resumed at ${st.pending === null ? st.stage : `question ${st.pending.qid}`}`, ...pull.log, ...r.out] };
923
+ }
924
+
925
+ function answer(args) {
926
+ const [ticket, qid, token, ...rest] = args;
927
+ if (token === undefined) throw new Usage(`answer needs <N> <qid> <token> — ${USAGE}`);
928
+ if (!isDigits(ticket) || Number(ticket) < 1) throw new Usage(`'${ticket}' is not a ticket number — ${USAGE}`);
929
+ const base = setup();
930
+ const n = Number(ticket);
931
+ const st = readPull(base.statePath(n));
932
+ if (st === null) throw new Usage(`no Pull in progress for #${n} — start it with: ${NAME}.mjs next --head ${n}`);
933
+ if (st.status !== "running") throw new Usage(`the Pull for #${n} is ${st.status}, not in progress`);
934
+ if (st.pending === null) throw new Usage(`the Pull for #${n} has no question pending — resume it with: ${NAME}.mjs next --head ${n}`);
935
+ if (st.pending.qid !== qid) throw new Usage(`the question pending for #${n} is ${st.pending.qid}, not ${qid}`);
936
+ const parsed = parseAnswer(qid, token, rest);
937
+ const pull = pullFor(base, st);
938
+ const r = pull.answer(qid, parsed) ?? pull.advance();
939
+ return { ...r, out: [...pull.log, ...r.out] };
940
+ }
941
+
942
+ // An unknown flag is refused the way every script that holds a command line of
943
+ // its own refuses one, through arg.mjs's die() at exit 2; every other mistake
944
+ // in the command line is exit 3.
945
+ function refuseUnknownFlags(sub, args) {
946
+ const known = sub === "next" ? ["--head"] : [];
947
+ for (const word of [sub, ...(sub === "next" ? args : [])]) {
948
+ if (typeof word === "string" && word.startsWith("-") && !known.includes(word)) die(`unknown flag ${word} — ${USAGE}`);
949
+ }
950
+ }
951
+
952
+ function main() {
953
+ const [sub, ...args] = process.argv.slice(2);
954
+ let r;
955
+ try {
956
+ refuseUnknownFlags(sub, args);
957
+ if (sub === "next") r = next(args);
958
+ else if (sub === "answer") r = answer(args);
959
+ else throw new Usage(USAGE);
960
+ } catch (e) {
961
+ if (e instanceof Usage) {
962
+ process.stderr.write(`${NAME}: ${e.message}\n`);
963
+ process.exitCode = 3;
964
+ return;
965
+ }
966
+ // Node exits 1 on an uncaught throw, and 1 here means the ticket left the
967
+ // Pull: a crash must never read as a verdict.
968
+ process.stderr.write(`${NAME}: ${e instanceof Refusal ? e.message : `unexpected: ${e?.stack ?? e}`}\n`);
969
+ process.exitCode = 2;
970
+ return;
971
+ }
972
+ for (const l of r.out) process.stdout.write(`${l}\n`);
973
+ for (const l of r.err) process.stderr.write(`${l}\n`);
974
+ process.exitCode = r.exit;
975
+ }
976
+
977
+ if (isCLI(import.meta.url)) main();
@@ -90,17 +90,26 @@ export function briefText(issue) {
90
90
  return String(issue.body ?? "");
91
91
  }
92
92
 
93
- /** The metric columns for a parsed `gh issue view --json title,body,comments,labels,createdAt`, or null when it is not one. */
94
- export function issueMetrics(issue, now = Date.now()) {
95
- if (issue === null || typeof issue !== "object" || Array.isArray(issue) || typeof issue.body !== "string") return null;
96
- const brief = briefText(issue).trim();
97
- const lines = brief.split(/\r?\n/);
93
+ /**
94
+ * The file paths a brief names: every backticked token without whitespace that
95
+ * holds a `/` or ends in an extension, in first-seen order, each once.
96
+ */
97
+ export function briefPaths(brief) {
98
98
  const paths = new Set();
99
99
  for (const m of brief.matchAll(/`([^`\n]+)`/g)) {
100
100
  const tok = m[1];
101
101
  if (/\s/.test(tok)) continue;
102
102
  if (tok.includes("/") || /\.[A-Za-z][A-Za-z0-9]*$/.test(tok)) paths.add(tok);
103
103
  }
104
+ return [...paths];
105
+ }
106
+
107
+ /** The metric columns for a parsed `gh issue view --json title,body,comments,labels,createdAt`, or null when it is not one. */
108
+ export function issueMetrics(issue, now = Date.now()) {
109
+ if (issue === null || typeof issue !== "object" || Array.isArray(issue) || typeof issue.body !== "string") return null;
110
+ const brief = briefText(issue).trim();
111
+ const lines = brief.split(/\r?\n/);
112
+ const paths = briefPaths(brief);
104
113
  const created = Date.parse(issue.createdAt ?? "");
105
114
  const kind = (Array.isArray(issue.labels) ? issue.labels : []).map((l) => l?.name).find((n) => KINDS.has(n)) ?? "";
106
115
  return {
@@ -108,8 +117,8 @@ export function issueMetrics(issue, now = Date.now()) {
108
117
  criteria: String(lines.filter((l) => /^\s*[-*]\s*\[[ xX]\]/.test(l)).length),
109
118
  comments: String(Array.isArray(issue.comments) ? issue.comments.length : 0),
110
119
  age_days: Number.isFinite(created) ? String(Math.max(0, Math.floor((now - created) / DAY_MS))) : "",
111
- paths: String(paths.size),
112
- test_paths: String([...paths].filter((p) => /\.test\.|(^|\/)tests?\//.test(p)).length),
120
+ paths: String(paths.length),
121
+ test_paths: String(paths.filter((p) => /\.test\.|(^|\/)tests?\//.test(p)).length),
113
122
  xrefs: String(new Set([...brief.matchAll(/#(\d+)/g)].map((m) => m[1])).size),
114
123
  kind,
115
124
  };
@@ -368,6 +368,20 @@ label or a premise the maintainer can read.
368
368
  Serial, main checkout, one Pull at a time. Never parallel, never inside a member —
369
369
  concurrent `worktree add` and label writes race.
370
370
 
371
+ A Pull's entry is `~/.fleet/bin/fleet-run pull.mjs next --head <N>`, run from the
372
+ main checkout (without `--head`, the next shortlist entry). It runs the
373
+ mechanical steps below in order and stops at each judgement with a `QUESTION
374
+ <qid>:` block and exit 10; `pull.mjs answer <N> <qid> <token> [--path <p>] [--]
375
+ [<text>…]` records the answer and resumes it. Exit 0 prints `DISPATCH {name,
376
+ agent, brief}`, the `task` call phase 2 makes; exit 1 means the ticket left the
377
+ Pull, so take the next entry; exit 2 names what could not be looked at —
378
+ `next --head <N>` again retries a step that failed, the same `answer` again
379
+ retries one that failed while applying an answer (the question stands), and
380
+ after a router refusal `next --head <N>` starts the ticket over; exit 3 is a
381
+ usage mistake, or an answer the question does not take, and records nothing.
382
+ The record is `<scratch>/impl-<N>/pull.json`. The steps below are what
383
+ the driver runs, and the guidance for answering `staleness` and `decided`.
384
+
371
385
  One free implementer slot is one Pull. The tick names the heads — `PULL #<n>
372
386
  #<m>`, one per free slot — and each Pull runs this sequence on its head,
373
387
  terminating in exactly one dispatch or an empty shortlist: