@feigi/fleet-ctl 3.59.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 +1 -1
- package/scripts/fleet-tick.mjs +124 -9
- package/scripts/pull.mjs +977 -0
- package/scripts/ticket-router.mjs +16 -7
- package/skills/run-team/SKILL.md +17 -1
package/package.json
CHANGED
package/scripts/fleet-tick.mjs
CHANGED
|
@@ -78,6 +78,17 @@
|
|
|
78
78
|
// take the registry census, never an action: it resets no
|
|
79
79
|
// `quiet`, changes no row and frees no slot, and the tick never
|
|
80
80
|
// settles or kills anything.
|
|
81
|
+
// reports `<scratch>/reports/<member>.json`, the report file a member
|
|
82
|
+
// writes beside the message it sends, for every live member
|
|
83
|
+
// token. `<scratch>` is the phase-0 receipt's `scratch`, else
|
|
84
|
+
// `--scratch`; with neither the check is skipped with one stderr
|
|
85
|
+
// line. A file on disk prints one `SETTLE <member>` line naming
|
|
86
|
+
// the `ledger.mjs settle <member> --from-report` it is for, and
|
|
87
|
+
// one whose `member` is not its filename's prints REPORT-MISMATCH
|
|
88
|
+
// instead; one that is there but cannot be read prints
|
|
89
|
+
// REPORT-UNREADABLE. Advice, like CHECK-LIVENESS: the tick
|
|
90
|
+
// settles nothing. A review runner has no report schema and files
|
|
91
|
+
// none, so no `review=` token is looked up.
|
|
81
92
|
//
|
|
82
93
|
// The pure half below is `reconcile()` over the counts `deriveRun()` reads off
|
|
83
94
|
// the ledger; main() does the I/O. Split so the guard table and the reading are
|
|
@@ -883,6 +894,7 @@ export function deriveRun({ rows, dispatched, drain }, prs, closed = new Set(),
|
|
|
883
894
|
// PR nobody has asked about keeps its review live.
|
|
884
895
|
const reviewing = [...byPr.entries()].filter(([, st]) => st.inFlight);
|
|
885
896
|
const liveReviews = reviewing.filter(([n]) => open.has(n) || !finished.has(n));
|
|
897
|
+
const unsettled = all.filter((m) => m.outcome === null).map((m) => m.name);
|
|
886
898
|
return {
|
|
887
899
|
implLive: live("impl"),
|
|
888
900
|
fixLive: live("fix-pr"),
|
|
@@ -967,9 +979,13 @@ export function deriveRun({ rows, dispatched, drain }, prs, closed = new Set(),
|
|
|
967
979
|
// member token, then each in-flight review by its PR — a `review=wf:`
|
|
968
980
|
// run carries no member token of its own.
|
|
969
981
|
live: [
|
|
970
|
-
...
|
|
982
|
+
...unsettled,
|
|
971
983
|
...liveReviews.map(([n]) => `review:PR#${n}`),
|
|
972
984
|
],
|
|
985
|
+
// Who may have a report file on disk, by the name it is filed under: every
|
|
986
|
+
// unsettled member token. A review runner has no report schema and a
|
|
987
|
+
// `review=wf:` run no member, so neither files one.
|
|
988
|
+
reporters: unsettled,
|
|
973
989
|
};
|
|
974
990
|
}
|
|
975
991
|
|
|
@@ -1077,6 +1093,45 @@ export function livenessLines({ live, seen, thresholds, now }) {
|
|
|
1077
1093
|
return out;
|
|
1078
1094
|
}
|
|
1079
1095
|
|
|
1096
|
+
// The report lines: one per name in `reporters` with a report file on disk, as
|
|
1097
|
+
// `{member, settle, line, key}`. `reports` maps a name to what main() read off
|
|
1098
|
+
// its file — `{path, since, member}`, `since` the file's mtime in ms and
|
|
1099
|
+
// `member` the file's own `member` field, undefined when it has none or is
|
|
1100
|
+
// not JSON, or `{path, unreadable}`, `unreadable` the error code of a file
|
|
1101
|
+
// that is there and cannot be read — and has no entry for a name with no file.
|
|
1102
|
+
// A file that names a member other than the one it is filed under prints
|
|
1103
|
+
// REPORT-MISMATCH instead, once, and an unreadable one REPORT-UNREADABLE; for
|
|
1104
|
+
// both `settle` is false. `reportsFrom`, when set, is the directory the
|
|
1105
|
+
// printed settle reads its file from: ledger.mjs reads the default scratch
|
|
1106
|
+
// root's `reports/` unless told otherwise. `key` is the line without its age,
|
|
1107
|
+
// what the digest `--fold-unchanged` compares takes, so a report waiting on
|
|
1108
|
+
// disk folds rather than moving the digest every minute.
|
|
1109
|
+
export function reportLines({ reporters, reports, now, reportsFrom = null }) {
|
|
1110
|
+
const out = [];
|
|
1111
|
+
const from = reportsFrom === null ? "" : ` --reports ${/^[\w./@%+=:,-]+$/.test(reportsFrom) ? reportsFrom : `'${reportsFrom.replaceAll("'", "'\\''")}'`}`;
|
|
1112
|
+
for (const member of new Set(reporters)) {
|
|
1113
|
+
const r = reports.get(member);
|
|
1114
|
+
if (r === undefined) continue;
|
|
1115
|
+
if (r.unreadable !== undefined) {
|
|
1116
|
+
const line = `REPORT-UNREADABLE ${r.path} (${r.unreadable})`;
|
|
1117
|
+
out.push({ member, settle: false, line, key: line });
|
|
1118
|
+
continue;
|
|
1119
|
+
}
|
|
1120
|
+
if (r.member !== member) {
|
|
1121
|
+
const named = typeof r.member === "string" ? r.member : JSON.stringify(r.member) ?? "none";
|
|
1122
|
+
const line = `REPORT-MISMATCH ${r.path} (member: ${named})`;
|
|
1123
|
+
out.push({ member, settle: false, line, key: line });
|
|
1124
|
+
continue;
|
|
1125
|
+
}
|
|
1126
|
+
const age = Math.floor(Math.max(0, now - r.since) / 60_000);
|
|
1127
|
+
out.push({
|
|
1128
|
+
member, settle: true, key: `SETTLE ${member}`,
|
|
1129
|
+
line: `SETTLE ${member} (report on disk since ${age}m — ledger.mjs settle ${member} --from-report${from})`,
|
|
1130
|
+
});
|
|
1131
|
+
}
|
|
1132
|
+
return out;
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1080
1135
|
// --apply's pure half. The merge-bot numbers `applied.reapAfter` names for
|
|
1081
1136
|
// THIS run: none when its `run` is not the controller record's `at`, since
|
|
1082
1137
|
// merge-bot numbering restarts with a run and the state file outlives it
|
|
@@ -1139,7 +1194,7 @@ export function reclaimSummary(stdout) {
|
|
|
1139
1194
|
|
|
1140
1195
|
import { execFileSync, spawnSync } from "node:child_process";
|
|
1141
1196
|
import { createHash } from "node:crypto";
|
|
1142
|
-
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
1197
|
+
import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
1143
1198
|
import { tmpdir } from "node:os";
|
|
1144
1199
|
import { dirname, join } from "node:path";
|
|
1145
1200
|
import { fileURLToPath } from "node:url";
|
|
@@ -1152,6 +1207,7 @@ import { statePath, readState, writeState, assessBeat, isStalled, isReported, st
|
|
|
1152
1207
|
import { checkMainCheckout, describe } from "./main-checkout.mjs";
|
|
1153
1208
|
import { readRunReceipt, phase0Gate } from "./phase0-receipt.mjs";
|
|
1154
1209
|
import { judgeRecord, ProcUnreadable } from "./proc.mjs";
|
|
1210
|
+
import { reportPath, reportsDir } from "./report-files.mjs";
|
|
1155
1211
|
|
|
1156
1212
|
const NAME = "fleet-tick";
|
|
1157
1213
|
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
|
|
@@ -1221,6 +1277,10 @@ const OPTIONS = {
|
|
|
1221
1277
|
// under parseArgs, and no path is legitimately empty, so empty resolves to
|
|
1222
1278
|
// the default.
|
|
1223
1279
|
state: { type: "string", default: "" },
|
|
1280
|
+
// The scratch root the report files are under, for a run whose phase-0
|
|
1281
|
+
// receipt names none; the receipt's `scratch` wins when it does. Empty is
|
|
1282
|
+
// absent, as with --state.
|
|
1283
|
+
scratch: { type: "string", default: "" },
|
|
1224
1284
|
// Minutes a live token of each family may run before CHECK-LIVENESS names it.
|
|
1225
1285
|
...Object.fromEntries(Object.entries(LIVENESS_FLAGS).map(([family, flag]) => [flag, { type: "string", default: String(LIVENESS_DEFAULTS[family]) }])),
|
|
1226
1286
|
};
|
|
@@ -1252,7 +1312,7 @@ function options() {
|
|
|
1252
1312
|
return {
|
|
1253
1313
|
implCap: positive("implementer-cap"), reviewerCap,
|
|
1254
1314
|
maxReviews: values["max-reviews"] === undefined ? reviewerCap : positive("max-reviews"),
|
|
1255
|
-
fold: values["fold-unchanged"], apply: values.apply, state: values.state || statePath(NAME),
|
|
1315
|
+
fold: values["fold-unchanged"], apply: values.apply, state: values.state || statePath(NAME), scratch: values.scratch,
|
|
1256
1316
|
liveness: Object.fromEntries(Object.entries(LIVENESS_FLAGS).map(([family, flag]) => [family, positive(flag)])),
|
|
1257
1317
|
};
|
|
1258
1318
|
}
|
|
@@ -1621,8 +1681,48 @@ function readRun(prs) {
|
|
|
1621
1681
|
}
|
|
1622
1682
|
}
|
|
1623
1683
|
|
|
1684
|
+
// The scratch root the report files are under, and whether it came from
|
|
1685
|
+
// `--scratch`: the phase-0 receipt's `scratch`, else `--scratch`, else null —
|
|
1686
|
+
// no root, no check. `ledger.mjs settle --from-report` reads the root
|
|
1687
|
+
// scratch-root.mjs prints unless given `--reports`, so a root named by the
|
|
1688
|
+
// flag is one the printed settle must be told.
|
|
1689
|
+
function reportsScratch(receipt, flag) {
|
|
1690
|
+
const named = receipt.read.state === "ok" ? receipt.read.receipt.scratch : undefined;
|
|
1691
|
+
if (typeof named === "string" && named !== "") return { root: named, flagged: false };
|
|
1692
|
+
return flag === "" ? null : { root: flag, flagged: true };
|
|
1693
|
+
}
|
|
1694
|
+
|
|
1695
|
+
// The report file of each name in `reporters`, as reportLines() takes them:
|
|
1696
|
+
// `{path, since, member}` per file on disk, `{path, unreadable}` for one that
|
|
1697
|
+
// cannot be read, nothing for a name with none. Only `member` is read out of a
|
|
1698
|
+
// file, and a file that is not JSON carries none.
|
|
1699
|
+
function readReports(scratch, reporters) {
|
|
1700
|
+
const out = new Map();
|
|
1701
|
+
for (const member of reporters) {
|
|
1702
|
+
const path = reportPath(scratch, member);
|
|
1703
|
+
let since, text;
|
|
1704
|
+
try {
|
|
1705
|
+
since = statSync(path).mtimeMs;
|
|
1706
|
+
text = readFileSync(path, "utf8");
|
|
1707
|
+
} catch (e) {
|
|
1708
|
+
if (e.code === "ENOENT" || e.code === "ENOTDIR") continue;
|
|
1709
|
+
out.set(member, { path, unreadable: e.code ?? "unknown error" });
|
|
1710
|
+
continue;
|
|
1711
|
+
}
|
|
1712
|
+
let named;
|
|
1713
|
+
try {
|
|
1714
|
+
const d = JSON.parse(text);
|
|
1715
|
+
named = d !== null && typeof d === "object" && !Array.isArray(d) ? d.member : undefined;
|
|
1716
|
+
} catch {
|
|
1717
|
+
named = undefined;
|
|
1718
|
+
}
|
|
1719
|
+
out.set(member, { path, since, member: named });
|
|
1720
|
+
}
|
|
1721
|
+
return out;
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1624
1724
|
function main() {
|
|
1625
|
-
const { fold, apply, state: path, liveness, ...caps } = options();
|
|
1725
|
+
const { fold, apply, state: path, liveness, scratch: scratchFlag, ...caps } = options();
|
|
1626
1726
|
const listPath = shortlistPath();
|
|
1627
1727
|
const current = readShortlist(listPath);
|
|
1628
1728
|
// Beside the shortlist, off the same git probe rather than a second one.
|
|
@@ -1734,6 +1834,12 @@ function main() {
|
|
|
1734
1834
|
...caps, ...run, heads, supply, dropped, shortlistStatus: current.status, refresh: fresh, mainCheckout, phase0, router,
|
|
1735
1835
|
});
|
|
1736
1836
|
const said = describe(mainCheckout, run.live);
|
|
1837
|
+
// The report files of the live members, read before the state file for the
|
|
1838
|
+
// reason given below. A member's report on disk is the outcome its message
|
|
1839
|
+
// was to carry, whether or not that message arrived.
|
|
1840
|
+
const scratch = reportsScratch(receipt, scratchFlag);
|
|
1841
|
+
if (scratch === null) console.error(`${NAME}: report files not checked — no scratch in the phase-0 receipt and no --scratch`);
|
|
1842
|
+
const reports = scratch === null ? new Map() : readReports(scratch.root, run.reporters);
|
|
1737
1843
|
// Re-read rather than reusing priorState: this must be the freshest
|
|
1738
1844
|
// snapshot, or this tick reverts whatever the heartbeat wrote while the
|
|
1739
1845
|
// reads above were in flight. Read before the lines are built because the
|
|
@@ -1746,18 +1852,24 @@ function main() {
|
|
|
1746
1852
|
// and frees no slot — and nothing here settles, kills or writes the ledger.
|
|
1747
1853
|
const seen = stampSeen({ live: run.live, prev: prev.seen, controller: prev.controller, now });
|
|
1748
1854
|
const stale = livenessLines({ live: run.live, seen, thresholds: liveness, now });
|
|
1749
|
-
|
|
1855
|
+
// Advisory the same way: a report on disk prints the settle it is for, and
|
|
1856
|
+
// nothing here runs it.
|
|
1857
|
+
const reported = reportLines({ reporters: run.reporters, reports, now, reportsFrom: scratch?.flagged ? reportsDir(scratch.root) : null });
|
|
1858
|
+
const above = [...(phase0.line === null ? [] : [phase0.line]), ...(said === null ? [] : [said]), ...stale.map((s) => s.line)];
|
|
1859
|
+
const rowLines = formatLines(rows);
|
|
1750
1860
|
// The run is over once it is draining and nothing is left in flight: no
|
|
1751
1861
|
// open PR and no implementer still holding a claim. Printed last and read
|
|
1752
1862
|
// as actionable, so it never folds away: the stop it names is the run's
|
|
1753
1863
|
// last act, and only the controller can write it.
|
|
1754
1864
|
const over = run.draining !== null && prs.length === 0 && run.implLive === 0;
|
|
1755
|
-
if (over)
|
|
1865
|
+
if (over) rowLines.push(RUN_OVER);
|
|
1866
|
+
const lines = [...above, ...reported.map((r) => r.line), ...rowLines];
|
|
1756
1867
|
|
|
1757
1868
|
// The back-off streak and the fold digest, written on EVERY tick: an edge
|
|
1758
1869
|
// tick that dispatched is the clearest possible "there is work here". Digest,
|
|
1759
|
-
// not the lines themselves, so the file stays readable.
|
|
1760
|
-
|
|
1870
|
+
// not the lines themselves, so the file stays readable. A report line goes in
|
|
1871
|
+
// without its age.
|
|
1872
|
+
const digest = createHash("sha256").update([...above, ...reported.map((r) => r.key), ...rowLines].join("\n")).digest("hex");
|
|
1761
1873
|
const acts = actionable(rows) || over;
|
|
1762
1874
|
// `seen` is pruned to the live set on the same write; an empty one removes
|
|
1763
1875
|
// the key. A file that was degraded at this read is left byte-identical, so
|
|
@@ -1784,11 +1896,14 @@ function main() {
|
|
|
1784
1896
|
// `quiet`, and named on the folded line for as long as it stays live
|
|
1785
1897
|
// past its threshold. The digest already moves when its bucket does.
|
|
1786
1898
|
const aged = stale.map((s) => `; CHECK-LIVENESS ${s.member} persists`).join("");
|
|
1899
|
+
// A report waiting on disk persists the same way, for as long as its
|
|
1900
|
+
// member stays live.
|
|
1901
|
+
const settle = reported.filter((r) => r.settle).map((r) => `; SETTLE ${r.member} persists`).join("");
|
|
1787
1902
|
// The to-spec drops the same way: advice, and the one reason an empty
|
|
1788
1903
|
// shortlist is not "no work".
|
|
1789
1904
|
const specs = specsDropped(dropped);
|
|
1790
1905
|
const drops = specs ? `; ${specs} persists` : "";
|
|
1791
|
-
console.log(`fleet-tick: unchanged, nothing to act on (quiet=${prev.quiet + 1})${held}${aged}${drops} — full rows on the next change`);
|
|
1906
|
+
console.log(`fleet-tick: unchanged, nothing to act on (quiet=${prev.quiet + 1})${held}${aged}${settle}${drops} — full rows on the next change`);
|
|
1792
1907
|
return;
|
|
1793
1908
|
}
|
|
1794
1909
|
for (const line of lines) console.log(line);
|
package/scripts/pull.mjs
ADDED
|
@@ -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
|
-
/**
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
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.
|
|
112
|
-
test_paths: String(
|
|
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
|
};
|
package/skills/run-team/SKILL.md
CHANGED
|
@@ -52,7 +52,9 @@ attribute the gap to the member until it answers.** A member re-sending on a
|
|
|
52
52
|
named request should state the original's msg_id and that it is a re-send, which
|
|
53
53
|
is what distinguishes a lost message from a member that never sent one; a
|
|
54
54
|
controller that skips the ask cannot tell those apart and will guess wrong in
|
|
55
|
-
whichever direction its expectations point.
|
|
55
|
+
whichever direction its expectations point. The tick prints `SETTLE <member>`
|
|
56
|
+
for a report file on disk, so a missing message is read off that line before
|
|
57
|
+
anyone is pinged.
|
|
56
58
|
|
|
57
59
|
Note this cuts against the paragraph above only in appearance: the default stays
|
|
58
60
|
*send once*, because unprompted re-sends were measured 2-to-1 false. The ask is
|
|
@@ -366,6 +368,20 @@ label or a premise the maintainer can read.
|
|
|
366
368
|
Serial, main checkout, one Pull at a time. Never parallel, never inside a member —
|
|
367
369
|
concurrent `worktree add` and label writes race.
|
|
368
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
|
+
|
|
369
385
|
One free implementer slot is one Pull. The tick names the heads — `PULL #<n>
|
|
370
386
|
#<m>`, one per free slot — and each Pull runs this sequence on its head,
|
|
371
387
|
terminating in exactly one dispatch or an empty shortlist:
|