pi-odd-worktree 3.15.1 → 3.16.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 (127) hide show
  1. package/README.md +48 -25
  2. package/extensions/odd-worktree-tools.ts +70 -212
  3. package/lib/shell-api/api.ts +523 -0
  4. package/lib/shell-api/arm.ts +83 -0
  5. package/lib/shell-api/bus.ts +1389 -0
  6. package/lib/shell-api/capture.ts +1340 -0
  7. package/lib/shell-api/card-style-line.ts +112 -0
  8. package/lib/shell-api/card-style-rows.ts +390 -0
  9. package/lib/shell-api/card-style-transform.ts +862 -0
  10. package/lib/shell-api/card-style-wiring.ts +477 -0
  11. package/lib/shell-api/card-styles.ts +153 -0
  12. package/lib/shell-api/config.ts +71 -0
  13. package/lib/shell-api/extension.ts +247 -0
  14. package/lib/shell-api/hook.ts +322 -0
  15. package/lib/shell-api/index.ts +88 -0
  16. package/lib/shell-api/message-design-adoption.ts +549 -0
  17. package/lib/shell-api/message-design-rows.ts +313 -0
  18. package/lib/shell-api/message-design-wiring.ts +369 -0
  19. package/lib/shell-api/message-designs.ts +746 -0
  20. package/lib/shell-api/notices.ts +137 -0
  21. package/lib/shell-api/plugin-lines.ts +877 -0
  22. package/lib/shell-api/presence.ts +258 -0
  23. package/lib/shell-api/repaint.ts +351 -0
  24. package/lib/shell-api/row-labels.ts +146 -0
  25. package/lib/shell-api/row-names.ts +273 -0
  26. package/lib/shell-api/row-origin.ts +144 -0
  27. package/lib/shell-api/rows.ts +591 -0
  28. package/lib/shell-api/section-panel.ts +378 -0
  29. package/lib/shell-api/section-pointer.ts +164 -0
  30. package/lib/shell-api/sections-preview.ts +275 -0
  31. package/lib/shell-api/sections-rows.ts +133 -0
  32. package/lib/shell-api/sidebar-render.ts +705 -0
  33. package/lib/shell-api/sidebar.ts +1126 -0
  34. package/lib/shell-api/store.ts +279 -0
  35. package/lib/shell-api/tool-design-adoption.ts +263 -0
  36. package/lib/shell-api/tool-design-rows.ts +307 -0
  37. package/lib/shell-api/tool-design-wiring.ts +481 -0
  38. package/lib/shell-api/tool-designs.ts +1411 -0
  39. package/lib/shell-api/transform-pipeline.ts +351 -0
  40. package/lib/shell-api/types.ts +803 -0
  41. package/lib/shell-api/visibility.ts +154 -0
  42. package/package.json +3 -2
  43. package/tools/files-bridge.test.js +81 -66
  44. package/tools/fixtures/load-extension.js +40 -18
  45. package/tools/issues-command.test.js +4 -7
  46. package/tools/issues-section.test.js +71 -81
  47. package/tools/odd-rail-wiring.test.js +16 -10
  48. package/tools/package-surface.test.js +42 -13
  49. package/tools/prs-command.test.js +11 -6
  50. package/tools/session-auto-name-wiring.test.js +39 -0
  51. package/tools/shell-api/api.test.ts +484 -0
  52. package/tools/shell-api/apply-on-move.test.ts +529 -0
  53. package/tools/shell-api/arm.test.ts +220 -0
  54. package/tools/shell-api/bridge-ready.test.ts +309 -0
  55. package/tools/shell-api/bus.test.ts +194 -0
  56. package/tools/shell-api/button-rows.test.ts +435 -0
  57. package/tools/shell-api/capture.test.ts +583 -0
  58. package/tools/shell-api/card-style-rows.test.ts +493 -0
  59. package/tools/shell-api/card-style-transform.test.ts +379 -0
  60. package/tools/shell-api/card-style-wiring.test.ts +258 -0
  61. package/tools/shell-api/card-styles-e2e.test.ts +502 -0
  62. package/tools/shell-api/card-styles.test.ts +324 -0
  63. package/tools/shell-api/card-transcript-path.test.ts +178 -0
  64. package/tools/shell-api/compatibility-regression.test.mjs +64 -0
  65. package/tools/shell-api/config.test.ts +93 -0
  66. package/tools/shell-api/docs-coverage.test.ts +82 -0
  67. package/tools/shell-api/e2e.test.ts +562 -0
  68. package/tools/shell-api/example-bash-identity.test.ts +372 -0
  69. package/tools/shell-api/example-bash-matrix.test.ts +856 -0
  70. package/tools/shell-api/example-designs.test.ts +737 -0
  71. package/tools/shell-api/example-neon-transform.test.ts +283 -0
  72. package/tools/shell-api/example-plain-style.test.ts +1225 -0
  73. package/tools/shell-api/extension.test.ts +157 -0
  74. package/tools/shell-api/fake-events.ts +58 -0
  75. package/tools/shell-api/fake-host.ts +211 -0
  76. package/tools/shell-api/fake-sidebar.ts +516 -0
  77. package/tools/shell-api/fake-transcript.ts +486 -0
  78. package/tools/shell-api/frame-telemetry.test.ts +317 -0
  79. package/tools/shell-api/hook.test.ts +196 -0
  80. package/tools/shell-api/manifest.test.ts +47 -0
  81. package/tools/shell-api/message-design-adoption.test.ts +611 -0
  82. package/tools/shell-api/message-design-follows.test.ts +361 -0
  83. package/tools/shell-api/message-design-pi-release.test.mjs +157 -0
  84. package/tools/shell-api/message-design-regressions.test.mjs +162 -0
  85. package/tools/shell-api/message-design-rows.test.ts +266 -0
  86. package/tools/shell-api/message-design-wiring.test.ts +362 -0
  87. package/tools/shell-api/message-designs.test.ts +339 -0
  88. package/tools/shell-api/new-category.test.ts +1101 -0
  89. package/tools/shell-api/notices.test.ts +292 -0
  90. package/tools/shell-api/plugin-integration-lines.test.ts +827 -0
  91. package/tools/shell-api/presence.test.ts +396 -0
  92. package/tools/shell-api/rail-part-hits.test.ts +281 -0
  93. package/tools/shell-api/rail-surfaces.test.ts +402 -0
  94. package/tools/shell-api/rail-width.test.ts +406 -0
  95. package/tools/shell-api/regression.test.ts +434 -0
  96. package/tools/shell-api/repaint-api.test.ts +200 -0
  97. package/tools/shell-api/reserved-categories.test.ts +250 -0
  98. package/tools/shell-api/row-labels.test.ts +261 -0
  99. package/tools/shell-api/row-names.test.ts +407 -0
  100. package/tools/shell-api/row-origin.test.ts +395 -0
  101. package/tools/shell-api/row-placement-regression.test.ts +797 -0
  102. package/tools/shell-api/row-placement.test.ts +410 -0
  103. package/tools/shell-api/section-interaction.test.ts +364 -0
  104. package/tools/shell-api/section-panel.test.ts +430 -0
  105. package/tools/shell-api/section-placement-rail.test.ts +390 -0
  106. package/tools/shell-api/section-placement.test.ts +386 -0
  107. package/tools/shell-api/sections-preview.test.ts +312 -0
  108. package/tools/shell-api/sections-rows.test.ts +293 -0
  109. package/tools/shell-api/sidebar-backend.test.ts +477 -0
  110. package/tools/shell-api/sidebar-e2e.test.ts +317 -0
  111. package/tools/shell-api/sidebar-hover.test.ts +276 -0
  112. package/tools/shell-api/sidebar-independent.test.ts +291 -0
  113. package/tools/shell-api/sidebar-render.test.ts +281 -0
  114. package/tools/shell-api/sidebar-sections.test.ts +247 -0
  115. package/tools/shell-api/store.test.ts +192 -0
  116. package/tools/shell-api/surface-repaint-cost.test.ts +520 -0
  117. package/tools/shell-api/tool-design-card-style.test.ts +308 -0
  118. package/tools/shell-api/tool-design-chain.test.ts +471 -0
  119. package/tools/shell-api/tool-design-cost.test.ts +591 -0
  120. package/tools/shell-api/tool-design-rows.test.ts +627 -0
  121. package/tools/shell-api/tool-design-scopes-audit.test.ts +212 -0
  122. package/tools/shell-api/tool-designs.test.ts +2412 -0
  123. package/tools/shell-api/transform-pipeline.test.ts +376 -0
  124. package/tools/shell-api/transforms-bus.test.ts +233 -0
  125. package/tools/shell-api/verifier-width-regressions.test.ts +147 -0
  126. package/tools/shell-api-rpc.test.js +189 -0
  127. package/tools/user-prompt-card.test.js +8 -9
