ceulen 0.1.0 → 0.5.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 (56) hide show
  1. package/CHANGELOG.md +150 -0
  2. package/README.md +103 -14
  3. package/extensions/index.ts +113 -0
  4. package/extensions/lib/env.ts +75 -0
  5. package/extensions/lib/panel.ts +1720 -0
  6. package/extensions/lib/registry.ts +182 -0
  7. package/extensions/modules/composer/index.ts +128 -0
  8. package/extensions/modules/composer/lib/settings.ts +55 -0
  9. package/extensions/modules/composer/lib/shapes.ts +436 -0
  10. package/extensions/modules/composer/test/editor.test.ts +138 -0
  11. package/extensions/modules/composer/test/module.test.ts +218 -0
  12. package/extensions/modules/composer/test/screen.test.ts +195 -0
  13. package/extensions/modules/composer/test/shapes.test.ts +175 -0
  14. package/extensions/modules/config/index.ts +298 -0
  15. package/extensions/modules/config/piSettings.ts +467 -0
  16. package/extensions/modules/config/plugins.ts +290 -0
  17. package/extensions/modules/config/test/kernel.test.ts +523 -0
  18. package/extensions/modules/config/test/kernelV4.test.ts +196 -0
  19. package/extensions/modules/config/test/menu.test.ts +226 -0
  20. package/extensions/modules/config/test/panel.test.ts +395 -0
  21. package/extensions/modules/config/test/piSettings.test.ts +185 -0
  22. package/extensions/modules/config/test/plugins.test.ts +181 -0
  23. package/extensions/modules/config/test/preview-block.test.ts +88 -0
  24. package/extensions/modules/ponytail/UPSTREAM +26 -0
  25. package/extensions/modules/ponytail/index.ts +336 -0
  26. package/extensions/modules/ponytail/lib/config.ts +149 -0
  27. package/extensions/modules/ponytail/lib/instructions.ts +98 -0
  28. package/extensions/modules/ponytail/lib/subagent.ts +31 -0
  29. package/extensions/modules/ponytail/test/extension.test.ts +422 -0
  30. package/extensions/modules/ponytail/test/helpers.test.ts +163 -0
  31. package/extensions/modules/ponytail/test/subagent.test.ts +33 -0
  32. package/extensions/modules/router/commands/commands.ts +99 -0
  33. package/extensions/modules/router/configPanel.ts +89 -0
  34. package/extensions/modules/router/index.ts +75 -0
  35. package/extensions/modules/router/lib/client.ts +390 -0
  36. package/extensions/modules/router/lib/config.ts +142 -0
  37. package/extensions/modules/router/lib/migrate.ts +92 -0
  38. package/extensions/modules/router/lib/provider.ts +138 -0
  39. package/extensions/modules/router/lib/refresh.ts +19 -0
  40. package/extensions/modules/router/test/guard.test.ts +77 -0
  41. package/extensions/modules/router/test/unit.test.ts +1126 -0
  42. package/extensions/modules/usage/index.ts +1975 -0
  43. package/extensions/modules/usage/test/context.test.ts +387 -0
  44. package/extensions/modules/usage/test/env-gating.test.ts +113 -0
  45. package/extensions/modules/usage/test/opencode-go-usage.test.ts +139 -0
  46. package/extensions/modules/usage/test/parsers.test.ts +244 -0
  47. package/extensions/modules/usage/test/stale-ctx-regression.test.ts +294 -0
  48. package/extensions/modules/usage/test/zai-anthropic-adapter.test.ts +40 -0
  49. package/package.json +15 -3
  50. package/skills/ponytail/SKILL.md +124 -0
  51. package/skills/ponytail-audit/SKILL.md +41 -0
  52. package/skills/ponytail-debt/SKILL.md +44 -0
  53. package/skills/ponytail-gain/SKILL.md +51 -0
  54. package/skills/ponytail-help/SKILL.md +73 -0
  55. package/skills/ponytail-review/SKILL.md +57 -0
  56. package/extensions/index.js +0 -42
