@feigi/fleet-ctl 3.110.3 → 3.111.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.
@@ -5,7 +5,7 @@ model: "@slow:high"
5
5
  spawns: task
6
6
  ---
7
7
 
8
- You are a fleet fix-applier. Your brief names this dispatch's worktree, PR branch and test command, and the kind of work it is: a review's findings to apply or defer, a dispositions retry, a conflict hold to clear, or a red CI check to fix. Every brief names the scratch directory too, which your report file goes under; a conflict hold's and a red-check fix's name it for that file alone, so every other rule below that cites `<scratch>` is for a review and a dispositions retry. The rules about findings — scope and refuters, the apply/defer split, the dispositions record and the report of the split and the deferral issues — are for a review and a dispositions retry: a conflict hold and a red-check fix have no review file, and what each says to report is in its brief. Every other rule below holds for every kind. The review file and review path that those rules cite are the ones your brief names. Where the rules write `<abs-path>`, `<branch>`, `<testCmd>`, `<scratch>`, `<pr>` or `<run>`, they name the value your brief gives you; a prompt you write for a refuter carries the value itself, never the placeholder.
8
+ You are a fleet fix-applier. Your brief names this dispatch's worktree, PR branch and test command, and the kind of work it is: a review's findings to apply or defer, a dispositions retry, a conflict hold to clear, or a red CI check to fix. Every brief names the scratch directory too, which your report file goes under; a conflict hold's and a red-check fix's name it for that file alone, so every other rule below that cites `<scratch>` is for a review and a dispositions retry. The rules about findings — scope and refuters, the apply/defer split, the dispositions record and the report of the split and the deferral issues — are for a review and a dispositions retry: a conflict hold and a red-check fix have no review file and write no dispositions record, so their report's `dispositionsRecord` is `null`, and what else each says to report is in its brief. Every other rule below holds for every kind. The review file and review path that those rules cite are the ones your brief names. Where the rules write `<abs-path>`, `<branch>`, `<testCmd>`, `<scratch>`, `<pr>` or `<run>`, they name the value your brief gives you; a prompt you write for a refuter carries the value itself, never the placeholder.
9
9
 
10
10
  **`edit` and `read` resolve a bare relative path against the SESSION ROOT —
11
11
  the controller's own main checkout — not against that worktree and not
@@ -332,8 +332,10 @@ Then write your report to the file your brief names,
332
332
  number on its `deferred` entry, the deferral issues as `{issue, subject}`
333
333
  entries — `filed` for every issue step 5 created, and `unrecorded` for one
334
334
  whose `ledger.mjs filed` failed twice, which the controller's settle records —
335
- `dispositionsRecord` your record's path and `testRun` your test result. Then
336
- send the one line your brief gives, `<your name>: <outcome> <path>`, and exit.
335
+ `dispositionsRecord` your record's path and `testRun` your test result, `null`
336
+ when no test run exists — a `no-op`, or a `failed` that never ran tests; a
337
+ non-null `testRun` always reflects a real run. Then send the one line your
338
+ brief gives, `<your name>: <outcome> <path>`, and exit.
337
339
  **Deferring everything is a normal
338
340
  outcome, not a stall:** nothing is then staged, `git commit` refuses an empty
