@feigi/fleet-ctl 3.112.0 → 3.113.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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/scripts/label-map.mjs +211 -35
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feigi/fleet-ctl",
3
- "version": "3.112.0",
3
+ "version": "3.113.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": {
@@ -2,9 +2,10 @@
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
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.
5
+ // that read, derive or write it: `show`, `ensure`, the derivation step that
6
+ // writes the map when nothing is uncertain, and `set`, which writes it from a
7
+ // derivation plus the maintainer's answer. Where the reader or `show`
8
+ // refuses the cache, the message names `ensure` as the step that writes the map.
8
9
  //
9
10
  // THE CACHE is `.fleet/labels.json`, resolved through fleet-dir.mjs's
10
11
  // fleetFile() like the pre-flight marker, so a member in its own worktree and
@@ -44,10 +45,38 @@
44
45
  // cache present but not readable or not
45
46
  // writable, `gh` could not answer, the label
46
47
  // list filled its limit, or a usage refusal.
48
+ // label-map.mjs set [--accept-suggestions] [--create] [<role>=<label> …]
49
+ // writes the map from a fresh derivation (as
50
+ // `ensure` runs it) plus the answer: each
51
+ // pair settles its role before the table is
52
+ // consulted, `--accept-suggestions` fills
53
+ // every other uncertain role with its
54
+ // suggestion, and an uncertain role left
55
+ // uncovered (a role with no suggestion
56
+ // included) is a refusal naming it. A string
57
+ // not in the tracker is created with
58
+ // `gh label create <string>` (no colour)
59
+ // only under `--create`, an "already exists"
60
+ // answer counting as existing, and the live
61
+ // list is read again so the map stores the
62
+ // tracker's spelling; without `--create` it
63
+ // is a refusal naming it. The cache is
64
+ // written (origin `maintainer` for every role
65
+ // a pair or `--accept-suggestions` settled)
66
+ // only when every mapped string exists live;
67
+ // exit 0 prints the map. Exit 1: a refusal
68
+ // naming the role and the rule, nothing
69
+ // written, nothing created. Exit 2: an
70
+ // unknown role, a malformed pair, a role
71
+ // answered twice or an unknown flag; no
72
+ // repository, `gh` could not answer, or the
73
+ // cache not readable or writable.
47
74
  // label-map.mjs show [<role>] the mapped string for <role>, or the whole
48
75
  // `roles` object as JSON with no role.
49
- // Exit 0 printed; 1 no cache or an invalid one, the message naming `ensure`;
50
- // 2 an unknown role, no repository, or a usage refusal (any other verb).
76
+ // `show` exits 0 printed; 1 no cache or an
77
+ // invalid one, the message naming `ensure`;
78
+ // 2 an unknown role or no repository. Any
79
+ // other verb is a usage refusal, exit 2.
51
80
  //
52
81
  // Zero deps: node builtins and sibling scripts only.
53
82
 
@@ -61,7 +90,7 @@ import { fleetFile, FleetDirUnresolvable } from "./fleet-dir.mjs";
61
90
 
62
91
  const NAME = "label-map";
63
92
  const die = makeDie(NAME);
64
- const USAGE = "usage: label-map.mjs ensure | show [<role>]";
93
+ const USAGE = "usage: label-map.mjs ensure | set [--accept-suggestions] [--create] [<role>=<label> …] | show [<role>]";
65
94
  const MAX_LENGTH = 50;
66
95
  const DERIVE = "run `label-map.mjs ensure`, the Label map derivation step";
67
96
 
@@ -278,6 +307,12 @@ export const LIVE_LABEL_LIMIT = 1000;
278
307
  // network is `ensure`'s exit 2 rather than a hang.
279
308
  const GH_TIMEOUT_MS = 60_000;
280
309
 
310
+ // `gh` run in `cwd` with GH_REPO blanked, since an ambient one would point the
311
+ // call at another repository's labels.
312
+ function spawnGh(args, cwd) {
313
+ return spawnSync("gh", args, { cwd, encoding: "utf8", env: gitEnv({ GH_REPO: "" }), stdio: ["ignore", "pipe", "pipe"], timeout: GH_TIMEOUT_MS });
314
+ }
315
+
281
316
  /**
282
317
  * The names of every label the tracker has, from `gh label list`. Throws
283
318
  * LabelMapUnavailable when `gh` cannot answer, answers something else, or
@@ -285,7 +320,7 @@ const GH_TIMEOUT_MS = 60_000;
285
320
  */
286
321
  export function readLiveLabels({ cwd = process.cwd() } = {}) {
287
322
  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 });
