pi-legion 0.16.0 → 2.0.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 (89) hide show
  1. package/CONTRIBUTING.md +58 -0
  2. package/README.md +313 -640
  3. package/agents/advisor.md +7 -5
  4. package/agents/centurion.md +53 -0
  5. package/agents/designer.md +33 -33
  6. package/agents/planner.md +1 -2
  7. package/agents/prototype.md +2 -2
  8. package/agents/reviewer.md +67 -31
  9. package/agents/scout.md +6 -2
  10. package/agents/worker.md +12 -3
  11. package/docs/contracts/esc-abort-v1.md +131 -0
  12. package/docs/contracts/esc-cascade-v2.md +100 -0
  13. package/docs/design.md +44 -25
  14. package/docs/legion-v2-contract.md +461 -0
  15. package/docs/legion-v2-delivery.md +62 -0
  16. package/docs/retire-hardening-contract.md +125 -0
  17. package/docs/subagents-teams.md +76 -0
  18. package/docs/tui-viewer-contract.md +276 -0
  19. package/docs/vexillatio-contract.md +162 -0
  20. package/index.ts +1462 -286
  21. package/package.json +12 -9
  22. package/skills/pi-legion/SKILL.md +74 -96
  23. package/src/agents/agents.ts +6 -11
  24. package/src/agents/overrides.ts +2 -1
  25. package/src/agents/paths.ts +1 -1
  26. package/src/agents/settings.ts +268 -20
  27. package/src/api.ts +47 -48
  28. package/src/{herdr → backends/legacy}/client.ts +14 -69
  29. package/src/{shared → backends/legacy}/cursor-chat.ts +2 -2
  30. package/src/{herdr → backends/legacy}/runner.ts +22 -9
  31. package/src/backends/legacy/types.ts +138 -0
  32. package/src/extension/auto-doctor.ts +144 -0
  33. package/src/extension/budget.ts +2 -2
  34. package/src/extension/child-guard.ts +214 -201
  35. package/src/extension/event-bus.ts +263 -0
  36. package/src/extension/legion-commands.ts +719 -0
  37. package/src/extension/legion-doctor.ts +888 -0
  38. package/src/extension/legion-stop.ts +150 -0
  39. package/src/extension/legion-tools.ts +816 -0
  40. package/src/extension/notify.ts +24 -19
  41. package/src/extension/playbook.ts +20 -89
  42. package/src/extension/recycle.ts +2 -7
  43. package/src/extension/runtime.ts +655 -105
  44. package/src/extension/scout-guard.ts +483 -0
  45. package/src/extension/slash.ts +89 -438
  46. package/src/extension/spawn-hints.ts +79 -0
  47. package/src/extension/summary.ts +17 -58
  48. package/src/legion/budget.ts +165 -0
  49. package/src/legion/db.ts +242 -0
  50. package/src/legion/events.ts +150 -0
  51. package/src/legion/mail.ts +412 -0
  52. package/src/legion/nodes.ts +461 -0
  53. package/src/legion/rebuild.ts +533 -0
  54. package/src/legion/state-machine.ts +313 -0
  55. package/src/legion/usage.ts +101 -0
  56. package/src/runs/acceptance.ts +82 -25
  57. package/src/runs/args.ts +51 -5
  58. package/src/runs/hygiene.ts +335 -0
  59. package/src/runs/orchestrator.ts +790 -1683
  60. package/src/runs/owner.ts +61 -0
  61. package/src/runs/provision.ts +135 -0
  62. package/src/runs/store.ts +44 -17
  63. package/src/runs/verify-queue.ts +195 -0
  64. package/src/shared/name.ts +29 -0
  65. package/src/shared/output-cap.ts +57 -0
  66. package/src/shared/progress.ts +57 -135
  67. package/src/shared/session.ts +243 -171
  68. package/src/shared/types.ts +107 -208
  69. package/src/supervisor/child-memory.ts +140 -0
  70. package/src/supervisor/proc-tree.ts +103 -0
  71. package/src/supervisor/rpc-supervisor.ts +1033 -0
  72. package/src/supervisor/types.ts +153 -0
  73. package/src/supervisor/ui-proxy.ts +226 -0
  74. package/src/tui/chat-items.ts +330 -0
  75. package/src/tui/live-overlay.ts +874 -0
  76. package/src/tui/status.ts +553 -27
  77. package/src/tui/tree-view.ts +808 -0
  78. package/src/tui/viz/canvas.ts +119 -0
  79. package/src/tui/viz/layout.ts +111 -0
  80. package/src/tui/viz/model.ts +123 -0
  81. package/src/tui/viz/palette.ts +188 -0
  82. package/src/tui/viz/panels.ts +530 -0
  83. package/src/tui/viz/railway.ts +313 -0
  84. package/src/tui/viz/rate.ts +211 -0
  85. package/src/tui/viz/view.ts +228 -0
  86. package/src/extension/parent-label.ts +0 -115
  87. package/src/profiles/classify.ts +0 -375
  88. package/src/profiles/profiles.ts +0 -730
  89. package/src/runs/layout.ts +0 -258
