pi-legion 5.0.1 → 5.2.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 (79) hide show
  1. package/CHANGELOG.md +858 -0
  2. package/CONTRIBUTING.md +33 -2
  3. package/README.md +10 -5
  4. package/agents/centurion.md +32 -7
  5. package/agents/scout.md +11 -0
  6. package/docs/contracts/abort-soft-interrupt-v1.md +162 -0
  7. package/docs/contracts/centurion-declared-phases-v1.md +104 -0
  8. package/docs/contracts/declarative-phase-machine-v5.md +43 -0
  9. package/docs/contracts/extension-inheritance-wiring-v1.md +88 -0
  10. package/docs/contracts/finished-cache-eviction-v1.md +169 -0
  11. package/docs/contracts/galaxy-scratch-v1.md +78 -0
  12. package/docs/contracts/legion-chart-frame-buckets-v1.md +201 -0
  13. package/docs/contracts/legion-main-screen-mount-v1.md +161 -0
  14. package/docs/contracts/legion-page-floor-v1.md +129 -0
  15. package/docs/contracts/legion-session-continuity-v1.md +118 -0
  16. package/docs/contracts/mailbox-delivery-v1.md +162 -0
  17. package/docs/contracts/notice-claim-v1.md +206 -0
  18. package/docs/contracts/partial-failure-exit-v1.md +235 -0
  19. package/docs/contracts/proc-sweep-v1.md +107 -0
  20. package/docs/contracts/provider-empty-generation-retry-v1.md +161 -0
  21. package/docs/contracts/stall-visibility-v1.md +218 -0
  22. package/docs/contracts/subagent-renewal-v1.md +5 -3
  23. package/docs/contracts/vexillatio-nonblocking-launch-v1.md +1 -0
  24. package/docs/contracts/viz-frame-alloc-v1.md +123 -0
  25. package/docs/contracts/wait-mail-preempt-v1.md +117 -0
  26. package/docs/contracts/wait-not-stop.md +1 -1
  27. package/docs/design.md +4 -1
  28. package/docs/inprocess-supervisor.md +9 -3
  29. package/docs/legion-v2-contract.md +122 -20
  30. package/docs/vexillatio-contract.md +5 -1
  31. package/index.ts +1903 -130
  32. package/package.json +5 -5
  33. package/skills/pi-legion/SKILL.md +2 -1
  34. package/src/agents/agents.ts +26 -1
  35. package/src/agents/settings.ts +67 -2
  36. package/src/api.ts +17 -0
  37. package/src/extension/child-guard.ts +2 -1
  38. package/src/extension/join.ts +54 -0
  39. package/src/extension/legion-commands.ts +15 -4
  40. package/src/extension/legion-doctor.ts +48 -6
  41. package/src/extension/legion-status.ts +44 -2
  42. package/src/extension/legion-tools.ts +1044 -109
  43. package/src/extension/notify.ts +31 -2
  44. package/src/extension/playbook.ts +6 -3
  45. package/src/extension/runtime.ts +882 -81
  46. package/src/extension/spawn-hints.ts +52 -12
  47. package/src/extension/summary.ts +7 -15
  48. package/src/extension/timing.ts +4 -15
  49. package/src/legion/db.ts +23 -1
  50. package/src/legion/events.ts +7 -0
  51. package/src/legion/interrupt.ts +98 -0
  52. package/src/legion/mail-release.ts +266 -0
  53. package/src/legion/mail.ts +456 -29
  54. package/src/legion/nodes.ts +31 -0
  55. package/src/legion/phase-conditions.ts +7 -1
  56. package/src/legion/phase-machine.ts +160 -8
  57. package/src/legion/state-machine.ts +34 -2
  58. package/src/runs/acceptance.ts +105 -6
  59. package/src/runs/args.ts +16 -0
  60. package/src/runs/child-scope.ts +323 -0
  61. package/src/runs/extension-inheritance.ts +145 -19
  62. package/src/runs/orchestrator.ts +613 -55
  63. package/src/runs/store.ts +149 -5
  64. package/src/shared/proc-sweep.ts +317 -0
  65. package/src/shared/progress.ts +11 -2
  66. package/src/shared/session-map.ts +29 -0
  67. package/src/shared/session.ts +308 -6
  68. package/src/shared/types.ts +34 -0
  69. package/src/supervisor/inprocess-supervisor.ts +158 -12
  70. package/src/supervisor/race-timeout.ts +55 -0
  71. package/src/supervisor/routing-supervisor.ts +55 -4
  72. package/src/supervisor/rpc-supervisor.ts +215 -29
  73. package/src/supervisor/types.ts +439 -2
  74. package/src/tui/status.ts +2 -1
  75. package/src/tui/viz/canvas.ts +358 -36
  76. package/src/tui/viz/palette.ts +18 -2
  77. package/src/tui/viz/panels.ts +507 -104
  78. package/src/tui/viz/rate.ts +120 -15
  79. package/src/tui/viz/view.ts +72 -4