323
+ const r = spawnGh(args, cwd);
289
324
  if (r.error?.code === "ETIMEDOUT") throw new LabelMapUnavailable(`gh label list timed out after ${GH_TIMEOUT_MS / 1000}s`);
290
325
  if (r.error) throw new LabelMapUnavailable(`could not run gh: ${r.error.message}`);
291
326
  if (r.signal) throw new LabelMapUnavailable(`gh was killed by ${r.signal}`);
@@ -327,19 +362,23 @@ const squash = (text) => lc(text).replace(/[^\p{L}\p{N}]/gu, "");
327
362
  /**
328
363
  * Derive the Label map from `table` (`{ present, rows }`), `live` (the
329
364
  * 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
365
+ * null; only its `roles` and `origin` records are read). `answers` (role ->
366
+ * string, a Map) are the maintainer's explicit answers: each settles its role,
367
+ * live or not, before the table is consulted — the role's own table row is
368
+ * not read — and a cached answer or a table row naming the same string loses
369
+ * to it as it would to a table row. Pure: no file, no `gh`. One of
332
370
  * { 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
371
+ * { kind: "break", faults: [{ role, rule, fix }] } the table or an answer breaks the string rules
372
+ * { kind: "uncertain", payload: { certain, uncertain }, roles, origin } the maintainer decides;
373
+ * `roles` and `origin` are the certain roles' and what settled them
335
374
  */
336
- export function deriveLabelMap({ table, live, cache }) {
375
+ export function deriveLabelMap({ table, live, cache, answers = new Map() }) {
337
376
  const exact = new Set(live);
338
377
  const byKey = new Map();
339
378
  for (const name of live) if (!byKey.has(lc(name))) byKey.set(lc(name), name);
340
379
  // The live label a string names, in the tracker's own spelling.
341
380
  const liveOf = (text) => (exact.has(text) ? text : byKey.get(lc(text)));
342
- const rowsOf = (role) => (Object.hasOwn(table.rows, role) ? [].concat(table.rows[role]) : []);
381
+ const rowsOf = (role) => (answers.has(role) ? [answers.get(role)] : Object.hasOwn(table.rows, role) ? [].concat(table.rows[role]) : []);
343
382
 
344
383
  const cacheRoles = isRecord(cache?.roles) ? cache.roles : {};
345
384
  const cacheOrigin = isRecord(cache?.origin) ? cache.origin : {};
@@ -432,31 +471,34 @@ export function deriveLabelMap({ table, live, cache }) {
432
471
 
433
472
  // The string rules on the verdicts, before any suggestion is withheld.
434
473
  const faults = [];
435
- const fixRow = (role) => `edit the ${role} row in ${TRIAGE_TABLE_FILE}`;
474
+ const what = (role) => (answers.has(role) ? `the ${role}=<label> pair` : `the ${role} row`);
475
+ const fixRow = (role) => (answers.has(role) ? `change ${what(role)}` : `edit the ${role} row in ${TRIAGE_TABLE_FILE}`);
476
+ const named = (role) => (answers.has(role) ? "its answer" : "its row");
436
477
  const firstRowOwner = new Map();
437
478
  for (const role of LABEL_ROLES) {
438
479
  const rows = rowsOf(role);
439
480
  for (const text of rows) {
440
481
  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) });
482
+ if (rule) faults.push({ role, rule: `${named(role)} names ${JSON.stringify(text)}, which is not a valid label string (${rule})`, fix: fixRow(role) });
442
483
  }
443
484
  if (rows.length === 0 || stringFault(rows[0])) continue;
444
485
  const owner = firstRowOwner.get(lc(rows[0]));
445
486
  if (owner !== undefined) {
487
+ const bothRows = !answers.has(role) && !answers.has(owner);
446
488
  faults.push({
447
489
  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}`,
490
+ rule: `${named(role)} names ${JSON.stringify(rows[0])}, the same string as ${what(owner)} (compared ignoring case)`,
491
+ fix: bothRows ? `edit the ${role} row or the ${owner} row in ${TRIAGE_TABLE_FILE}` : `change ${what(role)} or ${what(owner)}`,
450
492
  });
451
493
  } else {
452
494
  firstRowOwner.set(lc(rows[0]), role);
453
495
  }
454
- // `resolved` holds only roles with no row, so never this one.
496
+ // `resolved` holds only roles with no row and no answer, so never this one.
455
497
  for (const [other, verdict] of resolved) {
456
498
  if (lc(verdict.string) === lc(rows[0])) {
457
499
  faults.push({
458
500
  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)`,
501
+ rule: `${named(role)} names ${JSON.stringify(rows[0])}, the string ${other} resolves to as its default (${other} has no row and no answer of its own)`,
460
502
  fix: `${fixRow(role)}, or run \`label-map.mjs set ${other}=<label>\` to give ${other} another label`,
461
503
  });
462
504
  }
