pi-odd-worktree 2.1.0 → 3.0.1

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 -319
  2. package/extensions/odd-worktree-tools.ts +4182 -2539
  3. package/lib/bash-activity.js +1166 -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 +1421 -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 +323 -15
  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 -712
  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 +1420 -0
  75. package/tools/bash-design.test.js +1093 -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 +613 -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 +1889 -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 +417 -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 +1517 -67
  121. package/tools/issues-open-guard.test.js +1096 -0
  122. package/tools/issues-section.test.js +4235 -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 +2565 -309
  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 +419 -199
  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,825 @@
1
+ 'use strict';
2
+ // The drawing substrate of the Gentle worktree cards, in the two styles Gentle
3
+ // Shell offers: the rounded frame (`neon`) and the rail over a painted band
4
+ // (`float`).
5
+ //
6
+ // Ported from `lib/shell-card.ts` of gentle-shell (its suite is
7
+ // tests/shell-card.test.ts): the geometry, the chrome tables, the tone roles and
8
+ // the collapsed/expanded heading behaviour, because this package's two worktree
9
+ // tools draw their result cards with it (spec S5).
10
+ //
11
+ // What the style decides, and what it never decides: `floatRows` reads the style
12
+ // ONCE per render (lib/card-style.js) and draws the whole card in that one style,
13
+ // so no card is ever half of each. Content, order, truncation, the collapsed
14
+ // preview and the right-aligned elapsed time are the same text in both; only the
15
+ // chrome differs (the frame, the rail, the two padding rows and the tone
16
+ // background). `neon` keeps the rounded `╭ ╮ ╰ ╯ │` frame; `float` drops the box
17
+ // for a `▎` rail, pads every row to the full width and paints the tone
18
+ // background behind it, inside a transparent one-column margin on both sides.
19
+ //
20
+ // Colour is a THEME ROLE, never a colour, and the roles are the source's own
21
+ // tables: the frame (neon and float alike) paints `FRAME_ROLE[tone]`, the heading
22
+ // label paints `TITLE_ROLE[tone]` — its own tone, or the accent for INFO, whose
23
+ // plain border cannot carry it — and a card body is painted in `BODY_ROLE`. A card
24
+ // with nothing left to report may also name the role of its WHOLE closed box
25
+ // (`railRole`), which is how a labelled card's box reads as part of its label; a
26
+ // tone that owns the box keeps its own frame role, so a running or failed call is
27
+ // never painted in an identity colour (`TONE_OWNS_BOX`). So a call's state is
28
+ // readable from every cell of its card, both styles agree, and no hex value and no
29
+ // raw escape sequence is written down here.
30
+ //
31
+ // PAINT LAST is the substrate's ordering rule, and it is why the rows below are
32
+ // composed from PLAIN text: `cardBodyRows` wraps and clips the caller's plain
33
+ // rows, `cardLine` clips and pads one plain row, and only then is the content
34
+ // wrapped in its role. Nothing painted here is ever measured, truncated or padded
35
+ // again — so a helper that counts escape characters as columns (this package's own
36
+ // `/warp` fallback does) can neither cut into a sequence nor lose a character, and
37
+ // the drawn text is the same whatever the injected helpers are.
38
+ //
39
+ // Too narrow for float (under ten columns) or a theme with no `bg` for the tone
40
+ // role ⇒ the neon outline is drawn instead of a broken float card, so a card
41
+ // always renders whole.
42
+ //
43
+ // The card object this module draws has the source's shape, plus the one override
44
+ // the source's card holds, and two OPTIONAL refinements no existing card names (so
45
+ // every existing card is drawn byte for byte as before):
46
+ // { title, subtitle?, subtitleSegments?, labelBold?, body: string[], tone,
47
+ // glyph?, titleRole?, railRole? }
48
+ //
49
+ // `subtitleSegments` is the detail as the segments it is made of — `[{ text, role }]`,
50
+ // where a segment that names no role stays unpainted — so a card can say `read` in the
51
+ // theme's plain text, the separator in `muted`, a path in `accent` and a line range in
52
+ // `warning` on one row. The segments are still MEASURED as their plain text and
53
+ // painted afterwards, one segment at a time. `labelBold` bolds the label (never the
54
+ // glyph) inside the card's `titleRole`.
55
+ //
56
+ // `cardPaintedRows` is the one row shape for text this module must NOT re-paint: rows
57
+ // a caller already painted (Pi's Markdown renderer hands back exactly that) are
58
+ // measured with the injected ANSI-aware metrics, clipped, padded and framed, and each
59
+ // one keeps its own paint. No existing caller uses it, so the plain path every other
60
+ // card takes is untouched.
61
+ //
62
+ // `railRole` is the identity role the card's closed box is painted in, and it is
63
+ // honoured exactly as the source's `frameRole` does: by `floatRows` for one whole
64
+ // render, and by the heading helpers from the card's own field. A card that names
65
+ // none keeps the tone's frame role, so every existing card is drawn byte for byte
66
+ // as before.
67
+ //
68
+ // Colour arrives as an injected theme: `fg(role, text)` returns a string, and
69
+ // `bg(role, text)` — optional — paints the float background. No ANSI escape is
70
+ // composed here except the background reset the injected `bg` itself hands back,
71
+ // and no role name is invented: the roles are the source's `border`, `accent`,
72
+ // `success`, `warning`, `error`, `text`, `dim`, `muted` and the tone background
73
+ // roles `toolSuccessBg`, `toolPendingBg` and `toolErrorBg`.
74
+ //
75
+ // Text measurement is injected too, because this package has no install step and
76
+ // no node_modules: a `metrics` object is the REQUIRED last argument of every
77
+ // function that measures or clips text, and it is the only way this module does
78
+ // so. Its shape, taken from the host TUI helpers it stands in for:
79
+ // {
80
+ // visibleWidth(text) -> display columns of `text`
81
+ // truncateToWidth(text, width, ellipsis) -> `text` clipped to `width` columns
82
+ // wrapTextWithAnsi(text, width) -> `text` wrapped into rows of at
83
+ // most `width` columns
84
+ // }
85
+ // Roles are strings; tones come from `CARD_TONE`.
86
+
87
+ const { CARD_STYLE, cardStyle } = require('./card-style.js');
88
+
89
+ const CARD_TONE = {
90
+ INFO: 'info',
91
+ SUCCESS: 'success',
92
+ WARNING: 'warning',
93
+ ERROR: 'error',
94
+ };
95
+
96
+ const CARD_GLYPH = '✿';
97
+ // The frame and the label paint the same role for every tone except INFO, whose
98
+ // rounded frame stays in the theme's plain border role while its label carries
99
+ // the accent role — the rose look every informational card (sidebar, review
100
+ // preflight, a quiet Agents widget, ...) uses.
101
+ const FRAME_ROLE = {
102
+ [CARD_TONE.INFO]: 'border',
103
+ [CARD_TONE.SUCCESS]: 'success',
104
+ [CARD_TONE.WARNING]: 'warning',
105
+ [CARD_TONE.ERROR]: 'error',
106
+ };
107
+ // A card's label carries its tone; a card may still name its own label role
108
+ // (`titleRole`), and a card with nothing to report may name the role of its whole
109
+ // box (`railRole`). The frame keeps painting the tone whenever the tone owns the box.
110
+ const TITLE_ROLE = {
111
+ [CARD_TONE.INFO]: 'accent',
112
+ [CARD_TONE.SUCCESS]: 'success',
113
+ [CARD_TONE.WARNING]: 'warning',
114
+ [CARD_TONE.ERROR]: 'error',
115
+ };
116
+ // Which tones own the whole box instead of letting an idle card wear its own
117
+ // identity there (the source's own `TONE_OWNS_BOX`): an active state speaks for the
118
+ // call — amber while it runs, red once it failed — so only a card with nothing left
119
+ // to report paints its named identity around itself.
120
+ const TONE_OWNS_BOX = {
121
+ [CARD_TONE.INFO]: false,
122
+ [CARD_TONE.SUCCESS]: false,
123
+ [CARD_TONE.WARNING]: true,
124
+ [CARD_TONE.ERROR]: true,
125
+ };
126
+ const HINT_ROLE = 'dim';
127
+ const SUBTITLE_ROLE = 'muted';
128
+ // The card body's own role: the theme's plain text, so a body row never borrows
129
+ // the chrome's tone. `cardLine` paints it — after the row has been clipped and
130
+ // padded, as the last step, so no measurement ever sees the escape sequence.
131
+ const BODY_ROLE = 'text';
132
+ const SEPARATOR = '·';
133
+ const FRAME_COLUMNS = 4;
134
+ // Columns a heading row keeps for the call itself before its detail (or the key
135
+ // hint) is asked to give way to the next row.
136
+ const MIN_HEADING_COLUMNS = 12;
137
+
138
+ // The characters that draw the card around its content, one table per style.
139
+ // Rows are built from these by position, so content that happens to contain
140
+ // box-drawing characters is never rewritten. `▎ ` is one cell narrower than
141
+ // `╭─ `: the spare cell moves to the right end so the heading glyph starts in
142
+ // the same column as the body text.
143
+ const OUTLINE_CHROME = {
144
+ topLeft: '╭',
145
+ topLead: '─ ',
146
+ topRight: '╮',
147
+ rule: '─',
148
+ side: '│',
149
+ rail: '│',
150
+ bottomLeft: '╰',
151
+ bottomRight: '╯',
152
+ };
153
+ const FLOAT_CHROME = {
154
+ topLeft: '▎',
155
+ topLead: ' ',
156
+ topRight: ' ',
157
+ rule: ' ',
158
+ side: '▎',
159
+ rail: ' ',
160
+ bottomLeft: '▎',
161
+ bottomRight: ' ',
162
+ };
163
+
164
+ // The chrome in force for the draw in progress. Swapped only by `withChrome`,
165
+ // which `floatRows` owns, so a card is drawn entirely in one style.
166
+ let chrome = OUTLINE_CHROME;
167
+
168
+ function withChrome(next, run) {
169
+ const previous = chrome;
170
+ chrome = next;
171
+ try {
172
+ return run();
173
+ } finally {
174
+ chrome = previous;
175
+ }
176
+ }
177
+
178
+ function rule(length) {
179
+ return chrome.rule.repeat(Math.max(0, length));
180
+ }
181
+
182
+ // The identity role a card's closed box is painted in, when the card names one. The
183
+ // frame runs around every row, so it is a scope around a whole card rather than a
184
+ // parameter each row helper would have to carry: `floatRows` opens it for one
185
+ // render, and the heading helpers open it from the card's own `railRole`.
186
+ let railRole;
187
+
188
+ function withRailRole(role, run) {
189
+ const previous = railRole;
190
+ railRole = role;
191
+ try {
192
+ return run();
193
+ } finally {
194
+ railRole = previous;
195
+ }
196
+ }
197
+
198
+ /** Opens the scope a card's own `railRole` asks for, when it asks for one. */
199
+ function withCardRail(card, run) {
200
+ return card.railRole === undefined ? run() : withRailRole(card.railRole, run);
201
+ }
202
+
203
+ /**
204
+ * The one role every closed-frame cell is painted in: both top corners, the lead and
205
+ * rule of the top, the left side, the right rail, the bottom rule and both bottom
206
+ * corners. A tone that owns the box keeps its own frame role; otherwise an idle card
207
+ * wears the identity role it names, falling back to the tone. One role per card, so
208
+ * no row shows two colours side by side.
209
+ */
210
+ function frameRole(tone) {
211
+ return TONE_OWNS_BOX[tone] ? FRAME_ROLE[tone] : railRole ?? FRAME_ROLE[tone];
212
+ }
213
+
214
+ // The chrome paints the tone in BOTH styles: the source's `frame()` takes no
215
+ // exception for float, so the rail and the neon rule carry the same state — or the
216
+ // same identity role, when the card named one.
217
+ function frame(theme, tone, painted) {
218
+ return theme.fg(frameRole(tone), painted);
219
+ }
220
+
221
+ function titleRole(card) {
222
+ return card.titleRole ?? TITLE_ROLE[card.tone];
223
+ }
224
+
225
+ /** `text` bolded through the theme, or the text itself when the theme carries no such attribute. */
226
+ function boldText(text, theme) {
227
+ try {
228
+ if (theme !== null && typeof theme === 'object' && typeof theme.bold === 'function') {
229
+ const bold = theme.bold(text);
230
+ if (typeof bold === 'string') return bold;
231
+ }
232
+ } catch {
233
+ // A theme without a bold attribute keeps the text it was given.
234
+ }
235
+ return text;
236
+ }
237
+
238
+ /**
239
+ * The one paint step for card content: text that has ALREADY been measured,
240
+ * clipped and padded is wrapped in `role` here, and the result is never measured
241
+ * again. An empty string stays empty, so a paragraph break keeps its blank row
242
+ * and no role is painted onto nothing.
243
+ */
244
+ function painted(text, role, theme) {
245
+ return text === '' ? text : theme.fg(role, text);
246
+ }
247
+
248
+ /**
249
+ * The detail as the segments it is made of. A card that states none is one muted
250
+ * segment, which is exactly the single detail every card has always shown.
251
+ */
252
+ function subtitleSegments(card) {
253
+ const listed = Array.isArray(card.subtitleSegments) ? card.subtitleSegments : undefined;
254
+ if (listed === undefined) return [{ text: subtitlePlain(card), role: SUBTITLE_ROLE }];
255
+ return listed.map((segment) => {
256
+ const value = segment !== null && typeof segment === 'object' ? segment : {};
257
+ return {
258
+ text: typeof value.text === 'string' ? value.text : '',
259
+ role: typeof value.role === 'string' ? value.role : undefined,
260
+ };
261
+ });
262
+ }
263
+
264
+ /** The detail as PLAIN text: its segments joined, or the one string the card states. */
265
+ function subtitlePlain(card) {
266
+ if (!Array.isArray(card.subtitleSegments)) return typeof card.subtitle === 'string' ? card.subtitle : '';
267
+ return subtitleSegments(card).map((segment) => segment.text).join('');
268
+ }
269
+
270
+ /** The whole detail painted segment by segment: a segment that names no role stays plain. */
271
+ function subtitlePaint(card, theme) {
272
+ return subtitleSegments(card)
273
+ .map((segment) => (segment.role === undefined ? segment.text : painted(segment.text, segment.role, theme)))
274
+ .join('');
275
+ }
276
+
277
+ /**
278
+ * The detail clipped as PLAIN text to `budget` columns and painted afterwards, one
279
+ * segment at a time, so a role never covers a column its own text does not own. When
280
+ * `ellipsis` is asked for, a detail that does not fit ends in one in the role of the
281
+ * segment it lands on.
282
+ */
283
+ function subtitleClip(card, theme, budget, metrics, ellipsis) {
284
+ const segments = subtitleSegments(card);
285
+ const whole = segments.map((segment) => segment.text).join('');
286
+ const target = Math.max(0, Math.floor(budget));
287
+ const overflows = metrics.visibleWidth(whole) > target;
288
+ // An ellipsis costs one column of the budget, exactly as the one-row clip has always.
289
+ let remaining = ellipsis === true && overflows ? Math.max(0, target - 1) : target;
290
+ const kept = [];
291
+ let used = 0;
292
+ for (const segment of segments) {
293
+ if (remaining === 0) break;
294
+ const shown = metrics.truncateToWidth(segment.text, remaining, '');
295
+ if (shown === '') break;
296
+ kept.push({ text: shown, role: segment.role });
297
+ used += metrics.visibleWidth(shown);
298
+ remaining -= metrics.visibleWidth(shown);
299
+ if (shown !== segment.text) break;
300
+ }
301
+ if (ellipsis === true && overflows && target > used) {
302
+ const tail = kept.at(-1);
303
+ if (tail === undefined) kept.push({ text: '…' });
304
+ else tail.text = `${tail.text}…`;
305
+ used += 1;
306
+ }
307
+ const plain = kept.map((segment) => segment.text).join('');
308
+ return {
309
+ plain,
310
+ segments: kept,
311
+ painted: kept.map((segment) => (segment.role === undefined ? segment.text : painted(segment.text, segment.role, theme))).join(''),
312
+ width: used,
313
+ };
314
+ }
315
+
316
+ /** The plain width of the whole heading: the label, and the detail when it has one. */
317
+ function titleWidth(card, metrics) {
318
+ const head = `${card.glyph ?? CARD_GLYPH} ${card.title}`;
319
+ const detail = subtitlePlain(card);
320
+ return metrics.visibleWidth(head) + (detail !== '' ? metrics.visibleWidth(detail) + 3 : 0);
321
+ }
322
+
323
+ /**
324
+ * The heading, painted: measured and clipped as PLAIN text to `width` columns —
325
+ * the label first, then the detail's separator and the detail — with each
326
+ * surviving segment painted afterwards. A heading too wide for the rule is
327
+ * therefore cut on a column, never inside an escape sequence.
328
+ */
329
+ function titleText(card, theme, width, metrics) {
330
+ const head = `${card.glyph ?? CARD_GLYPH} ${card.title}`;
331
+ const headWidth = metrics.visibleWidth(head);
332
+ const paintHead = (plain) => paintedHead(card, theme, plain, head);
333
+ if (subtitlePlain(card) === '') {
334
+ const shown = headWidth <= width ? head : metrics.truncateToWidth(head, width, '');
335
+ return { styled: paintHead(shown), width: shown === head ? headWidth : metrics.visibleWidth(shown) };
336
+ }
337
+ const detailWidth = metrics.visibleWidth(subtitlePlain(card));
338
+ const fullWidth = headWidth + 3 + detailWidth;
339
+ if (fullWidth <= width) {
340
+ return {
341
+ styled: `${paintHead(head)} ${painted(SEPARATOR, SUBTITLE_ROLE, theme)} ${subtitlePaint(card, theme)}`,
342
+ width: fullWidth,
343
+ };
344
+ }
345
+ // Too wide: the plain prefix keeps the columns it can, exactly as the whole
346
+ // painted heading used to be clipped, and each segment is painted afterwards.
347
+ const shownHead = headWidth <= width ? head : metrics.truncateToWidth(head, width, '');
348
+ const shownHeadWidth = shownHead === head ? headWidth : metrics.visibleWidth(shownHead);
349
+ let remaining = Math.max(0, width - shownHeadWidth);
350
+ const separator = remaining === 0 ? '' : metrics.truncateToWidth(` ${SEPARATOR} `, remaining, '');
351
+ remaining = Math.max(0, remaining - metrics.visibleWidth(separator));
352
+ const detail = remaining === 0 ? { painted: '', width: 0 } : subtitleClip(card, theme, remaining, metrics, false);
353
+ return {
354
+ styled: `${paintHead(shownHead)}${painted(separator, SUBTITLE_ROLE, theme)}${detail.painted}`,
355
+ width: shownHeadWidth + metrics.visibleWidth(separator) + detail.width,
356
+ };
357
+ }
358
+
359
+ /**
360
+ * The head painted: one role for the glyph and the label, and — only when the card
361
+ * asks for it — the label bolded inside that role. A head clipped on the rule keeps
362
+ * whatever of each survives, painted once.
363
+ */
364
+ function paintedHead(card, theme, shown, head) {
365
+ const role = titleRole(card);
366
+ if (card.labelBold !== true) return painted(shown, role, theme);
367
+ const glyph = card.glyph ?? CARD_GLYPH;
368
+ if (shown === head) return `${painted(glyph, role, theme)} ${painted(boldText(card.title, theme), role, theme)}`;
369
+ const shownGlyph = shown.slice(0, Math.min(shown.length, glyph.length));
370
+ const rest = shown.slice(shownGlyph.length);
371
+ return `${painted(shownGlyph, role, theme)}${rest === '' ? '' : painted(boldText(rest, theme), role, theme)}`;
372
+ }
373
+
374
+ /** The top rule: the glyph and title, the detail, the filling rule and an optional right-aligned hint. */
375
+ function cardTop(card, theme, width, hint, metrics) {
376
+ return withCardRail(card, () => cardTopAt(card, theme, Math.max(0, Math.floor(width)), hint, metrics));
377
+ }
378
+
379
+ function cardTopAt(card, theme, targetWidth, hint, metrics) {
380
+ if (targetWidth === 0) return '';
381
+ if (targetWidth < 5) {
382
+ const left = frame(theme, card.tone, OUTLINE_CHROME.topLeft);
383
+ if (targetWidth === 1) return left;
384
+ return left + frame(theme, card.tone, `${rule(targetWidth - 2)}${chrome.topRight}`);
385
+ }
386
+
387
+ const fullHintWidth = hint ? metrics.visibleWidth(hint) + 2 : 0;
388
+ const shownHint = hint && titleWidth(card, metrics) + 5 + fullHintWidth <= targetWidth ? hint : undefined;
389
+ const hintWidth = shownHint ? fullHintWidth : 0;
390
+ // The heading is composed at the columns the hint leaves it: plain text in, a
391
+ // clipped plain heading and its painted form out. Its width is already known.
392
+ const title = titleText(card, theme, Math.max(0, targetWidth - 5 - hintWidth), metrics);
393
+ const fill = rule(targetWidth - title.width - 5 - hintWidth);
394
+ const tail = shownHint ? ` ${theme.fg(HINT_ROLE, shownHint)} ` : '';
395
+ return frame(theme, card.tone, chrome.topLeft) + frame(theme, card.tone, chrome.topLead) + title.styled + frame(theme, card.tone, ` ${fill}`) + tail + frame(theme, card.tone, chrome.topRight);
396
+ }
397
+
398
+ /**
399
+ * Whether a heading row keeps its key hint at this width. Callers that compose a
400
+ * subtitle from optional facts use it to shed the least important chip instead of
401
+ * silently losing the affordance.
402
+ */
403
+ function headingFits(card, hint, width, metrics) {
404
+ const targetWidth = Math.max(0, Math.floor(width));
405
+ const detail = subtitlePlain(card);
406
+ const head = metrics.visibleWidth(`${card.glyph ?? CARD_GLYPH} ${card.title}`) + (detail !== '' ? metrics.visibleWidth(detail) + 3 : 0);
407
+ return head + 5 + (hint ? metrics.visibleWidth(hint) + 2 : 0) <= targetWidth;
408
+ }
409
+
410
+ /**
411
+ * One body row: the sides, the padded content and the rail, clipped with a literal
412
+ * ellipsis. `text` is PLAIN: it is measured, clipped and padded first, and only
413
+ * then painted in `role` (the body role unless the row owns a role of its own, as
414
+ * the running row does). Nothing painted is measured, so the clip cannot cut into
415
+ * an escape sequence and the visible text never depends on how clever the
416
+ * injected helpers are.
417
+ */
418
+ function cardLine(text, tone, theme, width, metrics, role = BODY_ROLE) {
419
+ const targetWidth = Math.max(0, Math.floor(width));
420
+ if (targetWidth === 0) return '';
421
+ const left = frame(theme, tone, chrome.side);
422
+ if (targetWidth === 1) return left;
423
+ if (targetWidth === 2) return left + frame(theme, tone, OUTLINE_CHROME.side);
424
+ if (targetWidth === 3) return `${left} ${frame(theme, tone, OUTLINE_CHROME.side)}`;
425
+
426
+ const innerWidth = targetWidth - FRAME_COLUMNS;
427
+ const clipped = innerWidth === 0 ? '' : metrics.truncateToWidth(text, innerWidth, '…');
428
+ const padding = ' '.repeat(Math.max(0, innerWidth - metrics.visibleWidth(clipped)));
429
+ return `${left} ${painted(clipped, role, theme)}${padding} ${frame(theme, tone, chrome.rail)}`;
430
+ }
431
+
432
+ /**
433
+ * One body row whose text is ALREADY painted: the sides, the clipped content and the
434
+ * rail, with no role applied on top. The width is taken with the injected ANSI-aware
435
+ * metrics, so the clip never cuts inside a sequence and the padding never counts one;
436
+ * the frame, the padding and the rail stay this module's.
437
+ *
438
+ * This is the one shape for content another renderer painted (Pi's Markdown hands back
439
+ * exactly that), and it is additive: the plain `cardLine` path every other card takes
440
+ * is unchanged.
441
+ */
442
+ function cardPaintedLine(text, tone, theme, width, metrics) {
443
+ const targetWidth = Math.max(0, Math.floor(width));
444
+ if (targetWidth === 0) return '';
445
+ const left = frame(theme, tone, chrome.side);
446
+ if (targetWidth === 1) return left;
447
+ if (targetWidth === 2) return left + frame(theme, tone, OUTLINE_CHROME.side);
448
+ if (targetWidth === 3) return `${left} ${frame(theme, tone, OUTLINE_CHROME.side)}`;
449
+
450
+ const innerWidth = targetWidth - FRAME_COLUMNS;
451
+ const clipped = innerWidth === 0 ? '' : metrics.truncateToWidth(text, innerWidth, '…');
452
+ const padding = ' '.repeat(Math.max(0, innerWidth - metrics.visibleWidth(clipped)));
453
+ return `${left} ${clipped}${padding} ${frame(theme, tone, chrome.rail)}`;
454
+ }
455
+
456
+ /**
457
+ * Body rows for the frame from rows that are ALREADY painted — Pi's Markdown output —
458
+ * wrapped with the ANSI-aware seam, capped by the preview budget unless the card is
459
+ * expanded, and placed by `cardPaintedLine` without a role of ours over them.
460
+ */
461
+ function cardPaintedRows(rows, tone, theme, width, options, metrics) {
462
+ if (width <= 0) return [];
463
+ const list = Array.isArray(rows) ? rows : [];
464
+ const inner = cardInnerWidth(width);
465
+ const wrapped = list.flatMap((row) => String(row ?? '').split('\n').flatMap((line) => (line === '' ? [''] : metrics.wrapTextWithAnsi(line, inner))));
466
+ const limit = Math.max(0, Math.floor(options?.previewRows ?? 3));
467
+ const shown = options?.expanded ? wrapped : wrapped.slice(0, limit);
468
+ return shown.map((line) => cardPaintedLine(line, tone, theme, width, metrics));
469
+ }
470
+
471
+ /** The closing rule, with its content right-aligned when enough fill columns stay free. */
472
+ function cardBottom(tone, theme, width, content, metrics) {
473
+ const targetWidth = Math.max(0, Math.floor(width));
474
+ if (targetWidth === 0) return '';
475
+ const left = frame(theme, tone, chrome.bottomLeft);
476
+ if (targetWidth === 1) return left;
477
+ if (content === undefined || metrics.visibleWidth(content) === 0) return left + frame(theme, tone, `${rule(targetWidth - 2)}${chrome.bottomRight}`);
478
+ const contentWidth = metrics.visibleWidth(content) + 2;
479
+ // Responsive: the content rides the closing rule only when it fits with a minimum fill.
480
+ if (targetWidth - 2 - contentWidth < 3) return left + frame(theme, tone, `${rule(targetWidth - 2)}${chrome.bottomRight}`);
481
+ return left + frame(theme, tone, `${rule(targetWidth - 2 - contentWidth)} `) + theme.fg(HINT_ROLE, content) + frame(theme, tone, ` ${chrome.bottomRight}`);
482
+ }
483
+
484
+ function cardInnerWidth(width) {
485
+ return Math.max(1, width - FRAME_COLUMNS);
486
+ }
487
+
488
+ /**
489
+ * Body rows for the frame, from the caller's PLAIN rows: wrapped to the inner
490
+ * width, then capped by the preview budget (three rows by default) unless the card
491
+ * is expanded, and each surviving row clipped, padded and painted last by
492
+ * `cardLine` in `options.role` (the body role by default).
493
+ *
494
+ * This is the one body seam both card families use, and it takes plain text for a
495
+ * reason: the wrap and the clip are the measurements, the paint is not, so a
496
+ * caller cannot hand this function a painted row and have it measured twice.
497
+ */
498
+ function cardBodyRows(rows, tone, theme, width, options, metrics) {
499
+ if (width <= 0) return [];
500
+ const role = options.role === undefined ? BODY_ROLE : options.role;
501
+ const wrapped = rows.flatMap((row) => row.split('\n').flatMap((line) => (line === '' ? [''] : metrics.wrapTextWithAnsi(line, cardInnerWidth(width)))));
502
+ const limit = Math.max(0, Math.floor(options.previewRows ?? 3));
503
+ const shown = options.expanded ? wrapped : wrapped.slice(0, limit);
504
+ return shown.map((line) => cardLine(line, tone, theme, width, metrics, role));
505
+ }
506
+
507
+ // ---- the card's one click area ----
508
+ //
509
+ // Click-to-expand, host-driven. The installed Pi build delivers a click only to
510
+ // the component that CLAIMED the press: `tui-alt-screen.js` records
511
+ // `mousePressTarget` from the press dispatch (`if (result) … mousePressTarget =
512
+ // result.target`) and, on release at the same cell, synthesizes a `click`
513
+ // retargeted to that exact component. So the press must be handled or the click
514
+ // never arrives — the host's own `MouseRegion` around a tool card reacts to
515
+ // `click` alone and can never see one on its own.
516
+ //
517
+ // The whole drawn card is the area: `rows` is what `render` returned for the width
518
+ // it was called with, and `Container`/`Box` hand the component an event whose
519
+ // `x`/`y` are local to it and whose `width`/`height` are its own bounds. The hit
520
+ // area therefore follows the real geometry of both styles — the float heading
521
+ // band and its margins, the padded message card, a wrapped heading — instead of a
522
+ // second, drifting calculation. A left press claims the gesture without
523
+ // repainting the row it measured; the click it enables calls the card's own
524
+ // `toggleExpanded` callback, which flips THAT CARD's expansion choice and
525
+ // nothing else. Every other gesture and every cell outside the card stays the
526
+ // host's (text selection, links, right-click paste).
527
+ function cardMouseEvent(event, rows, toggleExpanded) {
528
+ const e = event !== null && typeof event === 'object' ? event : null;
529
+ if (e === null) return undefined;
530
+ if (e.button !== 'left') return undefined;
531
+ if (e.type !== 'press' && e.type !== 'click') return undefined;
532
+ if (typeof e.x !== 'number' || typeof e.y !== 'number') return undefined;
533
+ const width = Number.isFinite(e.width) ? Math.floor(e.width) : 0;
534
+ if (width <= 0) return undefined;
535
+ if (!Array.isArray(rows) || rows.length === 0) return undefined;
536
+ if (!(e.y >= 0 && e.y < rows.length)) return undefined;
537
+ if (!(e.x >= 0 && e.x < width)) return undefined;
538
+ if (e.type === 'press') return { handled: true, render: false };
539
+ try {
540
+ if (typeof toggleExpanded === 'function') toggleExpanded();
541
+ } catch {
542
+ // A hostile host callback never breaks the card or the transcript.
543
+ }
544
+ return { handled: true };
545
+ }
546
+
547
+ // The host draws a tool row as the call component followed, once a result exists,
548
+ // by the result component, which closes the frame. The call cannot see the result,
549
+ // so result renderers mark the row state both share, and a call still waiting for
550
+ // its first result closes its own frame.
551
+ const RESULT_MARK = Symbol.for('gentle-pi.card-result');
552
+ const RUNNING_TEXT = 'running…';
553
+ const RUNNING_ROLE = 'muted';
554
+
555
+ /** Result renderers mark the shared row state: from now on a result component closes the card. */
556
+ function markCardResult(state) {
557
+ if (state !== null && typeof state === 'object') state[RESULT_MARK] = true;
558
+ }
559
+
560
+ /** Whether a call card must close its own frame. Read it at render time: the result component is built after the call. */
561
+ function cardAwaitingResult(context) {
562
+ if (context.isPartial === false) return false;
563
+ const state = context.state;
564
+ return !(state !== null && typeof state === 'object' && state[RESULT_MARK] === true);
565
+ }
566
+
567
+ /** The muted body row of a call card that is still waiting for its result. */
568
+ function cardRunningLine(tone, theme, width, metrics) {
569
+ // Plain text plus its role: the substrate clips the text, then paints it.
570
+ return cardLine(RUNNING_TEXT, tone, theme, width, metrics, RUNNING_ROLE);
571
+ }
572
+
573
+ /**
574
+ * Calls may continue long or multiline headings inside the same frame. A detail
575
+ * that cannot share the top rule without crowding the call (or its key hint)
576
+ * continues on card rows below it, so a long call stays fully visible instead of
577
+ * being truncated.
578
+ */
579
+ function cardTopRows(card, theme, width, hint, metrics) {
580
+ return withCardRail(card, () => cardTopRowsAt(card, theme, width, hint, metrics));
581
+ }
582
+
583
+ function cardTopRowsAt(card, theme, width, hint, metrics) {
584
+ const target = Math.max(0, Math.floor(width));
585
+ if (target === 0) return [];
586
+ if (target < 8) return [cardTop(card, theme, target, hint, metrics)];
587
+ const [first = '', ...rest] = card.title.split('\n');
588
+ // Reserve the hint before wrapping, plus one rule column and enough heading
589
+ // space to retain identity. This policy belongs only to continuing tool tops.
590
+ const lead = metrics.visibleWidth(`${card.glyph ?? CARD_GLYPH} `);
591
+ const hintWidth = hint ? metrics.visibleWidth(hint) + 2 : 0;
592
+ const available = target - 6 - lead;
593
+ if (card.subtitle !== undefined) {
594
+ // Let the detail share the rule only when the whole heading (and the key hint)
595
+ // fits there; otherwise it continues below, where it keeps its width. A
596
+ // multi-line detail keeps its first line on the rule and its other lines below,
597
+ // so a script or heredoc never disappears behind a truncation.
598
+ const [detailFirst = '', ...detailRest] = subtitlePlain(card).split('\n');
599
+ const detailWidth = metrics.visibleWidth(detailFirst) + 3;
600
+ const inline = lead + metrics.visibleWidth(first) + detailWidth + hintWidth + 5 <= target;
601
+ const shownHint = inline ? hint : hint && available - hintWidth >= MIN_HEADING_COLUMNS ? hint : undefined;
602
+ const room = Math.max(1, available - (inline ? detailWidth : 0) - (shownHint ? hintWidth : 0));
603
+ const [head = '', ...overflow] = metrics.wrapTextWithAnsi(first, room);
604
+ // The detail continues in the muted role, and the heading's own overflow in
605
+ // the body role: both are handed to the substrate as PLAIN rows, so the wrap
606
+ // and the clip see text and the paint comes last. When the detail cannot share
607
+ // the rule it leaves the rule ENTIRELY: the segments it is drawn from are
608
+ // dropped with it, so the rule states the identity alone (exactly as a card
609
+ // with no detail does) and the detail follows once, below.
610
+ const detail = inline
611
+ ? detailRest
612
+ : subtitlePlain(card).split('\n').map((line, index) => (index === 0 ? `${SEPARATOR} ${line}` : line));
613
+ // A detail that names a role per segment is painted segment by segment and then
614
+ // placed as ALREADY painted rows, so no role is lost when it moves below the rule.
615
+ const segments = Array.isArray(card.subtitleSegments) && detailRest.length === 0;
616
+ const detailRows = segments && !inline
617
+ ? cardPaintedRows(
618
+ [subtitlePaint({ ...card, subtitleSegments: [{ text: `${SEPARATOR} `, role: SUBTITLE_ROLE }, ...card.subtitleSegments] }, theme)],
619
+ card.tone,
620
+ theme,
621
+ target,
622
+ { expanded: true },
623
+ metrics,
624
+ )
625
+ : cardBodyRows(detail, card.tone, theme, target, { expanded: true, role: SUBTITLE_ROLE }, metrics);
626
+ // The rule states the identity and, only when it shares it, the detail first
627
+ // line; the segments go with the detail they are drawn from.
628
+ const headCard = { ...card, subtitle: inline ? detailFirst : undefined, subtitleSegments: inline ? card.subtitleSegments : undefined, title: head };
629
+ return [
630
+ cardTop(headCard, theme, target, shownHint, metrics),
631
+ ...cardBodyRows([...overflow, ...rest], card.tone, theme, target, { expanded: true }, metrics),
632
+ ...detailRows,
633
+ ];
634
+ }
635
+ const shownHint = hint && available - hintWidth >= MIN_HEADING_COLUMNS ? hint : undefined;
636
+ const room = Math.max(1, available - (shownHint ? hintWidth : 0));
637
+ const [head = '', ...overflow] = metrics.wrapTextWithAnsi(first, room);
638
+ return [
639
+ cardTop({ ...card, title: head }, theme, target, shownHint, metrics),
640
+ ...cardBodyRows([...overflow, ...rest], card.tone, theme, target, { expanded: true }, metrics),
641
+ ];
642
+ }
643
+
644
+ /**
645
+ * A single-row heading: a detail too wide for the rule ends in an ellipsis instead
646
+ * of continuing on the rows below, so a collapsed card stays one line. Expanding
647
+ * the call is what reveals the complete detail.
648
+ */
649
+ function cardTopLine(card, theme, width, hint, detail, metrics) {
650
+ return withCardRail(card, () => cardTopLineAt(card, theme, width, hint, detail, metrics));
651
+ }
652
+
653
+ function cardTopLineAt(card, theme, width, hint, detail, metrics) {
654
+ const target = Math.max(0, Math.floor(width));
655
+ if (target < 8 || (card.subtitle === undefined && detail === undefined)) return cardTop(card, theme, target, hint, metrics);
656
+ const head = metrics.visibleWidth(`${card.glyph ?? CARD_GLYPH} ${card.title}`);
657
+ // The key hint comes first when it fits beside a readable detail; otherwise it
658
+ // yields its columns so the detail keeps an ellipsis instead of vanishing.
659
+ let shownHint = hint;
660
+ let room = target - 5 - (shownHint ? metrics.visibleWidth(shownHint) + 2 : 0) - head - 3;
661
+ if (room < 1 && shownHint !== undefined) {
662
+ shownHint = undefined;
663
+ room = target - 5 - head - 3;
664
+ }
665
+ // A card whose detail names a role per segment is clipped segment by segment: the
666
+ // one-row budget is what its own collapsed detail was measured against, and each
667
+ // surviving segment is painted in the role it names.
668
+ if (Array.isArray(card.subtitleSegments)) {
669
+ const plain = subtitlePlain(card);
670
+ const asked = detail === undefined ? plain : detail(Math.max(1, room));
671
+ const listed = asked === plain ? card.subtitleSegments : [{ text: asked, role: SUBTITLE_ROLE }];
672
+ const clipped = subtitleClip({ subtitleSegments: listed }, theme, Math.max(1, room), metrics, true);
673
+ return cardTop({ ...card, subtitle: clipped.plain, subtitleSegments: clipped.segments }, theme, target, shownHint, metrics);
674
+ }
675
+ // A heading that measures its own collapsed detail takes the room left once the
676
+ // chrome and the key hint have taken theirs, so a script folds into a stated
677
+ // count instead of vanishing behind an ellipsis.
678
+ const subtitle = detail === undefined ? subtitlePlain(card).split('\n').join(' ') : detail(Math.max(1, room));
679
+ const shown = room >= 1 && metrics.visibleWidth(subtitle) > room
680
+ ? `${metrics.truncateToWidth(subtitle, Math.max(1, room - 1), '')}…`
681
+ : subtitle;
682
+ return cardTop({ ...card, subtitle: shown }, theme, target, shownHint, metrics);
683
+ }
684
+
685
+ /** A closing rule with no content: the float style's padding row, and the plain rule. */
686
+ function cardBlank(tone, theme, width) {
687
+ const target = Math.max(0, Math.floor(width));
688
+ if (target === 0) return '';
689
+ const left = frame(theme, tone, chrome.bottomLeft);
690
+ if (target === 1) return left;
691
+ return left + frame(theme, tone, `${rule(target - 2)}${chrome.bottomRight}`);
692
+ }
693
+
694
+ /**
695
+ * Elapsed time for a closing rule, or undefined when the host reported no reliable
696
+ * duration. Sub-second runs read in milliseconds, longer ones in seconds with one
697
+ * decimal.
698
+ */
699
+ function cardElapsed(durationMs) {
700
+ if (durationMs === undefined || !Number.isFinite(durationMs) || durationMs < 0) return undefined;
701
+ return durationMs < 1000 ? `${Math.round(durationMs)}ms` : `${(durationMs / 1000).toFixed(1)}s`;
702
+ }
703
+
704
+ // ---- the float style ----
705
+
706
+ // The transparent margin on both sides of a float card, the narrowest width that
707
+ // still holds a rail plus content, and the tone background each tone paints.
708
+ const FLOAT_MARGIN = 1;
709
+ const FLOAT_MIN_WIDTH = 10;
710
+ const FLOAT_BG_ROLE = {
711
+ [CARD_TONE.INFO]: 'toolSuccessBg',
712
+ [CARD_TONE.SUCCESS]: 'toolSuccessBg',
713
+ [CARD_TONE.WARNING]: 'toolPendingBg',
714
+ [CARD_TONE.ERROR]: 'toolErrorBg',
715
+ };
716
+
717
+ // The background reset, assembled instead of written down: this module carries no
718
+ // raw escape sequence, and the only escape a float row holds is the opener the
719
+ // injected theme's own `bg(role, "")` handed back.
720
+ const ESC = String.fromCharCode(27);
721
+ const BG_RESET = `${ESC}[49m`;
722
+ // Full resets (the host's truncation inserts one) and background resets both
723
+ // clear the background, so the opener is re-armed after either one.
724
+ const BG_CLEARING = new RegExp(`${ESC}\\[(?:0|49)?m`, 'g');
725
+
726
+ /**
727
+ * The SGR that opens `role` as a background, or "" when the theme cannot paint
728
+ * it — the one signal that the float style is unavailable and the neon outline
729
+ * must be drawn instead.
730
+ */
731
+ function surfaceOpener(theme, role) {
732
+ if (theme === null || typeof theme !== 'object' || typeof theme.bg !== 'function') return '';
733
+ if (typeof role !== 'string' || role.length === 0) return '';
734
+ try {
735
+ const painted = theme.bg(role, '');
736
+ return typeof painted === 'string' && painted.endsWith(BG_RESET) ? painted.slice(0, -BG_RESET.length) : '';
737
+ } catch {
738
+ // A theme without the role keeps the neon frame instead of a broken float card.
739
+ return '';
740
+ }
741
+ }
742
+
743
+ /** The tone background opener when float applies at this width, or "" for the neon outline. */
744
+ function floatOpener(theme, tone, width) {
745
+ if (cardStyle() !== CARD_STYLE.FLOAT) return '';
746
+ if (Math.floor(width) < FLOAT_MIN_WIDTH) return '';
747
+ const role = Object.prototype.hasOwnProperty.call(FLOAT_BG_ROLE, tone) ? FLOAT_BG_ROLE[tone] : '';
748
+ return surfaceOpener(theme, role);
749
+ }
750
+
751
+ /** Paints one row behind the background `open` starts, inside the transparent margin. */
752
+ function paintSurfaceRow(row, open) {
753
+ const painted = String(row).replace(BG_CLEARING, (reset) => reset + open);
754
+ return `${open}${painted}${BG_RESET}`;
755
+ }
756
+
757
+ function paintFloat(rows, open) {
758
+ const margin = ' '.repeat(FLOAT_MARGIN);
759
+ return rows.map((row) => `${margin}${paintSurfaceRow(row, open)}${margin}`);
760
+ }
761
+
762
+ /**
763
+ * S5: the rows of one card component in the style the shell chose. `render`
764
+ * receives the width the card draws at — the full width for `neon`, two columns
765
+ * narrower for `float`, where the margins live — and returns the component's
766
+ * `{head, body, bottom, afterHeading}` parts. The style is decided ONCE, here, so
767
+ * a card is never half outline and half rail.
768
+ *
769
+ * Float adds the two padding rows upstream does — above the heading and between
770
+ * the heading and a body — and paints every row, padding included, behind the
771
+ * tone background. `afterHeading` tells it that the heading lives in the call
772
+ * component above, so a paired call and result still read as one card.
773
+ *
774
+ * `railRole` is the optional identity role the card's whole closed box is painted
775
+ * in, exactly as the source's `floatRows` takes it: the corners and rules of the
776
+ * neon frame and the rail of the float band alike, in both styles, unless the tone
777
+ * owns the box. Omitted (the default), every cell keeps the tone's frame role, so a
778
+ * card that names none is drawn exactly as before.
779
+ */
780
+ function floatRows(tone, theme, width, render, railRoleOverride) {
781
+ return withRailRole(railRoleOverride, () => floatRowsAt(tone, theme, Math.max(0, Math.floor(width)), render));
782
+ }
783
+
784
+ function floatRowsAt(tone, theme, target, render) {
785
+ const open = floatOpener(theme, tone, target);
786
+ if (open === '') {
787
+ const { head = [], body = [], bottom } = render(target);
788
+ return [...head, ...body, ...(bottom === undefined ? [] : [bottom])];
789
+ }
790
+ const inner = target - FLOAT_MARGIN * 2;
791
+ const rows = withChrome(FLOAT_CHROME, () => {
792
+ const { head = [], body = [], bottom, afterHeading = false } = render(inner);
793
+ const blank = cardBlank(tone, theme, inner);
794
+ return [
795
+ ...(head.length > 0 ? [blank, ...head] : []),
796
+ ...(body.length > 0 && (head.length > 0 || afterHeading) ? [blank] : []),
797
+ ...body,
798
+ ...(bottom === undefined ? [] : [bottom]),
799
+ ];
800
+ });
801
+ return paintFloat(rows, open);
802
+ }
803
+
804
+ module.exports = {
805
+ CARD_GLYPH,
806
+ CARD_STYLE,
807
+ CARD_TONE,
808
+ TONE_OWNS_BOX,
809
+ cardAwaitingResult,
810
+ cardBodyRows,
811
+ cardBottom,
812
+ cardElapsed,
813
+ cardInnerWidth,
814
+ cardLine,
815
+ cardMouseEvent,
816
+ cardPaintedLine,
817
+ cardPaintedRows,
818
+ cardRunningLine,
819
+ cardTop,
820
+ cardTopLine,
821
+ cardTopRows,
822
+ floatRows,
823
+ headingFits,
824
+ markCardResult,
825
+ };