339
341
  index, `~/.fleet/bin/fleet-run push-sync.mjs --branch <branch>` prints git's
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feigi/fleet-ctl",
3
- "version": "3.110.3",
3
+ "version": "3.111.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": {
@@ -1,9 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  // The Label map: the string the consumer's tracker uses for each Label role.
3
3
  // This module owns the map's cache format — the file, its validity rules, the
4
- // writer and the reader every role-reading script imports — and the `show`
5
- // verb. It derives nothing: the derivation step is `ensure`, which is not
6
- // here yet, so every refusal below names it as the step that writes the map.
4
+ // writer and the reader every role-reading script imports — and the verbs
5
+ // that read or derive it: `show`, and `ensure`, the derivation step that
6
+ // writes the map. Where the reader or `show` refuses the cache, the message
7
+ // names `ensure` as the step that writes the map.
7
8
  //
8
9
  // THE CACHE is `.fleet/labels.json`, resolved through fleet-dir.mjs's
9
10
  // fleetFile() like the pre-flight marker, so a member in its own worktree and
@@ -11,6 +12,7 @@
11
12
  // so the file is never committed, and it is never written by hand. Content:
12
13
  // derivedAt ISO time of the derivation that wrote it
13
14
  // table what the triage-label table said then: { present, rows: {role: string} }
15
+ // (a role with two rows of different strings maps to the array of them)
14
16
  // roles every Label role -> the string the tracker uses
15
17
  // origin every Label role -> "table" | "default" | "maintainer"
16
18
  //
@@ -28,6 +30,20 @@
28
30
  // It writes what it is handed: checking the map is its caller's step.
29
31
  //
30
32
  // CLI:
33
+ // label-map.mjs ensure the Label map derivation step. Reads the
34
+ // cache, the repository's triage-label table
35
+ // and the live label list (`gh label list`,
36
+ // every call), and prints the map as JSON
37
+ // (exit 0, writing the cache only when it
38
+ // derived one), or the question payload as
39
+ // JSON (exit 3, nothing written). It never
40
+ // creates a label. Exit 1: the table breaks
41
+ // the string rules, the message naming each
42
+ // role, the rule and the fix. Exit 2: no
43
+ // repository, the table not readable, the
44
+ // cache present but not readable or not
45
+ // writable, `gh` could not answer, the label
46
+ // list filled its limit, or a usage refusal.
31
47
  // label-map.mjs show [<role>] the mapped string for <role>, or the whole
32
48
  // `roles` object as JSON with no role.
33
49
  // Exit 0 printed; 1 no cache or an invalid one, the message naming `ensure`;
@@ -35,15 +51,17 @@
35
51
  //
36
52
  // Zero deps: node builtins and sibling scripts only.
37
53
 
54
+ import { spawnSync } from "node:child_process";
38
55
  import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
39
- import { dirname } from "node:path";
56
+ import { dirname, join } from "node:path";
40
57
  import { isCLI } from "./is-cli.mjs";
41
58
  import { makeDie, writeAll } from "./arg.mjs";
59
+ import { DEFAULT_GIT_TIMEOUT_MS, gitEnv } from "./git-env.mjs";
42
60
  import { fleetFile, FleetDirUnresolvable } from "./fleet-dir.mjs";
43
61
 
44
62
  const NAME = "label-map";
45
63
  const die = makeDie(NAME);
46
- const USAGE = "usage: label-map.mjs show [<role>]";
64
+ const USAGE = "usage: label-map.mjs ensure | show [<role>]";
47
65
  const MAX_LENGTH = 50;
48
66
  const DERIVE = "run `label-map.mjs ensure`, the Label map derivation step";
49
67
 
@@ -60,9 +78,11 @@ export const LABEL_ROLES = Object.freeze([
60
78
  "ready-to-merge",
61
79
  ]);
62
80
 
81
+ // `cause` is the filesystem's own error when the cache exists and cannot be
82
+ // read; an absent cache or one that does not parse has none.
63
83
  export class LabelMapUnreadable extends Error {
64
- constructor(message) {
65
- super(message);
84
+ constructor(message, options) {
85
+ super(message, options);
66
86
  this.name = "LabelMapUnreadable";
67
87
  }
68
88
  }
@@ -125,29 +145,41 @@ export function writeLabelMap(map, { cwd = process.cwd() } = {}) {
125
145
  return file;
126
146
  }
127
147
 
128
- /**
129
- * The `roles` object (every Label role -> its string) of the cache of the
130
- * repository `cwd` belongs to. Throws LabelMapUnreadable, its message naming
131
- * `ensure`, when the cache is absent, does not parse, lacks a role or breaks
132
- * the string rules; throws FleetDirUnresolvable outside a repository.
133
- */
134
- export function readLabelMap({ cwd = process.cwd() } = {}) {
148
+ // The parsed cache of the repository `cwd` belongs to, with its path. Throws
149
+ // LabelMapUnreadable, its message naming `ensure`, when the file is absent,
150
+ // cannot be read or does not parse; FleetDirUnresolvable outside a repository.
151
+ function loadCache(cwd) {
135
152
  const file = fleetFile(LABEL_MAP_FILE, { cwd });
136
153
  let text;
137
154
  try {
138
155
  text = readFileSync(file, "utf8");
139
156
  } catch (e) {
140
157
  if (e.code === "ENOENT") throw new LabelMapUnreadable(`no Label map at ${file}: ${DERIVE}`);
141
- throw new LabelMapUnreadable(`cannot read the Label map at ${file} (${e.code ?? e.message}): ${DERIVE}`);
158
+ throw new LabelMapUnreadable(`cannot read the Label map at ${file} (${e.code ?? e.message}): ${DERIVE}`, { cause: e });
142
159
  }
143
- let cache;
144
160
  try {
145
- cache = JSON.parse(text);
161
+ return { file, cache: JSON.parse(text) };
146
162
  } catch (e) {
147
163
  throw new LabelMapUnreadable(`the Label map at ${file} does not parse (${e.message}): ${DERIVE}`);
148
164
  }
165
+ }
166
+
167
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
168
+ const own = (record, key) => (Object.hasOwn(record, key) ? record[key] : undefined);
169
+
170
+ // The eight roles of `roles`, keyed in role order.
171
+ const inRoleOrder = (roles) => Object.fromEntries(LABEL_ROLES.map((role) => [role, roles[role]]));
172
+
173
+ /**
174
+ * The `roles` object (every Label role -> its string) of the cache of the
175
+ * repository `cwd` belongs to. Throws LabelMapUnreadable, its message naming
176
+ * `ensure`, when the cache is absent, does not parse, lacks a role or breaks
177
+ * the string rules; throws FleetDirUnresolvable outside a repository.
178
+ */
179
+ export function readLabelMap({ cwd = process.cwd() } = {}) {
180
+ const { file, cache } = loadCache(cwd);
149
181
  const roles = cache?.roles;
150
- if (roles === null || typeof roles !== "object" || Array.isArray(roles)) {
182
+ if (!isRecord(roles)) {
151
183
  throw new LabelMapUnreadable(`the Label map at ${file} holds no \`roles\` object: ${DERIVE}`);
152
184
  }
153
185
  const faults = labelStringFaults(roles);
@@ -155,12 +187,392 @@ export function readLabelMap({ cwd = process.cwd() } = {}) {
155
187
  const why = faults.map(({ role, rule }) => `${role}: ${rule}`).join("; ");
156
188
  throw new LabelMapUnreadable(`the Label map at ${file} is invalid — ${why}: ${DERIVE}`);
157
189
  }
158
- return Object.fromEntries(LABEL_ROLES.map((role) => [role, roles[role]]));
190
+ return inRoleOrder(roles);
159
191
  }
160
192
 
161
- function main() {
162
- const [verb, ...rest] = process.argv.slice(2);
163
- if (verb !== "show") die(verb === undefined ? USAGE : `unknown verb ${JSON.stringify(verb)}; ${USAGE}`);
193
+ // THE TABLE (TRIAGE_TABLE_FILE, under the checkout's top level): the
194
+ // first table whose second header cell, backticks and whitespace stripped, is
195
+ // TABLE_HEADER. A row is a table line whose first cell, stripped the same way,
196
+ // is a Label role and whose stripped second cell is not empty. `rows` maps a
197
+ // role to its string; a role with two rows of different strings maps to the
198
+ // array of them, in file order, so the cache's `table` still shows a changed
199
+ // second row. Any other table in the file is not read.
200
+ export const TRIAGE_TABLE_FILE = join("docs", "agents", "triage-labels.md");
201
+ const TABLE_HEADER = "Label in our tracker";
202
+
203
+ /** The tracker's answer could not be had, or the table could not be read: `ensure`'s exit 2. */
204
+ export class LabelMapUnavailable extends Error {
205
+ constructor(message) {
206
+ super(message);
207
+ this.name = "LabelMapUnavailable";
208
+ }
209
+ }
210
+
211
+ const stripCell = (cell) => cell.replace(/^[\s`]+|[\s`]+$/g, "");
212
+
213
+ // The cells of a markdown table line — any line holding an unescaped `|`, its
214
+ // leading and trailing pipes optional as GFM has them — or null for any other.
215
+ function cellsOf(line) {
216
+ let inner = line.trim();
217
+ if (!/(?<!\\)\|/.test(inner)) return null;
218
+ if (inner.startsWith("|")) inner = inner.slice(1);
219
+ if (inner.endsWith("|") && !inner.endsWith("\\|")) inner = inner.slice(0, -1);
220
+ return inner.split(/(?<!\\)\|/).map((cell) => cell.replace(/\\\|/g, "|"));
221
+ }
222
+
223
+ const isSeparator = (cells) => cells !== null && cells.every((cell) => /^\s*:?-+:?\s*$/.test(cell));
224
+
225
+ /** The `{ present: true, rows }` the triage-label table text says. */
226
+ export function parseTriageTable(text) {
227
+ const lines = text.split(/\r?\n/).map(cellsOf);
228
+ const found = new Map();
229
+ for (let i = 0; i + 1 < lines.length; i++) {
230
+ const head = lines[i];
231
+ if (head === null || head.length < 2 || !isSeparator(lines[i + 1]) || stripCell(head[1]) !== TABLE_HEADER) continue;
232
+ for (let j = i + 2; j < lines.length && lines[j] !== null; j++) {
233
+ const role = stripCell(lines[j][0]);
234
+ const value = stripCell(lines[j][1] ?? "");
235
+ if (!LABEL_ROLES.includes(role) || value === "") continue;
236
+ const strings = found.get(role) ?? [];
237
+ if (!strings.includes(value)) strings.push(value);
238
+ found.set(role, strings);
239
+ }
240
+ break;
241
+ }
242
+ const rows = {};
243
+ for (const role of LABEL_ROLES) {
244
+ const strings = found.get(role);
245
+ if (strings) rows[role] = strings.length === 1 ? strings[0] : strings;
246
+ }
247
+ return { present: true, rows };
248
+ }
249
+
250
+ /**
251
+ * The top level of the checkout `cwd` is in and the table it holds:
252
+ * `{ top, table }`, `table` being `{ present: false, rows: {} }` when the file
253
+ * is absent. Throws FleetDirUnresolvable outside a work tree and
254
+ * LabelMapUnavailable when the file exists and cannot be read.
255
+ */
256
+ export function readTriageTable({ cwd = process.cwd() } = {}) {
257
+ const r = spawnSync("git", ["rev-parse", "--show-toplevel"], { cwd, encoding: "utf8", env: gitEnv(), timeout: DEFAULT_GIT_TIMEOUT_MS });
258
+ const top = (r.stdout ?? "").trim();
259
+ if (r.status !== 0 || top === "") {
260
+ const why = (r.error?.message ?? (r.stderr ?? "").trim()) || `exit ${r.status}`;
261
+ throw new FleetDirUnresolvable(`could not resolve --show-toplevel: ${why}`);
262
+ }
263
+ const file = join(top, TRIAGE_TABLE_FILE);
264
+ let text;
265
+ try {
266
+ text = readFileSync(file, "utf8");
267
+ } catch (e) {
268
+ if (e.code === "ENOENT") return { top, table: { present: false, rows: {} } };
269
+ throw new LabelMapUnavailable(`cannot read ${file} (${e.code ?? e.message})`);
270
+ }
271
+ return { top, table: parseTriageTable(text) };
272
+ }
273
+
274
+ // The live label list is capped at this many labels per call: a list that
275
+ // fills the limit may be cut, and is a refusal (the capped-list rule).
276
+ export const LIVE_LABEL_LIMIT = 1000;
277
+ // `gh label list` is killed after this long, so a `gh` hung on auth or the
278
+ // network is `ensure`'s exit 2 rather than a hang.
279
+ const GH_TIMEOUT_MS = 60_000;
280
+
281
+ /**
282
+ * The names of every label the tracker has, from `gh label list`. Throws
283
+ * LabelMapUnavailable when `gh` cannot answer, answers something else, or
284
+ * the list fills LIVE_LABEL_LIMIT.
285
+ */
286
+ export function readLiveLabels({ cwd = process.cwd() } = {}) {
287
+ const args = ["label", "list", "--limit", String(LIVE_LABEL_LIMIT), "--json", "name"];
288
+ const r = spawnSync("gh", args, { cwd, encoding: "utf8", env: gitEnv({ GH_REPO: "" }), stdio: ["ignore", "pipe", "pipe"], timeout: GH_TIMEOUT_MS });
289
+ if (r.error?.code === "ETIMEDOUT") throw new LabelMapUnavailable(`gh label list timed out after ${GH_TIMEOUT_MS / 1000}s`);
290
+ if (r.error) throw new LabelMapUnavailable(`could not run gh: ${r.error.message}`);
291
+ if (r.signal) throw new LabelMapUnavailable(`gh was killed by ${r.signal}`);
292
+ if (r.status !== 0) {
293
+ throw new LabelMapUnavailable(`gh label list failed: ${(r.stderr ?? "").trim().split("\n")[0] || `exit ${r.status}`}`);
294
+ }
295
+ let rows;
296
+ try {
297
+ rows = JSON.parse(r.stdout);
298
+ } catch (e) {
299
+ throw new LabelMapUnavailable(`gh label list did not answer JSON (${e.message})`);
300
+ }
301
+ if (!Array.isArray(rows) || !rows.every((row) => isRecord(row) && typeof row.name === "string")) {
302
+ throw new LabelMapUnavailable("gh label list did not answer a list of { name }");
303
+ }
304
+ if (rows.length >= LIVE_LABEL_LIMIT) {
305
+ throw new LabelMapUnavailable(
306
+ `exactly ${rows.length} labels — the list is capped and may be truncated; a map derived from a cut list is not an answer`,
307
+ );
308
+ }
309
+ return rows.map((row) => row.name);
310
+ }
311
+
312
+ // A table's identity for "the table now in the repo equals the cached one":
313
+ // role order, so key order in the file does not matter; null for a malformed one.
314
+ function tableKey(table) {
315
+ if (!isRecord(table) || typeof table.present !== "boolean" || !isRecord(table.rows)) return null;
316
+ if (!Object.keys(table.rows).every((key) => LABEL_ROLES.includes(key))) return null;
317
+ return JSON.stringify([table.present, LABEL_ROLES.map((role) => own(table.rows, role) ?? null)]);
318
+ }
319
+
320
+ const lc = (text) => text.toLowerCase();
321
+ const compare = (a, b) => (lc(a) < lc(b) ? -1 : lc(a) > lc(b) ? 1 : a < b ? -1 : a > b ? 1 : 0);
322
+ // A label equals a role's name after lowercasing and dropping every
323
+ // non-alphanumeric character: `on-hold` for `onhold`, `Ready For Agent` for
324
+ // `ready-for-agent`.
325
+ const squash = (text) => lc(text).replace(/[^\p{L}\p{N}]/gu, "");
326
+
327
+ /**
328
+ * Derive the Label map from `table` (`{ present, rows }`), `live` (the
329
+ * tracker's label names) and `cache` (the parsed cache, any JSON value, or
330
+ * null; only its `roles` and `origin` records are read). Pure: no file, no
331
+ * `gh`. One of
332
+ * { kind: "certain", roles, origin } every role certain, the map valid
333
+ * { kind: "break", faults: [{ role, rule, fix }] } the table breaks the string rules
334
+ * { kind: "uncertain", payload: { certain, uncertain } } the maintainer decides
335
+ */
336
+ export function deriveLabelMap({ table, live, cache }) {
337
+ const exact = new Set(live);
338
+ const byKey = new Map();
339
+ for (const name of live) if (!byKey.has(lc(name))) byKey.set(lc(name), name);
340
+ // The live label a string names, in the tracker's own spelling.
341
+ const liveOf = (text) => (exact.has(text) ? text : byKey.get(lc(text)));
342
+ const rowsOf = (role) => (Object.hasOwn(table.rows, role) ? [].concat(table.rows[role]) : []);
343
+
344
+ const cacheRoles = isRecord(cache?.roles) ? cache.roles : {};
345
+ const cacheOrigin = isRecord(cache?.origin) ? cache.origin : {};
346
+ // The cache's strings decide which roles are gone, valid or not; only a
347
+ // cache whose strings pass the string rules carries answers. A role the
348
+ // cache lacks is no string to break them, so it drops no answer.
349
+ const cacheValid = labelStringFaults(cacheRoles).every(({ rule }) => rule === "missing");
350
+ const was = (role) => {
351
+ const text = own(cacheRoles, role);
352
+ return typeof text === "string" && text.trim() !== "" && liveOf(text) === undefined ? text : undefined;
353
+ };
354
+
355
+ const rowKeys = new Set(LABEL_ROLES.flatMap((role) => rowsOf(role).map(lc)));
356
+ // Live near matches of `role` the maintainer may be offered: none that the
357
+ // string rules reject, none that a table row or a carried answer holds.
358
+ const nearOf = (role, held) =>
359
+ [...exact]
360
+ .filter((name) => squash(name) === squash(role) && lc(name) !== lc(role) && stringFault(name) === null && !held.has(lc(name)))
361
+ .sort(compare);
362
+ const heldBy = (carried) => new Set([...rowKeys, ...[...carried].map((role) => lc(cacheRoles[role]))]);
363
+
364
+ // Roles with no row that the cache answered as the maintainer, the answer
365
+ // still live: the answers that carry over, before any is dropped.
366
+ const candidates = cacheValid
367
+ ? LABEL_ROLES.filter(
368
+ (role) =>
369
+ rowsOf(role).length === 0 &&
370
+ own(cacheOrigin, role) === "maintainer" &&
371
+ Object.hasOwn(cacheRoles, role) &&
372
+ liveOf(cacheRoles[role]) !== undefined,
373
+ )
374
+ : [];
375
+
376
+ // What each role with no row and no carried answer resolves to by its
377
+ // default: its certain string, or its suggestion.
378
+ const resolve = (carried, dropped) => {
379
+ const held = heldBy(carried);
380
+ const out = new Map();
381
+ for (const role of LABEL_ROLES) {
382
+ if (rowsOf(role).length || carried.has(role)) continue;
383
+ const def = liveOf(role);
384
+ const near = nearOf(role, held);
385
+ // A dropped answer and a gone label are asked again, a live default or not.
386
+ const askAgain = dropped.has(role) || was(role) !== undefined;
387
+ if (def !== undefined && near.length === 0 && !askAgain) out.set(role, { certain: true, string: def, origin: "default" });
388
+ else if (def !== undefined) out.set(role, { certain: false, string: def, origin: "default" });
389
+ else if (near.length) out.set(role, { certain: false, string: near[0], origin: "near-match" });
390
+ else out.set(role, { certain: false, string: role, origin: "default" });
391
+ }
392
+ return out;
393
+ };
394
+
395
+ // An answer is dropped when a table row names its string, or another role
396
+ // resolves to it as its default; dropping one can make its role resolve to
397
+ // its default and so drop another, so this runs until nothing more drops,
398
+ // starting with every answer carried. A carried role has no row and is
399
+ // never in `resolved`, so neither check can find the role itself.
400
+ const dropped = new Map();
401
+ let carried;
402
+ let resolved;
403
+ for (;;) {
404
+ carried = new Set(candidates.filter((role) => !dropped.has(role)));
405
+ resolved = resolve(carried, dropped);
406
+ let changed = false;
407
+ for (const role of carried) {
408
+ const key = lc(cacheRoles[role]);
409
+ let claimedBy = null;
410
+ for (const other of LABEL_ROLES) {
411
+ const row = rowsOf(other).find((text) => lc(text) === key);
412
+ if (row !== undefined) {
413
+ claimedBy = { role: other, string: row, by: "table" };
414
+ break;
415
+ }
416
+ }
417
+ if (claimedBy === null) {
418
+ for (const [other, verdict] of resolved) {
419
+ if (lc(verdict.string) === key) {
420
+ claimedBy = { role: other, string: verdict.string, by: "default" };
421
+ break;
422
+ }
423
+ }
424
+ }
425
+ if (claimedBy !== null) {
426
+ dropped.set(role, claimedBy);
427
+ changed = true;
428
+ }
429
+ }
430
+ if (!changed) break;
431
+ }
432
+
433
+ // The string rules on the verdicts, before any suggestion is withheld.
434
+ const faults = [];
435
+ const fixRow = (role) => `edit the ${role} row in ${TRIAGE_TABLE_FILE}`;
436
+ const firstRowOwner = new Map();
437
+ for (const role of LABEL_ROLES) {
438
+ const rows = rowsOf(role);
439
+ for (const text of rows) {
440
+ const rule = stringFault(text);
441
+ if (rule) faults.push({ role, rule: `its row names ${JSON.stringify(text)}, which is not a valid label string (${rule})`, fix: fixRow(role) });
442
+ }
443
+ if (rows.length === 0 || stringFault(rows[0])) continue;
444
+ const owner = firstRowOwner.get(lc(rows[0]));
445
+ if (owner !== undefined) {
446
+ faults.push({
447
+ role,
448
+ rule: `its row names ${JSON.stringify(rows[0])}, the same string as the ${owner} row (compared ignoring case)`,
449
+ fix: `edit the ${role} row or the ${owner} row in ${TRIAGE_TABLE_FILE}`,
450
+ });
451
+ } else {
452
+ firstRowOwner.set(lc(rows[0]), role);
453
+ }
454
+ // `resolved` holds only roles with no row, so never this one.
455
+ for (const [other, verdict] of resolved) {
456
+ if (lc(verdict.string) === lc(rows[0])) {
457
+ faults.push({
458
+ role,
459
+ rule: `its row names ${JSON.stringify(rows[0])}, the string ${other} resolves to as its default (${other} has no row and no answer of its own)`,
460
+ fix: `${fixRow(role)}, or run \`label-map.mjs set ${other}=<label>\` to give ${other} another label`,
461
+ });
462
+ }
463
+ }
464
+ }
465
+ if (faults.length) return { kind: "break", faults };
466
+
467
+ const held = heldBy(carried);
468
+ const certain = {};
469
+ const origin = {};
470
+ const uncertain = [];
471
+ for (const role of LABEL_ROLES) {
472
+ const rows = rowsOf(role);
473
+ let settled = null;
474
+ let suggested = null;
475
+ if (rows.length) {
476
+ const live1 = rows.length === 1 ? liveOf(rows[0]) : undefined;
477
+ if (live1 !== undefined) settled = { string: live1, origin: "table" };
478
+ else suggested = { string: liveOf(rows[0]) ?? rows[0], origin: "table" };
479
+ } else if (carried.has(role)) {
480
+ settled = { string: liveOf(cacheRoles[role]), origin: "maintainer" };
481
+ } else {
482
+ const verdict = resolved.get(role);
483
+ if (verdict.certain) settled = { string: verdict.string, origin: "default" };
484
+ else suggested = { string: verdict.string, origin: verdict.origin };
485
+ }
486
+ if (settled !== null) {
487
+ certain[role] = settled.string;
488
+ origin[role] = settled.origin;
489
+ continue;
490
+ }
491
+ // A gone role is never offered the string that vanished back.
492
+ const vanished = was(role);
493
+ const withheld = vanished !== undefined && lc(suggested.string) === lc(vanished);
494
+ const entry = {
495
+ role,
496
+ suggestion: withheld ? null : suggested.string,
497
+ origin: withheld ? "gone" : suggested.origin,
498
+ candidates: nearOf(role, held),
499
+ exists: !withheld && liveOf(suggested.string) !== undefined,
500
+ };
501
+ if (vanished !== undefined) entry.was = vanished;
502
+ if (dropped.has(role)) entry.claimedBy = dropped.get(role);
503
+ uncertain.push(entry);
504
+ }
505
+ if (uncertain.length) return { kind: "uncertain", payload: { certain, uncertain } };
506
+ // Nothing above lets two certain roles share a string; this is the belt to
507
+ // that suspenders, the same rules the reader and the writer's caller hold.
508
+ const broken = labelStringFaults(certain);
509
+ if (broken.length) return { kind: "break", faults: broken.map(({ role, rule }) => ({ role, rule, fix: fixRow(role) })) };
510
+ return { kind: "certain", roles: certain, origin };
511
+ }
512
+
513
+ /**
514
+ * The Label map derivation step: `{ code, stdout, stderr }` for the CLI to
515
+ * print. 0 the map (the cache valid as it stands, or derived and written),
516
+ * 1 the table breaks the string rules, 3 the question payload. Writes only
517
+ * the cache, and only on code 0 from a derivation; never creates a label.
518
+ * Throws FleetDirUnresolvable and LabelMapUnavailable, both exit 2.
519
+ */
520
+ export function ensureLabelMap({ cwd = process.cwd() } = {}) {
521
+ const { top, table } = readTriageTable({ cwd });
522
+ const live = readLiveLabels({ cwd: top });
523
+ let cache = null;
524
+ try {
525
+ cache = loadCache(cwd).cache;
526
+ } catch (e) {
527
+ if (!(e instanceof LabelMapUnreadable)) throw e;
528
+ // Absent or not parsing is derived again; a cache that exists and cannot
529
+ // be read may hold maintainer answers, so it is never written over.
530
+ if (e.cause) throw new LabelMapUnavailable(`cannot read the Label map at ${e.cause.path} (${e.cause.code ?? e.cause.message}); nothing written`);
531
+ }
532
+ const mapOf = (roles) => JSON.stringify(inRoleOrder(roles));
533
+ // Valid as it stands: every mapped string is in the tracker's own spelling,
534
+ // so a label whose case was changed after caching is derived again.
535
+ if (
536
+ isRecord(cache) &&
537
+ isRecord(cache.roles) &&
538
+ labelStringFaults(cache.roles).length === 0 &&
539
+ tableKey(cache.table) === tableKey(table) &&
540
+ LABEL_ROLES.every((role) => live.includes(cache.roles[role]))
541
+ ) {
542
+ return { code: 0, stdout: mapOf(cache.roles) };
543
+ }
544
+ const derived = deriveLabelMap({ table, live, cache });
545
+ if (derived.kind === "break") {
546
+ const lines = derived.faults.map(({ role, rule, fix }) => ` ${role}: ${rule}. Fix: ${fix}`);
547
+ return {
548
+ code: 1,
549
+ stderr: `\n${NAME}: ${TRIAGE_TABLE_FILE} gives a Label map that breaks the string rules; nothing written, nothing created:\n${lines.join("\n")}\n`,
550
+ };
551
+ }
552
+ if (derived.kind === "uncertain") return { code: 3, stdout: JSON.stringify(derived.payload) };
553
+ try {
554
+ writeLabelMap({ derivedAt: new Date().toISOString(), table, roles: derived.roles, origin: derived.origin }, { cwd });
555
+ } catch (e) {
556
+ throw new LabelMapUnavailable(`cannot write the Label map: ${e.message}`);
557
+ }
558
+ return { code: 0, stdout: mapOf(derived.roles) };
559
+ }
560
+
561
+ function ensure(rest) {
562
+ if (rest.length) die(`ensure takes no arguments, got: ${rest.join(" ")}; ${USAGE}`);
563
+ let result;
564
+ try {
565
+ result = ensureLabelMap();
566
+ } catch (e) {
567
+ if (e instanceof FleetDirUnresolvable || e instanceof LabelMapUnavailable) die(e.message);
568
+ throw e;
569
+ }
570
+ if (result.stderr) writeAll(2, result.stderr);
571
+ if (result.stdout !== undefined) console.log(result.stdout);
572
+ process.exitCode = result.code;
573
+ }
574
+
575
+ function show(rest) {
164
576
  if (rest.length > 1) die(`show takes at most one role, got: ${rest.join(" ")}; ${USAGE}`);
165
577
  const [role] = rest;
166
578
  if (role !== undefined && !LABEL_ROLES.includes(role)) {
@@ -179,4 +591,11 @@ function main() {
179
591
  console.log(role === undefined ? JSON.stringify(roles) : roles[role]);
180
592
  }
181
593
 
594
+ function main() {
595
+ const [verb, ...rest] = process.argv.slice(2);
596
+ if (verb === "ensure") return ensure(rest);
597
+ if (verb === "show") return show(rest);
598
+ die(verb === undefined ? USAGE : `unknown verb ${JSON.stringify(verb)}; ${USAGE}`);
599
+ }
600
+
182
601
  if (isCLI(import.meta.url)) main();
@@ -26,7 +26,12 @@
26
26
  // is no bail`, gives no reason in `bailDetail`, or names a `pr` or a
27
27
  // `head`, as `$.pr: <pr> is not null, with outcome "blocked" — a block
28
28
  // reports no PR`, or whose `bailed` outcome names a `pr` or a `head`, as
29
- // `$.pr: <pr> is not null, with outcome "bailed" — a bail reports no PR`
29
+ // `$.pr: <pr> is not null, with outcome "bailed" — a bail reports no PR`,
30
+ // and a fix-pr report whose `applied` outcome names no `testRun`, as
31
+ // `$.testRun: null, with outcome "applied" — an applied fix reports the
32
+ // test run behind it`, or that defers a `refuted` finding with no
33
+ // `dispositionsRecord`, as `$.dispositionsRecord: null, with a refuted
34
+ // deferral at $.deferred[<i>] — settle reads its reason from that record`
30
35
  // 2 usage: no or unknown subcommand, a wrong argument count, an unknown
31
36
  // family, any flag; or <file> could not be read; or print could not
32
37
  // write the schema to stdout. Refused on stderr, nothing on stdout
@@ -141,8 +146,10 @@ export const SCHEMAS = {
141
146
  deferred: listOf({ bucket: str, index: int, issue: id }),
142
147
  filed: issues,
143
148
  unrecorded: issues,
144
- dispositionsRecord: { type: "string", pattern: "^/" },
145
- testRun: obj({ cmd: str, exit: int, tests: int, cancelled: int }),
149
+ // `null` where nothing exists: a conflict hold or a red-check fix writes no
150
+ // dispositions record, and a no-op or a failed fix may have run no tests.
151
+ dispositionsRecord: { type: ["string", "null"], pattern: "^/" },
152
+ testRun: obj({ cmd: str, exit: int, tests: int, cancelled: int }, ["object", "null"]),
146
153
  confirmation: strings,
147
154
  }),
148
155
  finisher: report({
@@ -188,9 +195,12 @@ export function mergeBotVerdicts(report) {
188
195
  // text that is not only whitespace, and names no `pr` or `head`, since a block
189
196
  // reports no PR; a `bailed` outcome names no `pr` or `head` either, since a
190
197
  // bail is the pre-code outcome — a PR the member opened is outcome `pr`, which
191
- // settle checks. For a merge-bot report: each PR gets one verdict — merged,
192
- // held, conflict-held or refused — the last it reached in the pass, so a PR
193
- // named twice, in one list or in two, is a violation at its second entry.
198
+ // settle checks. For a fix-pr report: an `applied` outcome names its
199
+ // `testRun`, the run behind the commit, and a `refuted` deferral, under any
200
+ // outcome, names the `dispositionsRecord` settle reads its reason from. For a
201
+ // merge-bot report: each PR gets one verdict — merged, held, conflict-held or
202
+ // refused — the last it reached in the pass, so a PR named twice, in one list
203
+ // or in two, is a violation at its second entry.
194
204
  export function reportViolation(family, value) {
195
205
  const found = validate(SCHEMAS[family], value);
196
206
  if (found !== null) return found;
@@ -206,6 +216,15 @@ export function reportViolation(family, value) {
206
216
  if (value[field] !== null) return `$.${field}: ${show(value[field])} is not null, with outcome "bailed" — a bail reports no PR`;
207
217
  }
208
218
  }
219
+ if (family === "fix-pr") {
220
+ if (value.outcome === "applied" && value.testRun === null) {
221
+ return '$.testRun: null, with outcome "applied" — an applied fix reports the test run behind it';
222
+ }
223
+ const refuted = value.deferred.findIndex((d) => d.bucket === "refuted");
224
+ if (refuted !== -1 && value.dispositionsRecord === null) {
225
+ return `$.dispositionsRecord: null, with a refuted deferral at $.deferred[${refuted}] — settle reads its reason from that record`;
226
+ }
227
+ }
209
228
  if (family !== "merge-bot") return null;
210
229
  const first = new Map();
211
230
  for (const { pr, path } of mergeBotVerdicts(value)) {
@@ -136,8 +136,12 @@ recorded nothing — so run it again with `timeout: 0` on the call.
136
136
 
137
137
  Your report is a file, `<scratch>/reports/<your name>.json`, `<your name>` the
138
138
  `fix-pr-` name you were dispatched as, in the shape
139
- `~/.fleet/bin/fleet-run report-schema.mjs print fix-pr` prints. Write it
140
- before your final message, and send nothing until
139
+ `~/.fleet/bin/fleet-run report-schema.mjs print fix-pr` prints. A field with
140
+ nothing real to point at is `null`: `dispositionsRecord` for a conflict hold or
141
+ a red-check fix, which write no dispositions record, and `testRun` when no test
142
+ run exists — a `no-op`, or a `failed` that never ran tests. A non-null value
143
+ always reflects a real record or a real run. Write the report before your
144
+ final message, and send nothing until
141
145
  `~/.fleet/bin/fleet-run report-schema.mjs validate fix-pr <scratch>/reports/<your name>.json`
142
146
  answers `valid`. Your final message is then one line,
143
147
  `<your name>: <outcome> <scratch>/reports/<your name>.json`, `<outcome>` the