@@ -472,7 +514,10 @@ export function deriveLabelMap({ table, live, cache }) {
472
514
  const rows = rowsOf(role);
473
515
  let settled = null;
474
516
  let suggested = null;
475
- if (rows.length) {
517
+ if (answers.has(role)) {
518
+ // The tracker's own spelling when the string is live; as given when it is to be created.
519
+ settled = { string: liveOf(rows[0]) ?? rows[0], origin: "maintainer" };
520
+ } else if (rows.length) {
476
521
  const live1 = rows.length === 1 ? liveOf(rows[0]) : undefined;
477
522
  if (live1 !== undefined) settled = { string: live1, origin: "table" };
478
523
  else suggested = { string: liveOf(rows[0]) ?? rows[0], origin: "table" };
@@ -502,7 +547,7 @@ export function deriveLabelMap({ table, live, cache }) {
502
547
  if (dropped.has(role)) entry.claimedBy = dropped.get(role);
503
548
  uncertain.push(entry);
504
549
  }
505
- if (uncertain.length) return { kind: "uncertain", payload: { certain, uncertain } };
550
+ if (uncertain.length) return { kind: "uncertain", payload: { certain, uncertain }, roles: certain, origin };
506
551
  // Nothing above lets two certain roles share a string; this is the belt to
507
552
  // that suspenders, the same rules the reader and the writer's caller hold.
508
553
  const broken = labelStringFaults(certain);
@@ -510,14 +555,10 @@ export function deriveLabelMap({ table, live, cache }) {
510
555
  return { kind: "certain", roles: certain, origin };
511
556
  }
512
557
 
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() } = {}) {
558
+ // The three inputs of a derivation, read the same way for `ensure` and `set`:
559
+ // the table, the live label list and the cache (null when absent or not
560
+ // parsing, which is derived again).
561
+ function readDerivationInputs(cwd) {
521
562
  const { top, table } = readTriageTable({ cwd });
522
563
  const live = readLiveLabels({ cwd: top });
523
564
  let cache = null;
@@ -529,7 +570,21 @@ export function ensureLabelMap({ cwd = process.cwd() } = {}) {
529
570
  // be read may hold maintainer answers, so it is never written over.
530
571
  if (e.cause) throw new LabelMapUnavailable(`cannot read the Label map at ${e.cause.path} (${e.cause.code ?? e.cause.message}); nothing written`);
531
572
  }
532
- const mapOf = (roles) => JSON.stringify(inRoleOrder(roles));
573
+ return { top, table, live, cache };
574
+ }
575
+
576
+ const mapOf = (roles) => JSON.stringify(inRoleOrder(roles));
577
+ const faultLines = (faults) => faults.map(({ role, rule, fix }) => ` ${role}: ${rule}. Fix: ${fix}`).join("\n");
578
+
579
+ /**
580
+ * The Label map derivation step: `{ code, stdout, stderr }` for the CLI to
581
+ * print. 0 the map (the cache valid as it stands, or derived and written),
582
+ * 1 the table breaks the string rules, 3 the question payload. Writes only
583
+ * the cache, and only on code 0 from a derivation; never creates a label.
584
+ * Throws FleetDirUnresolvable and LabelMapUnavailable, both exit 2.
585
+ */
586
+ export function ensureLabelMap({ cwd = process.cwd() } = {}) {
587
+ const { table, live, cache } = readDerivationInputs(cwd);
533
588
  // Valid as it stands: every mapped string is in the tracker's own spelling,
534
589
  // so a label whose case was changed after caching is derived again.
535
590
  if (
@@ -543,10 +598,9 @@ export function ensureLabelMap({ cwd = process.cwd() } = {}) {
543
598
  }
544
599
  const derived = deriveLabelMap({ table, live, cache });
545
600
  if (derived.kind === "break") {
546
- const lines = derived.faults.map(({ role, rule, fix }) => ` ${role}: ${rule}. Fix: ${fix}`);
547
601
  return {
548
602
  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`,
603
+ stderr: `\n${NAME}: ${TRIAGE_TABLE_FILE} gives a Label map that breaks the string rules; nothing written, nothing created:\n${faultLines(derived.faults)}\n`,
550
604
  };
551
605
  }
552
606
  if (derived.kind === "uncertain") return { code: 3, stdout: JSON.stringify(derived.payload) };
@@ -558,11 +612,107 @@ export function ensureLabelMap({ cwd = process.cwd() } = {}) {
558
612
  return { code: 0, stdout: mapOf(derived.roles) };
559
613
  }
560
614
 
561
- function ensure(rest) {
562
- if (rest.length) die(`ensure takes no arguments, got: ${rest.join(" ")}; ${USAGE}`);
615
+ // `gh label create` says the label exists in these words; a label that exists
616
+ // is what `set` wanted, whoever made it.
617
+ const ALREADY_EXISTS = /already exists/i;
618
+
619
+ /**
620
+ * The Label map write: `{ code, stdout, stderr }` for the CLI to print. A
621
+ * fresh derivation (as `ensureLabelMap` runs it) plus the maintainer's
622
+ * answer: `answers` (role -> string, a Map) settle their roles first, and
623
+ * with `acceptSuggestions` every other uncertain role takes its suggestion.
624
+ * A string that does not exist in the tracker is created with `gh label
625
+ * create <string>` (no colour) only when `create` is set, and the live list
626
+ * is read again so the map stores the tracker's spelling. The cache is
627
+ * written only when every mapped string exists live, origin `maintainer` for
628
+ * every role an answer or an accepted suggestion settled. 0 the map written,
629
+ * 1 a refusal (the string rules, an uncovered uncertain role, a missing
630
+ * string without `create`), nothing written and nothing created. Throws
631
+ * FleetDirUnresolvable and LabelMapUnavailable, both exit 2 — one of them
632
+ * after labels were created, the message then naming them.
633
+ */
634
+ export function setLabelMap({ answers = new Map(), acceptSuggestions = false, create = false, cwd = process.cwd() } = {}) {
635
+ const refuse = (...lines) => ({ code: 1, stderr: `\n${NAME}: set refused; nothing written, nothing created:\n${lines.join("\n")}\n` });
636
+ const { top, table, live, cache } = readDerivationInputs(cwd);
637
+ const derived = deriveLabelMap({ table, live, cache, answers });
638
+ if (derived.kind === "break") return refuse(faultLines(derived.faults));
639
+
640
+ const roles = { ...derived.roles };
641
+ const origin = { ...derived.origin };
642
+ if (derived.kind === "uncertain") {
643
+ const uncovered = derived.payload.uncertain.filter((u) => !acceptSuggestions || u.suggestion === null);
644
+ if (uncovered.length) {
645
+ return refuse(
646
+ ...uncovered.map(({ role, suggestion, was }) =>
647
+ suggestion === null
648
+ ? ` ${role}: uncovered, and it has no suggestion (its label ${JSON.stringify(was)} is gone from the tracker); answer ${role}=<label>`
649
+ : ` ${role}: uncovered; answer ${role}=<label>, or pass --accept-suggestions to take ${JSON.stringify(suggestion)}`,
650
+ ),
651
+ );
652
+ }
653
+ for (const { role, suggestion } of derived.payload.uncertain) {
654
+ roles[role] = suggestion;
655
+ origin[role] = "maintainer";
656
+ }
657
+ }
658
+ const broken = labelStringFaults(roles);
659
+ if (broken.length) return refuse(...broken.map(({ role, rule }) => ` ${role}: ${rule}`));
660
+
661
+ // The live label a string names, in the tracker's own spelling.
662
+ const liveSpelling = (names) => {
663
+ const byKey = new Map();
664
+ for (const name of names) if (!byKey.has(lc(name))) byKey.set(lc(name), name);
665
+ return (text) => byKey.get(lc(text));
666
+ };
667
+ let spelling = liveSpelling(live);
668
+ const missing = LABEL_ROLES.filter((role) => spelling(roles[role]) === undefined);
669
+ // The labels this run created, named by every failure that follows one.
670
+ const made = [];
671
+ const named = (lead) => (made.length ? `; ${lead}: ${made.map((s) => JSON.stringify(s)).join(", ")}` : "");
672
+ if (missing.length) {
673
+ if (!create) {
674
+ return refuse(...missing.map((role) => ` ${role}: ${JSON.stringify(roles[role])} does not exist in the tracker; pass --create to create it`));
675
+ }
676
+ for (const role of missing) {
677
+ // A string that starts with `-` would be read as a flag.
678
+ const string = roles[role];
679
+ const r = spawnGh(["label", "create", ...(string.startsWith("-") ? ["--"] : []), string], top);
680
+ const said = `${r.stdout ?? ""}${r.stderr ?? ""}`;
681
+ const where = `${named("created before it")}; nothing written`;
682
+ if (r.error?.code === "ETIMEDOUT") throw new LabelMapUnavailable(`gh label create ${JSON.stringify(string)} timed out after ${GH_TIMEOUT_MS / 1000}s${where}`);
683
+ if (r.error) throw new LabelMapUnavailable(`could not run gh: ${r.error.message}${where}`);
684
+ if (r.signal) throw new LabelMapUnavailable(`gh was killed by ${r.signal} creating ${JSON.stringify(string)}${where}`);
685
+ if (r.status === 0) made.push(string);
686
+ else if (!ALREADY_EXISTS.test(said)) {
687
+ throw new LabelMapUnavailable(`gh label create ${JSON.stringify(string)} failed: ${said.trim().split("\n")[0] || `exit ${r.status}`}${where}`);
688
+ }
689
+ }
690
+ try {
691
+ spelling = liveSpelling(readLiveLabels({ cwd: top }));
692
+ } catch (e) {
693
+ if (!(e instanceof LabelMapUnavailable)) throw e;
694
+ throw new LabelMapUnavailable(`${e.message}${named("created")}; nothing written`);
695
+ }
696
+ }
697
+ for (const role of LABEL_ROLES) {
698
+ const name = spelling(roles[role]);
699
+ if (name === undefined) {
700
+ throw new LabelMapUnavailable(`${role}: ${JSON.stringify(roles[role])} is not in the tracker's label list after gh label create${named("created")}; nothing written`);
701
+ }
702
+ roles[role] = name;
703
+ }
704
+ try {
705
+ writeLabelMap({ derivedAt: new Date().toISOString(), table, roles: inRoleOrder(roles), origin: inRoleOrder(origin) }, { cwd });
706
+ } catch (e) {
707
+ throw new LabelMapUnavailable(`cannot write the Label map: ${e.message}${named("created")}`);
708
+ }
709
+ return { code: 0, stdout: mapOf(roles) };
710
+ }
711
+
712
+ function report(run) {
563
713
  let result;
564
714
  try {
565
- result = ensureLabelMap();
715
+ result = run();
566
716
  } catch (e) {
567
717
  if (e instanceof FleetDirUnresolvable || e instanceof LabelMapUnavailable) die(e.message);
568
718
  throw e;
@@ -572,6 +722,31 @@ function ensure(rest) {
572
722
  process.exitCode = result.code;
573
723
  }
574
724
 
725
+ function ensure(rest) {
726
+ if (rest.length) die(`ensure takes no arguments, got: ${rest.join(" ")}; ${USAGE}`);
727
+ report(ensureLabelMap);
728
+ }
729
+
730
+ function set(rest) {
731
+ const answers = new Map();
732
+ let acceptSuggestions = false;
733
+ let create = false;
734
+ for (const arg of rest) {
735
+ if (arg === "--accept-suggestions") acceptSuggestions = true;
736
+ else if (arg === "--create") create = true;
737
+ else if (arg.startsWith("-")) die(`unknown flag ${JSON.stringify(arg)}; ${USAGE}`);
738
+ else {
739
+ const eq = arg.indexOf("=");
740
+ if (eq === -1) die(`malformed pair ${JSON.stringify(arg)}: expected <role>=<label>; ${USAGE}`);
741
+ const role = arg.slice(0, eq);
742
+ if (!LABEL_ROLES.includes(role)) die(`unknown role ${JSON.stringify(role)} in ${JSON.stringify(arg)}; the roles are ${LABEL_ROLES.join(", ")}`);
743
+ if (answers.has(role)) die(`${role} is answered twice; ${USAGE}`);
744
+ answers.set(role, arg.slice(eq + 1));
745
+ }
746
+ }
747
+ report(() => setLabelMap({ answers, acceptSuggestions, create }));
748
+ }
749
+
575
750
  function show(rest) {
576
751
  if (rest.length > 1) die(`show takes at most one role, got: ${rest.join(" ")}; ${USAGE}`);
577
752
  const [role] = rest;
@@ -594,6 +769,7 @@ function show(rest) {
594
769
  function main() {
595
770
  const [verb, ...rest] = process.argv.slice(2);
596
771
  if (verb === "ensure") return ensure(rest);
772
+ if (verb === "set") return set(rest);
597
773
  if (verb === "show") return show(rest);
598
774
  die(verb === undefined ? USAGE : `unknown verb ${JSON.stringify(verb)}; ${USAGE}`);
599
775
  }