pi-odd-worktree 2.0.0 → 3.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 (160) hide show
  1. package/README.md +54 -311
  2. package/extensions/odd-worktree-tools.ts +4149 -2447
  3. package/lib/bash-activity.js +1164 -0
  4. package/lib/bash-design.js +684 -0
  5. package/lib/bash-destructive.js +559 -0
  6. package/lib/bash-frame.js +205 -0
  7. package/lib/card-content.js +23 -0
  8. package/lib/card-style.js +175 -0
  9. package/lib/checkout-facts.js +30 -70
  10. package/lib/codegraph-card-preview.js +628 -0
  11. package/lib/codegraph-card.js +515 -0
  12. package/lib/codegraph-compaction.js +76 -0
  13. package/lib/codegraph-daemon.js +246 -0
  14. package/lib/codegraph-edit-sync.js +182 -0
  15. package/lib/codegraph-guard-target.js +337 -0
  16. package/lib/codegraph-guard.js +211 -0
  17. package/lib/codegraph-index.js +1020 -0
  18. package/lib/codegraph-lock.js +607 -0
  19. package/lib/codegraph-mcp-config.js +134 -0
  20. package/lib/codegraph-mcp.js +123 -0
  21. package/lib/codegraph-paths.js +69 -0
  22. package/lib/codegraph-prompt/explore.md +11 -0
  23. package/lib/codegraph-prompt/fix.md +6 -0
  24. package/lib/codegraph-prompt/generic.md +8 -0
  25. package/lib/codegraph-prompt/judge.md +9 -0
  26. package/lib/codegraph-prompt/orchestrator.md +17 -0
  27. package/lib/codegraph-prompt/verify.md +10 -0
  28. package/lib/codegraph-prompt/worker.md +7 -0
  29. package/lib/codegraph-role.js +55 -0
  30. package/lib/codegraph-rules.js +146 -0
  31. package/lib/codegraph-session.js +303 -383
  32. package/lib/codegraph-warmup.js +139 -0
  33. package/lib/file-card-markdown.js +141 -0
  34. package/lib/file-card-resolver.js +245 -0
  35. package/lib/file-card.js +659 -0
  36. package/lib/files-index.js +387 -0
  37. package/lib/files-insert.js +81 -0
  38. package/lib/files-orders.js +326 -0
  39. package/lib/files-picker-view.js +1416 -0
  40. package/lib/files-preview.js +338 -0
  41. package/lib/files-scope-detail.js +171 -0
  42. package/lib/files-scope-view.js +507 -0
  43. package/lib/gh-issues.js +308 -14
  44. package/lib/issue-preview.js +26 -7
  45. package/lib/issues-bash-mutation.js +206 -0
  46. package/lib/issues-cache-store.js +261 -0
  47. package/lib/issues-section.js +710 -0
  48. package/lib/issues-view.js +649 -52
  49. package/lib/odd-prompt/odd-worktrees.md +21 -0
  50. package/lib/odd-worktrees-prompt.js +10 -28
  51. package/lib/related-issues-cache.js +210 -0
  52. package/lib/shell-card.js +825 -0
  53. package/lib/skill-odd-card.js +183 -0
  54. package/lib/tui-paint.js +4 -5
  55. package/lib/warp-create-panel.js +538 -250
  56. package/lib/warp-create-picker.js +56 -9
  57. package/lib/warp-delete-confirm.js +19 -28
  58. package/lib/warp-selector-view.js +160 -82
  59. package/lib/which-command.js +90 -0
  60. package/lib/worktree-card.js +267 -897
  61. package/lib/worktree-cards.js +383 -0
  62. package/lib/worktree-create.js +287 -0
  63. package/lib/worktree-git.js +3 -3
  64. package/lib/worktree-guard.js +548 -0
  65. package/lib/worktree-hooks.js +421 -711
  66. package/lib/worktree-list.js +120 -0
  67. package/lib/worktree-registry.js +162 -879
  68. package/lib/{worktree-close-herdr.js → worktree-remove.js} +9 -11
  69. package/lib/worktree-setup-runner.js +376 -0
  70. package/lib/worktree-setup.js +140 -0
  71. package/lib/worktree-warp-busy.js +462 -85
  72. package/lib/worktree-warp-sessions.js +1 -2
  73. package/package.json +2 -2
  74. package/tools/bash-activity.test.js +1419 -0
  75. package/tools/bash-design.test.js +1091 -0
  76. package/tools/bash-destructive.test.js +139 -0
  77. package/tools/card-content.test.js +44 -0
  78. package/tools/card-style.test.js +298 -0
  79. package/tools/codegraph-card-preview.test.js +254 -0
  80. package/tools/codegraph-card.test.js +1080 -0
  81. package/tools/codegraph-compaction.test.js +378 -0
  82. package/tools/codegraph-daemon.test.js +248 -0
  83. package/tools/codegraph-edit-sync.test.js +295 -0
  84. package/tools/codegraph-guard-target.test.js +174 -0
  85. package/tools/codegraph-guard.test.js +238 -0
  86. package/tools/codegraph-index.test.js +1948 -0
  87. package/tools/codegraph-lock.test.js +932 -0
  88. package/tools/codegraph-mcp-config.test.js +181 -0
  89. package/tools/codegraph-mcp.test.js +194 -0
  90. package/tools/codegraph-paths.test.js +44 -0
  91. package/tools/codegraph-role.test.js +30 -0
  92. package/tools/codegraph-rules.test.js +250 -0
  93. package/tools/codegraph-session.test.js +660 -391
  94. package/tools/codegraph-warmup.test.js +316 -0
  95. package/tools/commands.test.js +510 -31
  96. package/tools/file-card-markdown.test.js +188 -0
  97. package/tools/file-card.test.js +1289 -0
  98. package/tools/files-bridge.test.js +575 -0
  99. package/tools/files-command.test.js +610 -0
  100. package/tools/files-index.test.js +473 -0
  101. package/tools/files-insert.test.js +139 -0
  102. package/tools/files-orders.test.js +597 -0
  103. package/tools/files-picker-view.test.js +1871 -0
  104. package/tools/files-preview.test.js +452 -0
  105. package/tools/files-scope-detail.test.js +264 -0
  106. package/tools/files-scope-view.test.js +614 -0
  107. package/tools/fixtures/card-codegraph-outputs.js +110 -0
  108. package/tools/fixtures/codegraph-cli-stub.js +16 -0
  109. package/tools/fixtures/codegraph-init-process.js +28 -0
  110. package/tools/fixtures/codegraph-lock-worker.js +117 -0
  111. package/tools/fixtures/daemon-fake.js +98 -0
  112. package/tools/fixtures/daemon-mcp-server.js +39 -0
  113. package/tools/fixtures/daemon-warmup-worker.js +12 -0
  114. package/tools/fixtures/load-extension.js +136 -3
  115. package/tools/gh-issues-feedback.test.js +31 -7
  116. package/tools/gh-issues.test.js +391 -1
  117. package/tools/issue-preview.test.js +44 -7
  118. package/tools/issues-bash-mutation.test.js +101 -0
  119. package/tools/issues-cache-store.test.js +222 -0
  120. package/tools/issues-command.test.js +1512 -66
  121. package/tools/issues-open-guard.test.js +1096 -0
  122. package/tools/issues-section.test.js +4195 -0
  123. package/tools/issues-seed-query-regression.test.js +67 -0
  124. package/tools/issues-view.test.js +1489 -60
  125. package/tools/odd-worktrees-prompt.test.js +98 -65
  126. package/tools/package-surface.test.js +431 -36
  127. package/tools/related-issues-cache.test.js +324 -0
  128. package/tools/shell-card.test.js +834 -0
  129. package/tools/skill-odd-card.test.js +200 -0
  130. package/tools/t5-session-identity.test.js +44 -22
  131. package/tools/warp-busy-guard.test.js +2569 -308
  132. package/tools/warp-create-panel.test.js +499 -74
  133. package/tools/warp-create-picker.test.js +101 -5
  134. package/tools/warp-delete-confirm.test.js +49 -15
  135. package/tools/warp-empty-session.test.js +0 -1
  136. package/tools/warp-fallback-regression.test.js +533 -0
  137. package/tools/warp-selector-view.test.js +460 -196
  138. package/tools/which-command.test.js +126 -0
  139. package/tools/worktree-card.test.js +551 -0
  140. package/tools/worktree-cards.test.js +845 -0
  141. package/tools/worktree-changes.test.js +4 -5
  142. package/tools/worktree-create.test.js +489 -0
  143. package/tools/worktree-guard.test.js +823 -0
  144. package/tools/worktree-hooks.test.js +905 -0
  145. package/tools/worktree-list.test.js +170 -0
  146. package/tools/worktree-registry.test.js +89 -230
  147. package/tools/worktree-remove-async.test.js +318 -0
  148. package/tools/worktree-setup-runner.test.js +276 -0
  149. package/tools/worktree-setup.test.js +140 -0
  150. package/tools/worktree-tools.test.js +477 -93
  151. package/lib/codegraph-commands.js +0 -165
  152. package/lib/odd-prompt/odd-worktrees.with-codegraph.md +0 -19
  153. package/lib/odd-prompt/odd-worktrees.without-codegraph.md +0 -15
  154. package/lib/worktree-model-result.js +0 -291
  155. package/tools/codegraph-commands.test.js +0 -371
  156. package/tools/herdr-free-create.test.js +0 -161
  157. package/tools/worktree-close-herdr-async.test.js +0 -204
  158. package/tools/worktree-odd-migration.test.js +0 -224
  159. package/tools/worktree-registry-cache.test.js +0 -163
  160. package/tools/worktree-registry-odd.test.js +0 -231