@@ -0,0 +1,436 @@
1
+ /**
2
+ * Composer shapes — the full OMP vocabulary (band · box · claude · pi ·
3
+ * borderless · rule · field · rail) with OMP's labels/descriptions.
4
+ *
5
+ * OMP's ComposerStyle owns side chrome, fills and prompt gutters; pi's Editor
6
+ * paints content rows internally. The row CONTENT is still addressable: it is
7
+ * laid out at the shape's content width (`super.render(inner)`), and the TUI
8
+ * locates the hardware cursor with `visibleWidth(textBeforeMarker)` on the
9
+ * FINAL line — so chrome can wrap each composed row (rails, caps, gutter,
10
+ * fill) without touching text, wrapping, or cursor placement.
11
+ *
12
+ * Status: shapes that embed a status line in their chrome (band · box ·
13
+ * claude · rule) render model · dir · context% from live session data.
14
+ * OMP's standalone BOTTOM status bar has no twin here — pi's own footer
15
+ * already sits under the editor for every shape.
16
+ */
17
+
18
+ import { CustomEditor } from "@earendil-works/pi-coding-agent";
19
+ import { sliceByColumn, truncateToWidth, visibleWidth, type EditorTheme, type KeybindingsManager, type TUI } from "@earendil-works/pi-tui";
20
+
21
+ /** Live data the status line shows (fail-soft to blanks). */
22
+ export interface BandData {
23
+ model?: string;
24
+ cwd?: string;
25
+ /** Context-window usage percent, when known. */
26
+ pct?: number | null;
27
+ }
28
+
29
+ /** Styling hooks — the live editor and the /config preview both build these
30
+ * from the live theme, so the two can never drift. */
31
+ export interface ShapeTheme {
32
+ border: (s: string) => string;
33
+ accent: (s: string) => string;
34
+ text: (s: string) => string;
35
+ dim: (s: string) => string;
36
+ warn: (s: string) => string;
37
+ /** Filled surface (background + on-surface foreground), robust to nested
38
+ * SGR resets — the cursor glyph emits one, which would otherwise drop the
39
+ * fill from that point on (OMP's bgFill). */
40
+ fill: (s: string) => string;
41
+ inverse: (s: string) => string;
42
+ }
43
+
44
+ export const IDENTITY_THEME: ShapeTheme = {
45
+ border: (s) => s,
46
+ accent: (s) => s,
47
+ text: (s) => s,
48
+ dim: (s) => s,
49
+ warn: (s) => s,
50
+ fill: (s) => s,
51
+ inverse: (s) => s,
52
+ };
53
+
54
+ /** The slice of pi's Theme the shapes need (the live Theme satisfies it). */
55
+ export interface ThemeLike {
56
+ fg: (color: never, text: string) => string;
57
+ getBgAnsi?: (color: never) => string;
58
+ getFgAnsi?: (color: never) => string;
59
+ inverse?: (text: string) => string;
60
+ }
61
+
62
+ /** Build the shape styling from a live pi Theme. */
63
+ export function shapeTheme(t: ThemeLike): ShapeTheme {
64
+ const bg = t.getBgAnsi?.("userMessageBg" as never) ?? "";
65
+ const onBg = t.getFgAnsi?.("userMessageText" as never) ?? "";
66
+ return {
67
+ border: (s) => t.fg("borderMuted" as never, s),
68
+ accent: (s) => t.fg("accent" as never, s),
69
+ text: (s) => t.fg("text" as never, s),
70
+ dim: (s) => t.fg("dim" as never, s),
71
+ warn: (s) => t.fg("warning" as never, s),
72
+ fill: surfacePainter(bg + onBg),
73
+ inverse: (s) => t.inverse?.(s) ?? s,
74
+ };
75
+ }
76
+
77
+ export interface ShapeCtx {
78
+ /** FULL composer width (side chrome included). */
79
+ w: number;
80
+ /** Content lines scrolled out of view. */
81
+ hidden: number;
82
+ theme: ShapeTheme;
83
+ /** Pre-styled status line, when the shape embeds one. */
84
+ status?: string;
85
+ /** The active shape's prompt gutter (wired in at render time so row
86
+ * builders can align continuation rows without a second parameter). */
87
+ gutter?: string;
88
+ }
89
+
90
+ export interface RowOpts {
91
+ first: boolean;
92
+ isLast: boolean;
93
+ }
94
+
95
+ export interface ComposerShapeDef {
96
+ id: string;
97
+ /** OMP's selector label + description — the /config menu copy. */
98
+ label: string;
99
+ description: string;
100
+ /** Cells one side chrome consumes per side (0 = none). */
101
+ sideWidth: number;
102
+ /** Minimum editor paddingX this shape needs (host padding can raise it). */
103
+ padX: number;
104
+ /** True when the shape's top row embeds the status line (OMP's
105
+ * statusAttachment). Non-embedding shapes surface the working spinner
106
+ * through pi's native spinner-bearing rule instead. */
107
+ embedsStatus?: boolean;
108
+ /** First-row prompt gutter (OMP's defaultPromptGutter); continuation rows
109
+ * get spaces so the text column stays aligned. */
110
+ gutter?: string;
111
+ top?: (c: ShapeCtx) => string | undefined;
112
+ bottom?: (c: ShapeCtx) => string | undefined;
113
+ /** Wrap one composed editor row, padded to the content width. */
114
+ row: (c: ShapeCtx, text: string, o: RowOpts) => string;
115
+ }
116
+
117
+ // ── helpers ──────────────────────────────────────────────────────────────────
118
+
119
+ const spaces = (n: number) => " ".repeat(Math.max(0, n));
120
+
121
+ /** Pad a composed row to the content width (ANSI- and cursor-marker-safe). */
122
+ export const padRow = (inner: number, text: string) => text + spaces(inner - visibleWidth(text));
123
+
124
+ /** Surface painter that survives nested resets (OMP's bgFill): re-apply the
125
+ * bg+fg prefix after every reset the row text carries. */
126
+ export function surfacePainter(prefix: string): (s: string) => string {
127
+ return (s) => (prefix === "" ? s : prefix + s.replace(/\x1b\[0m/g, `\x1b[0m${prefix}`) + "\x1b[39m\x1b[49m");
128
+ }
129
+
130
+ /** One styled status line: model · dir · context% (segments drop out when the
131
+ * session hasn't provided them — never wrong, just shorter). */
132
+ export function statusLine(data: BandData | undefined, theme: ShapeTheme): string {
133
+ const sep = theme.dim(" · ");
134
+ const parts: string[] = [];
135
+ if (data?.model?.trim()) parts.push(theme.accent(data.model.trim()));
136
+ if (data?.cwd?.trim()) parts.push(theme.dim(data.cwd.trim()));
137
+ if (typeof data?.pct === "number" && Number.isFinite(data.pct)) {
138
+ const pct = Math.round(data.pct);
139
+ parts.push(pct > 80 ? theme.warn(`${pct}%`) : theme.dim(`${pct}%`));
140
+ }
141
+ return parts.join(sep);
142
+ }
143
+
144
+ function rule(w: number, th: ShapeTheme): string {
145
+ return th.border("─".repeat(Math.max(0, w)));
146
+ }
147
+
148
+ /** Rule carrying pi's native scroll indicator (` ↑ N more `), centered. */
149
+ function ruleWithScroll(w: number, hidden: number, th: ShapeTheme): string {
150
+ if (hidden > 0) {
151
+ const label = ` ↑ ${hidden} more `;
152
+ const lw = visibleWidth(label);
153
+ if (lw + 2 <= w) {
154
+ const left = Math.floor((w - lw) / 2);
155
+ return th.border("─".repeat(left) + label + "─".repeat(w - left - lw));
156
+ }
157
+ }
158
+ return rule(w, th);
159
+ }
160
+
161
+ /** Right-docked status chip on a rule (OMP's renderTopRule: left fill, status
162
+ * at the right edge, one rule cell after it). */
163
+ function topRuleChip(c: ShapeCtx): string {
164
+ const { w, theme, status } = c;
165
+ if (status && visibleWidth(status) > 0 && w > 2) {
166
+ const content = visibleWidth(status) > w - 2 ? truncateToWidth(status, w - 2, "…") : status;
167
+ return theme.border("─".repeat(Math.max(0, w - visibleWidth(content) - 1))) + content + theme.border("─");
168
+ }
169
+ return ruleWithScroll(w, c.hidden, theme);
170
+ }
171
+
172
+ /** Flush soft-capped status band (no frame). Reserved row: blank when the
173
+ * status has nothing to show yet, so the layout never shifts. */
174
+ function bandTop(c: ShapeCtx): string {
175
+ const { w, theme, status } = c;
176
+ if (!status || visibleWidth(status) === 0) return "";
177
+ const cap = theme.accent("╭─");
178
+ const scroll = c.hidden > 0 ? theme.border(` ↑${c.hidden} `) : "";
179
+ const budget = Math.max(1, w - visibleWidth(cap) - visibleWidth(scroll));
180
+ const body = truncateToWidth(` ${status} `, budget);
181
+ return cap + theme.fill(body + spaces(budget - visibleWidth(body))) + scroll;
182
+ }
183
+
184
+ /** Rounded box top: `╭─ status ─────╮` (status left-embedded, OMP's box). */
185
+ function boxTop(c: ShapeCtx): string {
186
+ const { w, theme, status } = c;
187
+ const inner = Math.max(0, w - 2);
188
+ if (!status || visibleWidth(status) === 0) return theme.border("╭" + "─".repeat(inner) + "╮");
189
+ const content = truncateToWidth(status, Math.max(1, inner - 4), "…");
190
+ // `╭─ ` (3) + content + ` ` (1) + fill + `─` (1) + `╮` (1) = w ⇒ fill = inner - content - 4.
191
+ const fill = "─".repeat(Math.max(0, inner - visibleWidth(content) - 4));
192
+ return theme.border("╭─ ") + content + theme.border(" " + fill + "─" + "╮");
193
+ }
194
+
195
+ /** Prompt gutter on the first row, aligned blanks on continuation rows. */
196
+ const gutterRow = (c: ShapeCtx, text: string, o: RowOpts) => {
197
+ const gw = visibleWidth(c.gutter ?? "");
198
+ if (gw === 0) return text;
199
+ return o.first ? sliceByColumn(c.gutter!, 0, gw, true) + text : spaces(gw) + text;
200
+ };
201
+
202
+ // ── the shapes (OMP order + copy) ────────────────────────────────────────────
203
+
204
+ export const SHAPES: ComposerShapeDef[] = [
205
+ {
206
+ id: "band",
207
+ label: "Status Band (Default)",
208
+ description: "Flush soft-capped status band above a curved prompt, no frame",
209
+ sideWidth: 0,
210
+ padX: 0,
211
+ embedsStatus: true,
212
+ gutter: "╰─ ",
213
+ top: bandTop,
214
+ row: (c, text, o) =>
215
+ (o.first ? c.theme.border(c.gutter ?? "") : spaces(visibleWidth(c.gutter ?? ""))) + text,
216
+ },
217
+ {
218
+ id: "box",
219
+ label: "Rounded Box",
220
+ description: "Status line embedded in top border, compact 2-line prompt",
221
+ sideWidth: 1,
222
+ padX: 2,
223
+ embedsStatus: true,
224
+ top: boxTop,
225
+ row: (c, text, o) => {
226
+ if (!o.isLast) return c.theme.border("│") + text + c.theme.border("│");
227
+ // Merge the bottom border into the last content row (OMP's box):
228
+ // `╰─ text ─╯` — one padding cell each side becomes the corner rule.
229
+ const trimStart = text.startsWith(" ") ? text.slice(1) : text;
230
+ const trimEnd = trimStart.endsWith(" ") ? trimStart.slice(0, -1) : trimStart;
231
+ return c.theme.border("╰─") + trimEnd + c.theme.border("─╯");
232
+ },
233
+ },
234
+ {
235
+ id: "claude",
236
+ label: "Claude Code",
237
+ description: "Full-width horizontal rules above and below, status line at bottom",
238
+ sideWidth: 0,
239
+ padX: 0,
240
+ embedsStatus: true,
241
+ gutter: "❯ ",
242
+ top: topRuleChip,
243
+ bottom: (c) => ruleWithScroll(c.w, c.hidden, c.theme),
244
+ row: (c, text, o) => (o.first ? c.theme.accent(c.gutter ?? "") : spaces(visibleWidth(c.gutter ?? ""))) + text,
245
+ },
246
+ {
247
+ id: "pi",
248
+ label: "Pi",
249
+ description: "Framed horizontal rules with status line at bottom",
250
+ sideWidth: 0,
251
+ padX: 1,
252
+ top: (c) => ruleWithScroll(c.w, c.hidden, c.theme),
253
+ bottom: (c) => ruleWithScroll(c.w, c.hidden, c.theme),
254
+ row: (_c, text) => text,
255
+ },
256
+ {
257
+ id: "borderless",
258
+ label: "Borderless",
259
+ description: "Clean prompt glyph with status line at bottom, no box borders",
260
+ sideWidth: 0,
261
+ padX: 0,
262
+ gutter: "❯ ",
263
+ row: (c, text, o) => (o.first ? c.theme.accent(c.gutter ?? "") : spaces(visibleWidth(c.gutter ?? ""))) + text,
264
+ },
265
+ {
266
+ id: "rule",
267
+ label: "Top Rule Dock",
268
+ description: "Single top rule with status docked onto it and below",
269
+ sideWidth: 0,
270
+ padX: 0,
271
+ embedsStatus: true,
272
+ gutter: "❯ ",
273
+ top: topRuleChip,
274
+ row: (c, text, o) => (o.first ? c.theme.accent(c.gutter ?? "") : spaces(visibleWidth(c.gutter ?? ""))) + text,
275
+ },
276
+ {
277
+ id: "field",
278
+ label: "Compact Field",
279
+ description: "Filled one-row field with accent end caps",
280
+ sideWidth: 1,
281
+ padX: 1,
282
+ row: (c, text) => c.theme.accent("▐") + c.theme.fill(text) + c.theme.accent("▌"),
283
+ },
284
+ {
285
+ id: "rail",
286
+ label: "Accent Rail",
287
+ description: "Filled one-row field anchored by a single accent rail",
288
+ sideWidth: 1,
289
+ padX: 1,
290
+ row: (c, text) => c.theme.accent("▎") + c.theme.fill(text),
291
+ },
292
+ ];
293
+
294
+ export const SHAPE_IDS: readonly string[] = SHAPES.map((s) => s.id);
295
+
296
+ /** OMP's default composer shape. */
297
+ export const DEFAULT_SHAPE = "band";
298
+
299
+ export function isShapeId(v: unknown): v is string {
300
+ return typeof v === "string" && SHAPE_IDS.includes(v);
301
+ }
302
+
303
+ /** Unknown ids fall back to the default (OMP's getComposerStyle contract) —
304
+ * a stale settings value must never break the editor. */
305
+ export function shapeById(id: string): ComposerShapeDef {
306
+ return SHAPES.find((s) => s.id === id) ?? SHAPES[0]!;
307
+ }
308
+
309
+ /** Gutter cells a shape's layout reserves on every row. */
310
+ export function gutterWidth(shape: ComposerShapeDef, w: number): number {
311
+ return Math.min(visibleWidth(shape.gutter ?? ""), Math.max(0, w - shape.sideWidth * 2 - 1));
312
+ }
313
+
314
+ /** Content width the editor lays text out at, for a given shape. */
315
+ export function contentWidth(shape: ComposerShapeDef, w: number): number {
316
+ return Math.max(1, w - shape.sideWidth * 2 - gutterWidth(shape, w));
317
+ }
318
+
319
+ /** Render one shape through its own chrome builders — the /config preview and
320
+ * the live editor share these, so the preview cannot drift. */
321
+ export function previewShape(id: string, w: number, theme: ShapeTheme, data?: BandData): string[] {
322
+ const shape = shapeById(id);
323
+ const inner = contentWidth(shape, w);
324
+ const c: ShapeCtx = { w, hidden: 0, theme, gutter: shape.gutter, status: statusLine(data, theme) || undefined };
325
+ const prompt = theme.text(truncateToWidth("Ask anything, edit files, run tools", Math.max(1, inner - shape.padX * 2 - 1), "…"));
326
+ const text = padRow(inner, spaces(shape.padX) + prompt + theme.inverse(" "));
327
+ const lines: string[] = [];
328
+ const top = shape.top?.(c);
329
+ if (top !== undefined) lines.push(top);
330
+ lines.push(shape.row(c, text, { first: true, isLast: true }));
331
+ const bottom = shape.bottom?.(c);
332
+ if (bottom !== undefined) lines.push(bottom);
333
+ return lines.map((l) => truncateToWidth(l, w, "", true));
334
+ }
335
+
336
+ type EditorCtorArgs = ConstructorParameters<typeof CustomEditor>;
337
+
338
+ /** The native editor re-chromed by a shape. Extends `CustomEditor` so pi
339
+ * duck-types the full app keybinding surface onto it (escape, ctrl+d,
340
+ * paste-image, extension shortcuts, action handlers). */
341
+ export class ShapeEditor extends CustomEditor {
342
+ private shape: ComposerShapeDef;
343
+ private shapeTheme: () => ShapeTheme;
344
+ private data: () => BandData | undefined;
345
+
346
+ constructor(shape: ComposerShapeDef, opts: { theme: () => ShapeTheme; data: () => BandData | undefined }, ...base: EditorCtorArgs) {
347
+ super(...base);
348
+ this.shape = shape;
349
+ this.shapeTheme = opts.theme;
350
+ this.data = opts.data;
351
+ super.setPaddingX(this.effectivePadding(super.getPaddingX()));
352
+ }
353
+
354
+ /** The shape owns its minimum padding; host padding may raise it. */
355
+ override setPaddingX(padding: number): void {
356
+ super.setPaddingX(this.effectivePadding(padding));
357
+ }
358
+
359
+ private effectivePadding(host: number): number {
360
+ const h = Number.isFinite(host) ? Math.max(0, Math.floor(host)) : 0;
361
+ return Math.max(h, this.shape.padX);
362
+ }
363
+
364
+ override render(width: number): string[] {
365
+ try {
366
+ const shape = this.shape;
367
+ const theme = this.safeTheme();
368
+ const inner = contentWidth(shape, width);
369
+ const raw = super.render(inner);
370
+ const ac = (this as unknown as { renderedAutocompleteHeight?: number }).renderedAutocompleteHeight;
371
+ const acH = typeof ac === "number" ? ac : 0;
372
+ const bottomIdx = Math.max(1, raw.length - acH - 1);
373
+ const content = raw.slice(1, bottomIdx);
374
+ const acRows = raw.slice(bottomIdx + 1);
375
+
376
+ const spinner = this.spinnerText();
377
+ const status = [spinner, statusLine(this.safeData(), theme)].filter(Boolean).join(" ");
378
+ const c: ShapeCtx = { w: width, hidden: this.hiddenLines(), theme, gutter: shape.gutter, status: status || undefined };
379
+
380
+ const out: string[] = [];
381
+ const top = shape.top?.(c);
382
+ if (spinner !== undefined && !shape.embedsStatus) {
383
+ // No status-bearing chrome on this shape — the spinner rides pi's
384
+ // native spinner-bearing rule instead (only while a turn runs).
385
+ out.push(this.nativeTop(raw[0]!, width, theme));
386
+ } else if (top !== undefined) {
387
+ out.push(top);
388
+ }
389
+ content.forEach((r, i) => out.push(shape.row(c, padRow(inner, r), { first: i === 0, isLast: i === content.length - 1 })));
390
+ const bottom = shape.bottom?.(c);
391
+ if (bottom !== undefined) out.push(bottom);
392
+ for (const r of acRows) out.push(shape.row(c, padRow(inner, r), { first: false, isLast: false }));
393
+ return out.map((l) => truncateToWidth(l, width, "", true));
394
+ } catch {
395
+ // A core feature must never take the editor down with it.
396
+ return super.render(width);
397
+ }
398
+ }
399
+
400
+ /** Keep the native spinner border visible at full width. */
401
+ private nativeTop(nativeLine: string, width: number, theme: ShapeTheme): string {
402
+ return nativeLine + theme.border("─".repeat(Math.max(0, width - visibleWidth(nativeLine))));
403
+ }
404
+
405
+ /** The working spinner glyph from the embedded indicator, when active. */
406
+ private spinnerText(): string | undefined {
407
+ try {
408
+ const ind = (this as unknown as { workingStatusIndicator?: { renderSpinnerInBorder?: (w: number) => string } }).workingStatusIndicator;
409
+ return ind && typeof ind.renderSpinnerInBorder === "function" ? ind.renderSpinnerInBorder(2) : undefined;
410
+ } catch {
411
+ return undefined;
412
+ }
413
+ }
414
+
415
+ private hiddenLines(): number {
416
+ // ponytail: private pi-tui scroll state, read guarded — 0 when it moves.
417
+ const v = (this as unknown as { scrollOffset?: unknown }).scrollOffset;
418
+ return typeof v === "number" ? v : 0;
419
+ }
420
+
421
+ private safeTheme(): ShapeTheme {
422
+ try {
423
+ return this.shapeTheme() ?? IDENTITY_THEME;
424
+ } catch {
425
+ return IDENTITY_THEME;
426
+ }
427
+ }
428
+
429
+ private safeData(): BandData | undefined {
430
+ try {
431
+ return this.data();
432
+ } catch {
433
+ return undefined;
434
+ }
435
+ }
436
+ }
@@ -0,0 +1,138 @@
1
+ /**
2
+ * ShapeEditor render tests — the critical invariants:
3
+ * 1. chrome wraps every content row at the exact full width;
4
+ * 2. the CURSOR_MARKER survives wrapping and lands at the right column
5
+ * (the TUI measures `visibleWidth(textBeforeMarker)` on the final line);
6
+ * 3. text is laid out at the shape's content width (no overflow/cut-off);
7
+ * 4. the working spinner stays visible while a turn runs.
8
+ */
9
+
10
+ import { describe, it } from "node:test";
11
+ import assert from "node:assert/strict";
12
+ import { CURSOR_MARKER, visibleWidth } from "@earendil-works/pi-tui";
13
+ import { IDENTITY_THEME, ShapeEditor, shapeById } from "../lib/shapes.ts";
14
+
15
+ const plain = (s: string) => s.replace(/\x1b\[[0-9;]*m/g, "");
16
+ const theme = { borderColor: (s: string) => s, fg: (_t: string, s: string) => s, bg: (_t: string, s: string) => s };
17
+ // Loose stubs: only the surface the editor touches (pi's TUI type is huge).
18
+ const tui = { terminal: { rows: 30 }, requestRender() {} } as never;
19
+
20
+ /** Build an editor with text and the cursor at the end (focused → marker). */
21
+ function editor(id: string, text = "hello", data: { model?: string; cwd?: string; pct?: number | null } = {}) {
22
+ const ed = new ShapeEditor(shapeById(id), { theme: () => IDENTITY_THEME, data: () => data }, tui, theme as never, {} as never, { embedWorkingStatus: true });
23
+ ed.focused = true;
24
+ ed.setText(text);
25
+ return ed;
26
+ }
27
+
28
+ const rendered = (ed: ShapeEditor, w = 40) => ed.render(w);
29
+
30
+ describe("ShapeEditor rendering", () => {
31
+ it("every rendered line is exactly the requested width, for every shape", () => {
32
+ for (const id of ["band", "box", "claude", "pi", "borderless", "rule", "field", "rail"]) {
33
+ for (const w of [24, 40, 61]) {
34
+ for (const line of rendered(editor(id), w)) {
35
+ assert.equal(visibleWidth(line), w, `${id}@${w}: ${JSON.stringify(plain(line))}`);
36
+ }
37
+ }
38
+ }
39
+ });
40
+
41
+ it("keeps the cursor marker and reports the expected cursor column", () => {
42
+ // pi: no side chrome → text starts at padX = 1; "hello" cursor at end ⇒ x=6.
43
+ const pi = rendered(editor("pi"), 40);
44
+ const piRow = pi.find((l) => l.includes(CURSOR_MARKER));
45
+ assert.ok(piRow, "marker preserved (pi)");
46
+ assert.equal(visibleWidth(piRow!.slice(0, piRow!.indexOf(CURSOR_MARKER))), 6);
47
+
48
+ // box: border + padX(2) ⇒ 3 cells of chrome before text.
49
+ const box = rendered(editor("box"), 40);
50
+ const boxRow = box.find((l) => l.includes(CURSOR_MARKER));
51
+ assert.ok(boxRow, "marker preserved (box)");
52
+ assert.equal(visibleWidth(boxRow!.slice(0, boxRow!.indexOf(CURSOR_MARKER))), 8);
53
+
54
+ // band: gutter `╰─ ` (3 cells) ⇒ cursor sits 3 cells right of the text start.
55
+ const band = rendered(editor("band"), 40);
56
+ const bandRow = band.find((l) => l.includes(CURSOR_MARKER));
57
+ assert.ok(bandRow, "marker preserved (band)");
58
+ assert.equal(visibleWidth(bandRow!.slice(0, bandRow!.indexOf(CURSOR_MARKER))), 8);
59
+ });
60
+
61
+ it("compacts a long single-line prompt into the shape's content width (no cut-off)", () => {
62
+ const long = "x".repeat(200);
63
+ for (const id of ["box", "band", "field", "rail"]) {
64
+ const ed = editor(id, long);
65
+ const lines = rendered(ed, 30).map(plain);
66
+ // The text row must contain a contiguous run of x's up to the content width.
67
+ const textRow = lines.find((l) => l.includes("x"));
68
+ assert.ok(textRow, `${id} rendered text`);
69
+ assert.ok(textRow!.includes("x".repeat(20)), `${id}: text not laid out to width`);
70
+ assert.equal(visibleWidth(textRow!), 30);
71
+ }
72
+ });
73
+
74
+ it("box merges the bottom border into the last row; other shapes keep their chrome", () => {
75
+ const box = rendered(editor("box"), 30).map(plain);
76
+ assert.ok(box[0]!.startsWith("╭") && box[0]!.endsWith("╮"), box[0]);
77
+ assert.ok(box[box.length - 1]!.startsWith("╰") && box[box.length - 1]!.endsWith("╯"), box[box.length - 1]);
78
+ const claude = rendered(editor("claude"), 30).map(plain);
79
+ assert.ok(claude[claude.length - 1]!.startsWith("─"), "claude closes with a rule");
80
+ const borderless = rendered(editor("borderless"), 30).map(plain);
81
+ assert.equal(borderless.length, 1, "borderless is a single row");
82
+ });
83
+
84
+ it("status-bearing shapes show the live status; band shows a blank reserved row without data", () => {
85
+ const withData = rendered(editor("box", "hi", { model: "GLM-5.3", cwd: "ceulen", pct: 42 }), 50).map(plain);
86
+ assert.ok(withData[0]!.includes("GLM-5.3") && withData[0]!.includes("42%"), withData[0]);
87
+ const empty = rendered(editor("band"), 50).map(plain);
88
+ assert.equal(empty[0]!.trim(), "", "band reserves its row (blank, full width)");
89
+ });
90
+
91
+ it("keeps the working spinner visible while a turn runs", () => {
92
+ for (const id of ["band", "pi", "borderless", "box"]) {
93
+ const ed = editor(id);
94
+ ed.setWorkingStatusIndicator({ renderInBorder: () => "⟳", renderSpinnerInBorder: () => "⟳" } as never);
95
+ const lines = rendered(ed, 40).map(plain);
96
+ assert.ok(lines.some((l) => l.includes("⟳")), `${id} keeps the spinner`);
97
+ }
98
+ });
99
+
100
+ it("drops back to shape chrome when the spinner clears", () => {
101
+ const ed = editor("borderless");
102
+ ed.setWorkingStatusIndicator({ renderInBorder: () => "⟳", renderSpinnerInBorder: () => "⟳" } as never);
103
+ assert.ok(rendered(ed, 40).some((l) => plain(l).includes("⟳")));
104
+ ed.setWorkingStatusIndicator(undefined);
105
+ assert.ok(!rendered(ed, 40).some((l) => plain(l).includes("⟳")), "spinner row gone");
106
+ });
107
+
108
+ it("applies the shape's minimum padding over the host's", () => {
109
+ const box = editor("box");
110
+ assert.ok(box.getPaddingX() >= shapeById("box").padX, "shape minimum padding applied");
111
+ box.setPaddingX(0);
112
+ assert.equal(box.getPaddingX(), shapeById("box").padX, "host 0 is raised to the shape minimum");
113
+ box.setPaddingX(3);
114
+ assert.equal(box.getPaddingX(), 3, "host padding may exceed the minimum");
115
+ });
116
+
117
+ it("survives a throwing theme/data getter by degrading to plain chrome", () => {
118
+ const ed = new ShapeEditor(
119
+ shapeById("band"),
120
+ {
121
+ theme: () => {
122
+ throw new Error("boom");
123
+ },
124
+ data: () => {
125
+ throw new Error("boom");
126
+ },
127
+ },
128
+ tui,
129
+ theme as never,
130
+ {} as never,
131
+ { embedWorkingStatus: true },
132
+ );
133
+ ed.setText("ok");
134
+ const lines = ed.render(30);
135
+ assert.ok(lines.length > 0 && lines.some((l) => plain(l).includes("ok")), "still renders");
136
+ for (const l of lines) assert.equal(visibleWidth(l), 30);
137
+ });
138
+ });