@@ -0,0 +1,862 @@
1
+ /**
2
+ * The line transformer (S3, S6, S12): what turns the host's already-drawn cards into the selected
3
+ * style's chrome.
4
+ *
5
+ * ## What it is given, and what it may change
6
+ *
7
+ * The host renders one component and gets `string[]` back; the bridge wraps that call, so this
8
+ * module takes the rows the host produced plus the width it rendered at, and returns rows. Only two
9
+ * things are ever rewritten: the rows of a card detected by the grammar below. Every other row is
10
+ * carried through as the SAME string (S3.4), and when there is nothing to do — `native`, no
11
+ * selection, a selection naming a style that no longer exists — the input array itself comes back
12
+ * (S3: "the same array reference, untouched").
13
+ *
14
+ * ## The float grammar it detects (`src/card-styles.ts` §2, from `lib/shell-card.ts`)
15
+ *
16
+ * A float card is: a one-column margin, then an accent bar `▎`, then one space — on every row. In
17
+ * that frame the rows are
18
+ *
19
+ * ```
20
+ * ▎ <spaces> opener (bar only: `cardBottom` with no content)
21
+ * ▎ <glyph> <title> … <hint> header (all the text a card's heading carries)
22
+ * ▎ <spaces> separator (ONLY when the card has a body)
23
+ * ▎ <text>… body row (one per wrapped row)
24
+ * ▎ <spaces> closer (identical to the opener)
25
+ * ```
26
+ *
27
+ * so detection is positional, never lexical: padding row, header row, then either one more
28
+ * padding row (an empty-body card — exactly three rows) or a separator, body rows and a closer.
29
+ * `neon` starts at column 0 with `╭`, `│` or `╰`, so it never matches `isFloatRow` and is left
30
+ * alone: the bridge must not repaint a card that did not use the float frame.
31
+ *
32
+ * ### The three ambiguities this pass has to choose between, spelled out
33
+ *
34
+ * 1. **A blank body row is byte-identical to the opener/closer.** `cardBodyRows` draws an empty
35
+ * paragraph as `cardLine("")`, which is a bar and spaces — the same string as the padding row.
36
+ * So the body of a card CONTAINING a blank row ends at that blank row, and its remaining rows
37
+ * are left as the host drew them. Chosen because the alternative (extend until a padding row
38
+ * that is followed by a non-float row) swallows the next card whenever two cards are adjacent.
39
+ * 2. **A heading's last text run may be a hint or a subtitle.** `cardTop` paints the hint as
40
+ * `" " + fg(dim, hint) + " "` and a subtitle as `" " + fg(muted, "·") + " " + fg(muted, sub)`, and
41
+ * at the character level both are text between runs of spaces. The structural difference used
42
+ * here: the hint is a single styled run flanked by UNSTYLED single spaces, and its SGR differs
43
+ * from the title's; a subtitle is preceded by the dotted run, not by an unstyled space. See
44
+ * `extractHeading` — when that structure is not there, NO split is guessed: the whole remainder
45
+ * becomes `title` and `hint` is undefined.
46
+ * 3. **The glyph.** The host always prints `${card.glyph ?? "✿"} ${title}`. The glyph is stripped
47
+ * from `title` when it is a single character followed by one space, because a style draws its own
48
+ * chrome (S2's context is the heading text, not the host's glyph); a card whose heading would
49
+ * lose its first word that way cannot be told apart from the normal case, and would need a glyph
50
+ * of more than one cell to happen.
51
+ *
52
+ * ## Failure is a pass-through (S6)
53
+ *
54
+ * Any throw — detection, extraction, or inside a style's `top`/`line`/`bottom` — returns the ORIGINAL
55
+ * array, so a card is never half-repainted, and records one failure for the diagnostics record. A style
56
+ * can degrade the look; it can never break the conversation. The transformer never catches a host
57
+ * failure: it is only given rows that already exist.
58
+ *
59
+ * ## Width discipline
60
+ *
61
+ * The host owns the frame width. A style that returns something wider is clipped here, never
62
+ * emitted — and if the clipped text had SGR active, a reset is appended so the paint cannot leak
63
+ * into the next row.
64
+ *
65
+ * This module is internal: `src/index.ts` does not re-export it.
66
+ */
67
+
68
+ import { resolveCardStyleSelection, type CardStyleSelection } from "./card-styles.ts";
69
+ import type { PaintSurface } from "./repaint.ts";
70
+ import { isRecord } from "./rows.ts";
71
+ import type { CardStyleRegistration } from "./types.ts";
72
+
73
+ /** The accent bar every float row starts with, one column in from the margin (`shell-card.ts:108`). */
74
+ const FLOAT_BAR = "▎";
75
+
76
+ /** A full reset, appended after a clipped styled line so the paint cannot leak. */
77
+ const RESET = "\u001b[0m";
78
+
79
+ /** One SGR sequence. Used for stripping and for reading a row's style runs. */
80
+ const SGR_ALL = /\u001b\[[0-9;]*m/gu;
81
+ /** The same sequence, sticky, for the clip walk (no regex state crosses calls). */
82
+ const SGR_AT = /\u001b\[[0-9;]*m/y;
83
+
84
+ /** SGR params that leave no foreground/background in force. */
85
+ const RESET_PARAMS = new Set(["", "0", "39", "49", "22", "23", "24", "25", "27", "28", "29"]);
86
+
87
+ /** How many failures are kept for the diagnostics record. */
88
+ const MAX_FAILURES = 32;
89
+
90
+ export interface CardStyleTransformFailure {
91
+ /** The style that threw. */
92
+ styleId: string;
93
+ message: string;
94
+ }
95
+
96
+ /**
97
+ * What the most recent frame did. the diagnostics record reports it, so "the style is selected but the
98
+ * conversation looks untouched" always has an answer.
99
+ */
100
+ export type CardStyleFrameOutcome =
101
+ | { kind: "transformed"; styleId: string; cards: number }
102
+ | { kind: "pass-through"; reason: "native" | "missing" | "no-card" }
103
+ | { kind: "failed"; styleId: string; message: string };
104
+
105
+ interface TransformState {
106
+ failures: CardStyleTransformFailure[];
107
+ /**
108
+ * The most recent frame per SURFACE (R4). The conversation and the rail repaint through this one
109
+ * transform, so "the style is selected but the sidebar looks untouched" has an answer per surface
110
+ * instead of one shared last-writer.
111
+ */
112
+ lastOutcomes: Partial<Record<PaintSurface, CardStyleFrameOutcome>>;
113
+ }
114
+
115
+ /** Process-global, like every other piece of bridge state (`./bus.ts` explains why). */
116
+ const TRANSFORM_STATE = Symbol.for("gentle-shell-bridge.card-style-transform.state.v1");
117
+
118
+ function transformHost(): Record<symbol, TransformState | undefined> {
119
+ // SAFETY: only `transformState()` writes this key, and it re-checks the shape it finds.
120
+ return globalThis as unknown as Record<symbol, TransformState | undefined>;
121
+ }
122
+
123
+ function isTransformStateLike(value: unknown): value is TransformState {
124
+ return isRecord(value) && Array.isArray(value.failures) && isRecord(value.lastOutcomes);
125
+ }
126
+
127
+ function transformState(): TransformState {
128
+ const host = transformHost();
129
+ const existing = host[TRANSFORM_STATE];
130
+ if (isTransformStateLike(existing)) return existing;
131
+ const created: TransformState = { failures: [], lastOutcomes: {} };
132
+ host[TRANSFORM_STATE] = created;
133
+ return created;
134
+ }
135
+
136
+ /** The failures the last frames recorded, oldest first. Read by the diagnostics record (T4). */
137
+ export function getCardStyleTransformFailures(): CardStyleTransformFailure[] {
138
+ return transformState().failures.map((failure) => ({ ...failure }));
139
+ }
140
+
141
+ /**
142
+ * What the last frame did on one surface, or `undefined` before that surface ran this transform once.
143
+ * The conversation is the default because it is the surface that existed first; the diagnostics record
144
+ * asks for both.
145
+ */
146
+ export function getCardStyleLastOutcome(
147
+ surface: PaintSurface = "conversation",
148
+ ): CardStyleFrameOutcome | undefined {
149
+ const outcome = transformState().lastOutcomes[surface];
150
+ return outcome === undefined ? undefined : { ...outcome };
151
+ }
152
+
153
+ /** Test-only seam; deliberately not re-exported from `src/index.ts`. */
154
+ export function resetCardStyleTransformForTests(): void {
155
+ const state = transformState();
156
+ state.failures.length = 0;
157
+ state.lastOutcomes = {};
158
+ }
159
+
160
+ function recordOutcome(surface: PaintSurface, outcome: CardStyleFrameOutcome): void {
161
+ transformState().lastOutcomes[surface] = outcome;
162
+ }
163
+
164
+ /** Record one failure, once per (style, message): a style that throws every frame is one fact. */
165
+ function recordFailure(styleId: string, message: string): void {
166
+ const state = transformState();
167
+ if (state.failures.some((failure) => failure.styleId === styleId && failure.message === message)) {
168
+ return;
169
+ }
170
+ state.failures.push({ styleId, message });
171
+ if (state.failures.length > MAX_FAILURES) {
172
+ state.failures.splice(0, state.failures.length - MAX_FAILURES);
173
+ }
174
+ }
175
+
176
+ function errorMessage(error: unknown): string {
177
+ return error instanceof Error ? error.message : String(error);
178
+ }
179
+
180
+ // ---------------------------------------------------------------------------------------------
181
+ // Row shapes
182
+ // ---------------------------------------------------------------------------------------------
183
+
184
+ function stripAnsi(line: string): string {
185
+ return line.replace(SGR_ALL, "");
186
+ }
187
+
188
+ /** `margin ▎ space` — the float frame's first three columns on every row it draws. */
189
+ function isFloatRow(stripped: string): boolean {
190
+ return stripped.length >= 3 && stripped.startsWith(` ${FLOAT_BAR} `);
191
+ }
192
+
193
+ /** A bar and nothing else: the opener, the separator and the closer all look like this. */
194
+ function isPaddingRow(stripped: string): boolean {
195
+ return isFloatRow(stripped) && stripped.slice(3).trim() === "";
196
+ }
197
+
198
+ /** A bar and some text: a heading or a body row. */
199
+ function isContentRow(stripped: string): boolean {
200
+ return isFloatRow(stripped) && stripped.slice(3).trim() !== "";
201
+ }
202
+
203
+ /** The text a card row carries, without the frame: what a style's `line` is given. */
204
+ function rowText(stripped: string): string {
205
+ return stripped.slice(3).trimEnd();
206
+ }
207
+
208
+ /** One span of a raw row with a single SGR state, and where it starts in the stripped row. */
209
+ interface Segment {
210
+ code: string;
211
+ text: string;
212
+ start: number;
213
+ }
214
+
215
+ /**
216
+ * Split a raw row into runs of constant SGR state, recording each run's start offset in the
217
+ * STRIPPED row, so a heading can be sliced by visible position afterwards.
218
+ */
219
+ function segmentsOf(raw: string): Segment[] {
220
+ const segments: Segment[] = [];
221
+ const pattern = new RegExp(SGR_ALL.source, "gu");
222
+ let code = "";
223
+ let cursor = 0;
224
+ let visible = 0;
225
+ for (let match = pattern.exec(raw); match !== null; match = pattern.exec(raw)) {
226
+ const text = raw.slice(cursor, match.index);
227
+ if (text !== "") {
228
+ segments.push({ code, text, start: visible });
229
+ visible += text.length;
230
+ }
231
+ code = sgrCode(match[0]);
232
+ cursor = match.index + match[0].length;
233
+ }
234
+ const tail = raw.slice(cursor);
235
+ if (tail !== "") segments.push({ code, text: tail, start: visible });
236
+ return segments;
237
+ }
238
+
239
+ /** The SGR that is in force after `sgr`; `""` for a reset, the sequence itself otherwise. */
240
+ function sgrCode(sgr: string): string {
241
+ const params = sgr.slice(2, -1);
242
+ const parts = params === "" ? [""] : params.split(";");
243
+ return parts.every((part) => RESET_PARAMS.has(part)) ? "" : sgr;
244
+ }
245
+
246
+ // ---------------------------------------------------------------------------------------------
247
+ // Heading extraction (S3.2): title and hint, once, in this one place
248
+ // ---------------------------------------------------------------------------------------------
249
+
250
+ export interface CardHeading {
251
+ /** The heading text without the host's glyph; undefined when the row carried none. */
252
+ title?: string;
253
+ /** The right-aligned hint, only when its structure proves it is one. */
254
+ hint?: string;
255
+ }
256
+
257
+ /**
258
+ * Extract a float card's heading from its header row.
259
+ *
260
+ * The split is proved structurally, never guessed: the hint is the last styled run of the row, it
261
+ * is flanked by UNSTYLED single spaces (`cardTop`'s `tail`), and its SGR differs from the title's
262
+ * (`HINT_ROLE` is `dim`). A subtitle (`· subtitle`, in the muted role) is preceded by the dotted run
263
+ * instead of an unstyled space, so it is not mistaken for a hint. When the structure does not hold,
264
+ * the whole remainder is the title and `hint` is undefined — a style then draws the heading exactly
265
+ * as the host printed it, which is worse-looking but never wrong.
266
+ */
267
+ export function extractHeading(rawHeader: string): CardHeading {
268
+ const stripped = stripAnsi(rawHeader);
269
+ if (!isFloatRow(stripped)) return {};
270
+ const segments = segmentsOf(rawHeader).filter((segment) => segment.start >= 3);
271
+ const firstContent = segments.findIndex((segment) => segment.text.trim() !== "");
272
+ if (firstContent === -1) return {};
273
+
274
+ let hint: string | undefined;
275
+ let titleEnd = stripped.length;
276
+ for (let index = segments.length - 1; index > firstContent; index -= 1) {
277
+ const candidate = segments[index];
278
+ if (candidate === undefined) break;
279
+ if (candidate.text.trim() === "") continue;
280
+ const before = segments[index - 1];
281
+ const after = segments[index + 1];
282
+ const proven =
283
+ before !== undefined &&
284
+ after !== undefined &&
285
+ before.code === "" &&
286
+ before.text.trim() === "" &&
287
+ after.code === "" &&
288
+ after.text.trim() === "" &&
289
+ candidate.code !== "" &&
290
+ candidate.code !== segments[firstContent]?.code;
291
+ if (proven) {
292
+ hint = candidate.text.trim();
293
+ titleEnd = candidate.start;
294
+ }
295
+ break;
296
+ }
297
+
298
+ const heading = stripGlyph(stripped.slice(3, titleEnd).trim());
299
+ return hint === undefined ? { title: heading } : { title: heading, hint };
300
+ }
301
+
302
+ /**
303
+ * Drop the host's leading glyph (`${card.glyph ?? "✿"} `). The glyph is always one character
304
+ * followed by exactly one space (`shell-card.ts:124`); the title is what follows it.
305
+ */
306
+ function stripGlyph(heading: string): string | undefined {
307
+ const characters = [...heading];
308
+ if (characters.length > 2 && characters[1] === " ") return characters.slice(2).join("");
309
+ return heading === "" ? undefined : heading;
310
+ }
311
+
312
+ // ---------------------------------------------------------------------------------------------
313
+ // Detection
314
+ // ---------------------------------------------------------------------------------------------
315
+
316
+ interface CardSpan {
317
+ /** The opener (padding) row. */
318
+ start: number;
319
+ /** The header row. */
320
+ header: number;
321
+ /** First body row; equals `bodyEnd` for an empty body. */
322
+ bodyStart: number;
323
+ /** One past the last body row. */
324
+ bodyEnd: number;
325
+ /** The closing padding row. */
326
+ closer: number;
327
+ }
328
+
329
+ function matchCard(stripped: readonly string[], start: number): CardSpan | undefined {
330
+ if (!isPaddingRow(stripped[start] ?? "")) return undefined;
331
+ if (!isContentRow(stripped[start + 1] ?? "")) return undefined;
332
+
333
+ const third = stripped[start + 2];
334
+ if (third === undefined) return undefined;
335
+
336
+ if (isContentRow(third)) {
337
+ // Header straight into body, with no separator: a shape `floatRows` can produce when a caller
338
+ // supplies a body without a head, and one that costs nothing to accept.
339
+ const closer = findCloser(stripped, start + 2);
340
+ if (closer === undefined) return undefined;
341
+ return { start, header: start + 1, bodyStart: start + 2, bodyEnd: closer, closer };
342
+ }
343
+ if (!isPaddingRow(third)) return undefined;
344
+
345
+ // A padding row after the header is a separator when body content follows it, and the closer when
346
+ // nothing does — which is what makes an empty-body card exactly three rows.
347
+ if (isContentRow(stripped[start + 3] ?? "")) {
348
+ const closer = findCloser(stripped, start + 3);
349
+ if (closer === undefined) return undefined;
350
+ return { start, header: start + 1, bodyStart: start + 3, bodyEnd: closer, closer };
351
+ }
352
+ return { start, header: start + 1, bodyStart: start + 2, bodyEnd: start + 2, closer: start + 2 };
353
+ }
354
+
355
+ /** The first padding row at or after `from`: the card's closer. An unterminated card is not a card. */
356
+ function findCloser(stripped: readonly string[], from: number): number | undefined {
357
+ for (let index = from; index < stripped.length; index += 1) {
358
+ if (isPaddingRow(stripped[index] ?? "")) return index;
359
+ }
360
+ return undefined;
361
+ }
362
+
363
+ /**
364
+ * Every float card in the frame, in order, skipping the rows it already claimed so a body row can
365
+ * never be read as the opener of the next card.
366
+ */
367
+ function findCards(lines: readonly string[]): CardSpan[] {
368
+ const stripped = lines.map((line) => stripAnsi(line));
369
+ const cards: CardSpan[] = [];
370
+ let index = 0;
371
+ while (index < stripped.length) {
372
+ const card = matchCard(stripped, index);
373
+ if (card === undefined) {
374
+ index += 1;
375
+ continue;
376
+ }
377
+ cards.push(card);
378
+ index = card.closer + 1;
379
+ }
380
+ return cards;
381
+ }
382
+
383
+ // ---------------------------------------------------------------------------------------------
384
+ // Width discipline
385
+ // ---------------------------------------------------------------------------------------------
386
+
387
+ /** Whether a code point occupies two terminal columns (the common wide/emoji ranges). */
388
+ function isWideCodePoint(code: number): boolean {
389
+ return (
390
+ (code >= 0x1100 && code <= 0x115f) ||
391
+ (code >= 0x2e80 && code <= 0xa4cf) ||
392
+ (code >= 0xac00 && code <= 0xd7a3) ||
393
+ (code >= 0xf900 && code <= 0xfaff) ||
394
+ (code >= 0xfe30 && code <= 0xfe6f) ||
395
+ (code >= 0xff00 && code <= 0xff60) ||
396
+ (code >= 0xffe0 && code <= 0xffe6) ||
397
+ (code >= 0x1f300 && code <= 0x1f64f) ||
398
+ (code >= 0x1f900 && code <= 0x1f9ff) ||
399
+ (code >= 0x20000 && code <= 0x3fffd)
400
+ );
401
+ }
402
+
403
+ /** Columns one character occupies: 0 for combining/control, 2 for wide, 1 otherwise. */
404
+ function cellWidth(char: string): number {
405
+ const code = char.codePointAt(0) ?? 0;
406
+ if (code < 32 || (code >= 0x7f && code < 0xa0)) return 0;
407
+ if (code >= 0x300 && code <= 0x36f) return 0;
408
+ return isWideCodePoint(code) ? 2 : 1;
409
+ }
410
+
411
+ /**
412
+ * The model pi-tui measures a row with, ported from `visibleWidth` (`pi-tui/dist/utils.js:212-268`,
413
+ * pi-tui 1.5.x):
414
+ *
415
+ * - ANSI/CSI, OSC and APC sequences are zero columns (`:228-257`, which strips through
416
+ * `extractAnsiCode`, so an OSC-8 hyperlink contributes its TEXT and not its URL);
417
+ * - a TAB is THREE columns, not one (`:229-231`, `clean.replace(/\t/g, " ")`);
418
+ * - the rest is segmented into GRAPHEME CLUSTERS (`:259-262`, `Intl.Segmenter` with
419
+ * `granularity: "grapheme"`) and each cluster is charged the way `graphemeWidth` charges it
420
+ * (`:143-207`): a lone printable ASCII byte one, a cluster of terminal-spacing marks its code
421
+ * point count, a cluster of nothing but ignorables/controls/marks/surrogates none, an RGI emoji
422
+ * (after the host's own `couldBeEmoji` prefilter, so bare `©`/`☺`/`▶` are NOT emoji) two, a
423
+ * leading regional-indicator pair two, otherwise the base's East Asian `W|F` width plus every
424
+ * terminal-spacing mark, mark-following VISIBLE code point (the consonant of an Indic conjunct
425
+ * after its virama: `क्‍ष` is two columns), halfwidth/fullwidth form and Thai/Lao AM vowel.
426
+ *
427
+ * This exists because `visibleColumns` counts per code point, charges a tab one column and only
428
+ * ignores SGR, so a row this package believes fits can measure wider to the host (or a fitting row
429
+ * can be cut). Anything contributed to the HOST's frame is measured the host's way
430
+ * (`./section-panel.ts`, `./sidebar-render.ts`, `./transform-pipeline.ts`), and the port is exact:
431
+ * measured against the installed `visibleWidth` for every Unicode code point, no cluster differs.
432
+ */
433
+ export function hostColumns(line: string): number {
434
+ if (line === "") return 0;
435
+ // Tabs first, exactly like the host: `clean.replace(/\t/g, " ")` (`utils.js:229-231`).
436
+ const expanded = line.includes("\t") ? line.replace(/\t/gu, " ") : line;
437
+ const clean = stripHostEscapes(expanded);
438
+ // Fast path, like the host's (`utils.js:216-221`): printable ASCII is one column per byte.
439
+ if (ASCII_ONLY.test(clean)) return clean.length;
440
+ let columns = 0;
441
+ for (const segment of graphemes(clean)) columns += clusterColumns(segment);
442
+ return columns;
443
+ }
444
+
445
+ /** One complete escape sequence at `index`, read exactly as pi-tui's `extractAnsiCode` reads it. */
446
+ function hostEscapeAt(line: string, index: number): { code: string; length: number } | undefined {
447
+ if (line[index] !== "\u001b") return undefined;
448
+ const kind = line[index + 1];
449
+ if (kind === "[") {
450
+ // CSI: `ESC [` up to and including the first final byte the host recognises.
451
+ let end = index + 2;
452
+ while (end < line.length && !/[mGKHJ]/u.test(line[end] ?? "")) end += 1;
453
+ return end < line.length ? { code: line.slice(index, end + 1), length: end + 1 - index } : undefined;
454
+ }
455
+ if (kind === "]" || kind === "_") {
456
+ // OSC / APC: terminated by BEL or by ST (`ESC \\`).
457
+ let end = index + 2;
458
+ while (end < line.length) {
459
+ if (line[end] === "\u0007") return { code: line.slice(index, end + 1), length: end + 1 - index };
460
+ if (line[end] === "\u001b" && line[end + 1] === "\\") {
461
+ return { code: line.slice(index, end + 2), length: end + 2 - index };
462
+ }
463
+ end += 1;
464
+ }
465
+ return undefined;
466
+ }
467
+ return undefined;
468
+ }
469
+
470
+ /** A row with every complete escape sequence removed, as the host strips before measuring. */
471
+ function stripHostEscapes(line: string): string {
472
+ if (!line.includes("\u001b")) return line;
473
+ let clean = "";
474
+ let index = 0;
475
+ while (index < line.length) {
476
+ const escape = hostEscapeAt(line, index);
477
+ if (escape !== undefined) {
478
+ index += escape.length;
479
+ continue;
480
+ }
481
+ clean += line[index];
482
+ index += 1;
483
+ }
484
+ return clean;
485
+ }
486
+
487
+ /** The URI of an OSC-8 hyperlink, or `""` for its closing sequence; `undefined` for anything else. */
488
+ function osc8Target(code: string): string | undefined {
489
+ if (!code.startsWith("\u001b]8;")) return undefined;
490
+ const end = code.endsWith("\u0007") ? code.length - 1 : code.length - 2;
491
+ const body = code.slice(4, end);
492
+ const separator = body.indexOf(";");
493
+ return separator === -1 ? undefined : body.slice(separator + 1);
494
+ }
495
+
496
+ /** A row of printable ASCII, the one shape whose width needs no grapheme segmentation. */
497
+ const ASCII_ONLY = /^[\x20-\x7e]*$/;
498
+
499
+ /** A grapheme segmenter, or `undefined` on a runtime without `Intl.Segmenter`. */
500
+ const GRAPHEMES: Intl.Segmenter | undefined =
501
+ typeof Intl === "object" && typeof Intl.Segmenter === "function"
502
+ ? new Intl.Segmenter(undefined, { granularity: "grapheme" })
503
+ : undefined;
504
+
505
+ /** The grapheme clusters of one row, falling back to code points when no segmenter exists. */
506
+ function graphemes(clean: string): string[] {
507
+ if (GRAPHEMES === undefined) return Array.from(clean);
508
+ const clusters: string[] = [];
509
+ for (const { segment } of GRAPHEMES.segment(clean)) clusters.push(segment);
510
+ return clusters;
511
+ }
512
+
513
+ /**
514
+ * A cluster made only of ignorables, controls, marks, formats or surrogates has no columns
515
+ * (`zeroWidthRegex`, `pi-tui/dist/utils.js:34`).
516
+ */
517
+ const ZERO_WIDTH_CLUSTER = /^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Mark}|\p{Surrogate})+$/v;
518
+
519
+ /** The marks an emoji or a consonant may carry before its base (`leadingNonPrintingRegex`, `:35`). */
520
+ const LEADING_NON_PRINTING =
521
+ /^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/v;
522
+
523
+ /** One character the host's trailing loop skips (`nonPrintingCharRegex`, `:36`). */
524
+ const NON_PRINTING_CHAR =
525
+ /^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Format}|\p{Mark}|\p{Surrogate})$/v;
526
+
527
+ /** One combining mark (`markCharRegex`, `:37`). */
528
+ const MARK_CHAR = /^\p{Mark}$/v;
529
+
530
+ /**
531
+ * The marks terminals allocate cells for, with or without a base (`terminalSpacingMarkRegex`,
532
+ * `:38-40`): spacing marks except a few zero-width exceptions, plus the scripts whose spacing marks
533
+ * legacy wcwidth tables charge. A lone `ि` is ONE column to the host, while a lone `्` is none.
534
+ */
535
+ const TERMINAL_SPACING_MARK =
536
+ /^(?:[\p{Spacing_Mark}--[\u1734\u302E\u302F]]|[\u065F\u0F7F\u102B\u102C\u1031\u1033-\u1035\u1038\u103A-\u103E])+$/v;
537
+
538
+ /** The emoji set the host tests AFTER its cheap prefilter (`rgiEmojiRegex`, `:41`). */
539
+ const RGI_EMOJI = /^\p{RGI_Emoji}$/v;
540
+
541
+ /**
542
+ * The host's cheap emoji prefilter (`couldBeEmoji`, `pi-tui/dist/utils.js:16-26`): broad blocks, an
543
+ * explicit emoji presentation selector, or a multi-code-unit sequence. Without it, `©` and `☺`
544
+ * would be charged as emoji when the host charges them one column.
545
+ */
546
+ function couldBeEmoji(segment: string): boolean {
547
+ const codePoint = segment.codePointAt(0) ?? 0;
548
+ return (
549
+ (codePoint >= 0x1f000 && codePoint <= 0x1fbff) ||
550
+ (codePoint >= 0x2300 && codePoint <= 0x23ff) ||
551
+ (codePoint >= 0x2600 && codePoint <= 0x27bf) ||
552
+ (codePoint >= 0x2b50 && codePoint <= 0x2b55) ||
553
+ segment.includes("\ufe0f") ||
554
+ segment.length > 2
555
+ );
556
+ }
557
+
558
+ /**
559
+ * The East Asian width of a base code point, as the host reads it: `W` or `F` is two columns, every
560
+ * other class one (`get-east-asian-width`'s `eastAsianWidth`, which `graphemeWidth` calls at
561
+ * `pi-tui/dist/utils.js:151`). The host depends on that package's generated tables; this is its
562
+ * `W|F` range set, flattened to `[start, end, start, end, …]`, so the port stays dependency-free.
563
+ * A lone code point is `[cp, cp]`.
564
+ */
565
+ const WIDE_RANGES: readonly number[] = [
566
+ 0x1100, 0x115f, 0x231a, 0x231b, 0x2329, 0x232a, 0x23e9, 0x23ec,
567
+ 0x23f0, 0x23f0, 0x23f3, 0x23f3, 0x25fd, 0x25fe, 0x2614, 0x2615,
568
+ 0x2630, 0x2637, 0x2648, 0x2653, 0x267f, 0x267f, 0x268a, 0x268f,
569
+ 0x2693, 0x2693, 0x26a1, 0x26a1, 0x26aa, 0x26ab, 0x26bd, 0x26be,
570
+ 0x26c4, 0x26c5, 0x26ce, 0x26ce, 0x26d4, 0x26d4, 0x26ea, 0x26ea,
571
+ 0x26f2, 0x26f3, 0x26f5, 0x26f5, 0x26fa, 0x26fa, 0x26fd, 0x26fd,
572
+ 0x2705, 0x2705, 0x270a, 0x270b, 0x2728, 0x2728, 0x274c, 0x274c,
573
+ 0x274e, 0x274e, 0x2753, 0x2755, 0x2757, 0x2757, 0x2795, 0x2797,
574
+ 0x27b0, 0x27b0, 0x27bf, 0x27bf, 0x2b1b, 0x2b1c, 0x2b50, 0x2b50,
575
+ 0x2b55, 0x2b55, 0x2e80, 0x2e99, 0x2e9b, 0x2ef3, 0x2f00, 0x2fd5,
576
+ 0x2ff0, 0x303e, 0x3041, 0x3096, 0x3099, 0x30ff, 0x3105, 0x312f,
577
+ 0x3131, 0x318e, 0x3190, 0x31e5, 0x31ef, 0x321e, 0x3220, 0x3247,
578
+ 0x3250, 0xa48c, 0xa490, 0xa4c6, 0xa960, 0xa97c, 0xac00, 0xd7a3,
579
+ 0xf900, 0xfaff, 0xfe10, 0xfe19, 0xfe30, 0xfe52, 0xfe54, 0xfe66,
580
+ 0xfe68, 0xfe6b, 0xff01, 0xff60, 0xffe0, 0xffe6, 0x16fe0, 0x16fe4,
581
+ 0x16ff0, 0x16ff6, 0x17000, 0x18cd5, 0x18cff, 0x18d1e, 0x18d80, 0x18df2,
582
+ 0x1aff0, 0x1aff3, 0x1aff5, 0x1affb, 0x1affd, 0x1affe, 0x1b000, 0x1b122,
583
+ 0x1b132, 0x1b132, 0x1b150, 0x1b152, 0x1b155, 0x1b155, 0x1b164, 0x1b167,
584
+ 0x1b170, 0x1b2fb, 0x1d300, 0x1d356, 0x1d360, 0x1d376, 0x1f004, 0x1f004,
585
+ 0x1f0cf, 0x1f0cf, 0x1f18e, 0x1f18e, 0x1f191, 0x1f19a, 0x1f200, 0x1f202,
586
+ 0x1f210, 0x1f23b, 0x1f240, 0x1f248, 0x1f250, 0x1f251, 0x1f260, 0x1f265,
587
+ 0x1f300, 0x1f320, 0x1f32d, 0x1f335, 0x1f337, 0x1f37c, 0x1f37e, 0x1f393,
588
+ 0x1f3a0, 0x1f3ca, 0x1f3cf, 0x1f3d3, 0x1f3e0, 0x1f3f0, 0x1f3f4, 0x1f3f4,
589
+ 0x1f3f8, 0x1f43e, 0x1f440, 0x1f440, 0x1f442, 0x1f4fc, 0x1f4ff, 0x1f53d,
590
+ 0x1f54b, 0x1f54e, 0x1f550, 0x1f567, 0x1f57a, 0x1f57a, 0x1f595, 0x1f596,
591
+ 0x1f5a4, 0x1f5a4, 0x1f5fb, 0x1f64f, 0x1f680, 0x1f6c5, 0x1f6cc, 0x1f6cc,
592
+ 0x1f6d0, 0x1f6d2, 0x1f6d5, 0x1f6d8, 0x1f6dc, 0x1f6df, 0x1f6eb, 0x1f6ec,
593
+ 0x1f6f4, 0x1f6fc, 0x1f7e0, 0x1f7eb, 0x1f7f0, 0x1f7f0, 0x1f90c, 0x1f93a,
594
+ 0x1f93c, 0x1f945, 0x1f947, 0x1f9ff, 0x1fa70, 0x1fa7c, 0x1fa80, 0x1fa8a,
595
+ 0x1fa8e, 0x1fac6, 0x1fac8, 0x1fac8, 0x1facd, 0x1fadc, 0x1fadf, 0x1faea,
596
+ 0x1faef, 0x1faf8, 0x20000, 0x2fffd, 0x30000, 0x3fffd,
597
+ ];
598
+
599
+ /** Whether a base code point is East Asian Wide or Fullwidth: two columns, as the host charges it. */
600
+ function isEastAsianWide(codePoint: number): boolean {
601
+ let low = 0;
602
+ let high = WIDE_RANGES.length / 2 - 1;
603
+ while (low <= high) {
604
+ const middle = (low + high) >> 1;
605
+ const start = WIDE_RANGES[middle * 2] ?? 0;
606
+ const end = WIDE_RANGES[middle * 2 + 1] ?? 0;
607
+ if (codePoint < start) high = middle - 1;
608
+ else if (codePoint > end) low = middle + 1;
609
+ else return true;
610
+ }
611
+ return false;
612
+ }
613
+
614
+ /**
615
+ * The columns one grapheme cluster occupies, as the host charges it (`graphemeWidth`,
616
+ * `pi-tui/dist/utils.js:143-207`), in the host's own order:
617
+ *
618
+ * 1. a lone printable ASCII byte is one column, a lone TAB three;
619
+ * 2. a cluster of terminal-spacing marks is its code point count (a lone `ि` is one, not zero);
620
+ * 3. a cluster of ignorables, controls, marks and surrogates is zero;
621
+ * 4. an RGI emoji (after the host's prefilter) is two, so `©`/`☺` are NOT emoji and `©️`/`1️⃣` are;
622
+ * 5. a leading regional-indicator pair is two; otherwise the base's East Asian width;
623
+ * 6. every trailing terminal-spacing mark adds one, and every VISIBLE code point that follows a
624
+ * mark adds its own width — which is why an Indic conjunct such as `क्‍ष` is TWO columns (base
625
+ * `क` plus the consonant `ष` after the virama), not one. Halfwidth/fullwidth forms and the
626
+ * Thai/Lao AM vowels add their own columns on the same walk.
627
+ */
628
+ function clusterColumns(cluster: string): number {
629
+ // The host's own fast path (`graphemeWidth`, `:149-159`).
630
+ if (cluster.length === 1) {
631
+ const code = cluster.charCodeAt(0);
632
+ if (code >= 0x20 && code <= 0x7e) return 1;
633
+ if (code === 0x09) return TAB_COLUMNS;
634
+ }
635
+ if (TERMINAL_SPACING_MARK.test(cluster)) return [...cluster].length;
636
+ if (ZERO_WIDTH_CLUSTER.test(cluster)) return 0;
637
+ if (couldBeEmoji(cluster) && RGI_EMOJI.test(cluster)) return 2;
638
+
639
+ const base = cluster.replace(LEADING_NON_PRINTING, "");
640
+ const codePoint = base.codePointAt(0);
641
+ if (codePoint === undefined) return 0;
642
+ if (codePoint >= 0x1f1e6 && codePoint <= 0x1f1ff) return 2;
643
+
644
+ let width = isEastAsianWide(codePoint) ? 2 : 1;
645
+ let followsMark = false;
646
+ for (const char of [...base].slice(1)) {
647
+ if (TERMINAL_SPACING_MARK.test(char)) {
648
+ width += 1;
649
+ followsMark = false;
650
+ continue;
651
+ }
652
+ if (MARK_CHAR.test(char)) {
653
+ followsMark = true;
654
+ continue;
655
+ }
656
+ if (NON_PRINTING_CHAR.test(char)) continue;
657
+ const trailing = char.codePointAt(0) ?? 0;
658
+ if (followsMark) width += isEastAsianWide(trailing) ? 2 : 1;
659
+ else if (trailing >= 0xff00 && trailing <= 0xffef) width += isEastAsianWide(trailing) ? 2 : 1;
660
+ else if (trailing === 0x0e33 || trailing === 0x0eb3) width += 1;
661
+ followsMark = false;
662
+ }
663
+ return width;
664
+ }
665
+
666
+ /**
667
+ * The visible columns of one row, SGR ignored, counted CODE POINT by code point. This is NOT the
668
+ * host's model: it charges a TAB one column, ignores no OSC/APC sequence and splits a grapheme
669
+ * cluster. Anything measured for the host's frame uses `hostColumns`.
670
+ */
671
+ export function visibleColumns(line: string): number {
672
+ let columns = 0;
673
+ let index = 0;
674
+ while (index < line.length) {
675
+ SGR_AT.lastIndex = index;
676
+ const escape = SGR_AT.exec(line);
677
+ if (escape !== null) {
678
+ index += escape[0].length;
679
+ continue;
680
+ }
681
+ const char = String.fromCodePoint(line.codePointAt(index) ?? 0);
682
+ index += char.length;
683
+ columns += cellWidth(char);
684
+ }
685
+ return columns;
686
+ }
687
+
688
+ /**
689
+ * Clip one row to the host's width, measured and cut the way the host measures and cuts.
690
+ *
691
+ * A row that already fits under `hostColumns` is returned BYTE-IDENTICAL, escapes included: the
692
+ * host's own rows must survive a transform that did not touch them (an OSC-8 hyperlink made this
693
+ * model disagree with pi-tui, and a fitting row was cut on the right).
694
+ *
695
+ * A row that must be cut keeps every escape it reaches whole, charges a TAB three columns and a
696
+ * grapheme cluster as a unit, and never splits one. An OSC-8 link left open by the cut is closed
697
+ * and an active SGR is reset, so the cut cannot leak a link or a paint into the following rows.
698
+ * Nothing is ever appended to fit: padding is the style's business.
699
+ */
700
+ export function clipToWidth(line: string, width: number): string {
701
+ // W2-2 first, at every width: a row that already fits is the same bytes. Measured the host's way,
702
+ // an ANSI-only row has zero columns, so it survives even at width zero.
703
+ if (hostColumns(line) <= width) return line;
704
+ if (width <= 0) return "";
705
+
706
+ // Segment the VISIBLE text, not one escape-free run at a time: an SGR sequence may sit inside a
707
+ // grapheme cluster (`👨` + SGR + `‍👩‍👧‍👦`), and cutting at a run boundary split that cluster.
708
+ // Every visible character is mapped back to where it starts in the raw row, so the kept prefix is
709
+ // one raw slice — escapes interleaved with the clusters that were kept, nothing half-emitted.
710
+ const visible: string[] = [];
711
+ const rawAt: number[] = [];
712
+ let index = 0;
713
+ while (index < line.length) {
714
+ const escape = hostEscapeAt(line, index);
715
+ if (escape !== undefined) {
716
+ index += escape.length;
717
+ continue;
718
+ }
719
+ rawAt.push(index);
720
+ visible.push(String.fromCodePoint(line.codePointAt(index) ?? 0));
721
+ index += visible[visible.length - 1]?.length ?? 1;
722
+ }
723
+ rawAt.push(line.length);
724
+
725
+ let used = 0;
726
+ let kept = 0;
727
+ let codePoints = 0;
728
+ for (const cluster of graphemes(visible.join(""))) {
729
+ const cells = cluster === "\t" ? TAB_COLUMNS : clusterColumns(cluster);
730
+ if (used + cells > width) break;
731
+ used += cells;
732
+ codePoints += [...cluster].length;
733
+ kept = codePoints;
734
+ }
735
+
736
+ let output = line.slice(0, rawAt[kept] ?? line.length);
737
+ let styled = false;
738
+ let linkOpen = false;
739
+ let scan = 0;
740
+ while (scan < output.length) {
741
+ const escape = hostEscapeAt(output, scan);
742
+ if (escape === undefined) {
743
+ scan += 1;
744
+ continue;
745
+ }
746
+ if (escape.code.endsWith("m")) styled = true;
747
+ const target = osc8Target(escape.code);
748
+ if (target !== undefined) linkOpen = target !== "";
749
+ scan += escape.length;
750
+ }
751
+ if (linkOpen) output += OSC8_CLOSE;
752
+ return styled ? `${output}${RESET}` : output;
753
+ }
754
+
755
+ /** How many columns the host charges for a TAB (`graphemeWidth`, `pi-tui/dist/utils.js:148-155`). */
756
+ const TAB_COLUMNS = 3;
757
+
758
+ /** The OSC-8 close, so a link opened before a cut does not stay clickable over the rows after it. */
759
+ const OSC8_CLOSE = "\u001b]8;;\u0007";
760
+
761
+ // ---------------------------------------------------------------------------------------------
762
+ // The transform
763
+ // ---------------------------------------------------------------------------------------------
764
+
765
+ /** What one card is redrawn with, computed once. */
766
+ function repaintCard(
767
+ lines: readonly string[],
768
+ card: CardSpan,
769
+ style: CardStyleRegistration,
770
+ width: number,
771
+ ): string[] {
772
+ const heading = extractHeading(lines[card.header] ?? "");
773
+ const output: string[] = [
774
+ clipToWidth(style.frame.top({ width, title: heading.title, hint: heading.hint }), width),
775
+ ];
776
+
777
+ const stripped = lines.map((line) => stripAnsi(line));
778
+ for (let row = card.bodyStart; row < card.bodyEnd; row += 1) {
779
+ output.push(
780
+ clipToWidth(
781
+ style.frame.line({
782
+ text: rowText(stripped[row] ?? ""),
783
+ width,
784
+ first: row === card.bodyStart,
785
+ }),
786
+ width,
787
+ ),
788
+ );
789
+ }
790
+
791
+ output.push(clipToWidth(style.frame.bottom({ width }), width));
792
+ return output;
793
+ }
794
+
795
+ /** Resolve the selection, recording what it means instead of ever throwing. */
796
+ function activeStyle(surface: PaintSurface): CardStyleRegistration | undefined {
797
+ let selection: CardStyleSelection;
798
+ try {
799
+ selection = resolveCardStyleSelection();
800
+ } catch (error) {
801
+ const message = errorMessage(error);
802
+ recordFailure("(selection)", message);
803
+ recordOutcome(surface, { kind: "failed", styleId: "(selection)", message });
804
+ return undefined;
805
+ }
806
+ if (selection.kind === "native") {
807
+ recordOutcome(surface, { kind: "pass-through", reason: "native" });
808
+ return undefined;
809
+ }
810
+ if (selection.kind === "missing") {
811
+ // S12: a selection nobody owns must not render chrome that no longer exists.
812
+ recordOutcome(surface, { kind: "pass-through", reason: "missing" });
813
+ return undefined;
814
+ }
815
+ return selection.style;
816
+ }
817
+
818
+ /**
819
+ * Rewrite every float card in `lines` with the selected style's chrome (S3, R1), or return `lines`
820
+ * itself when there is nothing to do or anything at all went wrong (S6, R2).
821
+ *
822
+ * One function serves every surface: the conversation wrapper (`./card-style-wiring.ts`) calls it
823
+ * with `conversation`, the rail wrapper with `rail`, and the frame is treated identically — the
824
+ * grammar, the clipping and the pass-through are the same code (R1: no second copy of the
825
+ * transform). `surface` only decides WHERE the frame outcome is recorded, so the diagnostics record can
826
+ * answer for both.
827
+ *
828
+ * The returned array is the input instance whenever the frame was not changed: `native`, no
829
+ * selection, a selection naming a style that no longer exists, no card in the frame, or a throw.
830
+ */
831
+ export function transformCardLines(
832
+ lines: string[],
833
+ width: number,
834
+ surface: PaintSurface = "conversation",
835
+ ): string[] {
836
+ const style = activeStyle(surface);
837
+ if (style === undefined) return lines;
838
+
839
+ try {
840
+ const cards = findCards(lines);
841
+ if (cards.length === 0) {
842
+ recordOutcome(surface, { kind: "pass-through", reason: "no-card" });
843
+ return lines;
844
+ }
845
+
846
+ const output: string[] = [];
847
+ let cursor = 0;
848
+ for (const card of cards) {
849
+ output.push(...lines.slice(cursor, card.start));
850
+ output.push(...repaintCard(lines, card, style, width));
851
+ cursor = card.closer + 1;
852
+ }
853
+ output.push(...lines.slice(cursor));
854
+ recordOutcome(surface, { kind: "transformed", styleId: style.id, cards: cards.length });
855
+ return output;
856
+ } catch (error) {
857
+ const message = errorMessage(error);
858
+ recordFailure(style.id, message);
859
+ recordOutcome(surface, { kind: "failed", styleId: style.id, message });
860
+ return lines;
861
+ }
862
+ }