@@ -0,0 +1,834 @@
1
+ 'use strict';
2
+ // S5 / T5a: the card drawing substrate in its TWO styles. Every case reads the
3
+ // public surface of lib/shell-card.js and pins what the source branch
4
+ // (lib/shell-card.ts and tests/shell-card.test.ts) draws — the rounded neon frame
5
+ // and the float rail. Width measurement, truncation and wrapping are the injected
6
+ // `metrics` seam, so this suite supplies deterministic fakes and never needs
7
+ // the host TUI package (this package has no node_modules).
8
+ //
9
+ // The style itself is the process-wide slot Gentle Shell publishes
10
+ // (`globalThis[Symbol.for("gentle-pi.card-style")]`) with the user's document as
11
+ // the fallback, so this suite points `GENTLE_PI_CONFIG_HOME` at a scratch
12
+ // directory: no case ever reads or writes the real user's preference, and the
13
+ // slot is cleared after each case that sets it.
14
+ const { test, before, after } = require('node:test');
15
+ const assert = require('node:assert/strict');
16
+ const { mkdtempSync, readFileSync, readdirSync, rmSync, unlinkSync, writeFileSync } = require('node:fs');
17
+ const { tmpdir } = require('node:os');
18
+ const { join } = require('node:path');
19
+ const {
20
+ CARD_GLYPH,
21
+ CARD_STYLE,
22
+ CARD_TONE,
23
+ TONE_OWNS_BOX,
24
+ cardAwaitingResult,
25
+ cardBodyRows,
26
+ cardBottom,
27
+ cardElapsed,
28
+ cardInnerWidth,
29
+ cardLine,
30
+ cardMouseEvent,
31
+ cardRunningLine,
32
+ cardTop,
33
+ cardTopLine,
34
+ cardTopRows,
35
+ floatRows,
36
+ headingFits,
37
+ markCardResult,
38
+ } = require('../lib/shell-card.js');
39
+ const { CARD_STYLE_SCHEMA, cardStyle } = require('../lib/card-style.js');
40
+
41
+ // ---- the style seam: the process-wide slot, and a scratch preference home ----
42
+
43
+ const CARD_STYLE_SLOT = Symbol.for('gentle-pi.card-style');
44
+
45
+ function useStyle(style) {
46
+ if (style === undefined) delete globalThis[CARD_STYLE_SLOT];
47
+ else globalThis[CARD_STYLE_SLOT] = style;
48
+ }
49
+
50
+ /** Runs `run` with the slot saying `style`, then clears the slot. */
51
+ function withStyle(style, run) {
52
+ useStyle(style);
53
+ try {
54
+ return run();
55
+ } finally {
56
+ useStyle(undefined);
57
+ }
58
+ }
59
+
60
+ let configHome;
61
+ const savedHome = process.env.GENTLE_PI_CONFIG_HOME;
62
+ const styleDocument = () => join(configHome, 'card-style.json');
63
+
64
+ function writeStyleDocument(contents) {
65
+ writeFileSync(styleDocument(), typeof contents === 'string' ? contents : JSON.stringify(contents));
66
+ }
67
+
68
+ function removeStyleDocument() {
69
+ try {
70
+ unlinkSync(styleDocument());
71
+ } catch {
72
+ // Already absent: the missing document is the case under test.
73
+ }
74
+ }
75
+
76
+ before(() => {
77
+ configHome = mkdtempSync(join(tmpdir(), 'odd-shell-card-style-'));
78
+ process.env.GENTLE_PI_CONFIG_HOME = configHome;
79
+ useStyle(undefined);
80
+ });
81
+
82
+ after(() => {
83
+ useStyle(undefined);
84
+ if (savedHome === undefined) delete process.env.GENTLE_PI_CONFIG_HOME;
85
+ else process.env.GENTLE_PI_CONFIG_HOME = savedHome;
86
+ rmSync(configHome, { recursive: true, force: true });
87
+ });
88
+
89
+ // ---- the injected text seam (fakes: plain ASCII, each character one column) ----
90
+
91
+ const ANSI = /\x1b\[[0-9;]*m/g;
92
+ const stripAnsi = (value) => value.replace(ANSI, '');
93
+ const chars = (value) => [...stripAnsi(value)];
94
+
95
+ const metrics = {
96
+ visibleWidth(value) {
97
+ return chars(value).length;
98
+ },
99
+ truncateToWidth(value, width, ellipsis = '') {
100
+ if (width <= 0) return '';
101
+ if (this.visibleWidth(value) <= width) return value;
102
+ const tail = ellipsis ?? '';
103
+ const keep = Math.max(0, width - [...tail].length);
104
+ return chars(value).slice(0, keep).join('') + tail;
105
+ },
106
+ wrapTextWithAnsi(value, width) {
107
+ const words = stripAnsi(value).split(' ');
108
+ if (width <= 0) return [stripAnsi(value)];
109
+ const lines = [];
110
+ let current = '';
111
+ for (const word of words) {
112
+ const candidate = current === '' ? word : `${current} ${word}`;
113
+ if ([...candidate].length <= width) {
114
+ current = candidate;
115
+ continue;
116
+ }
117
+ if (current !== '') {
118
+ lines.push(current);
119
+ current = '';
120
+ }
121
+ if ([...word].length <= width) {
122
+ current = word;
123
+ continue;
124
+ }
125
+ const rest = [...word];
126
+ while (rest.length > width) lines.push(rest.splice(0, width).join(''));
127
+ current = rest.join('');
128
+ }
129
+ lines.push(current);
130
+ return lines;
131
+ },
132
+ };
133
+
134
+ // ---- themes: a theme is an injected fg(role, text) (and optional bg) ----
135
+
136
+ const plainTheme = {
137
+ fg(_role, value) {
138
+ return value;
139
+ },
140
+ };
141
+
142
+ const taggedTheme = {
143
+ fg(role, value) {
144
+ return `<${role}>${value}</${role}>`;
145
+ },
146
+ };
147
+
148
+ // The background reset a Pi theme hands back at the end of `bg(role, "")`. It is
149
+ // spelled here, in the test, so the module under test can stay free of raw escapes.
150
+ const BG_RESET = '\x1b[49m';
151
+
152
+ /** A theme that records every role it paints and can paint the float background. */
153
+ function floatTheme() {
154
+ const roles = { fg: [], bg: [] };
155
+ return {
156
+ roles,
157
+ fg(role, value) {
158
+ roles.fg.push(role);
159
+ return `<${role}>${value}</${role}>`;
160
+ },
161
+ bg(role, value) {
162
+ roles.bg.push(role);
163
+ return `\x1b[48;5;240m${value}${BG_RESET}`;
164
+ },
165
+ };
166
+ }
167
+
168
+ /** A theme that records every role it is asked to paint, so no role is invented. */
169
+ function recordingTheme() {
170
+ const roles = [];
171
+ return {
172
+ roles,
173
+ fg(role, value) {
174
+ roles.push(role);
175
+ return value;
176
+ },
177
+ };
178
+ }
179
+
180
+ function card(overrides = {}) {
181
+ return {
182
+ title: 'Gentle AI',
183
+ subtitle: 'review preflight',
184
+ body: ['Receipt-driven development is enabled, and this worktree holds an unreviewed candidate.', '', 'Call the gentle_review tool with inspect and follow the transition it returns.'],
185
+ tone: CARD_TONE.INFO,
186
+ ...overrides,
187
+ };
188
+ }
189
+
190
+ // ---- exports and the two styles ----
191
+
192
+ test("the module exports the card surface and both styles", () => {
193
+ assert.equal(CARD_GLYPH, "✿");
194
+ assert.deepEqual(CARD_TONE, { INFO: "info", SUCCESS: "success", WARNING: "warning", ERROR: "error" });
195
+ assert.deepEqual(CARD_STYLE, { NEON: "neon", FLOAT: "float" }, "the two styles the shell offers, nothing else");
196
+ for (const [name, value] of Object.entries({ CARD_GLYPH, CARD_STYLE, CARD_TONE, cardAwaitingResult, cardBodyRows, cardBottom, cardElapsed, cardInnerWidth, cardLine, cardRunningLine, cardTop, cardTopLine, cardTopRows, floatRows, headingFits, markCardResult })) {
197
+ assert.ok(value !== undefined, `${name} is exported`);
198
+ }
199
+ });
200
+
201
+ // ---- inner width and body rows ----
202
+
203
+ test("cardInnerWidth is the frame width minus the four frame columns, never below one", () => {
204
+ assert.equal(cardInnerWidth(40), 36);
205
+ assert.equal(cardInnerWidth(5), 1);
206
+ assert.equal(cardInnerWidth(4), 1, "the floor is one column");
207
+ assert.equal(cardInnerWidth(0), 1);
208
+ assert.equal(cardInnerWidth(-7), 1);
209
+ });
210
+
211
+ test("a body row is padded to the full inner width and a wide row ends in a literal ellipsis", () => {
212
+ const padded = cardLine("hello", CARD_TONE.INFO, plainTheme, 20, metrics);
213
+ assert.equal(padded, `│ hello${" ".repeat(11)} │`);
214
+ assert.equal(metrics.visibleWidth(padded), 20);
215
+
216
+ const clipped = cardLine("x".repeat(30), CARD_TONE.SUCCESS, plainTheme, 12, metrics);
217
+ assert.equal(clipped, `│ ${"x".repeat(7)}… │`, "the inner width clips with U+2026, never a three dot ellipsis");
218
+ assert.equal(metrics.visibleWidth(clipped), 12);
219
+
220
+ assert.equal(cardLine("hi", CARD_TONE.INFO, plainTheme, 0, metrics), "");
221
+ assert.equal(cardLine("hi", CARD_TONE.INFO, plainTheme, 1, metrics), "│");
222
+ assert.equal(cardLine("hi", CARD_TONE.INFO, plainTheme, 2, metrics), "││");
223
+ assert.equal(cardLine("hi", CARD_TONE.INFO, plainTheme, 3, metrics), "│ │");
224
+
225
+ const tagged = cardLine("hi", CARD_TONE.ERROR, taggedTheme, 12, metrics);
226
+ assert.equal(tagged, `<error>│</error> <text>hi</text>${' '.repeat(6)} <error>│</error>`, "the sides carry the tone role, the content the body role and nothing is padded twice");
227
+ });
228
+
229
+ test("cardBodyRows wraps, splits paragraphs and applies the preview budget", () => {
230
+ const paragraph = "alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima";
231
+ const rows = cardBodyRows([paragraph], CARD_TONE.INFO, plainTheme, 30, { expanded: true }, metrics);
232
+ assert.ok(rows.length > 1, "a paragraph wider than the inner width wraps");
233
+ for (const row of rows) {
234
+ assert.equal(metrics.visibleWidth(row), 30, `"${row}" is not 30 wide`);
235
+ assert.match(row, /^│ .* │$/);
236
+ }
237
+ const rejoined = rows.map((row) => stripAnsi(row).slice(2, -2).trim()).join(" ");
238
+ assert.equal(rejoined, paragraph, "wrapping keeps every word");
239
+
240
+ const multiline = cardBodyRows(["one\ntwo\nthree\nfour"], CARD_TONE.INFO, plainTheme, 30, { expanded: true }, metrics);
241
+ assert.equal(multiline.length, 4, "each source line is its own row");
242
+ assert.ok(multiline.every((row) => !row.includes("\n")), "each returned row is physically one terminal row");
243
+
244
+ assert.equal(cardBodyRows(["one", "two", "three", "four"], CARD_TONE.INFO, plainTheme, 30, { expanded: false, previewRows: 3 }, metrics).length, 3, "the preview budget caps the rows");
245
+ assert.equal(cardBodyRows(["one", "two", "three", "four"], CARD_TONE.INFO, plainTheme, 30, { expanded: false }, metrics).length, 3, "three preview rows by default");
246
+ assert.deepEqual(cardBodyRows(["one"], CARD_TONE.INFO, plainTheme, 0, { expanded: true }, metrics), [], "no width draws nothing");
247
+ const empty = cardBodyRows(["", "one"], CARD_TONE.INFO, plainTheme, 12, { expanded: true }, metrics);
248
+ assert.equal(empty[0], `│${" ".repeat(10)}│`, "a blank line keeps the frame");
249
+
250
+ assert.deepEqual(cardBodyRows(["hi"], CARD_TONE.WARNING, taggedTheme, 12, { expanded: true }, metrics), [`<warning>│</warning> <text>hi</text>${' '.repeat(6)} <warning>│</warning>`]);
251
+ });
252
+
253
+ // ---- the top rule ----
254
+
255
+ test("cardTop draws the rounded frame with the glyph, the title and a dot separated detail", () => {
256
+ const row = cardTop(card(), plainTheme, 48, undefined, metrics);
257
+ assert.match(row, /^╭─ ✿ Gentle AI · review preflight ─+╮$/);
258
+ assert.equal(metrics.visibleWidth(row), 48);
259
+ assert.match(row, /╭─ ✿ Gentle AI · review preflight ─{13}╮$/, "the rule fills the remaining width");
260
+
261
+ const custom = cardTop(card({ glyph: "✎", subtitle: undefined }), plainTheme, 40, undefined, metrics);
262
+ assert.match(custom, /^╭─ ✎ Gentle AI ─+╮$/);
263
+
264
+ assert.equal(cardTop(card(), plainTheme, 0, undefined, metrics), "");
265
+ assert.equal(cardTop(card(), plainTheme, 1, undefined, metrics), "╭", "a one column frame is the corner alone");
266
+ assert.equal(cardTop(card(), plainTheme, 4, undefined, metrics), "╭──╮");
267
+ });
268
+
269
+ test("cardTop right-aligns a hint in the rule and drops it before truncating the heading", () => {
270
+ const hinted = cardTop(card(), plainTheme, 60, "ctrl+o expand", metrics);
271
+ assert.match(hinted, /^╭─ ✿ Gentle AI · review preflight ─+ ctrl\+o expand ╮$/);
272
+ assert.equal(metrics.visibleWidth(hinted), 60);
273
+
274
+ const dropped = cardTop(card(), plainTheme, 40, "ctrl+o expand", metrics);
275
+ assert.equal(dropped, "╭─ ✿ Gentle AI · review preflight ─────╮", "the hint yields before the heading does");
276
+ assert.equal(metrics.visibleWidth(dropped), 40);
277
+
278
+ const narrowed = cardTop(card({ subtitle: undefined, title: "Gentle AI review" }), plainTheme, 20, undefined, metrics);
279
+ assert.equal(narrowed, "╭─ ✿ Gentle AI rev ╮", "a heading too wide for the rule is clipped");
280
+ assert.equal(metrics.visibleWidth(narrowed), 20);
281
+ });
282
+
283
+ test("cardTop, cardLine and cardBottom paint the frame and the label in the tone's role", () => {
284
+ // The reference tables (lib/shell-card.ts TITLE_ROLE / FRAME_ROLE): every tone
285
+ // paints its own label, and INFO alone opens the accent its plain border cannot
286
+ // carry. The frame and the label therefore agree for every tone but INFO.
287
+ const roles = {
288
+ [CARD_TONE.INFO]: { frame: "border", title: "accent" },
289
+ [CARD_TONE.SUCCESS]: { frame: "success", title: "success" },
290
+ [CARD_TONE.WARNING]: { frame: "warning", title: "warning" },
291
+ [CARD_TONE.ERROR]: { frame: "error", title: "error" },
292
+ };
293
+ for (const [tone, expected] of Object.entries(roles)) {
294
+ const row = cardTop({ title: "t", subtitle: undefined, body: [], tone }, taggedTheme, 30, undefined, metrics);
295
+ assert.match(row, new RegExp(`^<${expected.frame}>╭</${expected.frame}><${expected.frame}>─ </${expected.frame}><${expected.title}>✿ t</${expected.title}>`), tone);
296
+ assert.match(cardLine("x", tone, taggedTheme, 30, metrics), new RegExp(`^<${expected.frame}>│</${expected.frame}>`), tone);
297
+ assert.match(cardBottom(tone, taggedTheme, 30, undefined, metrics), new RegExp(`^<${expected.frame}>╰</${expected.frame}>`), tone);
298
+ }
299
+
300
+ // INFO is the one card whose frame and label differ: the plain border with the
301
+ // accent label every informational card uses.
302
+ const info = cardTop(card(), taggedTheme, 80, undefined, metrics);
303
+ assert.equal(info, "<border>╭</border><border>─ </border><accent>✿ Gentle AI</accent> <muted>·</muted> <muted>review preflight</muted><border> ─────────────────────────────────────────────</border><border>╮</border>");
304
+ // A success card labels itself in its own role, not in the accent.
305
+ const success = cardTop(card({ tone: CARD_TONE.SUCCESS }), taggedTheme, 80, undefined, metrics);
306
+ assert.match(success, /^<success>╭<\/success><success>─ <\/success><success>✿ Gentle AI<\/success> <muted>·<\/muted> <muted>review preflight<\/muted><success> ─+<\/success><success>╮<\/success>$/);
307
+ assert.equal(success.includes("<warning>"), false, "a settled success is never labelled in the accent");
308
+ const error = cardTop(card({ tone: CARD_TONE.ERROR }), taggedTheme, 80, "ctrl+o to expand", metrics);
309
+ assert.equal(error, "<error>╭</error><error>─ </error><error>✿ Gentle AI</error> <muted>·</muted> <muted>review preflight</muted><error> ───────────────────────────</error> <dim>ctrl+o to expand</dim> <error>╮</error>");
310
+
311
+ // A card that names its own title role paints the label there and keeps the
312
+ // tone on the frame.
313
+ const labelled = cardTop(card({ glyph: "◎", title: "exploring", subtitle: "git status", tone: CARD_TONE.SUCCESS, titleRole: "mdLink" }), taggedTheme, 80, undefined, metrics);
314
+ assert.match(labelled, /^<success>╭<\/success><success>─ <\/success><mdLink>◎ exploring<\/mdLink> <muted>·<\/muted> <muted>git status<\/muted><success> /);
315
+ });
316
+
317
+ test("the card functions never paint a role the source branch does not use", () => {
318
+ const recorder = recordingTheme();
319
+ const bodies = ["alpha bravo charlie", "x".repeat(120)];
320
+ for (const tone of Object.values(CARD_TONE)) {
321
+ for (const width of [5, 12, 30, 60]) {
322
+ cardTop(card({ tone }), recorder, width, "ctrl+o", metrics);
323
+ cardTopLine(card({ tone }), recorder, width, "ctrl+o", undefined, metrics);
324
+ cardTopRows(card({ tone, title: "bash $ printf alpha bravo charlie delta" }), recorder, width, "ctrl+o", metrics);
325
+ cardBodyRows(bodies, tone, recorder, width, { expanded: true }, metrics);
326
+ cardBottom(tone, recorder, width, "1.2s", metrics);
327
+ cardRunningLine(tone, recorder, width, metrics);
328
+ }
329
+ }
330
+ assert.deepEqual([...new Set(recorder.roles)].sort(), ["accent", "border", "dim", "error", "muted", "success", "text", "warning"]);
331
+ });
332
+
333
+ test("a body row is clipped and padded on plain text and painted only afterwards", () => {
334
+ // The order the substrate guarantees: the text is measured and clipped first, and
335
+ // the role wraps the RESULT. So a clipped row is a complete paint of a plain clip,
336
+ // never a clip of a painted string.
337
+ assert.equal(cardLine("alpha bravo", CARD_TONE.INFO, taggedTheme, 16, metrics), `<border>│</border> <text>alpha bravo</text> <border>│</border>`, "a row that fits is painted whole, inside its padding");
338
+ assert.equal(cardLine("x".repeat(30), CARD_TONE.SUCCESS, taggedTheme, 12, metrics), `<success>│</success> <text>xxxxxxx…</text> <success>│</success>`, "the clip happens before the paint, so the mark closes the text and the role closes the mark");
339
+ const recorder = recordingTheme();
340
+ cardBodyRows(["alpha", "", "bravo"], CARD_TONE.INFO, recorder, 20, { expanded: true }, metrics);
341
+ assert.deepEqual(recorder.roles, ["border", "text", "border", "border", "border", "border", "text", "border"], "the body borrows neither the frame's tone nor the label's role, and a blank row is painted in no role at all");
342
+ });
343
+
344
+ test("no painted string is ever measured, clipped or padded", () => {
345
+ // The seam records every string the substrate asks it to measure. A theme that
346
+ // tags its roles makes a painted input unmistakable: none may ever arrive.
347
+ const seen = [];
348
+ const seam = {
349
+ visibleWidth(value) {
350
+ seen.push(String(value));
351
+ return metrics.visibleWidth(value);
352
+ },
353
+ truncateToWidth(value, width, ellipsis) {
354
+ seen.push(String(value));
355
+ return metrics.truncateToWidth(value, width, ellipsis);
356
+ },
357
+ wrapTextWithAnsi(value, width) {
358
+ seen.push(String(value));
359
+ return metrics.wrapTextWithAnsi(value, width);
360
+ },
361
+ };
362
+ for (const width of [60, 30, 22, 14]) {
363
+ cardTop(card({ title: "Gentle AI review", subtitle: "a detail far too wide for this rule", tone: CARD_TONE.WARNING }), taggedTheme, width, "ctrl+o to expand", seam);
364
+ cardTopLine(card({ title: "bash", subtitle: "printf alpha bravo charlie delta echo", tone: CARD_TONE.WARNING }), taggedTheme, width, "to expand", undefined, seam);
365
+ cardTopRows(card({ title: "bash $ printf alpha bravo charlie delta", subtitle: "and a detail", tone: CARD_TONE.WARNING }), taggedTheme, width, "ctrl+o", seam);
366
+ cardBodyRows(["alpha bravo charlie delta echo", ""], CARD_TONE.WARNING, taggedTheme, width, { expanded: true }, seam);
367
+ cardRunningLine(CARD_TONE.WARNING, taggedTheme, width, seam);
368
+ cardBottom(CARD_TONE.WARNING, taggedTheme, width, "1.2s", seam);
369
+ }
370
+ assert.ok(seen.length > 0, "the seam was exercised");
371
+ for (const value of seen) assert.equal(/<\/?[a-z]+>/.test(value), false, `a painted string reached the seam: ${value}`);
372
+ });
373
+
374
+ // ---- heading rows ----
375
+
376
+ test("a collapsed heading truncates an over-wide detail with an ellipsis and keeps the title and the hint", () => {
377
+ const value = { title: "bash", subtitle: "printf alpha bravo charlie delta echo foxtrot golf hotel", body: [], tone: CARD_TONE.WARNING };
378
+ const row = cardTopLine(value, plainTheme, 40, "to expand", undefined, metrics);
379
+ assert.equal(metrics.visibleWidth(row), 40);
380
+ assert.match(row, /^╭─ ✿ bash · printf .*….*to expand ╮$/, "the detail ends in an ellipsis instead of a second row");
381
+ assert.doesNotMatch(row, /golf/, "only what fits stays visible");
382
+ assert.match(row, /^╭─ ✿ bash /, "the title always survives the truncation");
383
+
384
+ const narrow = cardTopLine(value, plainTheme, 22, "to expand", undefined, metrics);
385
+ assert.equal(metrics.visibleWidth(narrow), 22);
386
+ assert.match(narrow, /…/, "truncation still ends in an ellipsis");
387
+ assert.doesNotMatch(narrow, /to expand/, "the hint yields its columns to the detail");
388
+
389
+ assert.match(cardTopLine({ ...value, subtitle: "git diff" }, plainTheme, 40, "to expand", undefined, metrics), /^╭─ ✿ bash · git diff ─+ to expand ╮$/);
390
+ assert.match(cardTopLine({ ...value, subtitle: "git diff\n--stat" }, plainTheme, 60, undefined, undefined, metrics), /^╭─ ✿ bash · git diff --stat ─+╮$/, "a multi-line detail collapses onto the one row");
391
+ assert.match(cardTopLine({ ...value, subtitle: undefined }, plainTheme, 40, "to expand", undefined, metrics), /^╭─ ✿ bash ─+ to expand ╮$/, "without a detail the row is a plain top rule");
392
+ const measured = cardTopLine(value, plainTheme, 40, undefined, (room) => `${room} files`, metrics);
393
+ assert.match(measured, /· \d+ files/, "a caller that measures its own detail receives the room left on the row");
394
+ });
395
+
396
+ test("an expanded heading wraps onto body rows instead of losing the detail", () => {
397
+ const detail = "printf alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike november oscar papa";
398
+ const value = { title: "bash", subtitle: detail, body: [], tone: CARD_TONE.WARNING };
399
+ const lines = cardTopRows(value, plainTheme, 60, "ctrl+o to expand", metrics);
400
+ assert.match(lines[0], /^╭─ ✿ bash ─+ ctrl\+o to expand ╮$/, "the title keeps the top rule and the hint");
401
+ assert.ok(!lines[0].includes("printf"), "a detail too wide for the rule never crowds the title");
402
+ assert.ok(lines.length > 1, "the detail continues inside the frame");
403
+ for (const line of lines) assert.equal(metrics.visibleWidth(line), 60, `"${line}" is not 60 wide`);
404
+ const shown = lines.slice(1).map((line) => stripAnsi(line).slice(2, -2).trim()).join(" ").replace(/\s+/g, " ").trim();
405
+ assert.equal(shown, `· ${detail}`, "the complete detail stays visible");
406
+
407
+ // A detail that fits keeps travelling on the title row, as every other card does.
408
+ const short = cardTopRows({ ...value, subtitle: "git status" }, plainTheme, 60, "ctrl+o to expand", metrics);
409
+ assert.match(short[0], /^╭─ ✿ bash · git status ─+ ctrl\+o to expand ╮$/);
410
+ assert.equal(short.length, 1);
411
+ });
412
+
413
+ test("a long title continues on body rows and a reserved hint never loses text", () => {
414
+ const title = "bash $ printf alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike november oscar papa";
415
+ const hint = "configured to expand";
416
+ // At 40 columns the reserved hint leaves less than MIN_HEADING_COLUMNS for the
417
+ // heading, so it yields its columns entirely (the source rule); no text is lost
418
+ // at any width.
419
+ for (const width of [40, 60, 120]) {
420
+ const lines = cardTopRows({ title, subtitle: undefined, body: [], tone: CARD_TONE.WARNING }, plainTheme, width, hint, metrics);
421
+ assert.match(lines[0], /^╭─ ✿ bash \$ printf /);
422
+ if (width >= 60) assert.match(lines[0], /configured to expand ╮$/, `the hint rides the rule at ${width}`);
423
+ else assert.doesNotMatch(lines[0], /configured/, "a hint that leaves no heading room gives way");
424
+ assert.ok(lines.length > 1, "the long heading continues inside the same frame");
425
+ for (const line of lines) assert.equal(metrics.visibleWidth(line), width, `"${line}" is not ${width} wide`);
426
+ const content = lines
427
+ .map((line, index) => (index === 0 ? line.replace(/^╭─ ✿ /, "").replace(/ ─+(?: configured to expand)? ?╮$/, "") : line.replace(/^│ /, "").replace(/ +│$/, "")))
428
+ .join(" ")
429
+ .replace(/\s+/g, " ")
430
+ .trim();
431
+ assert.equal(content, title, `hint reservation must not lose any heading text at ${width}`);
432
+ }
433
+ for (const width of [0, 1, 2, 3, 4, 5, 6, 7, 8]) {
434
+ const lines = cardTopRows({ title, subtitle: undefined, body: [], tone: CARD_TONE.INFO }, plainTheme, width, hint, metrics);
435
+ assert.ok(lines.every((line) => metrics.visibleWidth(line) <= width), `width ${width}`);
436
+ assert.ok(!lines.some((line) => line.includes("configured")), `no hint at ${width}`);
437
+ }
438
+ assert.deepEqual(cardTopRows({ title: "x", subtitle: undefined, body: [], tone: CARD_TONE.INFO }, plainTheme, 0, undefined, metrics), [], "no width draws no rows");
439
+ });
440
+
441
+ test("headingFits says whether a composed subtitle still leaves room for the key hint", () => {
442
+ const value = { title: "Agent status", subtitle: "explore", body: [], tone: CARD_TONE.INFO, glyph: "◎" };
443
+ const hint = "expand";
444
+ const needed = metrics.visibleWidth("◎ Agent status") + 3 + metrics.visibleWidth("explore") + 5 + metrics.visibleWidth(hint) + 2;
445
+ assert.equal(headingFits(value, hint, needed, metrics), true, "exactly enough columns still shows the hint");
446
+ assert.equal(headingFits(value, hint, needed - 1, metrics), false, "one column short is a no");
447
+ assert.equal(headingFits(value, undefined, needed - (metrics.visibleWidth(hint) + 2), metrics), true, "without a hint the head columns are enough");
448
+ assert.equal(headingFits(value, undefined, needed - (metrics.visibleWidth(hint) + 3), metrics), false, "and one column less is still a no");
449
+ assert.equal(headingFits({ ...value, subtitle: undefined }, hint, needed - 9, metrics), true, "no subtitle frees its separator and columns");
450
+ });
451
+
452
+ // ---- the running row and the closing rule ----
453
+
454
+ test("a running call draws one muted running row inside the frame", () => {
455
+ assert.equal(cardRunningLine(CARD_TONE.WARNING, plainTheme, 20, metrics), `│ running…${" ".repeat(8)} │`);
456
+ const recorder = recordingTheme();
457
+ assert.equal(cardRunningLine(CARD_TONE.INFO, recorder, 20, metrics), `│ running…${" ".repeat(8)} │`);
458
+ assert.deepEqual([...new Set(recorder.roles)].sort(), ["border", "muted"], "the text is muted and the frame keeps the tone");
459
+ for (const width of [0, 1, 2, 3, 4, 5, 6, 7, 8]) {
460
+ assert.ok(metrics.visibleWidth(cardRunningLine(CARD_TONE.WARNING, plainTheme, width, metrics)) <= width, `width ${width}`);
461
+ }
462
+ });
463
+
464
+ test("cardBottom closes the frame and right-aligns elapsed content only when three columns stay free", () => {
465
+ assert.equal(cardBottom(CARD_TONE.SUCCESS, plainTheme, 20, undefined, metrics), `╰${"─".repeat(18)}╯`);
466
+ assert.equal(cardBottom(CARD_TONE.SUCCESS, plainTheme, 20, "", metrics), `╰${"─".repeat(18)}╯`, "empty content draws the plain rule");
467
+ assert.equal(cardBottom(CARD_TONE.SUCCESS, plainTheme, 20, "1.2s", metrics), `╰${"─".repeat(12)} 1.2s ╯`);
468
+ assert.equal(metrics.visibleWidth(cardBottom(CARD_TONE.SUCCESS, plainTheme, 20, "1.2s", metrics)), 20);
469
+ // 20 - 2 - 6 = 12 columns of fill, and exactly three is still enough.
470
+ assert.equal(cardBottom(CARD_TONE.SUCCESS, plainTheme, 11, "1.2s", metrics), `╰${"─".repeat(3)} 1.2s ╯`);
471
+ assert.equal(cardBottom(CARD_TONE.SUCCESS, plainTheme, 10, "1.2s", metrics), `╰${"─".repeat(8)}╯`, "two free columns are not enough: the plain rule wins");
472
+ assert.equal(cardBottom(CARD_TONE.ERROR, taggedTheme, 20, "1.2s", metrics), `<error>╰</error><error>──────────── </error><dim>1.2s</dim><error> ╯</error>`);
473
+ assert.equal(cardBottom(CARD_TONE.ERROR, plainTheme, 0, "1.2s", metrics), "");
474
+ assert.equal(cardBottom(CARD_TONE.ERROR, plainTheme, 1, "1.2s", metrics), "╰");
475
+ });
476
+
477
+ test("cardElapsed reads milliseconds and seconds and is omitted when the duration is unknown", () => {
478
+ assert.equal(cardElapsed(0), "0ms");
479
+ assert.equal(cardElapsed(42), "42ms");
480
+ assert.equal(cardElapsed(999), "999ms");
481
+ assert.equal(cardElapsed(1200), "1.2s");
482
+ assert.equal(cardElapsed(60000), "60.0s");
483
+ for (const value of [undefined, Number.NaN, Number.POSITIVE_INFINITY, -5]) assert.equal(cardElapsed(value), undefined, String(value));
484
+ });
485
+
486
+ // ---- the shared row state ----
487
+
488
+ test("a call card awaits its result until the host finishes the row or a result renderer marks it", () => {
489
+ const state = {};
490
+ assert.equal(cardAwaitingResult({ isPartial: true, state }), true);
491
+ assert.equal(cardAwaitingResult({ state }), true, "an unknown lifecycle is still pending");
492
+ assert.equal(cardAwaitingResult({ isPartial: true }), true, "no shared state: only the final flag closes it");
493
+ assert.equal(cardAwaitingResult({ isPartial: false, state }), false, "a final result always exists");
494
+ markCardResult(state);
495
+ assert.equal(cardAwaitingResult({ isPartial: true, state }), false, "a partial result component closes the frame");
496
+ assert.deepEqual(Object.keys(state), [], "the mark never shows up as ordinary row state");
497
+ for (const value of [undefined, null, 1, "state"]) {
498
+ assert.doesNotThrow(() => markCardResult(value));
499
+ assert.equal(cardAwaitingResult({ isPartial: true, state: value }), true);
500
+ }
501
+ });
502
+
503
+ // ---- the float style, and the one style decision ----
504
+
505
+ // A card whose content is short enough that neither style's column difference can
506
+ // move a wrap boundary: this is the "same text, different chrome" card.
507
+ const SHORT_CARD = card({
508
+ subtitle: 'review preflight',
509
+ body: ['alpha bravo', 'charlie delta'],
510
+ });
511
+
512
+ /** A plain theme that can also paint the float background, so the text stays readable. */
513
+ function paintTheme() {
514
+ const roles = { fg: [], bg: [] };
515
+ return {
516
+ roles,
517
+ fg(role, value) {
518
+ roles.fg.push(role);
519
+ return value;
520
+ },
521
+ bg(role, value) {
522
+ roles.bg.push(role);
523
+ return `\x1b[48;5;240m${value}${BG_RESET}`;
524
+ },
525
+ };
526
+ }
527
+
528
+ /** One card component's parts, at the width the substrate hands the renderer. */
529
+ function partsAt(theme, value = SHORT_CARD, elapsed = '1.2s') {
530
+ return (width) => ({
531
+ head: [cardTop(value, theme, width, undefined, metrics)],
532
+ body: cardBodyRows(value.body, value.tone, theme, width, { expanded: true }, metrics),
533
+ bottom: cardBottom(value.tone, theme, width, elapsed, metrics),
534
+ });
535
+ }
536
+
537
+ /** The card's text with every chrome cell removed: what the reader actually reads. */
538
+ function contentOf(rows) {
539
+ return rows
540
+ .map((row) => stripAnsi(row).replace(/[╭╮╰╯─│▎]/g, ' ').replace(/\s+/g, ' ').trim())
541
+ .filter((text) => text.length > 0)
542
+ .join(' | ');
543
+ }
544
+
545
+ test('the float style draws the accent rail, the tone background and the two padding rows, and no box', () => {
546
+ const theme = floatTheme();
547
+ const rows = withStyle(CARD_STYLE.FLOAT, () => floatRows(CARD_TONE.WARNING, theme, 40, partsAt(theme)));
548
+ assert.equal(rows.length, 6, 'padding row, heading, padding row, two body rows and the closing row');
549
+ const visible = rows.map((row) => stripAnsi(row).replace(/<\/?[a-z:]+>/g, ''));
550
+ for (const row of rows) {
551
+ assert.equal(metrics.visibleWidth(stripAnsi(row).replace(/<\/?[a-z:]+>/g, '')), 40, 'every row is exactly the width the host asked for');
552
+ assert.ok(row.startsWith(' \x1b[48;5;240m'), 'every row is painted behind the tone background, inside the margin');
553
+ assert.ok(row.endsWith('\x1b[49m '), 'the background is closed before the right margin');
554
+ }
555
+ assert.equal(visible[0].trim(), '▎', 'the padding row above the heading keeps the rail');
556
+ assert.equal(visible[2].trim(), '▎', 'the separator between the heading and the body keeps it too');
557
+ assert.match(visible[1], /^ ▎ ✿ Gentle AI · review preflight +$/, 'the heading rides the rail with no corners');
558
+ assert.match(visible[3], /^ ▎ alpha bravo +$/, 'the body rides the rail with no sides');
559
+ assert.match(visible[5], /^ ▎ +1\.2s +$/, 'the closing row right-aligns the elapsed time');
560
+ for (const row of visible) assert.doesNotMatch(row, /[╭╮╰╯─│]/, 'the float style draws no box');
561
+ assert.deepEqual(theme.roles.bg, ['toolPendingBg'], 'the warning tone paints its own background role');
562
+ });
563
+
564
+ // ---- the rail role: one card, one role for its whole closed box ----
565
+
566
+ // The reference's `Card.railRole` (lib/shell-card.ts `frameRole`): a card with
567
+ // nothing left to report may name the role of its whole box — corners, rules, sides
568
+ // and rail — so the box reads as part of the label it belongs to. A tone that owns
569
+ // the box (a call still running, a call that failed) keeps its own frame role, and
570
+ // a card that names nothing keeps today's drawing byte for byte.
571
+ const RAIL_CARD = { title: 'codegraph', subtitle: 'init', body: ['→ initialized'], tone: CARD_TONE.INFO, glyph: '◎', titleRole: 'mdCode', railRole: 'mdCode' };
572
+
573
+ /** The card's rows with the fake theme taken out, so a width can be measured. */
574
+ const untag = (value) => stripAnsi(value).replace(/<[^>]*>/g, '');
575
+
576
+ function railParts(theme, value = RAIL_CARD) {
577
+ return (width) => ({
578
+ head: [cardTop(value, theme, width, undefined, metrics)],
579
+ body: cardBodyRows(value.body, value.tone, theme, width, { expanded: true }, metrics),
580
+ bottom: cardBottom(value.tone, theme, width, '1.2s', metrics),
581
+ });
582
+ }
583
+
584
+ test('a card that names a rail role paints its whole box there, and a status tone still owns it', () => {
585
+ // The reference's own table, which decides between the two: only a call still
586
+ // running or one that failed speaks for its box.
587
+ assert.deepEqual(TONE_OWNS_BOX, { info: false, success: false, warning: true, error: true });
588
+ const top = cardTop(RAIL_CARD, taggedTheme, 60, undefined, metrics);
589
+ assert.match(top, /^<mdCode>╭<\/mdCode><mdCode>─ <\/mdCode><mdCode>◎ codegraph<\/mdCode> <muted>·<\/muted> <muted>init<\/muted><mdCode> /, 'the corners and the lead carry the card role');
590
+ assert.match(top, /<mdCode> ─+<\/mdCode><mdCode>╮<\/mdCode>$/, 'and so do the rule and the closing corner');
591
+ assert.equal(top.includes('<border>'), false, 'no cell of the box keeps the tone role');
592
+
593
+ // A card that names no rail role is drawn exactly as before: the tone owns the box.
594
+ const described = cardTop({ ...RAIL_CARD, railRole: undefined }, taggedTheme, 60, undefined, metrics);
595
+ assert.match(described, /^<border>╭<\/border><border>─ <\/border>/);
596
+ assert.equal(described.includes('<mdCode>╭'), false);
597
+
598
+ // An active state speaks for the call: a running card keeps the warning role and a
599
+ // failed one the error role, whatever identity the card named.
600
+ assert.match(cardTop({ ...RAIL_CARD, tone: CARD_TONE.WARNING }, taggedTheme, 60, undefined, metrics), /^<warning>╭<\/warning>/);
601
+ assert.match(cardTop({ ...RAIL_CARD, tone: CARD_TONE.ERROR }, taggedTheme, 60, undefined, metrics), /^<error>╭<\/error>/);
602
+ });
603
+
604
+ test('the float style paints the rail, the padding rows and the closing rule in the card role', () => {
605
+ const theme = floatTheme();
606
+ const rows = withStyle(CARD_STYLE.FLOAT, () => floatRows(CARD_TONE.INFO, theme, 40, railParts(theme), 'mdCode'));
607
+ assert.equal(rows.length, 5, 'padding row, heading, padding row, one body row and the closing row');
608
+ for (const row of rows) {
609
+ assert.ok(row.includes('<mdCode>▎</mdCode>'), `"${row}" does not paint its rail in the card role`);
610
+ assert.equal(metrics.visibleWidth(untag(row)), 40, 'every row is the width the host asked for');
611
+ }
612
+ assert.equal(rows.join('\n').includes('<border>'), false, 'no cell of the band keeps the tone role');
613
+ assert.deepEqual(theme.roles.bg, ['toolSuccessBg'], 'the tone still decides the band the rail rides on');
614
+
615
+ // Without a rail role the float card is unchanged: the tone paints its rail.
616
+ const byTone = withStyle(CARD_STYLE.FLOAT, () => floatRows(CARD_TONE.INFO, theme, 40, railParts(theme)));
617
+ assert.ok(byTone.join('\n').includes('<border>▎</border>'));
618
+
619
+ // A running card keeps its own tone on the rail, and a failed one its error role.
620
+ const running = withStyle(CARD_STYLE.FLOAT, () => floatRows(CARD_TONE.WARNING, theme, 40, railParts(theme, { ...RAIL_CARD, tone: CARD_TONE.WARNING }), 'mdCode'));
621
+ assert.ok(running.join('\n').includes('<warning>▎</warning>'));
622
+ assert.equal(running.join('\n').includes('<mdCode>▎</mdCode>'), false);
623
+ const failed = withStyle(CARD_STYLE.FLOAT, () => floatRows(CARD_TONE.ERROR, theme, 40, railParts(theme, { ...RAIL_CARD, tone: CARD_TONE.ERROR }), 'mdCode'));
624
+ assert.ok(failed.join('\n').includes('<error>▎</error>'));
625
+ });
626
+
627
+ test('the float rail and the label take the tone role, and INFO its accent, never a colour of their own', () => {
628
+ // The reference contract (lib/shell-card.ts frame() and TITLE_ROLE): the float
629
+ // chrome paints the same FRAME_ROLE[tone] the neon frame does, and the label
630
+ // carries TITLE_ROLE[tone] — the tone, or the accent for INFO.
631
+ const expected = {
632
+ [CARD_TONE.INFO]: { frame: 'border', title: 'accent', bg: 'toolSuccessBg' },
633
+ [CARD_TONE.SUCCESS]: { frame: 'success', title: 'success', bg: 'toolSuccessBg' },
634
+ [CARD_TONE.WARNING]: { frame: 'warning', title: 'warning', bg: 'toolPendingBg' },
635
+ [CARD_TONE.ERROR]: { frame: 'error', title: 'error', bg: 'toolErrorBg' },
636
+ };
637
+ for (const [tone, roles] of Object.entries(expected)) {
638
+ const theme = floatTheme();
639
+ const rows = withStyle(CARD_STYLE.FLOAT, () => floatRows(tone, theme, 40, partsAt(theme, { ...SHORT_CARD, tone })));
640
+ const painted = rows.join('\n');
641
+ assert.ok(painted.includes(`<${roles.frame}>▎</${roles.frame}>`), `${tone}: the rail carries the tone role`);
642
+ assert.ok(painted.includes(`<${roles.title}>✿ Gentle AI</${roles.title}>`), `${tone}: the label carries its title role`);
643
+ assert.deepEqual([...new Set(theme.roles.fg)].sort(), [...new Set(['dim', 'muted', 'text', roles.frame, roles.title])].sort(), `${tone}: no role outside the tone, the label, the body text, the detail and the hint`);
644
+ assert.deepEqual(theme.roles.bg, [roles.bg], `${tone}: the float band paints its own tone background`);
645
+ }
646
+ });
647
+
648
+ test('the same card is the same text in both styles, and only the chrome differs', () => {
649
+ const theme = paintTheme();
650
+ const neon = withStyle(CARD_STYLE.NEON, () => floatRows(CARD_TONE.INFO, theme, 60, partsAt(theme)));
651
+ const float = withStyle(CARD_STYLE.FLOAT, () => floatRows(CARD_TONE.INFO, theme, 60, partsAt(theme)));
652
+ assert.equal(contentOf(float), contentOf(neon), 'same heading, same body, same elapsed time');
653
+ assert.match(stripAnsi(neon[0]), /^╭─ ✿ Gentle AI/);
654
+ assert.match(stripAnsi(float[1]), /^ ▎ ✿ Gentle AI/);
655
+ assert.equal(neon.some((row) => row.includes('▎')), false, 'the neon style draws no rail');
656
+ assert.equal(float.some((row) => /[╭╮╰╯─│]/.test(row)), false, 'the float style draws no box');
657
+ assert.equal(float.length, neon.length + 2, 'float adds its two padding rows, and nothing else');
658
+ });
659
+
660
+ test('the style decision is read once per render: the slot wins over the document, live', () => {
661
+ const theme = paintTheme();
662
+ const render = () => floatRows(CARD_TONE.INFO, theme, 40, partsAt(theme, { ...SHORT_CARD, tone: CARD_TONE.INFO }));
663
+
664
+ writeStyleDocument({ schema: CARD_STYLE_SCHEMA, style: CARD_STYLE.FLOAT });
665
+ assert.equal(cardStyle(), CARD_STYLE.FLOAT, 'the document answers when no host published a slot');
666
+ assert.match(stripAnsi(render()[0]), /▎/, 'the document says float: the rail');
667
+
668
+ useStyle(CARD_STYLE.NEON);
669
+ try {
670
+ assert.equal(cardStyle(), CARD_STYLE.NEON);
671
+ const neon = render();
672
+ assert.match(stripAnsi(neon[0]), /^╭─ /, 'the live slot wins over the float document');
673
+ assert.equal(neon.some((row) => row.includes('▎')), false);
674
+ } finally {
675
+ useStyle(undefined);
676
+ }
677
+ });
678
+
679
+ test('a malformed or missing document renders float, and a theme without the role renders neon', () => {
680
+ const theme = paintTheme();
681
+ const render = () => floatRows(CARD_TONE.INFO, theme, 40, partsAt(theme, { ...SHORT_CARD, tone: CARD_TONE.INFO }));
682
+
683
+ writeStyleDocument('{"schema":"gentle-pi.card-style/v1","style":"neon","extra":true}');
684
+ assert.equal(cardStyle(), CARD_STYLE.FLOAT, 'an extra key is not the document: float');
685
+ assert.match(stripAnsi(render()[0]), /▎/);
686
+
687
+ writeStyleDocument('not json at all');
688
+ assert.equal(cardStyle(), CARD_STYLE.FLOAT);
689
+ assert.match(stripAnsi(render()[0]), /▎/);
690
+
691
+ removeStyleDocument();
692
+ assert.equal(cardStyle(), CARD_STYLE.FLOAT, 'no document at all is float, the default');
693
+ assert.match(stripAnsi(render()[0]), /▎/);
694
+
695
+ // A theme that cannot paint the background (no `bg` at all) keeps the neon
696
+ // outline instead of a broken float card.
697
+ const plain = withStyle(CARD_STYLE.FLOAT, () => floatRows(CARD_TONE.INFO, plainTheme, 40, partsAt(plainTheme, { ...SHORT_CARD, tone: CARD_TONE.INFO })));
698
+ assert.match(stripAnsi(plain[0]), /^╭─ /, 'no background role: the neon frame');
699
+
700
+ // So does a `bg` that answers without the reset the float card needs to close
701
+ // its paint.
702
+ const hostile = { fg: (_role, value) => value, bg: () => 'not a background' };
703
+ const fallback = withStyle(CARD_STYLE.FLOAT, () => floatRows(CARD_TONE.INFO, hostile, 40, partsAt(hostile, { ...SHORT_CARD, tone: CARD_TONE.INFO })));
704
+ assert.match(stripAnsi(fallback[0]), /^╭─ /);
705
+
706
+ const throwing = { fg: (_role, value) => value, bg: () => { throw new Error('no such role'); } };
707
+ const caught = withStyle(CARD_STYLE.FLOAT, () => floatRows(CARD_TONE.INFO, throwing, 40, partsAt(throwing, { ...SHORT_CARD, tone: CARD_TONE.INFO })));
708
+ assert.match(stripAnsi(caught[0]), /^╭─ /, 'a hostile theme never breaks the card');
709
+ });
710
+
711
+ test('too narrow for float, the neon outline answers instead of a broken rail', () => {
712
+ const theme = paintTheme();
713
+ const render = (width) => withStyle(CARD_STYLE.FLOAT, () => floatRows(CARD_TONE.INFO, theme, width, partsAt(theme, { ...SHORT_CARD, tone: CARD_TONE.INFO })));
714
+ assert.match(stripAnsi(render(10)[0]), /▎/, 'ten columns is the narrowest float card');
715
+ const narrow = render(9);
716
+ assert.match(stripAnsi(narrow[0]), /^╭/, 'nine columns is the neon frame');
717
+ assert.equal(narrow.some((row) => row.includes('\x1b')), false, 'and no background is painted there');
718
+ assert.deepEqual(render(0).filter((row) => row !== ''), [], 'no width draws no content');
719
+ });
720
+
721
+ // ---- the card's one click area ----
722
+
723
+ // The installed Pi build delivers a click only to the component that CLAIMED the
724
+ // press (pi-tui tui-alt-screen.js records `mousePressTarget` from the press
725
+ // dispatch and retargets the synthesized `click` to it), so a card claims the
726
+ // cells it wants and nothing else. The whole drawn card is that area, and the
727
+ // click calls the card's own callback — the substrate decides no expansion of its
728
+ // own, so a card that flips only itself passes a callback that moves only itself.
729
+ const ROWS = ['abcdef', 'ghijkl'];
730
+
731
+ function mouseEvent(patch) {
732
+ return { type: 'click', button: 'left', x: 0, y: 0, width: 6, height: 2, screenX: 0, screenY: 0, shift: false, alt: false, ctrl: false, ...patch };
733
+ }
734
+
735
+ function countingToggle() {
736
+ const toggle = () => {
737
+ toggle.calls += 1;
738
+ };
739
+ toggle.calls = 0;
740
+ return toggle;
741
+ }
742
+
743
+ test('a left press claims the card so the click that follows can toggle it', () => {
744
+ const toggle = countingToggle();
745
+ assert.deepEqual(cardMouseEvent(mouseEvent({ type: 'press', x: 3, y: 0 }), ROWS, toggle), { handled: true, render: false }, 'the press claims the gesture without repainting the row it measured');
746
+ assert.equal(toggle.calls, 0, 'a press alone never toggles');
747
+ assert.deepEqual(cardMouseEvent(mouseEvent({ type: 'click', x: 3, y: 0 }), ROWS, toggle), { handled: true }, 'the retargeted click is handled');
748
+ assert.equal(toggle.calls, 1, 'the click on the heading toggles once');
749
+ });
750
+
751
+ test('every cell of the drawn card is the click area, not only the hint', () => {
752
+ const toggle = countingToggle();
753
+ for (let y = 0; y < ROWS.length; y += 1) {
754
+ for (const x of [0, 3, 5]) {
755
+ assert.deepEqual(cardMouseEvent(mouseEvent({ x, y }), ROWS, toggle), { handled: true }, `cell ${x},${y} is on the card`);
756
+ }
757
+ }
758
+ assert.equal(toggle.calls, ROWS.length * 3, 'each click toggled exactly once');
759
+ });
760
+
761
+ test('nothing outside the card and no other gesture is claimed', () => {
762
+ const toggle = countingToggle();
763
+ assert.equal(cardMouseEvent(mouseEvent({ y: ROWS.length }), ROWS, toggle), undefined, 'a row below the card belongs to the host');
764
+ assert.equal(cardMouseEvent(mouseEvent({ y: -1 }), ROWS, toggle), undefined, 'a row above the card belongs to the host');
765
+ assert.equal(cardMouseEvent(mouseEvent({ x: 6 }), ROWS, toggle), undefined, 'a column right of the card belongs to the host');
766
+ assert.equal(cardMouseEvent(mouseEvent({ x: -1 }), ROWS, toggle), undefined, 'a column left of the card belongs to the host');
767
+ assert.equal(cardMouseEvent(mouseEvent({ button: 'right' }), ROWS, toggle), undefined, 'the right button is the host\'s paste');
768
+ assert.equal(cardMouseEvent(mouseEvent({ button: 'middle' }), ROWS, toggle), undefined);
769
+ for (const type of ['move', 'drag', 'release', 'wheel']) {
770
+ assert.equal(cardMouseEvent(mouseEvent({ type }), ROWS, toggle), undefined, `a ${type} is not a click`);
771
+ assert.equal(cardMouseEvent(mouseEvent({ type: 'press' }), ROWS, toggle).handled, true, `a press is still claimed before a ${type}`);
772
+ }
773
+ assert.equal(cardMouseEvent(mouseEvent({ x: 'one' }), ROWS, toggle), undefined, 'a cell that is not a number is not a hit');
774
+ assert.equal(cardMouseEvent(undefined, ROWS, toggle), undefined, 'no event, nothing to claim');
775
+ assert.equal(cardMouseEvent(mouseEvent({}), [], toggle), undefined, 'nothing drawn, nothing claimed');
776
+ assert.equal(cardMouseEvent(mouseEvent({ width: 0 }), ROWS, toggle), undefined, 'a zero-width card has no cell');
777
+ assert.equal(toggle.calls, 0, 'none of the above toggled anything');
778
+ });
779
+
780
+ test('a hostile toggle never breaks the card or the transcript', () => {
781
+ const boom = () => {
782
+ throw new Error('host callback failed');
783
+ };
784
+ assert.deepEqual(cardMouseEvent(mouseEvent({}), ROWS, boom), { handled: true }, 'the click stays handled even when the toggle throws');
785
+ });
786
+
787
+ test('the card source writes no colour and no raw escape literal', () => {
788
+ for (const file of ['shell-card.js', 'worktree-cards.js', 'card-style.js']) {
789
+ const source = readFileSync(join(__dirname, '..', 'lib', file), 'utf8');
790
+ assert.doesNotMatch(source, /#[0-9a-fA-F]{3,8}\b/, `${file} names no hex colour`);
791
+ assert.doesNotMatch(source, /\b(?:rgb|rgba|hsl|hsla)\(/, `${file} composes no colour function`);
792
+ assert.equal(source.includes('\x1b'), false, `${file} holds no raw escape character`);
793
+ assert.doesNotMatch(source, /\\x1b|\\u001b/, `${file} holds no escape sequence literal`);
794
+ }
795
+ });
796
+
797
+ test('the tone to background table has exactly one owner in lib/', () => {
798
+ // S5/S6: the visible cards (/warp included) name a tone and nothing else. The
799
+ // role a tone paints behind a float card is decided in `shell-card.js`, once, so
800
+ // no card can drift into its own palette.
801
+ //
802
+ // `file-card.js` is the one exception, and for a different job: it names the HOST's
803
+ // own three box roles (`toolPendingBg`, `toolErrorBg`, `toolSuccessBg`) only to
804
+ // reproduce the box the host itself draws around a row this card hands back (a
805
+ // `registerToolRenderer` resolver runs per tool name, so its `renderShell: 'self'`
806
+ // would otherwise strip the host's box from every forwarded read/write row). Every
807
+ // tone role `file-card.js` DRAWS still comes from here.
808
+ const lib = join(__dirname, '..', 'lib');
809
+ const source = (file) => readFileSync(join(lib, file), 'utf8');
810
+ const roles = /tool(?:Success|Pending|Error)Bg/;
811
+ const owners = readdirSync(lib)
812
+ .filter((file) => file.endsWith('.js'))
813
+ .filter((file) => roles.test(source(file)));
814
+ // A THIRD module naming one of these roles is a second palette.
815
+ assert.deepEqual(owners, ['file-card.js', 'shell-card.js']);
816
+
817
+ // The host box names each of the host's roles exactly once IN CODE, inside its own
818
+ // table: a fourth background role, a copy of ours, or a second table would all
819
+ // break it. Prose is not a palette, so comments are stripped first.
820
+ const card = source('file-card.js')
821
+ .replace(/\/\*[\s\S]*?\*\//g, '')
822
+ .replace(/^\s*\/\/.*$/gm, '');
823
+ const named = [...card.matchAll(/\btool(?:Success|Pending|Error)Bg\b/g)].map((match) => match[0]).sort();
824
+ assert.deepEqual(named, ['toolErrorBg', 'toolPendingBg', 'toolSuccessBg'], 'file-card.js names the host box roles and no other');
825
+ assert.match(
826
+ card,
827
+ /const HOST_BOX = Object\.freeze\(\{[\s\S]*?PENDING: 'toolPendingBg',[\s\S]*?ERROR: 'toolErrorBg',[\s\S]*?SUCCESS: 'toolSuccessBg',?[\s\S]*?\}\);/,
828
+ 'the roles belong to the host box table, keyed by the host\'s own states',
829
+ );
830
+ // And no tone is mapped to a background role there: that would be a tone table of
831
+ // its own, which is exactly what this assertion protects.
832
+ assert.doesNotMatch(card, /(?:CARD_TONE\.\w+|['"]?(?:info|success|warning|error)['"]?)\s*:\s*['"]tool\w+Bg['"]/, 'file-card.js owns no tone -> background table');
833
+ assert.doesNotMatch(card, /['"]tool\w+Bg['"]\s*:\s*(?:CARD_TONE|[A-Z_]{2,})/, 'no background role is a key of a table of its own');
834
+ });