@@ -0,0 +1,313 @@
1
+ /**
2
+ * Above-input "railway" strip: one git-graph lane per live subagent.
3
+ *
4
+ * Only agents live now get a lane (oldest first, then shallowest), drawn on a
5
+ * single shared time axis that ends at "now". When an agent ends its lane and
6
+ * label disappear and the rows below shift up — no empty rows are ever kept.
7
+ * The strip is hidden entirely when no subagent is live. A spawn fork that
8
+ * slides off the left stays pinned there until that agent ends, so the parent
9
+ * vertical remains traceable.
10
+ */
11
+
12
+ import { formatAgentElapsed } from "../status.ts";
13
+ import { Canvas, ellipsize } from "./canvas.ts";
14
+ import { formatCount, isAgent, type VizNode } from "./model.ts";
15
+ import { roleColor, type VizTheme } from "./palette.ts";
16
+
17
+ export const RAIL_MAX_LANES = 4;
18
+ export const RAIL_MAX_LANES_NARROW = 3;
19
+ export const RAIL_NARROW_COLS = 80;
20
+ export const RAIL_WINDOW_MS = 6 * 60 * 1000;
21
+
22
+ /**
23
+ * Map a timestamp onto the shared railway axis.
24
+ *
25
+ * Using `floor(t/dt) - floor(origin/dt) - 1` (instead of `floor((t-origin)/dt)`)
26
+ * keeps every live lane's glyphs shifting by the exact same column count when
27
+ * the window slides — required for "all lanes scroll left in sync".
28
+ * The trailing `- 1` places `now` on the last drawable column (`axisWidth - 1`).
29
+ */
30
+ export function axisColumn(t: number, now: number, windowMs: number, axisWidth: number): number {
31
+ if (axisWidth <= 0 || windowMs <= 0) return 0;
32
+ const dt = windowMs / axisWidth;
33
+ const originCol = Math.floor((now - windowMs) / dt);
34
+ return Math.floor(t / dt) - originCol - 1;
35
+ }
36
+
37
+
38
+ export interface RailInput {
39
+ nodes: readonly VizNode[];
40
+ now: number;
41
+ width: number;
42
+ /** Output tok/s over the shared 60s generation window. */
43
+ rate: number;
44
+ windowMs?: number;
45
+ /** Lane scroll position when more agents are live than lanes fit. */
46
+ scroll?: RailScroll;
47
+ /** Dim hint on the header rule (e.g. stop controls while the main agent is idle). */
48
+ hint?: string;
49
+ /** Shorter variant used when the full hint does not fit. */
50
+ hintShort?: string;
51
+ }
52
+
53
+ /**
54
+ * Scroll state: `topId` anchors the view to the agent in the top visible lane
55
+ * so agents ending above it don't shift what's on screen; `offset` is the
56
+ * fallback when that agent itself is gone.
57
+ */
58
+ export interface RailScroll {
59
+ offset: number;
60
+ topId?: string;
61
+ }
62
+
63
+ export interface RailRender {
64
+ canvas: Canvas;
65
+ /** Node id rendered on each output row (undefined for the header). */
66
+ nodeIdsByRow: Array<string | undefined>;
67
+ /**
68
+ * Per-cell owner map, hit[y][x] = node id whose glyph is drawn there (lane
69
+ * segments, fork connectors, name column), produced in the same pass that
70
+ * draws the canvas. Header, dotted background and padding are undefined.
71
+ */
72
+ hit: Array<Array<string | undefined>>;
73
+ shown: VizNode[];
74
+ hidden: VizNode[];
75
+ /** Resolved (clamped) scroll window. */
76
+ offset: number;
77
+ total: number;
78
+ maxLanes: number;
79
+ }
80
+
81
+ function endOf(node: VizNode): number {
82
+ return node.status === "running" ? Number.POSITIVE_INFINITY : node.endedAt ?? node.startedAt;
83
+ }
84
+
85
+ /** Agents alive at t, in lane priority order: oldest first, then shallowest, then name. */
86
+ export function liveAt(nodes: readonly VizNode[], t: number): VizNode[] {
87
+ return nodes
88
+ .filter((node) => isAgent(node) && node.startedAt <= t && t < endOf(node))
89
+ .sort((a, b) => a.startedAt - b.startedAt || a.depth - b.depth || a.name.localeCompare(b.name));
90
+ }
91
+
92
+ /**
93
+ * Clamp a scroll request to the live list. The anchor agent keeps its lane on
94
+ * top while it lives; new agents (appended at the bottom, oldest-first order)
95
+ * never move the view; when everything fits the offset is 0.
96
+ */
97
+ export function resolveScroll(live: readonly VizNode[], maxLanes: number, scroll?: RailScroll): number {
98
+ const maxOffset = Math.max(0, live.length - Math.max(0, maxLanes));
99
+ if (maxOffset === 0 || !scroll) return 0;
100
+ let offset = scroll.offset;
101
+ if (scroll.topId !== undefined && offset > 0) {
102
+ const index = live.findIndex((node) => node.id === scroll.topId);
103
+ if (index >= 0) offset = index;
104
+ }
105
+ return Math.min(maxOffset, Math.max(0, Math.round(offset)));
106
+ }
107
+
108
+ /** "5-8/12" — 1-based visible lane range over the live total. */
109
+ export function scrollIndicator(offset: number, shown: number, total: number): string {
110
+ return `${offset + 1}-${offset + shown}/${total}`;
111
+ }
112
+
113
+ /**
114
+ * Lane assignment with compaction: live agents in priority order, the window
115
+ * [offset, offset+maxLanes) gets rows 0..k-1; the rest are scrolled out.
116
+ */
117
+ export function assignLanes(nodes: readonly VizNode[], t: number, maxLanes: number, scroll?: RailScroll): {
118
+ lanes: Map<string, number>;
119
+ shown: VizNode[];
120
+ hidden: VizNode[];
121
+ offset: number;
122
+ total: number;
123
+ } {
124
+ const live = liveAt(nodes, t);
125
+ const offset = resolveScroll(live, maxLanes, scroll);
126
+ const shown = live.slice(offset, offset + Math.max(0, maxLanes));
127
+ return {
128
+ lanes: new Map(shown.map((node, index) => [node.id, index])),
129
+ shown,
130
+ hidden: [...live.slice(0, offset), ...live.slice(offset + shown.length)],
131
+ offset,
132
+ total: live.length,
133
+ };
134
+ }
135
+
136
+ export function maxLanesFor(width: number): number {
137
+ return width < RAIL_NARROW_COLS ? RAIL_MAX_LANES_NARROW : RAIL_MAX_LANES;
138
+ }
139
+
140
+ export function formatRate(rate: number): string {
141
+ return `${formatCount(rate)} tok/s`;
142
+ }
143
+
144
+ export function renderRailway(input: RailInput): RailRender | undefined {
145
+ const width = Math.max(0, Math.floor(input.width));
146
+ if (width < 20) return undefined;
147
+ const { nodes, now } = input;
148
+ const maxLanes = maxLanesFor(width);
149
+ const current = assignLanes(nodes, now, maxLanes, input.scroll);
150
+ const rows = current.shown.length;
151
+ if (rows === 0) return undefined;
152
+ const portrait = width < RAIL_NARROW_COLS;
153
+ const windowMs = input.windowMs ?? RAIL_WINDOW_MS;
154
+ const nameCol = portrait ? Math.max(8, Math.min(16, Math.floor(width * 0.32))) : Math.min(38, Math.max(24, Math.floor(width * 0.3)));
155
+ const LX = 1;
156
+ const AW = Math.max(4, width - LX - nameCol - 2);
157
+ const canvas = new Canvas(width, rows + 1);
158
+ const hit: Array<Array<string | undefined>> = Array.from({ length: rows + 1 }, () => new Array<string | undefined>(width).fill(undefined));
159
+ const byId = new Map(nodes.map((node) => [node.id, node]));
160
+ const color = (node: VizNode): string => roleColor(node.role);
161
+
162
+ // One shared time axis. Absolute column math (floor(t/dt) − floor(origin/dt))
163
+ // makes every lane shift by the *same* integer when `now` advances; the older
164
+ // floor((t − origin)/dt) form crossed quantization boundaries per-lane and
165
+ // looked like independent scrolling. "now" always lands on the last drawable
166
+ // column; only agents live NOW get a lane (ended ones vanish and rows compact).
167
+ const colOf = (t: number): number => axisColumn(t, now, windowMs, AW);
168
+ const cells = new Map<string, { ch: string; color: string; owner: string }>();
169
+ let owner = "";
170
+ // Spawn ticks on the header rule for root-spawned live lanes (first sibling owns it).
171
+ const headerTicks = new Map<number, { color: string; owner: string }>();
172
+ const put = (c: number, r: number, ch: string, col: string, by: string = owner): void => {
173
+ if (c < 0 || c >= AW || r < 0 || r >= rows) return;
174
+ cells.set(`${c},${r}`, { ch, color: col, owner: by });
175
+ };
176
+ for (const [id, r] of current.lanes) {
177
+ const node = byId.get(id)!;
178
+ owner = id;
179
+ const col = color(node);
180
+ const start = colOf(node.startedAt);
181
+ const c0 = Math.max(0, start);
182
+ for (let c = c0; c < AW; c++) put(c, r, "━", col);
183
+ // Fork tick: join the nearest shown live ancestor's lane; otherwise the
184
+ // root trunk (header). When the spawn column has scrolled off the left,
185
+ // pin the fork to column 0 so a live child keeps its parent vertical,
186
+ // even if the parent lane itself has left the window. The lane body
187
+ // still ends at "now" and keeps scrolling; ended agents have no lane.
188
+ const forkX = Math.max(0, start);
189
+ let parent = node.parentId ? byId.get(node.parentId) : undefined;
190
+ let p: number | undefined;
191
+ while (parent && isAgent(parent) && p === undefined) {
192
+ p = current.lanes.get(parent.id);
193
+ parent = parent.parentId ? byId.get(parent.parentId) : undefined;
194
+ }
195
+ if (p === r) { put(forkX, r, start < 0 ? "┄" : "╺", col); continue; }
196
+ // No visible ancestor lane: the child was spawned from the root, whose
197
+ // implicit trunk is the header rule (row -1). Siblings forking at the same
198
+ // x share one vertical: an earlier sibling's ╰ becomes ├ when a later
199
+ // sibling's connector passes through it. A ┄ continuation (spawn already
200
+ // off-screen, no fork of its own) joins the same way a ━ lane does.
201
+ const from = p ?? -1;
202
+ put(forkX, r, from < r ? "╰" : "╭", col);
203
+ for (let y = Math.min(from, r) + 1; y < Math.max(from, r); y++) {
204
+ const cell = cells.get(`${forkX},${y}`);
205
+ if (!cell) put(forkX, y, "│", col);
206
+ else if (cell.ch === "━" || cell.ch === "┄") cell.ch = "┿"; // crossing another lane: that lane keeps the cell
207
+ else if (cell.ch === "╰" && from < r) cell.ch = "├";
208
+ else if (cell.ch === "╭" && from > r) cell.ch = "├";
209
+ }
210
+ if (from < 0) { if (!headerTicks.has(forkX)) headerTicks.set(forkX, { color: col, owner: id }); continue; }
211
+ const pc = cells.get(`${forkX},${from}`);
212
+ // The branch point is part of the child's fork, so clicking it opens the child.
213
+ // A parent that itself starts on this column (╰/╭, including a fork pinned to
214
+ // the left edge) grows a downward arm so the vertical actually meets the child.
215
+ if (pc && (pc.ch === "━" || pc.ch === "┄")) put(forkX, from, from < r ? "┳" : "┻", pc.color);
216
+ else if (pc && pc.ch === "╰" && from < r) pc.ch = "├";
217
+ else if (pc && pc.ch === "╭" && from > r) pc.ch = "├";
218
+ }
219
+
220
+ // Header: plain rule; the only glyphs on it are ┬ spawn ticks of live root-spawned lanes.
221
+ const y0 = 1;
222
+ for (let x = 0; x < width; x++) canvas.set(x, 0, "─", "borderMuted");
223
+ for (let r = 0; r < rows; r++) for (let c = 0; c < AW; c++) canvas.set(LX + c, y0 + r, "·", "borderMuted");
224
+ for (const [key, cell] of cells) {
225
+ const [c, r] = key.split(",").map(Number) as [number, number];
226
+ canvas.set(LX + c, y0 + r, cell.ch, cell.color);
227
+ hit[y0 + r]![LX + c] = cell.owner;
228
+ }
229
+
230
+ const live = current.total;
231
+ const above = current.offset > 0;
232
+ const below = current.offset + rows < live;
233
+ const rateText = formatRate(input.rate);
234
+ const winLabel = ` −${Math.max(1, Math.round(windowMs / 60000))}m `;
235
+ canvas.text(LX + 1, 0, winLabel, "dim");
236
+ const range = above || below ? ` · ${scrollIndicator(current.offset, rows, live)} ${above ? "▲" : " "}${below ? "▼" : " "}` : "";
237
+ const header = portrait
238
+ ? ` ${live} live${range} · ${rateText} `
239
+ : ` legion ${live} live${range} · ${rateText} `;
240
+ const headerX = Math.max(LX + 1 + winLabel.length, width - header.length - 1);
241
+ canvas.text(headerX, 0, header, "accent", { bold: true, maxX: width - 1 });
242
+ if (input.hint) {
243
+ // Between the window label and the summary, with a rule gap on both sides.
244
+ const hx = LX + 1 + winLabel.length + 1;
245
+ const room = headerX - 1 - hx;
246
+ const pick = [input.hint, input.hintShort].find((text) => text && Array.from(text).length + 2 <= room);
247
+ if (pick) canvas.text(hx, 0, ` ${pick} `, "dim");
248
+ }
249
+ for (const [c, tick] of headerTicks) {
250
+ if (canvas.get(LX + c, 0)?.ch !== "─") continue; // never draw over header text
251
+ canvas.set(LX + c, 0, "┬", tick.color);
252
+ hit[0]![LX + c] = tick.owner;
253
+ }
254
+
255
+ const nameX = LX + AW;
256
+ current.shown.forEach((node, i) => {
257
+ const y = y0 + i;
258
+ const col = color(node);
259
+ canvas.set(nameX, y, "▶", col, { bold: true });
260
+ for (let x = nameX; x < width; x++) hit[y]![x] = node.id;
261
+ // Scroll hints at the right edge: ▲ on the top lane, ▼ on the bottom lane.
262
+ const overflow = i === 0 && above ? " ▲" : i === rows - 1 && below ? " ▼" : "";
263
+ const avail = width - (nameX + 2) - overflow.length;
264
+ if (portrait) {
265
+ canvas.text(nameX + 2, y, ellipsize(node.name, avail), col, { bold: true });
266
+ } else {
267
+ const longest = Math.max(...current.shown.map((n) => Array.from(n.name).length));
268
+ const nameW = Math.min(16, longest, Math.max(6, avail - 8));
269
+ canvas.text(nameX + 2, y, ellipsize(node.name, nameW), col, { bold: true });
270
+ const room = Math.max(0, avail - nameW - 1);
271
+ const elapsed = formatAgentElapsed({
272
+ state: node.status,
273
+ startedAt: node.startedAt,
274
+ ...(node.endedAt !== undefined ? { finishedAt: node.endedAt } : {}),
275
+ ...(node.currentTurnStartedAt !== undefined ? { currentTurnStartedAt: node.currentTurnStartedAt } : {}),
276
+ ...(node.currentTurnEndedAt !== undefined ? { currentTurnEndedAt: node.currentTurnEndedAt } : {}),
277
+ }, now);
278
+ const full = `${node.role} · ${elapsed}`;
279
+ const detail = ellipsize(Array.from(full).length <= room ? full : elapsed, room);
280
+ canvas.text(nameX + 3 + nameW, y, detail, "dim");
281
+ }
282
+ if (overflow) canvas.text(width - overflow.length, y, overflow, "text", { bold: true });
283
+ });
284
+
285
+ return {
286
+ canvas,
287
+ nodeIdsByRow: [undefined, ...current.shown.map((node) => node.id)],
288
+ hit,
289
+ shown: current.shown,
290
+ hidden: current.hidden,
291
+ offset: current.offset,
292
+ total: current.total,
293
+ maxLanes,
294
+ };
295
+ }
296
+
297
+ export function railwayLines(input: RailInput, theme: VizTheme): {
298
+ lines: string[];
299
+ nodeIdsByRow: Array<string | undefined>;
300
+ hitAt: (x: number, y: number) => string | undefined;
301
+ /** Resolved window (undefined when hidden); total > maxLanes means scrollable. */
302
+ window?: { offset: number; total: number; maxLanes: number; topId?: string };
303
+ } {
304
+ const rendered = renderRailway(input);
305
+ if (!rendered) return { lines: [], nodeIdsByRow: [], hitAt: () => undefined };
306
+ const { hit } = rendered;
307
+ return {
308
+ lines: rendered.canvas.toLines(theme),
309
+ nodeIdsByRow: rendered.nodeIdsByRow,
310
+ hitAt: (x, y) => hit[y]?.[x],
311
+ window: { offset: rendered.offset, total: rendered.total, maxLanes: rendered.maxLanes, topId: rendered.shown[0]?.id },
312
+ };
313
+ }
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Minimal in-memory token-rate sampling.
3
+ *
4
+ * Every tok/s figure in the UI (railway header, /legion header, chart "now",
5
+ * tree detail t/s) uses ONE definition:
6
+ *
7
+ * numerator = Δ cumulative output tokens over the trailing window
8
+ * denominator = Δ cumulative generationMs over the same window
9
+ * (falls back to wall-clock window only when generationMs
10
+ * is unavailable / zero for that node)
11
+ *
12
+ * generationMs comes from session JSONL: sum of (assistant_ts − prior
13
+ * user/toolResult_ts). Idle and tool gaps are excluded. Approximate —
14
+ * usage lands when each assistant message completes, not mid-stream.
15
+ */
16
+
17
+ import type { VizNode } from "./model.ts";
18
+
19
+ export const RATE_WINDOW_MS = 60_000;
20
+ const DEFAULT_RETENTION_MS = 6 * 60 * 60 * 1000;
21
+ const MAX_SAMPLES_PER_NODE = 4096;
22
+
23
+ interface Series {
24
+ role: string;
25
+ ts: number[];
26
+ /** Cumulative output tokens. */
27
+ value: number[];
28
+ /** Cumulative generation wall ms (parallel to value). */
29
+ gen: number[];
30
+ }
31
+
32
+ export interface RateSeries {
33
+ /** Bucket end timestamps. */
34
+ times: number[];
35
+ /** tok/s per bucket per role. */
36
+ byRole: Map<string, number[]>;
37
+ total: number[];
38
+ }
39
+
40
+ export class RateSampler {
41
+ private readonly series = new Map<string, Series>();
42
+ private readonly retentionMs: number;
43
+ private first: number | undefined;
44
+
45
+ constructor(options: { retentionMs?: number } = {}) {
46
+ this.retentionMs = options.retentionMs ?? DEFAULT_RETENTION_MS;
47
+ }
48
+
49
+ get startedAt(): number | undefined {
50
+ return this.first;
51
+ }
52
+
53
+ record(now: number, nodes: readonly VizNode[]): void {
54
+ if (!Number.isFinite(now)) return;
55
+ if (this.first === undefined) this.first = now;
56
+ for (const node of nodes) {
57
+ if (node.id === "root") continue;
58
+ let s = this.series.get(node.id);
59
+ if (!s) {
60
+ s = { role: node.role, ts: [], value: [], gen: [] };
61
+ this.series.set(node.id, s);
62
+ // A node born after sampling began starts from zero at its spawn time.
63
+ if (node.startedAt > this.first && node.startedAt < now) {
64
+ s.ts.push(node.startedAt);
65
+ s.value.push(0);
66
+ s.gen.push(0);
67
+ }
68
+ }
69
+ s.role = node.role;
70
+ const last = s.value[s.value.length - 1];
71
+ const lastGen = s.gen[s.gen.length - 1];
72
+ const lastTs = s.ts[s.ts.length - 1];
73
+ // Cumulative counters never decrease; ignore regressions from stale sources.
74
+ const value = last === undefined ? node.tokensOut : Math.max(last, node.tokensOut);
75
+ const gen = lastGen === undefined ? node.generationMs : Math.max(lastGen, node.generationMs);
76
+ if (lastTs !== undefined && now <= lastTs) {
77
+ s.value[s.value.length - 1] = value;
78
+ s.gen[s.gen.length - 1] = gen;
79
+ continue;
80
+ }
81
+ if (
82
+ last !== undefined &&
83
+ value === last &&
84
+ gen === lastGen &&
85
+ s.value.length >= 2 &&
86
+ s.value[s.value.length - 2] === last &&
87
+ s.gen[s.gen.length - 2] === lastGen
88
+ ) {
89
+ // Collapse flat runs: move the trailing sample forward.
90
+ s.ts[s.ts.length - 1] = now;
91
+ continue;
92
+ }
93
+ s.ts.push(now);
94
+ s.value.push(value);
95
+ s.gen.push(gen);
96
+ this.prune(s, now);
97
+ }
98
+ }
99
+
100
+ private prune(s: Series, now: number): void {
101
+ const cutoff = now - this.retentionMs;
102
+ let drop = 0;
103
+ while (drop < s.ts.length - 1 && s.ts[drop + 1]! < cutoff) drop++;
104
+ if (s.ts.length - drop > MAX_SAMPLES_PER_NODE) drop = s.ts.length - MAX_SAMPLES_PER_NODE;
105
+ if (drop > 0) {
106
+ s.ts.splice(0, drop);
107
+ s.value.splice(0, drop);
108
+ s.gen.splice(0, drop);
109
+ }
110
+ }
111
+
112
+ /** Cumulative output tokens at time t (linear between samples, clamped at the ends). */
113
+ valueAt(nodeId: string, t: number): number {
114
+ const s = this.series.get(nodeId);
115
+ if (!s || s.ts.length === 0) return 0;
116
+ return interpolate(s.ts, s.value, t);
117
+ }
118
+
119
+ /** Cumulative generationMs at time t. */
120
+ genAt(nodeId: string, t: number): number {
121
+ const s = this.series.get(nodeId);
122
+ if (!s || s.ts.length === 0) return 0;
123
+ return interpolate(s.ts, s.gen, t);
124
+ }
125
+
126
+ /**
127
+ * Output tok/s over the trailing window: ΔtokensOut / (ΔgenerationMs/1000).
128
+ * When the node has no generationMs samples in the window, falls back to
129
+ * wall-clock window length so a ledger-only path still yields a number.
130
+ */
131
+ nodeRate(nodeId: string, now: number, windowMs = RATE_WINDOW_MS): number {
132
+ if (windowMs <= 0) return 0;
133
+ const dOut = Math.max(0, this.valueAt(nodeId, now) - this.valueAt(nodeId, now - windowMs));
134
+ if (dOut <= 0) return 0;
135
+ const dGen = Math.max(0, this.genAt(nodeId, now) - this.genAt(nodeId, now - windowMs));
136
+ const seconds = dGen > 0 ? dGen / 1000 : windowMs / 1000;
137
+ return dOut / seconds;
138
+ }
139
+
140
+ totalRate(now: number, windowMs = RATE_WINDOW_MS): number {
141
+ let sum = 0;
142
+ for (const id of this.series.keys()) sum += this.nodeRate(id, now, windowMs);
143
+ return sum;
144
+ }
145
+
146
+ nodeIds(): string[] {
147
+ return [...this.series.keys()];
148
+ }
149
+
150
+ /**
151
+ * Bucketed tok/s for [from, to], stacked by role. Each bucket is the
152
+ * trailing-window average ending at the bucket edge (window = max(bucket
153
+ * span, RATE_WINDOW_MS)), so the last bucket equals the header "now" and
154
+ * bursty per-turn token flushes do not render as spikes.
155
+ */
156
+ buckets(from: number, to: number, count: number, windowMs = RATE_WINDOW_MS): RateSeries {
157
+ const n = Math.max(1, Math.floor(count));
158
+ const span = Math.max(1, to - from);
159
+ const times = Array.from({ length: n }, (_, i) => from + (span * (i + 1)) / n);
160
+ const byRole = new Map<string, number[]>();
161
+ const total = new Array<number>(n).fill(0);
162
+ for (const [id, s] of this.series) {
163
+ const row = byRole.get(s.role) ?? new Array<number>(n).fill(0);
164
+ const rates = this.nodeBuckets(id, from, to, n, windowMs);
165
+ for (let i = 0; i < n; i++) {
166
+ row[i] = row[i]! + rates[i]!;
167
+ total[i] = total[i]! + rates[i]!;
168
+ }
169
+ byRole.set(s.role, row);
170
+ }
171
+ return { times, byRole, total };
172
+ }
173
+
174
+ nodeBuckets(nodeId: string, from: number, to: number, count: number, windowMs = RATE_WINDOW_MS): number[] {
175
+ const s = this.series.get(nodeId);
176
+ const n = Math.max(1, Math.floor(count));
177
+ if (!s) return new Array<number>(n).fill(0);
178
+ const span = Math.max(1, to - from);
179
+ const w = Math.max(span / n, windowMs, 1);
180
+ const out: number[] = [];
181
+ for (let i = 0; i < n; i++) {
182
+ const t = from + (span * (i + 1)) / n;
183
+ out.push(this.nodeRate(nodeId, t, w));
184
+ }
185
+ return out;
186
+ }
187
+
188
+ clear(): void {
189
+ this.series.clear();
190
+ this.first = undefined;
191
+ }
192
+ }
193
+
194
+ function interpolate(ts: number[], value: number[], t: number): number {
195
+ if (ts.length === 0) return 0;
196
+ if (t <= ts[0]!) return value[0]!;
197
+ const last = ts.length - 1;
198
+ if (t >= ts[last]!) return value[last]!;
199
+ let lo = 0;
200
+ let hi = last;
201
+ while (hi - lo > 1) {
202
+ const mid = (lo + hi) >> 1;
203
+ if (ts[mid]! <= t) lo = mid;
204
+ else hi = mid;
205
+ }
206
+ const t0 = ts[lo]!;
207
+ const t1 = ts[hi]!;
208
+ const v0 = value[lo]!;
209
+ const v1 = value[hi]!;
210
+ return t1 === t0 ? v1 : v0 + ((v1 - v0) * (t - t0)) / (t1 - t0);
211
+ }