@feigi/fleet-ctl 3.145.0 → 3.147.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.145.0",
3
+ "version": "3.147.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": {
@@ -40,7 +40,7 @@ import { repoIdentity } from "./compute-cell-evidence.mjs";
40
40
  import { readCostGuard } from "./fleet-tick.mjs";
41
41
  import { parseFrontmatter } from "./tier-roles.mjs";
42
42
  import { isImplementer } from "./member-outcomes.mjs";
43
- import { validateTable } from "./ticket-router.mjs";
43
+ import { FIT_FILE, validateTable } from "./ticket-router.mjs";
44
44
  import { LabelMapUnreadable, readLabelMap } from "./label-map.mjs";
45
45
  import { FleetDirUnresolvable } from "./fleet-dir.mjs";
46
46
  // The heartbeat's liveness mark and the controller record beside it, read here
@@ -858,17 +858,17 @@ export function readCheckoutTable(stateDir) {
858
858
  return table instanceof Error ? { status: "unreadable", why: table.message } : { status: "ok", table };
859
859
  }
860
860
 
861
- // The Preview fit metrics-refresh.mjs writes beside the guard,
862
- // `.fleet/router-preview.json`: `{ status: "ok", preview }`, `{ status: "missing" }`
861
+ // The Fit metrics-refresh.mjs writes beside the guard,
862
+ // `.fleet/router-fit.json`: `{ status: "ok", fit }`, `{ status: "missing" }`
863
863
  // or `{ status: "unreadable", why }`. Its `table` is read through `validateTable`,
864
864
  // as the installed one is, and its `n_rows`, which `validateTable` does not check
865
865
  // and the tab prints, must be a count; `computed_at` and `guard_computed_at` must
866
866
  // be strings, and `tsv_blobs` and `prior` objects, their values checked where the
867
867
  // tab reads them.
868
- export function readPreviewFile(stateDir) {
868
+ export function readFitFile(stateDir) {
869
869
  let text;
870
870
  try {
871
- text = readFileSync(join(stateDir, "router-preview.json"), "utf8");
871
+ text = readFileSync(join(stateDir, FIT_FILE), "utf8");
872
872
  } catch (e) {
873
873
  return e.code === "ENOENT" ? { status: "missing" } : { status: "unreadable", why: e.code ?? e.message };
874
874
  }
@@ -884,7 +884,7 @@ export function readPreviewFile(stateDir) {
884
884
  const table = validateTable(p.table);
885
885
  if (table instanceof Error) return { status: "unreadable", why: table.message };
886
886
  if (!Number.isInteger(table.n_rows) || table.n_rows < 0) return { status: "unreadable", why: "router table: `n_rows` is not a count" };
887
- return { status: "ok", preview: { computed_at: p.computed_at, guard_computed_at: p.guard_computed_at, tsv_blobs: p.tsv_blobs, prior: p.prior, table } };
887
+ return { status: "ok", fit: { computed_at: p.computed_at, guard_computed_at: p.guard_computed_at, tsv_blobs: p.tsv_blobs, prior: p.prior, table } };
888
888
  }
889
889
 
890
890
  // A receipt's `metrics` step, `{ status, at, output }`, or null: no receipt, one
@@ -1342,7 +1342,7 @@ export async function gather({ ledgerFile, prevFile, stateFile = null, stateDir
1342
1342
  // either (a guard that reads as missing, no receipts, the read carried as it was).
1343
1343
  const guard = stateDir === null ? { status: "missing" } : readGuardFile(stateDir);
1344
1344
  const guardJson = stateDir === null ? null : readGuardJson(stateDir);
1345
- const preview = stateDir === null ? { status: "missing" } : readPreviewFile(stateDir);
1345
+ const fit = stateDir === null ? { status: "missing" } : readFitFile(stateDir);
1346
1346
  const closeoutPr = stateDir === null ? null : readCloseoutPr(stateDir);
1347
1347
  const checkoutTable = stateDir === null ? { status: "missing" } : readCheckoutTable(stateDir);
1348
1348
  const receipts = stateDir === null
@@ -1358,6 +1358,6 @@ export async function gather({ ledgerFile, prevFile, stateFile = null, stateDir
1358
1358
  : await Promise.all([carryModelRoles(prev?.modelRoles, now), carryMainMetrics(prev?.mainMetrics, now, repoUrl)]);
1359
1359
  return { ledger, issues, prs, merged, closed, closedIssues, ci, prev, repo, repoUrl, workspace, port, spend, beat, ticked, acted, controller, stallOwner: stallOwnerOf, poolOk,
1360
1360
  roles, labelMapError,
1361
- poolCapped, prsOk, prsCapped, guard, guardJson, preview, receipts, closeoutPr, agents, modelRoles, mainMetrics, install, objective, implementers: [...implementers.values()], routerTable, checkoutTable,
1361
+ poolCapped, prsOk, prsCapped, guard, guardJson, fit, receipts, closeoutPr, agents, modelRoles, mainMetrics, install, objective, implementers: [...implementers.values()], routerTable, checkoutTable,
1362
1362
  now, interval };
1363
1363
  }
@@ -37,7 +37,8 @@
37
37
  // `NEED tier-outcomes append <n>`, and the step is pending.
38
38
  // The verdicts come from `tier-outcomes.mjs append`, which
39
39
  // works them out from the Charges; this script never writes one.
40
- // metrics `metrics-refresh.mjs`. Any non-zero exit is a failed step.
40
+ // metrics `metrics-refresh.mjs --no-fit`: close-out computes no Fit,
41
+ // the next run's phase 0 does. Any non-zero exit is a failed step.
41
42
  // gather run-records.mjs's gather(): every run archive `ledger.mjs
42
43
  // rotate` left in `.fleet/` (`ledger.<stamp>.md`,
43
44
  // `phase0.<stamp>.json`, `closeout.<stamp>.json`) into
@@ -349,7 +350,7 @@ function stepTierOutcomes({ cwd }) {
349
350
  }
350
351
 
351
352
  function stepMetrics({ cwd }) {
352
- const r = node("metrics-refresh.mjs", [], { cwd });
353
+ const r = node("metrics-refresh.mjs", ["--no-fit"], { cwd });
353
354
  return r.status === 0 ? ok(r.stdout) : failed(`metrics-refresh.mjs failed: ${detail(r)}`);
354
355
  }
355
356
 
@@ -369,6 +369,9 @@ function reasonWords(r, table) {
369
369
  case "guard-missing": return [part("no cost guard yet: default Cell only")];
370
370
  case "no-issue-json": return [part("issue unreadable when routed")];
371
371
  case "no-sizing": return [part("no sizing")];
372
+ case "fit-missing": return [part("no Fit: starting table")];
373
+ case "fit-unreadable": return [part("Fit unreadable: starting table")];
374
+ case "fit-invalid": return [part("Fit invalid: starting table")];
372
375
  default: return [part(`recorded as ${r.reason}`)];
373
376
  }
374
377
  }
@@ -867,7 +870,7 @@ export function computeBoard(inputs) {
867
870
  cellEvidence: computeCellEvidence({
868
871
  guard: inputs.guard,
869
872
  guardJson: inputs.guardJson,
870
- preview: inputs.preview,
873
+ fit: inputs.fit,
871
874
  receipts: inputs.receipts,
872
875
  closeoutPr: inputs.closeoutPr,
873
876
  openPrs: inputs.prsOk === false ? null : { numbers: (inputs.prs ?? []).map((p) => p.number), capped: inputs.prsCapped === true },
@@ -1,7 +1,7 @@
1
1
  // The cockpit's Cell evidence tab, as a value: computeCellEvidence() turns what
2
2
  // gather() read (the cost guard, the receipts' `metrics` steps, the installed
3
3
  // definitions, the installed router table and package, the carried `modelRoles`
4
- // read, the Preview fit) into the model the page lays out.
4
+ // read, the Fit) into the model the page lays out.
5
5
  // Pure, like compute-board.mjs, which calls it and puts the answer in
6
6
  // `board.json` as `cellEvidence`: no file, no process, no clock. Every word the
7
7
  // tab shows is built here, so a test pins it where it is made and the page only
@@ -14,11 +14,16 @@
14
14
  // routes-now side the Cell the installed router table plus the workspace's guard
15
15
  // route to, why, and how a Pull on that row is dispatched (ticket-router.mjs's
16
16
  // rowDispatch, the function `route` itself calls), and on the evidence-favours
17
- // side the same for the Preview fit's table (`.fleet/router-preview.json`, which
18
- // metrics-refresh.mjs writes beside the guard), marked where its Cell differs.
19
- // The receipts' newest `metrics` step, which the guard section quotes when there
20
- // is no guard, also feeds the evidence-favours side: a refit that step says
21
- // failed, with no fit written after it, is said in that side's heading.
17
+ // side the same for the Fit's table (`.fleet/router-fit.json`, which
18
+ // metrics-refresh.mjs writes beside the guard at phase 0), marked where its Cell
19
+ // differs. The installed table is the starting table: `route` with no `--table`
20
+ // routes by the Fit beside its `--guard`, and by the installed table only when
21
+ // that Fit is missing, unreadable or invalid, so routes now lays out the
22
+ // installed table, not always the one `route` routes by.
23
+ // The receipts' newest `metrics` step is what the guard section quotes when there
24
+ // is no guard; the newest one that tried a refit feeds the evidence-favours side:
25
+ // a refit that step says failed, with no fit written after it, is said in that
26
+ // side's heading.
22
27
  // Figures show only from a guard `readCostGuard` (fleet-tick.mjs, the reader
23
28
  // the tick judges the file by) accepts; `guard` here is that reader's own
24
29
  // answer, `{ status: "ok", guard }` or
@@ -32,7 +37,7 @@
32
37
  import { isDeepStrictEqual } from "node:util";
33
38
  import { CELL, OBJECTIVES, POLICY_CELL } from "./ledger-grammar.mjs";
34
39
  import { costGuardFault } from "./fleet-tick.mjs";
35
- import { MIN_N, parseGuard, readGuard, rowDispatch } from "./ticket-router.mjs";
40
+ import { MIN_N, parseGuard, readGuard, rowDispatch, shortStartingCells } from "./ticket-router.mjs";
36
41
  import { implementerCell, modelsEqual, parseModelRoute, resolveRole } from "./tier-roles.mjs";
37
42
 
38
43
  // The implementer Cells, in the order the guard section draws them: one per
@@ -119,19 +124,30 @@ function tierRoute(role, level, generation, modelRoles) {
119
124
 
120
125
  // ---------------------------------------------------------------------------
121
126
  // The newest `metrics` step of the phase 0 and close-out receipts: the guard
122
- // section quotes it when there is no guard, and evidence favours reads a failed refit off it.
127
+ // section quotes it when there is no guard. Evidence favours reads a failed
128
+ // refit off the newest one that tried a refit instead.
123
129
  // ---------------------------------------------------------------------------
124
130
 
125
131
  // `step` is `{ status, at, output }` or null. A step that has not run carries no
126
132
  // refresh to quote.
127
133
  const ran = (step) => step != null && step.status !== "pending" && Number.isFinite(Date.parse(step.at));
128
134
 
135
+ // The newest of `steps` by `at`; on equal times, the first. Null for none.
136
+ const newest = (steps) => (steps.length === 0 ? null : steps.reduce((a, b) => (Date.parse(b.at) > Date.parse(a.at) ? b : a)));
137
+
129
138
  // The newest `metrics` step of the two receipts that has run, by `at`; on equal
130
139
  // times, phase 0's. Null when neither receipt has run one.
131
140
  function newestStep(receipts) {
132
- const steps = [receipts?.phase0, receipts?.closeout].filter(ran);
133
- if (steps.length === 0) return null;
134
- return steps.reduce((a, b) => (Date.parse(b.at) > Date.parse(a.at) ? b : a));
141
+ return newest([receipts?.phase0, receipts?.closeout].filter(ran));
142
+ }
143
+
144
+ // The newest `metrics` step of the two receipts that tried a refit — its output
145
+ // carries a `metrics-refresh: fit:` line — picked as newestStep picks. A
146
+ // close-out's step, which runs with `--no-fit` and computes no Fit, and a step
147
+ // that stopped before its refit tried none, so neither hides an earlier
148
+ // failure. Null when neither receipt's step tried one.
149
+ function newestRefit(receipts) {
150
+ return newest([receipts?.phase0, receipts?.closeout].filter((s) => ran(s) && /metrics-refresh: fit: /.test(String(s.output ?? ""))));
135
151
  }
136
152
 
137
153
  // metrics-refresh's own line from a step's output: the cost-guard duty's, else
@@ -156,11 +172,11 @@ function newestRefresh(step) {
156
172
  return { verb, at: step.at, why };
157
173
  }
158
174
 
159
- // Why the Preview fit's refit failed, off a `metrics` step's output: the rest of
160
- // metrics-refresh's `preview: failed — ` line, trimmed, or null when the output
175
+ // Why the Fit failed, off a `metrics` step's output: the rest of
176
+ // metrics-refresh's `fit: failed — ` line, trimmed, or null when the output
161
177
  // has none. Found anywhere in a line, as refreshLine finds its own.
162
178
  export function refitFailure(output) {
163
- const m = /metrics-refresh: preview: failed — ([^\n]*)/.exec(String(output ?? ""));
179
+ const m = /metrics-refresh: fit: failed — ([^\n]*)/.exec(String(output ?? ""));
164
180
  return m === null ? null : m[1].trim();
165
181
  }
166
182
 
@@ -483,12 +499,13 @@ function routesSource(table, install, repoUrl) {
483
499
  return { same, owner: named === null ? "another repository" : named.name, runs, text: [runs, fitted, installed].join(" · "), check };
484
500
  }
485
501
 
486
- // The Cells short of `MIN_N` merged PRs in the table's `guard.n`, in the table's
487
- // order, as one phrase: past tense for an installed table, whose counts are what
488
- // its fit saw ("had"), present for the Preview fit, whose counts are the
489
- // workspace's own now ("has", "have").
502
+ // The starting Cells short of `MIN_N` merged PRs in the table's `guard.n` — the
503
+ // Cells burn-in waits for, and no others — in their order, as one phrase: past
504
+ // tense for an installed table, whose counts are what its fit saw ("had"),
505
+ // present for the Fit, whose counts are the workspace's own now ("has",
506
+ // "have").
490
507
  function shortWords(table, tense = "past") {
491
- const short = table.cells.filter((c) => (table.guard.n[c] ?? 0) < MIN_N).map((c) => [c, table.guard.n[c] ?? 0]);
508
+ const short = shortStartingCells(table.guard.n);
492
509
  if (short.length === 0) return null;
493
510
  const each = short.length === 1 ? "it needs" : "each needs";
494
511
  const one = tense === "past" ? "had" : "has";
@@ -511,7 +528,7 @@ function routesHeading(table, guard, source) {
511
528
  if (!table.fitted_commit) return `never fitted: ${drawn}`;
512
529
  const short = shortWords(table);
513
530
  const ends = source.same ? "" : "; it ends with a later fit, reaching this install with a plugin release";
514
- return `stage ${table.stage} at its fit on ${source.owner}'s runs: ${short === null ? "every Cell had its merged PRs" : short}; ${drawn}${ends}`;
531
+ return `burn-in at its fit on ${source.owner}'s runs: ${short === null ? "every starting Cell had its merged PRs" : short}; ${drawn}${ends}`;
515
532
  }
516
533
 
517
534
  // One row's dispatch, in the words a heading or a row carries: what `route` does
@@ -549,7 +566,7 @@ function intervalWords(range, objective) {
549
566
  }
550
567
 
551
568
  // One row of a table under the guard — the installed table for routes now, the
552
- // Preview fit's for evidence favours: the Cell it routes to and why, its
569
+ // Fit's for evidence favours: the Cell it routes to and why, its
553
570
  // dispatch, and each candidate's n (null where the table carries no count),
554
571
  // verdict and interval.
555
572
  function rowEntry(table, guard, modelRoles, objective, stratum) {
@@ -620,22 +637,23 @@ function routesNow({ table, guard, modelRoles, install, repoUrl, checkout }) {
620
637
  }
621
638
 
622
639
  // ---------------------------------------------------------------------------
623
- // Policy rows: what the evidence favours — the Preview fit, `.fleet/router-preview.json`.
640
+ // Policy rows: what the evidence favours — the Fit, `.fleet/router-fit.json`.
624
641
  // ---------------------------------------------------------------------------
625
642
 
626
643
  const FAVOURS = "evidence favours";
627
644
 
628
- // The evidence-favours side with no Preview fit to lay out: its heading says
645
+ // The evidence-favours side with no Fit to lay out: its heading says
629
646
  // why, and its column is empty — nothing is unknown there, there is nothing to show.
630
647
  const noFit = (heading, labels = []) => ({
631
- title: FAVOURS, source: { text: "Preview fit", check: null }, heading, labels, footnotes: [], rows: null, unread: null,
648
+ title: FAVOURS, source: { text: "Fit", check: null }, heading, labels, footnotes: [], rows: null, unread: null,
632
649
  });
633
650
 
634
- // The newest refit failed: `step` is the receipts' newest `metrics` step, `p`
635
- // the Preview fit read, null when none was. Said while that step's output holds
636
- // the failed line and no fit was written after it — a `computed_at` before the
637
- // step's `at`, or one that is no time. A later step, a fit written after this
638
- // one, or the receipt no longer read clears it.
651
+ // The newest refit failed: `step` is the receipts' newest `metrics` step that
652
+ // tried a refit, newestRefit's pick, `p` the Fit read, null when none was. Said
653
+ // while that step's output holds the failed line and no fit was written after
654
+ // it — a `computed_at` before the step's `at`, or one that is no time. A later
655
+ // step that tried a refit, a fit written after this one, or the receipt no
656
+ // longer read clears it; a close-out step, which tries none, does not.
639
657
  function refitLabel(step, p) {
640
658
  if (step === null) return [];
641
659
  const why = refitFailure(step.output);
@@ -645,15 +663,15 @@ function refitLabel(step, p) {
645
663
  return [`the newest refit failed at ${when(step.at)}: ${why}`];
646
664
  }
647
665
 
648
- // The Preview fit's heading labels, against `raw`, the guard on disk, `routed`,
666
+ // The Fit's heading labels, against `raw`, the guard on disk, `routed`,
649
667
  // readGuard's answer for it, `table`, the installed one, and `records`, whether
650
668
  // the fit read the guard's files: fitted beside another guard, on other records,
651
669
  // or against another prior. The prior is
652
- // compared only on what the fit takes from it — `stage`, `cells`, `classifier`,
670
+ // compared only on what the fit takes from it — `cells`, `classifier`,
653
671
  // `splits`, and `window_start` when the guard gives none — so a release that changes only
654
672
  // what the fit recomputes, or `fitted_commit` and `version`, raises nothing: the
655
673
  // next phase 0's refit would come out the same.
656
- function previewLabels(p, raw, routed, table, records) {
674
+ function fitLabels(p, raw, routed, table, records) {
657
675
  const labels = [];
658
676
  if (p.guard_computed_at !== raw.computed_at) labels.push(`fitted beside the guard of ${when(p.guard_computed_at)}, not this one`);
659
677
  if (records === null) labels.push("fitted on the guard's records: not checked: this guard predates the blob ids it needs");
@@ -662,7 +680,7 @@ function previewLabels(p, raw, routed, table, records) {
662
680
  labels.push("fitted against the installed table: not checked: no router table read");
663
681
  return labels;
664
682
  }
665
- const read = ["stage", "cells", "classifier", "splits", ...(routed.window_start === null ? ["window_start"] : [])];
683
+ const read = ["cells", "classifier", "splits", ...(routed.window_start === null ? ["window_start"] : [])];
666
684
  const prior = isRecord(p.prior) ? p.prior : {};
667
685
  if (read.some((k) => !isDeepStrictEqual(prior[k], table[k]))) {
668
686
  const version = prior.version === "0.0.0" ? "linked checkout" : (typeof prior.version === "string" ? prior.version : "no version");
@@ -685,19 +703,19 @@ function nDiffers(p, raw, records) {
685
703
  }).map((e) => e.cell);
686
704
  }
687
705
 
688
- // The evidence-favours side: the Preview fit's table laid out row by row under
706
+ // The evidence-favours side: the Fit's table laid out row by row under
689
707
  // the workspace's guard, as routes now lays out the installed one, each row's
690
- // Cell marked where it differs from the Cell routes now gives that row. `preview`
691
- // is gather's read, `{ status: "ok", preview } | { status: "missing" } | {
708
+ // Cell marked where it differs from the Cell routes now gives that row. `fit`
709
+ // is gather's read, `{ status: "ok", fit } | { status: "missing" } | {
692
710
  // status: "unreadable", why }`; `guard` readCostGuard's answer and `routed`
693
711
  // readGuard's for the same file, null when the router reads none; `step` the
694
- // receipts' newest `metrics` step, newestStep's pick; `mark` the footnote mark
712
+ // receipts' newest `metrics` step that tried a refit, newestRefit's pick; `mark` the footnote mark
695
713
  // its n footnote takes.
696
- function evidenceFavours({ preview, guard, routed, table, modelRoles, step, mark }) {
697
- if (routed === null) return noFit("no Preview fit: it is written only beside a cost guard");
698
- if (preview?.status === "unreadable") return noFit(`no Preview fit read: ${preview.why}`, refitLabel(step, null));
699
- if (preview?.status !== "ok") return noFit("no Preview fit yet: the next phase 0 writes one", refitLabel(step, null));
700
- const p = preview.preview;
714
+ function evidenceFavours({ fit: read, guard, routed, table, modelRoles, step, mark }) {
715
+ if (routed === null) return noFit("no Fit: it is written only beside a cost guard");
716
+ if (read?.status === "unreadable") return noFit(`no Fit read: ${read.why}`, refitLabel(step, null));
717
+ if (read?.status !== "ok") return noFit("no Fit yet: the next phase 0 writes one", refitLabel(step, null));
718
+ const p = read.fit;
701
719
  const fit = p.table;
702
720
  const raw = guard.guard;
703
721
  // Whether the fit read the guard's files: null when the guard names no blob
@@ -715,9 +733,9 @@ function evidenceFavours({ preview, guard, routed, table, modelRoles, step, mark
715
733
  };
716
734
  return {
717
735
  title: FAVOURS,
718
- source: { text: ["Preview fit", "this repository's runs", `computed ${when(p.computed_at)}`, plural(fit.n_rows, "Pull")].join(" · "), check: null },
719
- heading: fit.burn_in ? `stage ${fit.stage}: ${shortWords(fit, "present") ?? "every Cell has its merged PRs"}` : null,
720
- labels: [...refitLabel(step, p), ...previewLabels(p, raw, routed, table, records)],
736
+ source: { text: ["Fit", "this repository's runs", `computed ${when(p.computed_at)}`, plural(fit.n_rows, "Pull")].join(" · "), check: null },
737
+ heading: fit.burn_in ? `burn-in: ${shortWords(fit, "present") ?? "every starting Cell has its merged PRs"}` : null,
738
+ labels: [...refitLabel(step, p), ...fitLabels(p, raw, routed, table, records)],
721
739
  footnotes: differ.length === 0 ? [] : [{ mark, text: `${list(differ)}: the guard counts merges by GitHub's state, the fit by Rulings, and the fit admits only drawn or rule-sized Pulls` }],
722
740
  rows: Object.fromEntries(OBJECTIVES.map((o) => [o,
723
741
  Object.fromEntries(Object.keys(fit.rows[o]).map((s) => [s, entry(o, s)])),
@@ -820,14 +838,18 @@ function prIsOpen(pr, openPrs) {
820
838
  return openPrs.capped === true ? null : false;
821
839
  }
822
840
 
823
- // The guard's and the Preview fit's TSV blob ids against main's. `alert` is the
841
+ // The guard's and the Fit's TSV blob ids against main's. `alert` is the
824
842
  // alert while the records are not on main, else null; `note`, in its place, is
825
843
  // a note under the guard section's heading: a check that could not run is never
826
844
  // an alert, so an offline cockpit raises none. `main` is the carried read of
827
845
  // `docs/metrics`, `{ value: { blobs }, readAt, error }`, `blobs` null for a 404.
828
846
  // A guard that names no blob ids has nothing to compare, and neither has one
829
- // whose cockpit read nothing (`main` null).
830
- function recordsAgainstMain({ read, preview, main, closeoutPr, openPrs }) {
847
+ // whose cockpit read nothing (`main` null). The Fit is compared only while it
848
+ // was fitted beside this guard: a guard written after it — a close-out's,
849
+ // which computes no Fit, or one whose refit failed — moves on alone, and
850
+ // evidence favours' heading already says the Fit was fitted beside another
851
+ // guard.
852
+ function recordsAgainstMain({ read, fit, main, closeoutPr, openPrs }) {
831
853
  const none = { alert: null, note: null };
832
854
  if (main == null || read?.status !== "ok") return none;
833
855
  const g = read.guard;
@@ -840,7 +862,7 @@ function recordsAgainstMain({ read, preview, main, closeoutPr, openPrs }) {
840
862
  if (blobs === null) return { alert: null, note: "records against main: main holds no metrics yet" };
841
863
  if (!isRecord(blobs)) return unchecked("main's docs/metrics not read yet");
842
864
 
843
- const mine = preview?.status === "ok" ? preview.preview : null;
865
+ const mine = fit?.status === "ok" && fit.fit.guard_computed_at === g.computed_at ? fit.fit : null;
844
866
  const held = (ids, path) => (isRecord(ids) && Object.hasOwn(ids, path) ? ids[path] : undefined);
845
867
  const paths = [...new Set([...Object.keys(g.tsv_blobs), ...(mine === null ? [] : Object.keys(mine.tsv_blobs))])].sort();
846
868
  const lines = [];
@@ -855,14 +877,14 @@ function recordsAgainstMain({ read, preview, main, closeoutPr, openPrs }) {
855
877
  if (!gd && !fd) continue;
856
878
  guardDiffers ||= gd;
857
879
  fitDiffers ||= fd;
858
- const said = [guardId === undefined ? null : fitId === guardId ? `the guard and the Preview fit read ${blob8(guardId)}` : `the guard read ${blob8(guardId)}`,
859
- fitId === undefined || fitId === guardId ? null : `the Preview fit read ${blob8(fitId)}`].filter(Boolean);
880
+ const said = [guardId === undefined ? null : fitId === guardId ? `the guard and the Fit read ${blob8(guardId)}` : `the guard read ${blob8(guardId)}`,
881
+ fitId === undefined || fitId === guardId ? null : `the Fit read ${blob8(fitId)}`].filter(Boolean);
860
882
  lines.push(`${path}: ${said.join(", ")}; main holds ${onMain === undefined ? "none" : blob8(onMain)}`);
861
883
  }
862
884
  if (lines.length === 0) return none;
863
885
 
864
886
  const both = guardDiffers && fitDiffers;
865
- const subject = both ? "the guard and the Preview fit" : guardDiffers ? "the guard" : "the Preview fit";
887
+ const subject = both ? "the guard and the Fit" : guardDiffers ? "the guard" : "the Fit";
866
888
  const pr = Number.isInteger(closeoutPr?.number) ? closeoutPr.number : null;
867
889
  const open = prIsOpen(pr, openPrs);
868
890
  const computed = guardDiffers ? g.computed_at : mine.computed_at;
@@ -876,7 +898,7 @@ function recordsAgainstMain({ read, preview, main, closeoutPr, openPrs }) {
876
898
  const committed = Date.parse(closeoutPr.at);
877
899
  if (!Number.isFinite(committed)) return unchecked(`the close-out receipt records no time for PR #${pr}'s commit step`);
878
900
  const built = Date.parse(computed);
879
- if (!Number.isFinite(built)) return unchecked(`the ${guardDiffers ? "guard" : "Preview fit"} records no time it was computed`);
901
+ if (!Number.isFinite(built)) return unchecked(`the ${guardDiffers ? "guard" : "Fit"} records no time it was computed`);
880
902
  sentence = built <= committed
881
903
  ? `${subject} ${both ? "count" : "counts"} the rows of open PR #${pr}, not on main yet`
882
904
  : `${subject} ${both ? "lack" : "lacks"} the rows of open PR #${pr}`;
@@ -928,20 +950,20 @@ function readersAlert(json) {
928
950
  * cellLine). `table` is the installed router table `validateTable` accepted or
929
951
  * null, `install` the install's `{ name, version, repository, error }`
930
952
  * (`repository` its url), `repoUrl` the workspace's, `objective` the live
931
- * run's Objective or null between runs, and `preview` the Preview fit as gather
932
- * read `.fleet/router-preview.json`: `{ status: "ok", preview: { computed_at,
953
+ * run's Objective or null between runs, and `fit` the Fit as gather
954
+ * read `.fleet/router-fit.json`: `{ status: "ok", fit: { computed_at,
933
955
  * guard_computed_at, tsv_blobs, prior, table } }`, `{ status: "missing" }` or
934
956
  * `{ status: "unreadable", why }`. An input left out reads as nothing
935
957
  * read: a missing guard, no receipt, no definitions, no `modelRoles` read, no
936
- * Pull, no table, no install, no Objective, no Preview fit.
958
+ * Pull, no table, no install, no Objective, no Fit.
937
959
  */
938
- export function computeCellEvidence({ guard, receipts, agents, modelRoles = null, pulls = [], table = null, install = null, repoUrl = null, objective = null, preview = null,
960
+ export function computeCellEvidence({ guard, receipts, agents, modelRoles = null, pulls = [], table = null, install = null, repoUrl = null, objective = null, fit = null,
939
961
  guardJson = null, mainMetrics = null, closeoutPr = null, openPrs = null, checkoutTable = null }) {
940
962
  const routed = guard?.status === "ok" ? readGuard(guard.guard) : null;
941
963
  const routes = routesNow({ table, guard: routed, modelRoles, install, repoUrl, checkout: checkoutTable });
942
964
  const step = newestStep(receipts);
943
- const favours = evidenceFavours({ preview, guard, routed, table, modelRoles, step, mark: superscript(routes.footnotes.length + 1) });
944
- const records = recordsAgainstMain({ read: guard, preview, main: mainMetrics, closeoutPr, openPrs });
965
+ const favours = evidenceFavours({ fit, guard, routed, table, modelRoles, step: newestRefit(receipts), mark: superscript(routes.footnotes.length + 1) });
966
+ const records = recordsAgainstMain({ read: guard, fit, main: mainMetrics, closeoutPr, openPrs });
945
967
  return {
946
968
  alerts: [records.alert, noRulingAlert(guard), readersAlert(guardJson)].filter((a) => a !== null),
947
969
  policy: policyRowsView({ sides: [routes, favours], objective }),
@@ -527,7 +527,7 @@ export function routerRows(s) {
527
527
  const usd = (x) => (x === null ? "n/a" : `$${x.toFixed(2)}`);
528
528
  const vs = (c) => `${c.cell} ${usd(c.mean_usd)} vs ${usd(b.mean_usd)}, fail ${pct(c.fail_rate)} vs ${pct(b.fail_rate)}, n=${c.n}/${b.n}`;
529
529
  if (verdict === "tripped") {
530
- const retired = g.guard.retire ? "; every non-default stage-1 cell tripped — the router retires" : "";
530
+ const retired = g.guard.retire ? "; every non-default starting Cell tripped — the router retires" : "";
531
531
  return row("DEFAULT-ONLY", `cost guard: ${cells.filter((c) => tripped.includes(c.cell)).map(vs).join("; ")}${retired}; ${age}`);
532
532
  }
533
533
  const others = cells.filter((c) => c.cell !== b.cell);
@@ -854,6 +854,12 @@ export const CELL_DEF = new RegExp(`^fleet-implementer-${CELL.source.slice(1)}`)
854
854
  // bare row to.
855
855
  export const POLICY_CELL = "slow-high";
856
856
 
857
+ // The Cells burn-in covers: the three models at `high`. A Cell exploration adds
858
+ // is none of them, whatever its merged PRs: burn-in neither draws it nor waits
859
+ // for it. Exported so ticket-router.mjs's burn-in and pr-cost.mjs's retire
860
+ // condition read one list, though neither script imports the other.
861
+ export const STARTING_CELLS = Object.freeze(["slow-high", "task-high", "smol-high"]);
862
+
857
863
  // The Exploration Pull's draw: uniform over every cell but
858
864
  // `policyCell`, keyed off the row's own `session` and `ticket`, so the draw
859
865
  // is reproducible from the row and a re-dispatch of the same ticket in the
@@ -910,7 +916,9 @@ export const isRulePath = (x) => typeof x === "string" && RULE_PATH.test(x);
910
916
  // receipt, and every Routing names the one it routed by.
911
917
  export const OBJECTIVES = Object.freeze(["cost", "speed"]);
912
918
  const DRAWN_BY = Object.freeze(["burn-in", "every-5th"]);
913
- export const ROUTING_REASONS = Object.freeze(["ok", "no-issue-json", "no-sizing", "guard-missing", "guard-tripped", "table-cell-tripped"]);
919
+ export const ROUTING_REASONS = Object.freeze([
920
+ "ok", "no-issue-json", "no-sizing", "guard-missing", "guard-tripped", "table-cell-tripped", "fit-missing", "fit-unreadable", "fit-invalid",
921
+ ]);
914
922
  const SIZINGS = Object.freeze(["light", "heavy"]);
915
923
  const ROUTING_KEYS = Object.freeze(["POLICY", "CELL", "DRAW", "BY", "STRATUM", "BRIEF", "CRITERIA", "PARENT", "SIZED", "OBJECTIVE", "TRIPPED", "REASON"]);
916
924
  const PARENT_AT = ROUTING_KEYS.indexOf("PARENT");
@@ -2,13 +2,15 @@
2
2
  // The run's metrics duties that keep the router's inputs current: move the
3
3
  // pending ticket-features rows into the tracked corpus, widen a member-outcomes
4
4
  // corpus written before its latest columns, refresh the cost guard over it, then
5
- // write the Preview fit beside that guard.
5
+ // write the Fit beside that guard.
6
6
  //
7
- // metrics-refresh.mjs [--repo <dir>]
7
+ // metrics-refresh.mjs [--repo <dir>] [--no-fit]
8
8
  //
9
9
  // --repo the workspace whose `.fleet/` and `docs/metrics/` the duties read
10
10
  // and write; default the main checkout of the repository the cwd is
11
11
  // in, where the router script appends its pending rows
12
+ // --no-fit the duties only, no Fit: close-out passes it, so a run computes
13
+ // one Fit, at its phase 0, and each close-out's rows route the next run
12
14
  //
13
15
  // DRAIN. `ticket-router.mjs route` appends one row per Pull to
14
16
  // `.fleet/ticket-features.pending.tsv`; this moves them into
@@ -59,28 +61,34 @@
59
61
  // (no verdict yet — the baseline cell has too few merged PRs) are verdicts the
60
62
  // router and `fleet-tick.mjs` consume, not failures; any other non-zero exit is.
61
63
  //
62
- // PREVIEW FIT. After the cost guard wrote a guard, and only then, the Router's
63
- // fit (`ticket-router.mjs`'s fitTable) runs in-process over the working-tree
64
- // TSVs the guard just read and the guard just written, with the installed
65
- // router table (`router-table.json` beside the scripts) as its prior and no
66
- // commit. It writes `.fleet/router-preview.json` through a temp file and a
67
- // rename: `computed_at`, `guard_computed_at` (the guard's own `computed_at`),
68
- // `tsv_blobs` (the git blob id of each TSV it read, keyed by path as the guard
69
- // keys its own), `prior` (the installed table's `fitted_commit`, `stage`,
70
- // `cells`, `classifier`, `splits` and `window_start`, and the install's `package.json`
71
- // `version`) and the fitted `table`. The cockpit lays it out as what the
72
- // evidence favours; nothing routes by it and nothing commits it. It is called
73
- // in-process because a fit has no verdict for an exit status to carry, and the
74
- // `fit` CLI reads the TSVs only as committed. It never fails the run: an error
75
- // prints `metrics-refresh: preview: failed — <why>`, leaves the old file in
76
- // place and leaves the exit status as the other duties set it. That line stays
77
- // on stdout: the cockpit reads it off the receipts' `metrics` step, and
78
- // close-out's receipt keeps only stdout from a run that exits 0.
64
+ // FIT. After the cost guard wrote a guard, and only then, the Router's fit
65
+ // (`ticket-router.mjs`'s fitTable) runs in-process over the working-tree TSVs
66
+ // the guard just read and the guard just written, with the starting table
67
+ // (`router-table.json` beside the scripts) as its prior and no commit. It
68
+ // writes the Fit, `.fleet/router-fit.json`, through a temp file and a rename:
69
+ // `computed_at`, `guard_computed_at` (the guard's own `computed_at`),
70
+ // `guard` (the guard it used, as the router reads it: its `computed_at`,
71
+ // `tripped`, per-Cell `n` and `window_start`), `tsv_blobs` (the git blob id of
72
+ // each TSV it read, keyed by path as the guard keys its own), `prior` (the
73
+ // starting table's `fitted_commit`, `cells`, `classifier`, `splits` and
74
+ // `window_start`, and the install's `package.json` `version`) and the
75
+ // fitted `table`. `ticket-router.mjs route` routes by that `table`, read
76
+ // beside the guard; nothing commits the file. The Fit is a pure function of
77
+ // those records: the TSVs at the recorded blob ids, the guard and the prior
78
+ // fit to the same table again. With no records it is the starting table's
79
+ // fit, as any other. It is called in-process because a fit has no verdict
80
+ // for an exit status to carry, and the `fit` CLI reads the TSVs only as
81
+ // committed. It never fails the run: an error prints `metrics-refresh: fit:
82
+ // failed — <why>`, leaves the old file in place, so the run routes by the
83
+ // last Fit that computed, and leaves the exit status as the other duties set
84
+ // it. That line stays on stdout: the cockpit reads it off the receipts'
85
+ // `metrics` step, and close-out's receipt keeps only stdout from a run that
86
+ // exits 0.
79
87
  //
80
88
  // One `metrics-refresh: <duty>: …` line per duty on stdout. Exit 0 when no
81
89
  // duty failed; 1 when one failed — named on stderr, and the duties after
82
90
  // it did not run (each is safe to run again); 2 on a usage error. The
83
- // Preview fit is not one of those duties: it never sets the exit status.
91
+ // Fit is not one of those duties: it never sets the exit status.
84
92
 
85
93
  import { spawnSync } from "node:child_process";
86
94
  import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
@@ -94,7 +102,7 @@ import { COLUMNS as MEMBER_COLUMNS, ENDINGS, isImplementer, parseTsv as parseMem
94
102
  import { blobId } from "./pr-cost.mjs";
95
103
  import { FEATURE_COLUMNS, parseFeatures } from "./pull-attribution.mjs";
96
104
  import { REPORT_STATUSES } from "./report-files.mjs";
97
- import { DEFAULT_TABLE, INSTALL_PACKAGE, fitTable, installVersion, readGuard, validateTable } from "./ticket-router.mjs";
105
+ import { DEFAULT_TABLE, FIT_FILE, INSTALL_PACKAGE, fitTable, installVersion, readGuard, validateTable } from "./ticket-router.mjs";
98
106
  import { parseTierOutcomes } from "./tier-outcomes.mjs";
99
107
 
100
108
  const NAME = "metrics-refresh";
@@ -105,7 +113,7 @@ const MEMBERS = join("docs", "metrics", "member-outcomes.tsv");
105
113
  const TIERS = join("docs", "metrics", "tier-outcomes.tsv");
106
114
  const CORPUS = [MEMBERS, TIERS, FEATURES];
107
115
  const GUARD = join(".fleet", "cost-guard.json");
108
- const PREVIEW = join(".fleet", "router-preview.json");
116
+ const FIT = join(".fleet", FIT_FILE);
109
117
  // pr-cost.mjs --guard: 0 no cell tripped, 3 a cell tripped, 4 no verdict yet —
110
118
  // all three are verdicts its readers consume; anything else is a failure.
111
119
  const GUARD_VERDICT_EXITS = new Set([0, 3, 4]);
@@ -276,19 +284,19 @@ function costGuard(repo) {
276
284
  return g;
277
285
  }
278
286
 
279
- // The Preview fit over `repo`'s working-tree TSVs and `written`, the guard file the
287
+ // The Fit over `repo`'s working-tree TSVs and `written`, the guard file the
280
288
  // guard duty just wrote (parsed), with the router table at `tablePath` as its
281
- // prior, written to `.fleet/router-preview.json` through a temp file and a
282
- // rename. Throws on anything it cannot read, fit or write, before the rename, so
283
- // the old file stays as it was.
284
- export function writePreview(repo, written, { tablePath = DEFAULT_TABLE, packagePath = INSTALL_PACKAGE, now = new Date() } = {}) {
289
+ // prior, written to `.fleet/router-fit.json` through a temp file and a rename.
290
+ // Throws on anything it cannot read, fit or write, before the rename, so the
291
+ // old file stays as it was.
292
+ export function writeFit(repo, written, { tablePath = DEFAULT_TABLE, packagePath = INSTALL_PACKAGE, now = new Date() } = {}) {
285
293
  const guard = readGuard(written);
286
294
  if (guard === null) throw new Error(`${GUARD} is not a guard the router reads`);
287
295
  let prior;
288
296
  try {
289
297
  prior = validateTable(JSON.parse(readFileSync(tablePath, "utf8")));
290
298
  } catch (e) {
291
- throw new Error(`cannot read the installed router table ${tablePath}: ${e.code ?? e.message}`);
299
+ throw new Error(`cannot read the starting router table ${tablePath}: ${e.code ?? e.message}`);
292
300
  }
293
301
  if (prior instanceof Error) throw new Error(`${tablePath}: ${prior.message}`);
294
302
  // Keyed by the path as the guard keys its own (pr-cost.mjs reads these, relative to the workspace).
@@ -302,14 +310,14 @@ export function writePreview(repo, written, { tablePath = DEFAULT_TABLE, package
302
310
  const verdicts = read(TIERS, parseTierOutcomes);
303
311
  const features = read(FEATURES, parseFeatures);
304
312
  const table = fitTable({ prior, features, members, verdicts, guard, commit: null });
305
- const preview = {
313
+ const record = {
306
314
  computed_at: now.toISOString(),
307
315
  guard_computed_at: written.computed_at,
316
+ guard: { computed_at: written.computed_at, tripped: guard.tripped, n: guard.n, window_start: guard.window_start },
308
317
  tsv_blobs: Object.fromEntries(Object.entries(tsvBlobs).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))),
309
318
  prior: {
310
319
  fitted_commit: prior.fitted_commit,
311
320
  version: installVersion(packagePath),
312
- stage: prior.stage,
313
321
  cells: prior.cells,
314
322
  classifier: prior.classifier,
315
323
  splits: prior.splits,
@@ -317,28 +325,28 @@ export function writePreview(repo, written, { tablePath = DEFAULT_TABLE, package
317
325
  },
318
326
  table,
319
327
  };
320
- const file = join(repo, PREVIEW);
321
- writeFileSync(`${file}.tmp`, `${JSON.stringify(preview, null, 2)}\n`);
328
+ const file = join(repo, FIT);
329
+ writeFileSync(`${file}.tmp`, `${JSON.stringify(record, null, 2)}\n`);
322
330
  renameSync(`${file}.tmp`, file);
323
- return preview;
331
+ return record;
324
332
  }
325
333
 
326
- // The Preview fit as the run calls it: only beside a guard the guard duty wrote, and
334
+ // The Fit as the run calls it: only beside a guard the guard duty wrote, and
327
335
  // never a failure of the run — its error is a line, and the exit stays as it was.
328
- function preview(repo, written) {
329
- if (written === null) return say(`preview: skipped, no guard written — ${PREVIEW} left as it is`);
336
+ function fit(repo, written) {
337
+ if (written === null) return say(`fit: skipped, no guard written — ${FIT} left as it is`);
330
338
  let p;
331
339
  try {
332
- p = writePreview(repo, written);
340
+ p = writeFit(repo, written);
333
341
  } catch (e) {
334
- return say(`preview: failed — ${e.message}`);
342
+ return say(`fit: failed — ${e.message}`);
335
343
  }
336
- say(`preview: fitted ${p.table.n_rows} Pull${p.table.n_rows === 1 ? "" : "s"}, stage ${p.table.stage}${p.table.burn_in ? ", in burn-in" : ""}; ${PREVIEW} computed ${p.computed_at}`);
344
+ say(`fit: fitted ${p.table.n_rows} Pull${p.table.n_rows === 1 ? "" : "s"}${p.table.burn_in ? ", in burn-in" : ""}; ${FIT} computed ${p.computed_at}`);
337
345
  }
338
346
 
339
347
  function main() {
340
348
  const die = makeDie(NAME);
341
- const F = defineFlags(die, { flags: { repo: "value" } });
349
+ const F = defineFlags(die, { flags: { repo: "value", "no-fit": "bool" } });
342
350
  F.sweep();
343
351
  F.stray();
344
352
  let repo = F.arg("repo") === null ? null : resolve(F.arg("repo"));
@@ -361,7 +369,7 @@ function main() {
361
369
  return;
362
370
  }
363
371
  }
364
- preview(repo, written);
372
+ if (!F.has("no-fit")) fit(repo, written);
365
373
  }
366
374
 
367
375
  if (isCLI(import.meta.url)) main();
@@ -88,6 +88,7 @@ import { fleetFile, FleetDirUnresolvable } from "./fleet-dir.mjs";
88
88
  import { isCLI } from "./is-cli.mjs";
89
89
  import { parseTsv as parseMemberTsv } from "./member-outcomes.mjs";
90
90
  import { AttributionError, TRIP_POINTS, attribute, bootUnit, bootstrapDiffCI, parseFeatures, tally, underFloor } from "./pull-attribution.mjs";
91
+ import { STARTING_CELLS } from "./ledger-grammar.mjs";
91
92
  import { RulingError, parseTierOutcomes } from "./tier-outcomes.mjs";
92
93
 
93
94
  const NAME = "pr-cost";
@@ -97,8 +98,6 @@ const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
97
98
  // this constant in a reviewed change.
98
99
  export const WINDOW_START = "2026-10-03";
99
100
  export const BASELINE_CELL = "slow-high";
100
- // Stage 1 is the model axis at fixed `high`.
101
- export const STAGE_1 = ["slow-high", "task-high", "smol-high"];
102
101
  export const MIN_N = 20;
103
102
  export const EXIT = { ok: 0, tripped: 3, none: 4 };
104
103
  export const GH_PR_LIMIT = 1000;
@@ -221,10 +220,10 @@ export function computeReport({ members, tiers, features, prs, routerTable = nul
221
220
  }
222
221
  }
223
222
  const verdict = baseline.n < MIN_N ? "none" : tripped.length ? "tripped" : "ok";
224
- // Retire: every non-default stage-1 cell tripped before any row of either
223
+ // Retire: every non-default starting Cell tripped before any row of either
225
224
  // objective's set adopted one.
226
225
  const adopted = Object.values(routerTable?.rows ?? {}).some((set) => Object.values(set).some((c) => c !== BASELINE_CELL));
227
- const retire = !adopted && STAGE_1.filter((c) => c !== BASELINE_CELL).every((c) => tripped.includes(c));
226
+ const retire = !adopted && STARTING_CELLS.filter((c) => c !== BASELINE_CELL).every((c) => tripped.includes(c));
228
227
 
229
228
  return {
230
229
  window_start: windowStart,
@@ -312,7 +311,7 @@ export function formatReport(report) {
312
311
  for (const o of f.older) lines.push(line(o, "older"));
313
312
  }
314
313
  const b = report.baseline;
315
- lines.push(`# verdict: ${report.verdict} (baseline ${b.cell} n=${b.n}/${MIN_N}${report.tripped.length ? `; tripped ${report.tripped.join(" ")}` : ""})${report.retire ? " — retire: every non-default stage-1 cell tripped" : ""}`);
314
+ lines.push(`# verdict: ${report.verdict} (baseline ${b.cell} n=${b.n}/${MIN_N}${report.tripped.length ? `; tripped ${report.tripped.join(" ")}` : ""})${report.retire ? " — retire: every non-default starting Cell tripped" : ""}`);
316
315
  lines.push(`# window_start ${report.window_start}; pending PRs: ${report.pending.length ? report.pending.join(" ") : "none"}`);
317
316
  const ab = report.ab;
318
317
  lines.push(ab.status === "not-run"
@@ -2,7 +2,6 @@
2
2
  "window_start": "2026-10-03",
3
3
  "fitted_commit": "e5040b9a96d304b3ce8a40c2b2d35b143f66d450",
4
4
  "n_rows": 268,
5
- "stage": 2,
6
5
  "cells": [
7
6
  "slow-high",
8
7
  "task-high",
@@ -10,7 +9,7 @@
10
9
  "slow-medium",
11
10
  "task-max"
12
11
  ],
13
- "burn_in": true,
12
+ "burn_in": false,
14
13
  "splits": {},
15
14
  "rows": {
16
15
  "cost": {
@@ -16,6 +16,12 @@
16
16
  // routing by the objective's row set, and appends the Pull's
17
17
  // ticket-features row to the pending TSV (by default
18
18
  // `ticket-features.pending.tsv` beside `--guard`, in the run's `.fleet/`).
19
+ // With no `--table` it routes by the Fit, `router-fit.json` beside
20
+ // `--guard`, which metrics-refresh.mjs writes at phase 0. A Fit that is
21
+ // absent, unreadable, unparseable or fails validateTable routes by the
22
+ // starting table beside the script instead, and `REASON` names why:
23
+ // `fit-missing`, `fit-unreadable` or `fit-invalid`. A missing guard routes
24
+ // the default cell whatever the table, so it names no Fit there.
19
25
  // The paths its brief names are looked up under the working directory,
20
26
  // the checkout, for `named_lines`. Exit 0 on every data degradation — a
21
27
  // missing or unreadable issue, sizing or guard file degrades the line,
@@ -54,7 +60,7 @@ import { isDeepStrictEqual } from "node:util";
54
60
  import { isCLI } from "./is-cli.mjs";
55
61
  import { gitEnv } from "./git-env.mjs";
56
62
  import { makeDie, defineFlags } from "./arg.mjs";
57
- import { CELL, OBJECTIVES, POLICY_CELL, drawCell, formatRouting, isRulePath, parseMember } from "./ledger-grammar.mjs";
63
+ import { CELL, OBJECTIVES, POLICY_CELL, STARTING_CELLS, drawCell, formatRouting, isRulePath, parseMember } from "./ledger-grammar.mjs";
58
64
  import { objectiveFromReceipt, sessionFromReceipt } from "./phase0-receipt.mjs";
59
65
  import { parseTsv as parseMemberTsv } from "./member-outcomes.mjs";
60
66
  import {
@@ -75,8 +81,10 @@ const EXPLORE_EVERY = 5;
75
81
  export const MIN_N = 20;
76
82
  const ADOPT_RATIO = 0.75;
77
83
  export const FIT_EVERY_MERGED = 50;
78
- // Stage 2 adds the effort cells on the roles whose stage-1 cell survived.
79
- const STAGE2 = Object.freeze([{ cell: "slow-medium", survives: "slow-high" }, { cell: "task-max", survives: "task-high" }]);
84
+ // The starting Cells short of MIN_N merged PRs in a guard's `n`, each with its
85
+ // count, in their order: burn-in holds while any is. A Cell the guard has no
86
+ // count for has 0.
87
+ export const shortStartingCells = (n) => STARTING_CELLS.map((c) => [c, n[c] ?? 0]).filter(([, k]) => k < MIN_N);
80
88
  const KINDS = new Set(["bug", "enhancement", "documentation"]);
81
89
  const DAY_MS = 86_400_000;
82
90
 
@@ -344,7 +352,6 @@ export function validateTable(t) {
344
352
  }
345
353
  }
346
354
  if (typeof t.burn_in !== "boolean") return bad("`burn_in` is not a boolean");
347
- if (!Number.isInteger(t.stage) || t.stage < 1) return bad("`stage` is not a positive integer");
348
355
  const cl = t.classifier;
349
356
  if (cl === null || typeof cl !== "object") return bad("`classifier` is not an object");
350
357
  if (cl.b !== null && cl.b !== "haiku" && cl.b !== "jev") return bad("`classifier.b` is not null, \"haiku\" or \"jev\"");
@@ -368,13 +375,20 @@ export function bArmLive(table, objective) {
368
375
  /** The row a group routes by: its own, else the `*` row's — as a name no node of the table holds does, such as a group a Routing filed under another table names. */
369
376
  export const rowFor = (rows, stratum) => rows[stratum] ?? rows["*"];
370
377
 
378
+ /**
379
+ * The Cells an exploring Pull may draw, before the guard's tripped Cells (and, after burn-in, the policy Cell) leave
380
+ * any out: burn-in draws the starting Cells, whatever `cells` the table holds, and a draw after it the table's own.
381
+ * The fit judges `burn_in` over the same starting Cells, so the Cells that end burn-in are the Cells it draws.
382
+ */
383
+ const drawPool = (table) => (table.burn_in ? STARTING_CELLS : table.cells);
384
+
371
385
  /**
372
386
  * What `route` does with one row under one guard, with no per-Pull input.
373
387
  * `guard` is readGuard's answer or null. `policy` is the row's Cell, or the
374
388
  * default cell when there is no guard or the row's Cell is tripped; `reason`
375
389
  * is `guard-missing`, `table-cell-tripped` or `ok`. `draw` is what an
376
390
  * exploring Pull picks from — `by` `burn-in` (every Pull) or `every-5th` —
377
- * over `cells`: the table's Cells less the tripped, and on an every-5th draw
391
+ * over `cells`: drawPool()'s Cells less the tripped, and on an every-5th draw
378
392
  * less the `cost` row's Cell for the stratum too, as the guard leaves it (the
379
393
  * default cell when that row's Cell is tripped), whichever objective routes
380
394
  * the row. It is null with no guard and when no Cell is left to draw.
@@ -386,7 +400,7 @@ export function rowDispatch({ table, guard, objective, stratum }) {
386
400
  const adjust = (cell) => (tripped.has(cell) ? POLICY_CELL : cell);
387
401
  const row = rowFor(table.rows[objective], stratum);
388
402
  const by = table.burn_in ? "burn-in" : "every-5th";
389
- const left = table.cells.filter((c) => !tripped.has(c));
403
+ const left = drawPool(table).filter((c) => !tripped.has(c));
390
404
  const cells = table.burn_in ? left : left.filter((c) => c !== adjust(rowFor(table.rows.cost, stratum)));
391
405
  return {
392
406
  policy: adjust(row),
@@ -430,6 +444,27 @@ export function readGuard(raw) {
430
444
  return r.ok ? r.guard : null;
431
445
  }
432
446
 
447
+ /** The Fit's file name: metrics-refresh.mjs writes it beside the cost guard, and `route` reads it there. */
448
+ export const FIT_FILE = "router-fit.json";
449
+
450
+ /**
451
+ * The table the Fit beside `guardPath` holds, `{ table, fallback: null }`, or `{ table: null, fallback }` when
452
+ * there is none to route by: `fallback` is the Routing `REASON` that names why — `fit-missing` for no file,
453
+ * `fit-unreadable` for one that will not read or parse, `fit-invalid` for one whose `table` validateTable refuses.
454
+ */
455
+ export function readFitBeside(guardPath) {
456
+ let text;
457
+ try {
458
+ text = readFileSync(join(dirname(guardPath), FIT_FILE), "utf8");
459
+ } catch (e) {
460
+ return { table: null, fallback: e.code === "ENOENT" ? "fit-missing" : "fit-unreadable" };
461
+ }
462
+ let fit;
463
+ try { fit = JSON.parse(text); } catch { return { table: null, fallback: "fit-unreadable" }; }
464
+ const table = validateTable(fit?.table);
465
+ return table instanceof Error ? { table: null, fallback: "fit-invalid" } : { table, fallback: null };
466
+ }
467
+
433
468
  /** The sizing verdict on a live B Pull: `{ src, label, usd }`, or null when it is unusable. */
434
469
  function readSizing(raw, classifier) {
435
470
  if (raw === null || typeof raw !== "object" || raw.source !== classifier.b) return null;
@@ -456,15 +491,18 @@ export function sessionDate(session) {
456
491
  * it leaves out the cell the `cost` set routes the group to, whichever set
457
492
  * routes the Pull, so a Pull draws the same cell under both. A live B Pull
458
493
  * records its sizing verdict and routes as an A Pull does: a label names no
459
- * group of the tree.
494
+ * group of the tree. `fallback` is readFitBeside's REASON when `table` is the
495
+ * starting table standing in for a Fit, else null: it is the first thing that
496
+ * went wrong, except beside no guard, where the table routes nothing.
460
497
  * @returns {{ line: string, row: Record<string,string> }}
461
498
  */
462
499
  export function route({
463
500
  session, ticket, arm, implRow, chainHead = false, issue, sizing = null, guard, table, objective, now = Date.now(),
464
- root = process.cwd(), version = installVersion(),
501
+ root = process.cwd(), version = installVersion(), fallback = null,
465
502
  }) {
466
503
  let reason = null;
467
504
  const degrade = (r) => { reason ??= r; };
505
+ if (fallback !== null && guard !== null) degrade(fallback);
468
506
 
469
507
  const metrics = issueMetrics(issue, now);
470
508
  if (metrics === null) degrade("no-issue-json");
@@ -501,7 +539,7 @@ export function route({
501
539
  const exploring = table.burn_in || (implRow % EXPLORE_EVERY === 0 && !chainHead);
502
540
  if (exploring) {
503
541
  const policyCell = table.burn_in ? null : drawRow.policy;
504
- if (table.cells.some((c) => c !== policyCell && guard.tripped.includes(c))) degrade("guard-tripped");
542
+ if (drawPool(table).some((c) => c !== policyCell && guard.tripped.includes(c))) degrade("guard-tripped");
505
543
  if (drawRow.draw !== null) {
506
544
  // rowDispatch already left the policy Cell out of `cells`: nothing more to withhold.
507
545
  const d = drawCell({ session, ticket, policyCell: null, cells: drawRow.draw.cells });
@@ -742,7 +780,10 @@ function judgeSpeedRow(est, pulls, cells, tripped, costCell) {
742
780
  * `reasons.speed` holds `judgeSpeedRow()`'s record for each node with a `cost`
743
781
  * row of its own (the root always has one), from that row's cell, the base when
744
782
  * the record has no cell; a node with none holds its parent's `speed` row and
745
- * an `unjudged` record.
783
+ * an `unjudged` record. `cells` is the prior's: the fit adds no Cell. `burn_in`
784
+ * holds until every starting Cell has MIN_N merged PRs on its newest generation
785
+ * (`guard.n`, which starts again at 0 when a role's model changes): no other
786
+ * Cell the table holds ends it or holds it, whatever its merged PRs.
746
787
  */
747
788
  export function fitTable({ prior, features, members, verdicts, guard, commit = null }) {
748
789
  const window = guard.window_start ?? prior.window_start ?? null;
@@ -751,44 +792,27 @@ export function fitTable({ prior, features, members, verdicts, guard, commit = n
751
792
  const { estimates, pulls } = estimate(units, order, nodes);
752
793
  const tripped = new Set(guard.tripped);
753
794
 
754
- let { stage, cells } = prior;
755
- cells = [...cells];
756
- // The rows and their reasons over `cells`: a fitted table's `reasons` cover exactly its `cells`.
757
- const judgeRows = () => {
758
- const rows = { cost: {}, speed: {} };
759
- const reasons = { cost: {}, speed: {} };
760
- for (const s of nodes) {
761
- const up = parentOf(s);
762
- const cost = judgeRow(estimates[s], pulls[s], cells, tripped);
763
- const own = cost.cell !== null || up === null;
764
- const costCell = cost.cell ?? (up === null ? POLICY_CELL : rows.cost[up]);
765
- const speed = own ? judgeSpeedRow(estimates[s], pulls[s], cells, tripped, costCell) : unjudged();
766
- const speedCell = speed.cell ?? (own ? costCell : rows.speed[up]);
767
- rows.cost[s] = costCell;
768
- rows.speed[s] = speedCell;
769
- reasons.cost[s] = { ...cost, cell: costCell };
770
- reasons.speed[s] = { ...speed, cell: speedCell };
771
- }
772
- return { rows, reasons };
773
- };
774
- let { rows, reasons } = judgeRows();
775
- const atN = (c) => (guard.n[c] ?? 0) >= MIN_N;
776
- const adopted = Object.values(rows).some((set) => set["*"] !== POLICY_CELL);
777
- if (stage === 1 && cells.every(atN) && (adopted || cells.some((c) => tripped.has(c)))) {
778
- stage = 2;
779
- for (const { cell, survives } of STAGE2) {
780
- if (!cells.includes(cell) && cells.includes(survives) && !tripped.has(survives)) cells.push(cell);
781
- }
782
- // The stage-2 cells were added after the rows were judged: judge the rows again over the new `cells`.
783
- ({ rows, reasons } = judgeRows());
795
+ // The rows and their reasons over the table's `cells`: a fitted table's `reasons` cover exactly its `cells`.
796
+ const rows = { cost: {}, speed: {} };
797
+ const reasons = { cost: {}, speed: {} };
798
+ for (const s of nodes) {
799
+ const up = parentOf(s);
800
+ const cost = judgeRow(estimates[s], pulls[s], prior.cells, tripped);
801
+ const own = cost.cell !== null || up === null;
802
+ const costCell = cost.cell ?? (up === null ? POLICY_CELL : rows.cost[up]);
803
+ const speed = own ? judgeSpeedRow(estimates[s], pulls[s], prior.cells, tripped, costCell) : unjudged();
804
+ const speedCell = speed.cell ?? (own ? costCell : rows.speed[up]);
805
+ rows.cost[s] = costCell;
806
+ rows.speed[s] = speedCell;
807
+ reasons.cost[s] = { ...cost, cell: costCell };
808
+ reasons.speed[s] = { ...speed, cell: speedCell };
784
809
  }
785
810
  return {
786
811
  window_start: window,
787
812
  fitted_commit: commit,
788
813
  n_rows: units.length,
789
- stage,
790
- cells,
791
- burn_in: !cells.every(atN),
814
+ cells: prior.cells,
815
+ burn_in: shortStartingCells(guard.n).length > 0,
792
816
  splits: prior.splits,
793
817
  rows,
794
818
  classifier: prior.classifier,
@@ -898,11 +922,15 @@ function main() {
898
922
  if (foreign) die(`--${foreign} does not apply to ${mode === "check" ? "--check" : mode}`);
899
923
  const need = (name) => F.arg(name) ?? die(`${mode === "check" ? "--check" : mode} needs --${name}`);
900
924
 
925
+ // `route` with no `--table` routes by the Fit beside `--guard`, else by the starting table.
926
+ const fit = mode === "route" && F.arg("table") === null && F.arg("guard") !== null ? readFitBeside(F.arg("guard")) : null;
901
927
  const tablePath = mode === "route" ? (F.arg("table") ?? DEFAULT_TABLE) : need("table");
902
- let table;
903
- try { table = JSON.parse(readFileSync(tablePath, "utf8")); } catch (e) { die(`cannot read the router table ${tablePath}: ${e.message}`); }
904
- const valid = validateTable(table);
905
- if (valid instanceof Error) die(`${tablePath}: ${valid.message}`);
928
+ let table = fit?.table ?? null;
929
+ if (table === null) {
930
+ try { table = JSON.parse(readFileSync(tablePath, "utf8")); } catch (e) { die(`cannot read the router table ${tablePath}: ${e.message}`); }
931
+ const valid = validateTable(table);
932
+ if (valid instanceof Error) die(`${tablePath}: ${valid.message}`);
933
+ }
906
934
 
907
935
  if (mode === "route") {
908
936
  const ticket = need("ticket");
@@ -938,6 +966,7 @@ function main() {
938
966
  const { line, row } = route({
939
967
  session, ticket: Number(ticket), arm, implRow: Number(implRowArg), chainHead: F.has("chain-head"),
940
968
  issue: readJson(issuePath), sizing: readJson(F.arg("sizing")), guard: readGuard(readJson(guardPath)), table, objective, root, version,
969
+ fallback: fit?.fallback ?? null,
941
970
  });
942
971
  const pending = F.arg("pending") ?? join(dirname(guardPath), "ticket-features.pending.tsv");
943
972
  // The header decision and the append are not atomic and take no lock. That is
@@ -1037,7 +1066,7 @@ function main() {
1037
1066
  const next = joined(() => fitTable({ prior: table, features, members, verdicts, guard, commit: sha }));
1038
1067
  writeFileSync(`${tablePath}.tmp`, `${JSON.stringify(next, null, 2)}\n`);
1039
1068
  renameSync(`${tablePath}.tmp`, tablePath);
1040
- process.stdout.write(`${NAME}: fitted ${next.n_rows} Pulls at ${short(sha)}; rows ${JSON.stringify(next.rows)}; burn_in ${next.burn_in}; stage ${next.stage}; cells ${cellCounts(next.estimates)}\n${rowLines(next.reasons)}`);
1069
+ process.stdout.write(`${NAME}: fitted ${next.n_rows} Pulls at ${short(sha)}; rows ${JSON.stringify(next.rows)}; burn_in ${next.burn_in}; cells ${cellCounts(next.estimates)}\n${rowLines(next.reasons)}`);
1041
1070
  }
1042
1071
 
1043
1072
  if (isCLI(import.meta.url)) main();
@@ -104,7 +104,7 @@ issue number among the reasons — comes before that PR's WARNING and says why.
104
104
 
105
105
  **Drain the pending ticket-features rows and refresh the cost guard, after
106
106
  the member-outcomes scrape and every `tier-outcomes.mjs append`, before the
107
- metrics files are committed.** `~/.omp/plugins/node_modules/@feigi/fleet-ctl/scripts/fleet-run metrics-refresh.mjs`
107
+ metrics files are committed.** `~/.omp/plugins/node_modules/@feigi/fleet-ctl/scripts/fleet-run metrics-refresh.mjs --no-fit`
108
108
  moves `.fleet/ticket-features.pending.tsv` — the row the router script
109
109
  appended for each Pull at dispatch — into `docs/metrics/ticket-features.tsv`,
110
110
  deduped on `session`+`agent`, so this run's own rows are in the file that gets
@@ -112,10 +112,9 @@ committed; that file is a run artifact too and is committed with the other
112
112
  two. It then widens a `docs/metrics/member-outcomes.tsv` written before the
113
113
  newest columns, as at phase 0 — a file already at the current width is left
114
114
  as it is — and then runs `pr-cost.mjs --guard`, which rewrites
115
- `.fleet/cost-guard.json` from all three files. After a guard it wrote it writes
116
- the Preview fit, `.fleet/router-preview.json`, for the cockpit alone: it is not
117
- a metrics file and is never committed, and its `preview: failed — <why>` line
118
- leaves the exit as it was. Exit 0: every duty ran. The guard's
115
+ `.fleet/cost-guard.json` from all three files. `--no-fit` computes no Fit:
116
+ one Fit per run, at phase 0, so the rows this close-out commits route the
117
+ next run, and `.fleet/router-fit.json` is left as it is. Exit 0: every duty ran. The guard's
119
118
  own exit 3 (a cell tripped) and 4 (no verdict yet, baseline too thin) are
120
119
  verdicts the router and `fleet-tick.mjs` read, never failures; the script
121
120
  absorbs them. Exit 1 names the duty that failed on stderr and the duties after it
@@ -247,10 +247,15 @@ and the guard the script also widens a `docs/metrics/member-outcomes.tsv`
247
247
  written before the newest columns: each row gains them, `ending` reads
248
248
  `unknown` on an implementer's row, and nothing else changes. Without that,
249
249
  phase 0, the close-out scrape and `tier-outcomes.mjs append` refuse the file.
250
- After a guard it wrote, the script writes the Preview fit,
251
- `.fleet/router-preview.json`, which only the cockpit reads: nothing routes by
252
- it and nothing commits it, and a `metrics-refresh: preview: failed — <why>`
253
- line leaves the exit at 0, so it never stops the run.
250
+ After a guard it wrote, the script computes the Fit — the router's table fitted
251
+ over the three metrics files and that guard, with the starting table beside the
252
+ scripts as its prior — and writes it to `.fleet/router-fit.json`, which every
253
+ Pull of this run routes by. Nothing commits it. One Fit per run: close-out
254
+ computes none, so each close-out's rows route the next run. A
255
+ `metrics-refresh: fit: failed — <why>` line leaves the previous file as it
256
+ was and the exit at 0, so it never stops the run: the run routes by the last
257
+ Fit that computed, else by the starting table. A skipped guard skips the Fit
258
+ too, and both files are left as they are.
254
259
 
255
260
  ## Launch the cockpit
256
261
 
@@ -276,8 +276,13 @@ one; a B Pull routes exactly as an A one until the table opens arm B.
276
276
  row set of the run's Objective, `OBJECTIVE`, which it reads off the phase-0
277
277
  receipt. The printed line is the
278
278
  whole routing decision — never re-derive `CELL` from the table, the guard or
279
- this paragraph. A missing or unreadable `.fleet/cost-guard.json` routes the
280
- default cell only (`REASON=guard-missing`), burn-in included. On the ledger the
279
+ this paragraph. The table it routes by is the Fit phase 0 wrote,
280
+ `.fleet/router-fit.json` beside `--guard`; a Fit that is absent, unreadable,
281
+ unparseable or not a valid table routes by the starting table beside the
282
+ script, and `REASON` says so (`fit-missing`, `fit-unreadable`, `fit-invalid`).
283
+ A missing or unreadable `.fleet/cost-guard.json` routes the
284
+ default cell only (`REASON=guard-missing`), burn-in included, whatever the Fit
285
+ holds. On the ledger the
281
286
  whole line, `REASON` with it, is the Pull's `## Routed` entry; a row carries no
282
287
  `route=` (an older row's `route=<REASON>` still reads).
283
288
 
@@ -441,10 +446,12 @@ controller's probe could not look.
441
446
  **Every 5th Pull by ledger count goes at an exploration cell.** Count the `impl-`
442
447
  rows in `.fleet/ledger.md` at Pull time; the Pull that creates row 5, 10, 15 …
443
448
  is an Exploration Pull, and the router draws its cell: `k = 1 +
444
- (sha256("<session>\t<ticket>")[0:8] mod K)` over `router-table.json`'s
449
+ (sha256("<session>\t<ticket>")[0:8] mod K)` over the routing table's
445
450
  `cells` minus the policy cell, in token order. Under either Objective that
446
451
  policy cell is the `cost` row set's, so the draw is the same under both. While the table's `burn_in` is
447
- true every Pull draws, over every cell, the policy cell included. An
452
+ true every Pull draws, over the starting cells (the three models at `high`) the
453
+ guard has not tripped, the policy cell included; a cell the table lists beyond
454
+ them is never drawn. An
448
455
  Exploration Pull records `tier=<cell>` in the row, and a replacement inherits the row's tier —
449
456
  written at the Pull's row step, ahead of `ledger.mjs dispatch`, which reads it
450
457
  and prints `fleet-implementer-<cell>` as the `agent` to dispatch. A Pull the