trantor 0.18.146 → 0.18.148

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 (43) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/bin/advise.mjs +23 -7
  4. package/bin/capacity.mjs +18 -2
  5. package/bin/cli.mjs +6 -2
  6. package/bin/connect.mjs +10 -3
  7. package/bin/crew-runner.mjs +25 -2
  8. package/bin/dispatch.mjs +78 -0
  9. package/bin/integrate.mjs +14 -2
  10. package/bin/review.mjs +35 -0
  11. package/hooks/sessionstart.mjs +4 -1
  12. package/hub/routes/capacity.mjs +30 -23
  13. package/hub/routes/dispatcher.mjs +97 -0
  14. package/hub/routes/insights.mjs +68 -4
  15. package/hub/routes/worktree-status.mjs +56 -0
  16. package/hub.mjs +2 -1
  17. package/kimi.plugin.json +1 -1
  18. package/lib/capacity.mjs +94 -16
  19. package/lib/dispatcher/acceptance.mjs +314 -0
  20. package/lib/dispatcher/accounts.mjs +442 -0
  21. package/lib/dispatcher/admission.mjs +719 -0
  22. package/lib/dispatcher/breakers.mjs +70 -0
  23. package/lib/dispatcher/executor.mjs +486 -0
  24. package/lib/dispatcher/forecast.mjs +391 -0
  25. package/lib/dispatcher/harness/boundary-linux.mjs +246 -0
  26. package/lib/dispatcher/harness/boundary-macos.mjs +237 -0
  27. package/lib/dispatcher/harness/contract.mjs +198 -0
  28. package/lib/dispatcher/harness/crew.mjs +463 -0
  29. package/lib/dispatcher/harness/publication.mjs +188 -0
  30. package/lib/dispatcher/migrate-attempts.mjs +51 -0
  31. package/lib/dispatcher/planner.mjs +516 -0
  32. package/lib/dispatcher/policy.mjs +9 -0
  33. package/lib/dispatcher/preflight.mjs +247 -0
  34. package/lib/dispatcher/resources.mjs +44 -0
  35. package/lib/dispatcher/schemas.mjs +3 -1
  36. package/lib/dispatcher/spend.mjs +319 -0
  37. package/lib/dispatcher/store.mjs +207 -2
  38. package/lib/fitness.mjs +227 -41
  39. package/lib/review-gate.mjs +63 -0
  40. package/lib/telemetry-ship.mjs +8 -7
  41. package/lib/worktree-status.mjs +216 -0
  42. package/mcp.mjs +53 -7
  43. package/package.json +1 -1