@@ -9,35 +9,118 @@ export interface Cell {
9
9
  inverse?: boolean;
10
10
  }
11
11
 
12
+ /**
13
+ * #362: the grid owns `width × height` mutable cells, allocated once in the
14
+ * constructor. `set()` writes through to the existing cell instead of building
15
+ * a fresh object per write (measured 52–128 B/write, 4,583–9,691 writes/frame).
16
+ *
17
+ * Consequence for readers: `get()` and `cells` are a **live view**, not a
18
+ * snapshot. A cell object returned by `get()` is re-written in place by the next
19
+ * `set()` on that coordinate, so hold the value (`cell.ch`), never the object.
20
+ *
21
+ * Consequence for writers (#369, contract §4): a cell's `color` may only change
22
+ * through `set()`. `roleCounts` is the table `roles()`/`toLines()` resolve the
23
+ * palette from, and only `set()` knows to decrement the role it replaced — a
24
+ * direct `cell.color = …` write leaves the old role counted forever, i.e. a ghost
25
+ * role that changes which token the roles still painted are assigned. Nothing in
26
+ * the tree writes `color` outside `set()`/`reset()` today; that has to stay true.
27
+ */
12
28
  export class Canvas {
13
29
  readonly width: number;
14
30
  readonly height: number;
15
31
  readonly cells: Cell[][];
16
32
 
33
+ /**
34
+ * #364: agent types painted into this grid, as live counts, maintained by
35
+ * `set()` instead of scanning all `W×H` cells at paint time. `roles()` used to
36
+ * walk every cell (12,000 at 200×60) and `slice()` a string per role-coloured
37
+ * cell — measured ~75KB/frame, none of it information.
38
+ *
39
+ * Contract T5: this table must match the grid exactly. A role that is no
40
+ * longer painted (its cell overwritten) changes how `resolveRolePalette`
41
+ * assigns colours to the roles that ARE painted, so `set()` decrements the
42
+ * role it replaced and `reset()` zeroes the table. Counts are never deleted —
43
+ * keys are stable role names, so a `set()` on an existing key allocates
44
+ * nothing (contract T7: `set()` must not start allocating again).
45
+ */
46
+ private readonly roleCounts = new Map<string, number>();
47
+
17
48
  constructor(width: number, height: number) {
18
49
  this.width = Math.max(0, Math.floor(width));
19
50
  this.height = Math.max(0, Math.floor(height));
20
- this.cells = Array.from({ length: this.height }, () =>
21
- Array.from({ length: this.width }, () => ({ ch: " " }) as Cell),
22
- );
51
+ const cells: Cell[][] = new Array(this.height);
52
+ for (let y = 0; y < this.height; y++) {
53
+ const row: Cell[] = new Array(this.width);
54
+ for (let x = 0; x < this.width; x++) row[x] = { ch: " " } as Cell;
55
+ cells[y] = row;
56
+ }
57
+ this.cells = cells;
23
58
  }
24
59
 
60
+ /**
61
+ * Live cell at `(x, y)` — re-written in place by the next `set()`. Do not retain
62
+ * it, and never write `color` through it: only `set()` keeps `roleCounts` (and
63
+ * with it the palette) in step with the grid (contract §4).
64
+ */
25
65
  get(x: number, y: number): Cell | undefined {
26
66
  return this.cells[y]?.[x];
27
67
  }
28
68
 
29
- set(x: number, y: number, ch: string, color?: string, style: { bold?: boolean; inverse?: boolean } = {}): void {
69
+ /**
70
+ * #364 A5: blank every cell in place (and forget the roles) so one canvas can
71
+ * paint frame after frame. The cell OBJECTS survive — `get()`/`cells` stay a
72
+ * live view of the same grid (contract I5) — and the cost is W×H field writes
73
+ * instead of W×H fresh objects (+190KB/472KB per frame).
74
+ *
75
+ * Only `view.ts`'s production render path may use this; `new Canvas(W, H)`
76
+ * keeps its exact old semantics and cost.
77
+ */
78
+ reset(): void {
79
+ for (let y = 0; y < this.height; y++) {
80
+ const row = this.cells[y]!;
81
+ for (let x = 0; x < this.width; x++) {
82
+ const cell = row[x]!;
83
+ cell.ch = " ";
84
+ cell.color = undefined;
85
+ cell.bold = undefined;
86
+ cell.inverse = undefined;
87
+ }
88
+ }
89
+ for (const role of this.roleCounts.keys()) this.roleCounts.set(role, 0);
90
+ }
91
+
92
+ set(x: number, y: number, ch: string, color?: string, style: Readonly<{ bold?: boolean; inverse?: boolean }> = NO_STYLE): void {
30
93
  const row = this.cells[y];
31
94
  if (!row || x < 0 || x >= this.width) return;
32
- row[x] = { ch: sanitizeChar(ch), color, ...style };
95
+ const cell = row[x] as Cell;
96
+ // #364: keep the painted-role table in step with the grid. Both lookups are
97
+ // memoized/`startsWith`-only, so this stays allocation-free.
98
+ const nextRole = roleIdOf(color);
99
+ const prevRole = roleIdOf(cell.color);
100
+ if (nextRole !== prevRole) {
101
+ if (prevRole !== undefined) this.roleCounts.set(prevRole, (this.roleCounts.get(prevRole) ?? 0) - 1);
102
+ if (nextRole !== undefined) this.roleCounts.set(nextRole, (this.roleCounts.get(nextRole) ?? 0) + 1);
103
+ }
104
+ // Explicit field writes: an object spread here would allocate an intermediate
105
+ // object per write, which is the whole cost #362 is removing.
106
+ cell.ch = sanitizeChar(ch);
107
+ cell.color = color;
108
+ cell.bold = style.bold;
109
+ cell.inverse = style.inverse;
33
110
  }
34
111
 
35
112
  /** Write text clipped to [x, maxX). Returns the column after the last written cell. */
36
- text(x: number, y: number, value: string, color?: string, style: { bold?: boolean; inverse?: boolean; maxX?: number } = {}): number {
113
+ text(x: number, y: number, value: string, color?: string, style: Readonly<TextStyle> = NO_TEXT_STYLE): number {
37
114
  const limit = Math.min(this.width, style.maxX ?? this.width);
38
115
  let col = x;
39
- for (const ch of Array.from(value)) {
116
+ // #364: walk code points by index instead of `Array.from(value)` — the old
117
+ // loop allocated one throw-away array per written string, and the galaxy
118
+ // writes ~100 label strings and the legend per frame. The decode is
119
+ // `codePointAt`/`codePointLength`, the same pair `cellWidth`/`ellipsize` use
120
+ // (one implementation, and `sanitizeChar` collapses a wide glyph as before).
121
+ for (let i = 0; i < value.length; i += codePointLength(value, i)) {
40
122
  if (col >= limit) break;
123
+ const ch = codePointAt(value, i);
41
124
  if (col >= 0) this.set(col, y, ch, color, style);
42
125
  col++;
43
126
  }
@@ -46,26 +129,129 @@ export class Canvas {
46
129
 
47
130
  /** Agent types referenced by deferred `role:` colors in this canvas. */
48
131
  roles(): Set<string> {
49
- const roles = new Set<string>();
50
- for (const row of this.cells) for (const cell of row) {
51
- if (cell.color?.startsWith(ROLE_COLOR_PREFIX)) roles.add(cell.color.slice(ROLE_COLOR_PREFIX.length));
132
+ return new Set(this.roleList());
133
+ }
134
+
135
+ /**
136
+ * Present roles, in the order they were first written. `toLines` composes the
137
+ * palette cache key from this, so it has to be exactly the set of roles still
138
+ * on the grid (contract T5) — a count of 0 means the role was overwritten.
139
+ */
140
+ private roleList(): string[] {
141
+ const out: string[] = [];
142
+ for (const [role, count] of this.roleCounts) if (count > 0) out.push(role);
143
+ return out;
144
+ }
145
+
146
+ /**
147
+ * #364 (contract T5): a palette is a function of the theme **and** of exactly
148
+ * the roles this canvas paints — dropping a role changes which token the
149
+ * remaining ones get. Both parts are in the key, so a stale palette can never
150
+ * be returned; the cache only ever saves the `resolveRolePalette` work
151
+ * (`tokenSwatch` regexes over every candidate token) for an unchanged frame.
152
+ */
153
+ private rolePalette(theme: VizTheme): Map<string, string> {
154
+ let byTheme = PALETTES.get(theme);
155
+ if (!byTheme) {
156
+ byTheme = new Map();
157
+ PALETTES.set(theme, byTheme);
52
158
  }
53
- return roles;
159
+ const roles = this.roleList().sort();
160
+ // `length + \u0000` separator: role names are arbitrary strings, so a plain
161
+ // `join(",")` would let `["x,y"]` and `["x", "y"]` (different frames, different
162
+ // palettes) share one cache entry — the second frame would get the first's
163
+ // assignment and one of its roles would fall back to `text`.
164
+ const key = `${roles.length}\u0000${roles.join("\u0000")}`;
165
+ const cached = byTheme.get(key);
166
+ if (cached) return cached;
167
+ const resolved = resolveRolePalette(theme, roles);
168
+ if (byTheme.size >= PALETTE_CACHE_MAX) byTheme.clear();
169
+ byTheme.set(key, resolved);
170
+ return resolved;
54
171
  }
55
172
 
56
- toLines(theme: VizTheme, palette = resolveRolePalette(theme, this.roles())): string[] {
57
- const resolve = (color: string | undefined): string | undefined =>
58
- color?.startsWith(ROLE_COLOR_PREFIX) ? palette.get(color.slice(ROLE_COLOR_PREFIX.length)) ?? "text" : color;
59
- return this.cells.map((row) => renderRow(row.map((cell) => cell.color?.startsWith(ROLE_COLOR_PREFIX) ? { ...cell, color: resolve(cell.color) } : cell), theme));
173
+ toLines(theme: VizTheme, palette?: Map<string, string>): string[] {
174
+ const colors = palette ?? this.rolePalette(theme);
175
+ const lines: string[] = new Array(this.height);
176
+ for (let y = 0; y < this.height; y++) lines[y] = renderRow(this.cells[y]!, theme, colors);
177
+ return lines;
60
178
  }
61
179
 
62
180
  toPlain(): string[] {
63
- return this.cells.map((row) => row.map((cell) => cell.ch).join(""));
181
+ const lines: string[] = new Array(this.height);
182
+ for (let y = 0; y < this.height; y++) {
183
+ const row = this.cells[y]!;
184
+ const width = row.length;
185
+ PLAIN_CHARS.length = width;
186
+ for (let x = 0; x < width; x++) PLAIN_CHARS[x] = row[x]!.ch;
187
+ lines[y] = PLAIN_CHARS.join("");
188
+ }
189
+ return lines;
64
190
  }
65
191
  }
66
192
 
67
- /** Keep cells single-width: wide/control characters become a placeholder. */
193
+ /** Shared empty style so a `set(x, y, ch)` call allocates no default object. */
194
+ const NO_STYLE: Readonly<{ bold?: boolean; inverse?: boolean }> = {};
195
+
196
+ /** Style knobs `text()` reads; every shared style constant is a `Readonly<TextStyle>`. */
197
+ export interface TextStyle {
198
+ bold?: boolean;
199
+ inverse?: boolean;
200
+ maxX?: number;
201
+ }
202
+
203
+ /**
204
+ * #364: `text()`'s default argument was `{}` — a fresh object per call, i.e. one
205
+ * per written string (~1,200 per 200x60 frame, measured 58KB). The painter never
206
+ * mutates the style object, so one shared instance serves every style-less call.
207
+ * `Readonly` is what makes "never mutates" a type error instead of a comment.
208
+ */
209
+ const NO_TEXT_STYLE: Readonly<TextStyle> = {};
210
+
211
+ /** Palette cache bound: one theme × one role set is a handful of entries. */
212
+ const PALETTE_CACHE_MAX = 32;
213
+ const PALETTES = new WeakMap<VizTheme, Map<string, Map<string, string>>>();
214
+
215
+ /**
216
+ * `role:worker` → `worker`, memoized so `set()` can keep the painted-role table
217
+ * without allocating a slice per write (contract T7). Bounded: the value side is
218
+ * a role name, of which a run has a handful.
219
+ */
220
+ const ROLE_IDS = new Map<string, string>();
221
+ const ROLE_IDS_MAX = 512;
222
+
223
+ function roleIdOf(color: string | undefined): string | undefined {
224
+ if (color === undefined || !color.startsWith(ROLE_COLOR_PREFIX)) return undefined;
225
+ const cached = ROLE_IDS.get(color);
226
+ if (cached !== undefined) return cached;
227
+ const id = color.slice(ROLE_COLOR_PREFIX.length);
228
+ if (ROLE_IDS.size >= ROLE_IDS_MAX) ROLE_IDS.clear();
229
+ ROLE_IDS.set(color, id);
230
+ return id;
231
+ }
232
+
233
+ /**
234
+ * Keep cells single-width: wide/control characters become a placeholder.
235
+ *
236
+ * #362: memoized per input char. `String.fromCodePoint` allocates a fresh string
237
+ * for every code point outside Latin-1, and the chart/galaxy paint `█ ⣿ ─` tens of
238
+ * thousands of times per frame — without this cache `set()` would still allocate
239
+ * one string per write. The table is bounded (terminal cell glyphs are a small set)
240
+ * and cleared if a pathological caller ever feeds it thousands of distinct chars.
241
+ */
242
+ const SANITIZED = new Map<string, string>();
243
+ const SANITIZED_MAX = 4096;
244
+
68
245
  export function sanitizeChar(ch: string): string {
246
+ const hit = SANITIZED.get(ch);
247
+ if (hit !== undefined) return hit;
248
+ const out = sanitizeUncached(ch);
249
+ if (SANITIZED.size >= SANITIZED_MAX) SANITIZED.clear();
250
+ SANITIZED.set(ch, out);
251
+ return out;
252
+ }
253
+
254
+ function sanitizeUncached(ch: string): string {
69
255
  if (ch.length === 0) return " ";
70
256
  const code = ch.codePointAt(0)!;
71
257
  if (code < 0x20 || (code >= 0x7f && code < 0xa0)) return " ";
@@ -87,38 +273,174 @@ function isWide(code: number): boolean {
87
273
  );
88
274
  }
89
275
 
276
+ /** Length of the code point at `i`, in UTF-16 units (2 only for a surrogate pair). */
277
+ function codePointLength(value: string, i: number): number {
278
+ const code = value.charCodeAt(i);
279
+ if (code >= 0xd800 && code <= 0xdbff && i + 1 < value.length) {
280
+ const low = value.charCodeAt(i + 1);
281
+ if (low >= 0xdc00 && low <= 0xdfff) return 2;
282
+ }
283
+ return 1;
284
+ }
285
+
286
+ /** The code point starting at `i` as a string (a lone surrogate comes back as itself). */
287
+ function codePointAt(value: string, i: number): string {
288
+ return codePointLength(value, i) === 2 ? value.slice(i, i + 2) : (value[i] as string);
289
+ }
290
+
90
291
  /** Grapheme / cell count (UTF-16-safe). Prefer over `String.length` for layout budgets. */
91
292
  export function cellWidth(value: string): number {
92
- return Array.from(value).length;
293
+ // #364: same answer as `Array.from(value).length` without materialising the array.
294
+ let count = 0;
295
+ for (let i = 0; i < value.length; i += codePointLength(value, i)) count++;
296
+ return count;
93
297
  }
94
298
 
95
299
  /** Truncate plain text to `width` single-width cells with an ellipsis. */
96
300
  export function ellipsize(value: string, width: number): string {
97
- const chars = Array.from(value).map(sanitizeChar);
98
301
  if (width <= 0) return "";
99
- if (chars.length <= width) return chars.join("");
100
- return `${chars.slice(0, Math.max(0, width - 1)).join("")}…`;
302
+ if (cellWidth(value) <= width) return sanitizeAll(value);
303
+ const keep = Math.max(0, width - 1);
304
+ let out = "";
305
+ let taken = 0;
306
+ for (let i = 0; i < value.length && taken < keep; i += codePointLength(value, i)) {
307
+ out += sanitizeChar(codePointAt(value, i));
308
+ taken++;
309
+ }
310
+ return `${out}…`;
311
+ }
312
+
313
+ /**
314
+ * `Array.from(value).map(sanitizeChar).join("")`, but returns `value` untouched
315
+ * when nothing needs sanitising — which is the common case (agent names, role
316
+ * names, legend labels) and what keeps `ellipsize` allocation-free there.
317
+ * #364 A2/A3: the old version built a per-code-point array + string for every
318
+ * label on every frame.
319
+ */
320
+ function sanitizeAll(value: string): string {
321
+ let changed = false;
322
+ for (let i = 0; i < value.length; i += codePointLength(value, i)) {
323
+ const raw = codePointAt(value, i);
324
+ if (sanitizeChar(raw) !== raw) {
325
+ changed = true;
326
+ break;
327
+ }
328
+ }
329
+ if (!changed) return value;
330
+ let out = "";
331
+ for (let i = 0; i < value.length; i += codePointLength(value, i)) out += sanitizeChar(codePointAt(value, i));
332
+ return out;
101
333
  }
102
334
 
103
- function renderRow(row: Cell[], theme: VizTheme): string {
335
+ /**
336
+ * One row of cells → one terminal line.
337
+ *
338
+ * #364 A3: the role colours are resolved here, from the palette, instead of
339
+ * copying every role-coloured cell into a `{...cell, color}` clone first
340
+ * (measured 1,123/1,865 clones × 70–72B per frame). Runs are still merged on the
341
+ * RESOLVED colour, which is what the clone-then-merge did — two role cells whose
342
+ * tokens collide must stay one run, exactly as before.
343
+ *
344
+ * Contract T6: `theme.fg` is applied only to a run that has a colour AND at
345
+ * least one non-whitespace glyph (the old `text.trim().length > 0`), because the
346
+ * page floor relies on a row's trailing bare spaces carrying no SGR.
347
+ */
348
+ function renderRow(row: Cell[], theme: VizTheme, palette: Map<string, string>): string {
104
349
  let out = "";
105
350
  let i = 0;
106
- while (i < row.length) {
107
- const start = row[i]!;
108
- let text = "";
109
- while (
110
- i < row.length &&
111
- row[i]!.color === start.color &&
112
- !!row[i]!.bold === !!start.bold &&
113
- !!row[i]!.inverse === !!start.inverse
114
- ) {
115
- text += row[i]!.ch;
116
- i++;
351
+ const cells = row.length;
352
+ while (i < cells) {
353
+ const first = row[i]!;
354
+ const startColor = resolvedColor(first, palette);
355
+ const bold = !!first.bold;
356
+ const inverse = !!first.inverse;
357
+ let end = i + 1;
358
+ while (end < cells) {
359
+ const cell = row[end]!;
360
+ if (!!cell.bold !== bold || !!cell.inverse !== inverse || resolvedColor(cell, palette) !== startColor) break;
361
+ end++;
362
+ }
363
+ const len = end - i;
364
+ // The run's text, with as few objects as its shape allows. `text += ch` per
365
+ // cell builds one ConsString per append — ~9.6k appends per 200x60 frame,
366
+ // measured 230KB — and one `join()` per run costs ~8B per char. Length-1 runs
367
+ // reuse the cell's own string, an all-same run collapses to one `repeat()`
368
+ // (page-floor row tails, borders, solid braille fills), and everything else
369
+ // goes through the reused buffer.
370
+ let text: string;
371
+ if (len === 1) {
372
+ text = first.ch;
373
+ } else {
374
+ let uniform = true;
375
+ for (let k = i + 1; k < end; k++) {
376
+ if (row[k]!.ch !== first.ch) {
377
+ uniform = false;
378
+ break;
379
+ }
380
+ }
381
+ if (uniform) {
382
+ text = first.ch.repeat(len);
383
+ } else if (len === 2) {
384
+ text = first.ch + row[i + 1]!.ch;
385
+ } else {
386
+ ROW_CHARS.length = len;
387
+ for (let k = 0; k < len; k++) ROW_CHARS[k] = row[i + k]!.ch;
388
+ text = ROW_CHARS.join("");
389
+ }
390
+ }
391
+ let visible = false;
392
+ if (startColor !== undefined) {
393
+ for (let k = i; k < end; k++) {
394
+ if (isVisible(row[k]!.ch)) {
395
+ visible = true;
396
+ break;
397
+ }
398
+ }
117
399
  }
118
- let styled = start.color && text.trim().length > 0 ? theme.fg(start.color, text) : text;
119
- if (start.bold && theme.bold) styled = theme.bold(styled);
120
- if (start.inverse && theme.inverse) styled = theme.inverse(styled);
400
+ i = end;
401
+ let styled = startColor && visible ? theme.fg(startColor, text) : text;
402
+ if (bold && theme.bold) styled = theme.bold(styled);
403
+ if (inverse && theme.inverse) styled = theme.inverse(styled);
121
404
  out += styled;
122
405
  }
123
406
  return out;
124
407
  }
408
+
409
+ /**
410
+ * Reusable per-row buffers (#364, contract A1).
411
+ *
412
+ * `line += cell.ch` looks free but builds one ConsString per append: a 200-cell
413
+ * row cost ~288KB/frame for `toPlain` alone (measured 373KB against 12KB of
414
+ * actual text). Pushing into a reused array and joining once per row keeps the
415
+ * allocation proportional to the row's length instead of its cell count.
416
+ * Neither painter is reentrant, and `toPlain` uses its own buffer so the two can
417
+ * never interleave.
418
+ */
419
+ const ROW_CHARS: string[] = [];
420
+ const PLAIN_CHARS: string[] = [];
421
+
422
+ /** A cell's colour with `role:` tokens resolved through the palette. */
423
+ function resolvedColor(cell: Cell, palette: Map<string, string>): string | undefined {
424
+ const color = cell.color;
425
+ if (color === undefined) return undefined;
426
+ const role = roleIdOf(color);
427
+ return role === undefined ? color : palette.get(role) ?? "text";
428
+ }
429
+
430
+ /** `text.trim().length > 0` for one glyph, without building the trimmed string. */
431
+ function isVisible(ch: string): boolean {
432
+ for (let i = 0; i < ch.length; i++) if (!isWhitespaceCode(ch.charCodeAt(i))) return true;
433
+ return false;
434
+ }
435
+
436
+ /** The code points `String.prototype.trim` strips (same set as regex `\s`). */
437
+ function isWhitespaceCode(code: number): boolean {
438
+ if (code === 0x20) return true;
439
+ if (code < 0x09 || (code > 0x0d && code < 0xa0)) return false;
440
+ return (
441
+ code === 0x09 || code === 0x0a || code === 0x0b || code === 0x0c || code === 0x0d ||
442
+ code === 0xa0 || code === 0x1680 || (code >= 0x2000 && code <= 0x200a) ||
443
+ code === 0x2028 || code === 0x2029 || code === 0x202f || code === 0x205f ||
444
+ code === 0x3000 || code === 0xfeff
445
+ );
446
+ }
@@ -47,12 +47,28 @@ export function roleToken(role: string): string {
47
47
  /** Prefix marking a cell color as "the color of this agent type", resolved per theme at paint time. */
48
48
  export const ROLE_COLOR_PREFIX = "role:";
49
49
 
50
+ /**
51
+ * `roleColor` used to build two strings per call (a `toLowerCase()` and the
52
+ * template) and the galaxy asks for one per edge, per node and per label —
53
+ * hundreds per frame, for the same handful of values.
54
+ *
55
+ * #364 A2: memoized on the role name, which is a stable scalar; the function is
56
+ * pure, so there is no invalidation to get wrong (contract I7 — the key *is* the
57
+ * input). The cap only stops a pathological caller from growing the table.
58
+ */
59
+ const ROLE_COLOR_CACHE = new Map<string, string>();
60
+ const ROLE_COLOR_CACHE_MAX = 512;
61
+
50
62
  /** Deferred per-type color; resolved by `resolveRolePalette` when a canvas is painted. */
51
63
  export function roleColor(role: string): string {
64
+ const cached = ROLE_COLOR_CACHE.get(role);
65
+ if (cached !== undefined) return cached;
52
66
  // The ledger root is the user's own pi session, not an agent type: keep it
53
67
  // neutral so it never takes a type's color (centurion owns accent).
54
- if (role.toLowerCase() === "root") return "text";
55
- return `${ROLE_COLOR_PREFIX}${role.toLowerCase()}`;
68
+ const out = role.toLowerCase() === "root" ? "text" : `${ROLE_COLOR_PREFIX}${role.toLowerCase()}`;
69
+ if (ROLE_COLOR_CACHE.size >= ROLE_COLOR_CACHE_MAX) ROLE_COLOR_CACHE.clear();
70
+ ROLE_COLOR_CACHE.set(role, out);
71
+ return out;
56
72
  }
57
73
 
58
74
  /**