@feigi/fleet-ctl 3.34.0 → 3.35.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.34.0",
3
+ "version": "3.35.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,188 @@
1
+ #!/usr/bin/env node
2
+ // The consumer-repo pre-flight: what the fleet needs from this machine and
3
+ // this repository before a run-team run may shortlist or dispatch anything.
4
+ // run-team calls it at the start of Phase 0, so the checks run without the
5
+ // maintainer copying a block by hand.
6
+ //
7
+ // THE CHECKS are the CHECKS table below, one probe per row, each run with the
8
+ // main checkout as its cwd. A row passes when its argv exits 0 and, where the
9
+ // row says `want`, its stdout carries a line equal to that string — or, for
10
+ // `want: NONEMPTY`, any non-blank line. A row marked `warn` reports a miss as a
11
+ // WARN and passes: the CI-workflow row, because a repo without a workflow
12
+ // named CI still runs, its workflow named per call (`ci-state.mjs
13
+ // --workflow`) or declared absent (`--declare-no-ci`). Every other miss is a
14
+ // FAIL. Every row runs, so one run names every failure, not the first.
15
+ //
16
+ // No row names a manifest, a lockfile or a test runner: the consumer's Install
17
+ // step and Test entrypoint come from its Recipe, and the fleet keeps no table
18
+ // of supported technologies.
19
+ //
20
+ // THE MARKER. A run where nothing FAILed writes `.fleet/preflight.json`
21
+ // (resolved through fleet-dir.mjs, so a worktree and the main checkout name
22
+ // the same file) holding a sha256 of the check set: every row's name, argv,
23
+ // `want` and `warn`. A later run whose check set hashes the same prints
24
+ // PREFLIGHT SKIPPED and runs nothing — the rows cost several `gh` calls, and
25
+ // every controller tick already spends its own share of the secondary rate
26
+ // limit. A row added, removed or changed moves the hash, so the next run
27
+ // checks again. A failed run writes no marker. A marker that cannot be read
28
+ // is treated as absent. Deleting the file makes the next run check again.
29
+ //
30
+ // CLI (no arguments):
31
+ // preflight.mjs one `ok|WARN|FAIL <name>[: why]` line per row, then
32
+ // `PREFLIGHT OK`, `PREFLIGHT SKIPPED` or
33
+ // `PREFLIGHT FAILED: <names>`.
34
+ // Exit 0 passed or skipped, 1 a row failed, 2 could not run
35
+ // (an argument given, no repository) or could not write the
36
+ // marker after every row passed, the row lines printed first.
37
+ //
38
+ // Zero deps: node builtins and sibling scripts only.
39
+
40
+ import { spawnSync } from "node:child_process";
41
+ import { createHash } from "node:crypto";
42
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
43
+ import { dirname, join } from "node:path";
44
+ import { isCLI } from "./is-cli.mjs";
45
+ import { makeDie } from "./arg.mjs";
46
+ import { fleetFile } from "./fleet-dir.mjs";
47
+ import { gitEnv } from "./git-env.mjs";
48
+
49
+ export const MARKER_FILE = "preflight.json";
50
+ export const NONEMPTY = { nonEmpty: true };
51
+ const PROBE_TIMEOUT_MS = 60_000;
52
+ const NAME = "preflight";
53
+ const die = makeDie(NAME);
54
+
55
+ const label = (l) => ({ name: `label:${l}`, argv: ["gh", "label", "list", "--search", l, "--json", "name", "--jq", ".[].name"], want: l });
56
+
57
+ // A workflow file whose top-level `name:` is CI, matched the way ci-state.mjs
58
+ // reads a workflow's name: either quote style, and a trailing ` # comment` is
59
+ // not part of the name. A plain `^name: *CI *$` would WARN for a repo
60
+ // `--workflow CI` resolves without trouble.
61
+ const CI_NAMED = String.raw`grep -lE "^name:[[:space:]]*[\"']?CI[\"']?([[:space:]]+#.*)?[[:space:]]*\$" .github/workflows/*.y*ml`;
62
+
63
+ // A leading `~/` in an argv element is the user's home, expanded at run time
64
+ // and hashed as written, so the hash does not change with the box.
65
+ export const CHECKS = [
66
+ { name: "binary:node", argv: ["node", "-v"] },
67
+ { name: "binary:git", argv: ["git", "--version"] },
68
+ { name: "binary:gh", argv: ["gh", "--version"] },
69
+ { name: "binary:jq", argv: ["jq", "--version"] },
70
+ { name: "binary:python3", argv: ["python3", "--version"] },
71
+ { name: "binary:shasum", argv: ["shasum", "--version"] },
72
+ { name: "gh-auth", argv: ["gh", "auth", "status"] },
73
+ { name: "origin-remote", argv: ["git", "remote", "get-url", "origin"] },
74
+ { name: "origin-main", argv: ["git", "rev-parse", "--verify", "-q", "origin/main"] },
75
+ { name: "worktrees-ignored", argv: ["git", "check-ignore", "-q", ".worktrees/probe"] },
76
+ { name: "fleet-ignored", argv: ["git", "check-ignore", "-q", ".fleet/probe"] },
77
+ label("ready-for-agent"),
78
+ label("in-progress"),
79
+ label("ready-to-merge"),
80
+ { name: "allow-merge-commit", argv: ["gh", "api", "repos/{owner}/{repo}", "--jq", ".allow_merge_commit"], want: "true" },
81
+ { name: "ruleset", argv: ["gh", "api", "repos/{owner}/{repo}/rulesets", "--jq", ".[].name"], want: NONEMPTY },
82
+ { name: "ci-workflow", argv: ["sh", "-c", CI_NAMED], warn: true },
83
+ { name: "resolver", argv: ["~/.fleet/bin/fleet-run", "--root"] },
84
+ ];
85
+
86
+ /** sha256 over every row's name, argv, want and warn, in table order. */
87
+ export function checkSetHash(checks) {
88
+ const rows = checks.map(({ name, argv, want, warn }) => [name, argv, want, warn === true]);
89
+ return createHash("sha256").update(JSON.stringify(rows)).digest("hex");
90
+ }
91
+
92
+ const wanted = (want) => (want === NONEMPTY ? "a non-blank line" : `a line "${want}"`);
93
+
94
+ // One row: null when it passed, else why it did not.
95
+ function probe({ argv, want }, cwd, env, timeoutMs) {
96
+ const shown = argv.join(" ");
97
+ if (argv.some((a) => a.startsWith("~/")) && !env.HOME) return `${shown} did not run: HOME is not set`;
98
+ const [cmd, ...args] = argv.map((a) => (a.startsWith("~/") ? join(env.HOME, a.slice(2)) : a));
99
+ const r = spawnSync(cmd, args, { cwd, env, encoding: "utf8", timeout: timeoutMs });
100
+ // ENOENT and EACCES mean it never started; ETIMEDOUT and ENOBUFS mean it ran
101
+ // and was killed, so a hung `gh` is not reported as a missing binary.
102
+ if (r.error?.code === "ETIMEDOUT") return `${shown} timed out after ${timeoutMs}ms`;
103
+ if (r.error?.code === "ENOBUFS") return `${shown} output exceeded maxBuffer`;
104
+ if (r.error) return `${shown} did not run: ${r.error.code ?? r.error.message}`;
105
+ if (r.status !== 0) {
106
+ const last = r.stderr.trim().split("\n").at(-1);
107
+ return `${shown} ${r.signal ? `killed by ${r.signal}` : `exited ${r.status}`}${last ? `: ${last}` : ""}`;
108
+ }
109
+ if (want === undefined) return null;
110
+ const lines = r.stdout.split("\n").map((l) => l.trim());
111
+ const said = lines.filter(Boolean);
112
+ const hit = want === NONEMPTY ? said.length > 0 : lines.includes(want);
113
+ return hit ? null : `${shown} printed ${said.length ? JSON.stringify(said.join(" ")) : "nothing"}, want ${wanted(want)}`;
114
+ }
115
+
116
+ function readMarker(path) {
117
+ try {
118
+ return JSON.parse(readFileSync(path, "utf8"))?.checks;
119
+ } catch {
120
+ return null;
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Run `checks` from the main checkout `cwd` belongs to, unless the marker
126
+ * records this exact check set as passed. Writes the marker when no row
127
+ * failed. Throws FleetDirUnresolvable when `cwd` is in no repository.
128
+ *
129
+ * Returns `{ skipped, marker, results: [{name, warn, ok, why}], failed,
130
+ * writeError }`; `writeError` is null, or says why the marker could not be
131
+ * written — the rows have run by then, so they come back with it.
132
+ */
133
+ export function runPreflight({ checks = CHECKS, cwd = process.cwd(), env = process.env, timeoutMs = PROBE_TIMEOUT_MS } = {}) {
134
+ const marker = fleetFile(MARKER_FILE, { cwd });
135
+ const workspace = dirname(dirname(marker));
136
+ const hash = checkSetHash(checks);
137
+ if (readMarker(marker) === hash) return { skipped: true, marker, results: [], failed: [], writeError: null };
138
+
139
+ const childEnv = gitEnv({}, env);
140
+ const results = checks.map((c) => {
141
+ const why = probe(c, workspace, childEnv, timeoutMs);
142
+ return { name: c.name, warn: c.warn === true, ok: why === null, why };
143
+ });
144
+ const failed = results.filter((r) => !r.ok && !r.warn).map((r) => r.name);
145
+ let writeError = null;
146
+ if (failed.length === 0) {
147
+ const tmp = `${marker}.${process.pid}.tmp`;
148
+ try {
149
+ mkdirSync(dirname(marker), { recursive: true });
150
+ writeFileSync(tmp, `${JSON.stringify({ checks: hash, passed: new Date().toISOString() })}\n`);
151
+ try {
152
+ renameSync(tmp, marker);
153
+ } catch (e) {
154
+ rmSync(tmp, { force: true });
155
+ throw e;
156
+ }
157
+ } catch (e) {
158
+ writeError = `cannot write ${marker}: ${e?.code ?? e?.message}`;
159
+ }
160
+ }
161
+ return { skipped: false, marker, results, failed, writeError };
162
+ }
163
+
164
+ function main() {
165
+ // No flags at all, so not defineFlags: its unknown-flag refusal lists the
166
+ // accepted flags, and this script has none to list.
167
+ if (process.argv.length > 2) die(`takes no arguments, got: ${process.argv.slice(2).join(" ")}`);
168
+ let r;
169
+ try {
170
+ r = runPreflight();
171
+ } catch (e) {
172
+ die(e.message);
173
+ }
174
+ if (r.skipped) {
175
+ console.log(`PREFLIGHT SKIPPED: this check set already passed (${r.marker}; delete it to check again)`);
176
+ return;
177
+ }
178
+ for (const x of r.results) console.log(x.ok ? `ok ${x.name}` : `${x.warn ? "WARN" : "FAIL"} ${x.name}: ${x.why}`);
179
+ if (r.failed.length) {
180
+ console.log(`PREFLIGHT FAILED: ${r.failed.join(", ")}`);
181
+ process.exitCode = 1;
182
+ return;
183
+ }
184
+ if (r.writeError) die(r.writeError);
185
+ console.log(`PREFLIGHT OK (${r.marker})`);
186
+ }
187
+
188
+ if (isCLI(import.meta.url)) main();
@@ -288,6 +288,22 @@ phase, or in any later one, asks the maintainer which tickets to take.
288
288
  read that fails. `main-checkout.mjs --check` prints the same answer
289
289
  without a tick.
290
290
 
291
+ **Run the pre-flight, once the pin and the baseline are recorded.**
292
+ `~/.fleet/bin/fleet-run preflight.mjs` checks what this machine and this
293
+ repository must give the fleet — the binaries, `gh` auth, `origin/main`,
294
+ `.worktrees/` and `.fleet/` ignored, the three labels, merge commits on, a
295
+ ruleset, the Resolver — and prints one `ok`, `WARN` or `FAIL` line per
296
+ check, each naming its check. **Exit 1 stops the run:** no shortlist, no
297
+ dispatch. Report every `FAIL` line to the maintainer by its check's name;
298
+ the run starts again once they are fixed. Exit 2 means it could not run at
299
+ all, or every check passed and the marker could not be written, and stops
300
+ the run the same way. `WARN ci-workflow` stops nothing:
301
+ a repo with no workflow named CI still runs, its workflow named per call
302
+ with `--workflow` or declared absent with `--declare-no-ci`. A pass writes
303
+ `.fleet/preflight.json`, keyed to a hash of the check set, and every later
304
+ run prints `PREFLIGHT SKIPPED` without a single `gh` call until a check is
305
+ added or changed.
306
+
291
307
  **Check the merge gate against its spec, once the fast-forward has put the
292
308
  ratified spec in front of you.** Where the workspace checks a ruleset spec
293
309
  in, `.github/scripts/apply-ruleset.sh --check` compares it to the live gate