@@ -2,6 +2,7 @@
2
2
  import { readFileSync, statSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { join } from "node:path";
5
+ import { classifyAttemptVerification, validateAcceptanceRecord } from "../../lib/dispatcher/acceptance.mjs";
5
6
 
6
7
  let ledgerCache = { mtimeMs: -1, rows: [] };
7
8
  const TURN_OUTCOMES = new Set(["completed", "asked", "blocked", "no-delivery", "empty", "stalled", "cut", "rejected", "api-error"]);
@@ -26,19 +27,34 @@ function validAttempt(attempt, row, nowMs) {
26
27
  if (attempt.commit !== "" && (typeof attempt.commit !== "string" || !/^[0-9a-f]{40}$/i.test(attempt.commit))) return null;
27
28
  if (!TURN_OUTCOMES.has(attempt.outcome) || attempt.outcome !== row.outcome || typeof attempt.infraFailure !== "boolean") return null;
28
29
  if (!(attempt.tokens === null || safeInteger(attempt.tokens))) return null;
29
- return {
30
+ // B2 (#14672): additive verification evidence, validated but NOT trusted — a producer-embedded
31
+ // acceptance is re-adjudicated on every read and never counts unless it survives independence.
32
+ const acceptance = attempt.acceptance == null ? null : validateAcceptanceRecord(attempt.acceptance);
33
+ if (attempt.acceptance != null && !acceptance) return null;
34
+ const producerIdentityIds = attempt.producerIdentityIds === undefined || attempt.producerIdentityIds === null
35
+ ? undefined : (Array.isArray(attempt.producerIdentityIds) && attempt.producerIdentityIds.length <= 100
36
+ && attempt.producerIdentityIds.every(id => stringWithin(id, 200)) ? attempt.producerIdentityIds : null);
37
+ if (producerIdentityIds === null) return null;
38
+ const cardRevision = attempt.cardRevision === undefined || attempt.cardRevision === null
39
+ ? undefined : (safeInteger(attempt.cardRevision) ? attempt.cardRevision : null);
40
+ if (cardRevision === null) return null;
41
+ const valid = {
30
42
  id: attempt.id, card: attempt.card, seat: attempt.seat, project: attempt.project,
31
43
  provider: attempt.provider, model: attempt.model, effort: attempt.effort, harness: attempt.harness,
32
44
  taskKind: attempt.taskKind, difficulty: attempt.difficulty, machine: attempt.machine,
33
45
  start: attempt.start, end: attempt.end, commit: attempt.commit, outcome: attempt.outcome,
34
46
  infraFailure: attempt.infraFailure, tokens: attempt.tokens,
35
47
  };
48
+ if (acceptance !== null) valid.acceptance = acceptance;
49
+ if (producerIdentityIds !== undefined) valid.producerIdentityIds = producerIdentityIds;
50
+ if (cardRevision !== undefined) valid.cardRevision = cardRevision;
51
+ return valid;
36
52
  }
37
53
 
38
54
  function validTurnRow(row, nowMs) {
39
55
  if (!row || typeof row !== "object" || Array.isArray(row)) return null;
40
56
  if ("prompt" in row || "output" in row || "text" in row) return null;
41
- if (typeof row.id !== "string" || !/^[0-9a-f]{32}$/i.test(row.id) || row.v !== 1) return null;
57
+ if (typeof row.id !== "string" || !/^[0-9a-f]{32}$/i.test(row.id) || (row.v !== 1 && row.v !== 2)) return null;
42
58
  if (!safeInteger(row.ts, 1) || row.ts > nowMs + 60000 || !safeInteger(row.turn, 1)) return null;
43
59
  if (!stringWithin(row.persona, 120) || !stringWithin(row.agent, 80) || !stringWithin(row.project, 80)) return null;
44
60
  // A machine with no label configured reports "" (lib/machine-label.mjs): that is a valid row, not a dropped one.
@@ -55,13 +71,55 @@ function validTurnRow(row, nowMs) {
55
71
  if (row.stderrTail !== undefined && (typeof row.stderrTail !== "string" || row.stderrTail.length > 8000)) return null;
56
72
  if (row.extensions !== undefined && !safeInteger(row.extensions)) return null;
57
73
  if (row.boxMs !== undefined && !safeInteger(row.boxMs)) return null;
74
+ // B2 (#14672, §5.2): v2 adds top-level executionAttemptId/generation/segmentId to the same v1
75
+ // fields and the same dedupe ID. Links are all-null, or a non-null attempt id with a positive
76
+ // generation (segment may stay null when unknown); unbound/forged v2 links are rejected, never
77
+ // stored, and never downgraded to v1.
78
+ if (row.v === 2) {
79
+ const attemptIdOk = row.executionAttemptId == null || stringWithin(row.executionAttemptId, 200);
80
+ const generationOk = row.executionGeneration == null || safeInteger(row.executionGeneration, 1);
81
+ const segmentOk = row.executionSegmentId == null || stringWithin(row.executionSegmentId, 200);
82
+ const linked = row.executionAttemptId != null && row.executionGeneration != null;
83
+ const unlinked = row.executionAttemptId == null && row.executionGeneration == null;
84
+ if (!attemptIdOk || !generationOk || !segmentOk || (!linked && !unlinked)) return null;
85
+ }
58
86
  const attempt = row.attempt === undefined ? null : validAttempt(row.attempt, row, nowMs);
59
87
  if (row.attempt !== undefined && !attempt) return null;
60
88
  const valid = { ...row, id: row.id.toLowerCase(), verdict: row.verdict.slice(0, 600) };
89
+ if (row.v === 1) {
90
+ delete valid.executionAttemptId;
91
+ delete valid.executionGeneration;
92
+ delete valid.executionSegmentId;
93
+ } else {
94
+ valid.executionAttemptId = row.executionAttemptId == null ? null : String(row.executionAttemptId);
95
+ valid.executionGeneration = row.executionGeneration == null ? null : Number(row.executionGeneration);
96
+ valid.executionSegmentId = row.executionSegmentId == null ? null : String(row.executionSegmentId);
97
+ }
61
98
  if (attempt) valid.attempt = attempt;
62
99
  return valid;
63
100
  }
64
101
 
102
+ // The v2 executor-attempt view (§5.2 read projection): attempts with explicit pending/legacy
103
+ // status. Only an acceptance that survives read-side re-adjudication marks accepted/failed; a
104
+ // producer-embedded acceptance is rejected and the attempt stays pending.
105
+ function executorAttemptView(row) {
106
+ const attempt = row.attempt;
107
+ const verification = classifyAttemptVerification({ ...attempt, executionAttemptId: row.executionAttemptId == null ? null : row.executionAttemptId });
108
+ return {
109
+ id: row.executionAttemptId != null ? row.executionAttemptId : attempt.id,
110
+ generation: row.executionGeneration == null ? null : row.executionGeneration,
111
+ segmentId: row.executionSegmentId == null ? null : row.executionSegmentId,
112
+ provenance: row.executionAttemptId != null ? "managed" : "legacy",
113
+ project: attempt.project, card: attempt.card, cardRevision: attempt.cardRevision === undefined ? null : attempt.cardRevision,
114
+ seat: attempt.seat, producerIdentityIds: attempt.producerIdentityIds === undefined ? [] : attempt.producerIdentityIds,
115
+ provider: attempt.provider, model: attempt.model, effort: attempt.effort, harness: attempt.harness,
116
+ taskKind: attempt.taskKind, difficulty: attempt.difficulty, machine: attempt.machine,
117
+ outcome: attempt.outcome, start: attempt.start, end: attempt.end, commit: attempt.commit,
118
+ tokens: attempt.tokens, infraFailure: attempt.infraFailure,
119
+ verification: { status: verification.status, acceptance: verification.acceptance, rejected: verification.rejected },
120
+ };
121
+ }
122
+
65
123
  export async function routeInsights({ res, q, P, req, auth, ctx }) {
66
124
  const { state, json, canon, now, body, scopeAllows, filterReadable, turnTelemetry, AUTH_MODE } = ctx;
67
125
  if (req.method === "POST" && P === "/telemetry/turns") {
@@ -101,8 +159,14 @@ export async function routeInsights({ res, q, P, req, auth, ctx }) {
101
159
  project: q.project || "", agent: q.agent || "",
102
160
  since: numberQuery(q.since, 0), until: numberQuery(q.until, Number.MAX_SAFE_INTEGER),
103
161
  });
104
- const attempts = rows.filter(row => row.attempt).map(row => row.attempt);
105
- return json(res, 200, { attempts: filterReadable(auth, attempts, attempt => attempt.project || "").slice(0, limit) });
162
+ const withAttempts = rows.filter(row => row.attempt);
163
+ // Default remains the legacy projection (§5.2); `?version=2` exposes executor attempts with
164
+ // explicit pending/legacy status. Operational "completed" stats never change here.
165
+ if (q.version === "2") {
166
+ const projected = withAttempts.map(row => executorAttemptView(row));
167
+ return json(res, 200, { attempts: filterReadable(auth, projected, attempt => attempt.project || "").slice(0, limit) });
168
+ }
169
+ return json(res, 200, { attempts: filterReadable(auth, withAttempts.map(row => row.attempt), attempt => attempt.project || "").slice(0, limit) });
106
170
  }
107
171
  if (req.method === "GET" && P === "/economics") { // the brain's books, surfaced: scrooge ledger + quota profile
108
172
  const out = { scrooge: null, lifetime: null, profile: null };
@@ -0,0 +1,56 @@
1
+ import { z } from "zod";
2
+
3
+ const name = z.string().min(1).max(80).regex(/^[A-Za-z0-9_.-]+$/);
4
+ const file = z.object({
5
+ path: z.string().min(1).max(500).refine(path => !path.includes("\0") && !path.includes("\n")),
6
+ status: z.string().length(2),
7
+ added: z.number().int().nonnegative().nullable(),
8
+ removed: z.number().int().nonnegative().nullable(),
9
+ });
10
+ const snapshot = z.object({
11
+ seat: name,
12
+ project: name,
13
+ machine: name,
14
+ branch: z.string().min(1).max(200).nullable(),
15
+ head: z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),
16
+ ahead: z.number().int().nonnegative().nullable(),
17
+ fileCount: z.number().int().nonnegative(),
18
+ files: z.array(file).max(200),
19
+ observedAt: z.number().int().positive(),
20
+ sequence: z.number().int().positive(),
21
+ }).refine(status => status.fileCount >= status.files.length);
22
+
23
+ const latest = new Map();
24
+
25
+ export async function routeWorktreeStatus({ req, res, q, P, auth, ctx }) {
26
+ if (P !== "/worktree-status" || (req.method !== "GET" && req.method !== "POST")) return false;
27
+ if (req.method === "GET") {
28
+ const parsed = name.safeParse(q.project);
29
+ if (!parsed.success) return ctx.json(res, 400, { error: "project required" });
30
+ const project = ctx.canon(parsed.data);
31
+ if (!ctx.canRead(auth, project)) return ctx.json(res, 403, { error: "forbidden" });
32
+ const statuses = [...latest.values()]
33
+ .filter(status => status.project === project)
34
+ .sort((a, b) => a.seat.localeCompare(b.seat) || a.machine.localeCompare(b.machine));
35
+ return ctx.json(res, 200, { statuses });
36
+ }
37
+
38
+ const parsed = snapshot.safeParse(await ctx.body(req));
39
+ if (!parsed.success) return ctx.json(res, 400, { error: "invalid worktree status", issues: parsed.error.issues });
40
+ const status = { ...parsed.data, project: ctx.canon(parsed.data.project) };
41
+ if (ctx.AUTH_MODE === "enforce" && !ctx.scopeAllows(auth?.identity, status.project, "write")) {
42
+ return ctx.json(res, 403, { error: "forbidden" });
43
+ }
44
+ if (auth?.identity?.kind === "agent" && auth.identity.name !== `${status.seat}:${status.project}`) {
45
+ return ctx.json(res, 403, { error: "agent may report only its own seat" });
46
+ }
47
+ const key = `${status.project}\0${status.seat}\0${status.machine}`;
48
+ const previous = latest.get(key);
49
+ if (previous && (status.observedAt < previous.observedAt ||
50
+ (status.observedAt === previous.observedAt && status.sequence <= previous.sequence))) {
51
+ return ctx.json(res, 200, { ok: true, status: previous });
52
+ }
53
+ latest.set(key, status);
54
+ ctx.pushEventToStreams({ ts: ctx.now(), type: "worktree-status", project: status.project, by: status.seat, status });
55
+ return ctx.json(res, 200, { ok: true, status });
56
+ }
package/hub.mjs CHANGED
@@ -22,6 +22,7 @@ import { routeReviews } from "./hub/routes/reviews.mjs";
22
22
  import { migrateReviews } from "./hub/review-store.mjs";
23
23
  import { routeDevices } from "./hub/routes/devices.mjs";
24
24
  import { createSessionRuntime } from "./hub/routes/session.mjs";
25
+ import { routeWorktreeStatus } from "./hub/routes/worktree-status.mjs";
25
26
  import { routeCapacity } from "./hub/routes/capacity.mjs"; // #14653: registered ahead of sessionChat so the /machines/health mirror runs first
26
27
  import { createNotifier } from "./hub/notifier.mjs";
27
28
  import { createHubDiagnostics } from "./lib/hub-diagnostics.mjs";
@@ -140,7 +141,7 @@ const sessionChat = createSessionRuntime({
140
141
  appendEvent: events.appendEvent, pushEventToStreams: events.pushEventToStreams, notifier,
141
142
  attachmentsDir: join(DATA_DIR, "attachments"),
142
143
  });
143
- const routes = [routeDevices, routeAdmin, routeCards, routeInsights, routeMessages, routeReviews, routeCapacity, sessionChat.route];
144
+ const routes = [routeWorktreeStatus, routeDevices, routeAdmin, routeCards, routeInsights, routeMessages, routeReviews, routeCapacity, sessionChat.route];
144
145
 
145
146
  const publicAuth = createAuthRuntime({
146
147
  state: store.state, markDirty: store.markDirty, AUTH_MODE: "enforce", SUPERSEDE_GRACE_MS,
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.146",
3
+ "version": "0.18.148",
4
4
  "description": "Trantor — the hub-world for AI agent crews: live message bus, presence, project Kanban/flow board + crew orchestration for independent AI coding agents (Claude, Codex, Gemini, Kimi, DeepSeek). This manifest makes Kimi Code CLI a first-class ORCHESTRATOR, mirroring .claude-plugin/plugin.json. Hooks are the CANONICAL hooks/** executed through the kimi dialect bridge (kimi/bridge.mjs) — docs/KIMI-BRIDGE-CONTRACT.md.",
5
5
  "interface": {
6
6
  "displayName": "Trantor",
package/lib/capacity.mjs CHANGED
@@ -1,11 +1,12 @@
1
1
  // #14653: the pure views behind GET /capacity and `trantor capacity` — budgets (windows, resets,
2
2
  // prepaid, merged across machine snapshots), burn rate from turn telemetry, seats with their last
3
- // turn, machine rows joined with seat counts, and online-seat faults for direct work left
4
- // unconsumed past the delivery ledger's high-water mark (#14662).
3
+ // turn, machine rows joined with seat counts, and online-seat faults (#14662). #14671: the burn
4
+ // rate now carries crew USD spend from real receipts — slice 2 reported turns/tokens only.
5
5
 
6
6
  // Unknown values stay null; ages ride along so a consumer can say HOW unknown ("12m old", "no
7
7
  // beat"). Pure: a function over the hub's state and telemetry rows, so tests feed fixtures.
8
8
  import { fmtReset, isLow, DEFAULT_LOW, DEFAULT_LOW_QUOTA_PCT } from "./balances.mjs";
9
+ import { crewSpend } from "./dispatcher/spend.mjs";
9
10
 
10
11
  const GiB = 1024 ** 3;
11
12
  const SUCCESS_OUTCOMES = new Set(["completed", "asked", "blocked"]);
@@ -65,9 +66,11 @@ export function budgetsView({ state, nowMs, thresholds = DEFAULT_LOW, quotaPct =
65
66
  }
66
67
 
67
68
  // Burn rate per trailing window (1h for "right now", 24h for the pace). Totals count every row
68
- // (an aggregate); bySeat lists only seats the reader may see — canSee is the route's visibility
69
- // predicate, defaulted open for pure/off-mode use.
70
- export function burnView({ rows, nowMs, canSee = () => true }) {
69
+ // (an aggregate); bySeat lists only seats the reader may see. spendReceipts (#14671) carry the
70
+ // CREW's real USD outflow — one-shot and dispatcher receipts, never token-derived estimates;
71
+ // unknown receipts count, they never sum as zero.
72
+ export function burnView({ rows, nowMs, canSee = () => true, spendReceipts = [] }) {
73
+ const spend = crewSpend({ receipts: spendReceipts, nowMs });
71
74
  const windows = {};
72
75
  for (const [name, spanMs] of [["1h", 3600e3], ["24h", 86400e3]]) {
73
76
  const sinceMs = nowMs - spanMs;
@@ -83,6 +86,19 @@ export function burnView({ rows, nowMs, canSee = () => true }) {
83
86
  if (seat.lastTs == null || Number(r.ts) > seat.lastTs) seat.lastTs = Number(r.ts);
84
87
  seats.set(key, seat);
85
88
  }
89
+ for (const seat of (spend.windows[name] || {}).bySeat || []) {
90
+ const key = `${seat.persona}\u0000${seat.project}`;
91
+ const existing = seats.get(key);
92
+ if (existing) {
93
+ existing.spendUsdMicros = seat.spendUsdMicros;
94
+ existing.spendCalls = seat.calls;
95
+ } else {
96
+ seats.set(key, { persona: seat.persona, project: seat.project, agent: "",
97
+ turns: 0, tokens: 0, failures: 0, lastTs: null,
98
+ spendUsdMicros: seat.spendUsdMicros, spendCalls: seat.calls });
99
+ }
100
+ }
101
+ const spendWindow = spend.windows[name] || { spendUsdMicros: 0, billedUsdMicros: 0, estimatedUsdMicros: 0, unknownCount: 0 };
86
102
  windows[name] = {
87
103
  sinceMs,
88
104
  hours,
@@ -90,7 +106,11 @@ export function burnView({ rows, nowMs, canSee = () => true }) {
90
106
  tokens: inWindow.reduce((acc, r) => acc + (Number(r.tokens) || 0), 0),
91
107
  turnsPerHour: inWindow.length ? +(inWindow.length / hours).toFixed(2) : 0,
92
108
  tokensPerHour: inWindow.length ? +((inWindow.reduce((acc, r) => acc + (Number(r.tokens) || 0), 0)) / hours).toFixed(0) : 0,
93
- bySeat: [...seats.values()].filter((s) => canSee(s)).sort((a, b) => b.turns - a.turns),
109
+ spendUsdMicros: spendWindow.spendUsdMicros,
110
+ spendBilledUsdMicros: spendWindow.billedUsdMicros,
111
+ spendEstimatedUsdMicros: spendWindow.estimatedUsdMicros,
112
+ spendUnknownCount: spendWindow.unknownCount,
113
+ bySeat: [...seats.values()].filter((s) => canSee(s)).sort((a, b) => b.turns - a.turns || (b.spendUsdMicros || 0) - (a.spendUsdMicros || 0)),
94
114
  };
95
115
  }
96
116
  return { windows };
@@ -144,19 +164,77 @@ export function seatsView({ peers, lastRows, messages = [], nowMs, onlineMs, stu
144
164
  .sort((a, b) => (b.online - a.online) || (b.lastSeen - a.lastSeen) || a.session.localeCompare(b.session));
145
165
  }
146
166
 
147
- // Seat counts per machine from presence (the runner cannot know its siblings): total seats seen
148
- // within the TTL window, and how many are online right now.
149
- export function machineSeatCounts(peers, nowMs, { ttlMs, onlineMs }) {
150
- const counts = new Map();
151
- for (const p of Object.values(peers || {})) {
152
- const machine = String(p.machine || "");
153
- if (!machine || !p.lastSeen || p.lastSeen < nowMs - ttlMs) continue;
154
- const row = counts.get(machine) || { machine, seats: 0, seatsOnline: 0 };
167
+ // Machine rows for /capacity (#14702): the /machines/health beat registry joined with seat counts
168
+ // from presence, over every machine name the hub knows (beats, presence labels, balances hosts).
169
+ // The join key is lowercased: the same machine arrives as a runner's chosen label ("netcup") and
170
+ // as a balances host name ("MacBook-Pro-M1") and keeps ONE row under its best display name.
171
+ export function machinesView({ beats = [], peers = {}, nowMs, ttlMs, onlineMs, balanceMachines = [] }) {
172
+ const display = new Map();
173
+ const learn = (name) => {
174
+ const raw = String(name || "").trim();
175
+ if (!raw || raw.length > 60) return;
176
+ const key = raw.toLowerCase();
177
+ const cur = display.get(key);
178
+ if (cur == null || (cur === cur.toLowerCase() && raw !== raw.toLowerCase())) display.set(key, raw);
179
+ };
180
+ for (const h of beats) learn(h?.machine);
181
+ for (const [, p] of Object.entries(peers || {})) learn(p?.machine);
182
+ for (const m of balanceMachines) learn(m);
183
+
184
+ const hostOf = (session) => {
185
+ const s = String(session || "");
186
+ const i = s.indexOf(":");
187
+ return i > 0 ? s.slice(0, i) : "";
188
+ };
189
+ // An unlabeled session's "host:project" id (the convention touch() itself derives the project
190
+ // from) attributes it to a machine the hub already knows: that is how the operator's Mac lists,
191
+ // whose clients ship no valid lowercase label ("MacBook-Pro-M1" fails the label grammar, so
192
+ // presence carries nothing). A persona-prefixed crew session spawns no pseudo-machine row.
193
+ const machineOf = (session, p) => {
194
+ const label = String(p?.machine || "").trim();
195
+ if (label) return label;
196
+ const host = hostOf(session);
197
+ return host && display.has(host.toLowerCase()) ? host : "";
198
+ };
199
+
200
+ const seatsBy = new Map();
201
+ for (const [session, p] of Object.entries(peers || {})) {
202
+ if (!p?.lastSeen || p.lastSeen < nowMs - ttlMs) continue;
203
+ const name = machineOf(session, p);
204
+ if (!name) continue;
205
+ const key = name.toLowerCase();
206
+ const row = seatsBy.get(key) || { seats: 0, seatsOnline: 0, presenceTs: 0 };
155
207
  row.seats += 1;
156
208
  if (p.lastSeen > nowMs - onlineMs) row.seatsOnline += 1;
157
- counts.set(machine, row);
209
+ row.presenceTs = Math.max(row.presenceTs, p.lastSeen);
210
+ seatsBy.set(key, row);
211
+ }
212
+
213
+ const rows = [];
214
+ const seen = new Set();
215
+ for (const h of beats) {
216
+ const key = String(h?.machine || "").trim().toLowerCase();
217
+ if (!key || seen.has(key)) continue;
218
+ seen.add(key);
219
+ const counts = seatsBy.get(key);
220
+ rows.push({ ...h, machine: display.get(key) || h.machine,
221
+ seats: counts?.seats || 0, seatsOnline: counts?.seatsOnline || 0, heartbeat: true,
222
+ presenceAgeMs: counts ? Math.max(0, nowMs - counts.presenceTs) : null });
223
+ }
224
+ // Machines only presence knows (no runner heartbeat) still list, with null health and their seat
225
+ // count; a balances host nobody beats and nobody runs stays off — no beat and no seats says
226
+ // nothing worth a row.
227
+ for (const [key, counts] of seatsBy) {
228
+ if (seen.has(key)) continue;
229
+ rows.push({
230
+ machine: display.get(key) || key, cpuPct: null, memUsed: null, memTotal: null, cores: null,
231
+ memPressurePct: null, swapUsed: null, swapTotal: null, diskFree: null, diskTotal: null,
232
+ ts: null, ageMs: null, stale: true, heartbeat: false,
233
+ seats: counts.seats, seatsOnline: counts.seatsOnline,
234
+ presenceAgeMs: Math.max(0, nowMs - counts.presenceTs),
235
+ });
158
236
  }
159
- return counts;
237
+ return rows.sort((a, b) => a.machine.localeCompare(b.machine));
160
238
  }
161
239
 
162
240
  const numberOrNull = (v) => (Number.isFinite(Number(v)) ? Number(v) : null);