pi-odd-worktree 3.0.1 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,706 @@
1
+ 'use strict';
2
+ // The `diff` DESIGN: the second `registerToolDesign` line this package contributes, over `write` and
3
+ // `edit`, drawn as an IDE pane in the ACTIVE THEME's own roles.
4
+ //
5
+ // It is the same shape as `lib/bash-design.js`: a registration on gentle-shell-bridge's published
6
+ // API, not a renderer. The bridge owns Pi's one `registerToolRenderer` resolver, builds the HOST's
7
+ // own card and hands this module the rows that card drew:
8
+ //
9
+ // apply(lines, { width, tool, theme, part, render }) -> lines
10
+ //
11
+ // ONE line, `diff`, covers the two tools that change a file. `/gentle:customize` -> `Cards` draws
12
+ // it as `Card diff`, keeps the host's own card first as `default` (stored `native`) and shows this
13
+ // design's value as `color`. The line is UNSCOPED: the path scope belongs to the `Card tags`
14
+ // line's own claim on the same two tools (gentle-shell-bridge 0.9.0 maps a scope to ONE
15
+ // (`line`, `tool`) claim, so one unscoped claim and any number of scoped ones coexist), and a call
16
+ // that line owns is painted by it before this one is asked.
17
+ //
18
+ // What it draws:
19
+ // * `write` — an IDE pane built from the call's own `content`: a line-number gutter and the
20
+ // syntax-highlighted body the host's highlighter paints (`agent.highlightCode` through the seam
21
+ // `extensions/odd-worktree-tools.ts` hands over, exactly the one `/files` uses). Collapsed shows
22
+ // the host's own budget (ten lines) and states the rest in a fold row; `ctx.render.expanded`
23
+ // shows all of it. The pane is measured and clipped to the width it draws at as PLAIN text and
24
+ // painted afterwards (invariant 17), so no painted row is ever measured or clipped.
25
+ //
26
+ // WHERE it draws is the host's shape, not this module's. Gentle Shell's quiet tool card is
27
+ // `renderShell: "self"` and splits one card across the two halves: the CALL rows are the frame's
28
+ // top rule — the heading and, once the call finished, the host's own `ctrl+o to expand` hint —
29
+ // and the RESULT rows are the body between the frame's sides plus the closing rule. So the call
30
+ // half is handed back BYTE for BYTE (nothing of the host's frame or hint is lost), and the pane
31
+ // is painted in the result half INSIDE that frame: the host's leading band row (float) and its
32
+ // closing rule stay exactly as drawn, and every pane row reuses the host's own frame cells —
33
+ // `│ `…` │` for neon, ` ▎ `…three columns for float — measured against the frame's inner width.
34
+ // A host whose rows carry no frame (Pi's own shell draws the frame outside the renderer, so the
35
+ // design only ever sees the body there) gets the whole pane from the call half instead, and the
36
+ // host's own hint row, when it drew one, follows the fold row unchanged. No hint is ever
37
+ // invented and none is ever dropped.
38
+ // * `edit` — the host's own diff, recoloured: additions in the theme's `toolDiffAdded` role,
39
+ // deletions in `toolDiffRemoved`, hunk headers and context in `muted`/`text`, and the code of a
40
+ // row highlighted with the language `args.path` names. The row's text is never changed, so its
41
+ // width survives, and the transform is idempotent: a row already wearing this paint comes back
42
+ // identical.
43
+ //
44
+ // S6: every bridge member stays optional and defensive. A bridge without `registerToolDesign`, or
45
+ // one older than the release that can take a second line on these two tools (0.9.0, whose per-
46
+ // (`line`, `tool`) claim is what lets `diff` and `tools` both name a write), registers NOTHING: the
47
+ // host keeps drawing its own card and no value is offered for a row the bridge would refuse.
48
+ //
49
+ // Nothing here writes a colour: every colour is a theme role handed to `theme.fg`, every throw
50
+ // degrades to the host's rows, and a path the FILE card claims (`lib/skill-odd-card.js`) is left
51
+ // exactly as the host drew it.
52
+
53
+ const { charColumns, textColumns, visibleChars } = require('./bash-frame.js');
54
+ const { fileCardIdentity } = require('./skill-odd-card.js');
55
+
56
+ // The bridge line this design is the value of. The bridge names the row `Card <line>` — `Card diff`.
57
+ const LINE_NAME = 'diff';
58
+ // The tools the line covers: the two that change a file.
59
+ const WRITE_TOOL = 'write';
60
+ const EDIT_TOOL = 'edit';
61
+ // The bridge release that can take a per-(`line`, `tool`) claim (gentle-shell-bridge 0.9.0). Older
62
+ // releases let ONE line own a tool and refuse a second one whole, so this design is registered only
63
+ // where the release is known to read the claim: an unregistered row is better than a refusal.
64
+ const LINE_VERSION = [0, 9, 0];
65
+ // Stable across loads and unique per line: a reload replaces this design, never stacks one.
66
+ const DIFF_DESIGN_ID = 'odd-worktree.diff';
67
+ // The value the user reads on the bridge's line, next to the reserved `default`.
68
+ const DIFF_DESIGN_LABEL = 'color';
69
+ const DIFF_DESIGN_PLUGIN_NAME = 'Odd worktree';
70
+
71
+ // Pi's own collapsed budget for a write body (`dist/core/tools/renderers/write.js`), so the pane is
72
+ // as tall as the card it replaces and `ctrl+o` reveals the rest exactly as it did.
73
+ const COLLAPSED_LINES = 10;
74
+ // The narrowest pane that still reads as an IDE: a gutter plus a few columns of code. Below it the
75
+ // host's own rows are drawn instead of a broken layout.
76
+ const MIN_CODE_COLUMNS = 8;
77
+ // The narrowest gutter: two digits, a rule and a space.
78
+ const MIN_NUMBER_WIDTH = 2;
79
+ // Trailing cells that are the host's frame rather than the row's own text.
80
+ const TRAILING_CHROME = new Set(['│', '▎', '|', '┃', '║', '╮', '╯']);
81
+
82
+ // The bridge keeps ONE persisted value per line in its own store (`bridge-tool-designs` ->
83
+ // `selections` -> `{ "$lines": { "diff": <design id> } }`, documented in the bridge's contract). It
84
+ // has no notion of a default design: an absent value reads `native`. So a first run would open on
85
+ // `default` unless this package offers `color` once, itself.
86
+ const BRIDGE_SELECTION_STORE = 'bridge-tool-designs';
87
+ const BRIDGE_SELECTION_KEY = 'selections';
88
+ const BRIDGE_LINES_KEY = '$lines';
89
+ // This package's own marker that `color` was already offered on this machine. Without it a user who
90
+ // later picks `default` would get `color` back on the next load.
91
+ const OWN_STORE = 'odd-worktree';
92
+ const SEEDED_KEY = 'diffDesignSeeded';
93
+
94
+ // Nothing here caches a drawing or a highlight. A theme is a LIVE object Pi can switch under a
95
+ // renderer and the host's highlighter resolves the global theme on every call, so a cached row — or a
96
+ // cached escape — is a function of state this module cannot key (see `highlightLines` and
97
+ // `applyDiffDesign`). The card re-renders only while a call streams or when something repaints.
98
+
99
+ // ---- plain text, measured before it is painted (invariant 17) ----
100
+
101
+ /** A row's visible characters, every escape dropped. */
102
+ function plainOf(row) {
103
+ return visibleChars(row).map((entry) => entry.char).join('');
104
+ }
105
+
106
+ /** `text` clipped to `width` columns with an ellipsis; plain text in, plain text out. */
107
+ function clipPlain(text, width, ellipsis = '…') {
108
+ const target = Math.max(0, Math.floor(width));
109
+ if (target <= 0) return '';
110
+ if (textColumns(text) <= target) return text;
111
+ const markColumns = textColumns(ellipsis);
112
+ if (markColumns > target) return clipPlain(text, target, '');
113
+ const keep = target - markColumns;
114
+ let kept = '';
115
+ let used = 0;
116
+ for (const char of text) {
117
+ const columns = charColumns(char);
118
+ if (used + columns > keep) break;
119
+ kept += char;
120
+ used += columns;
121
+ }
122
+ return `${kept}${ellipsis}`;
123
+ }
124
+
125
+ /** One theme role's paint, or the plain text when this theme cannot paint that role. */
126
+ function paint(theme, role, text) {
127
+ try {
128
+ if (theme === null || typeof theme !== 'object' || typeof theme.fg !== 'function') return text;
129
+ const painted = theme.fg(role, text);
130
+ return typeof painted === 'string' && painted.includes(text) ? painted : text;
131
+ } catch {
132
+ return text;
133
+ }
134
+ }
135
+
136
+ /** The path a call names: `path` first (the stable field), then the alias Pi's own write reads. */
137
+ function callPath(args) {
138
+ if (args === null || typeof args !== 'object') return undefined;
139
+ if (typeof args.path === 'string' && args.path.length > 0) return args.path;
140
+ if (typeof args.file_path === 'string' && args.file_path.length > 0) return args.file_path;
141
+ return undefined;
142
+ }
143
+
144
+ // ---- the host's highlighter, through the seam this package already wraps for `/files` ----
145
+
146
+ /**
147
+ * The language `path` names, or `undefined`. The seam is `filesAgentSeam`'s: `getLanguageFromPath`
148
+ * answers a language only when Pi knows one, and every throw degrades to no language at all.
149
+ */
150
+ function languageOf(path, seam) {
151
+ try {
152
+ if (typeof path !== 'string' || path.length === 0) return undefined;
153
+ const read = seam !== null && typeof seam === 'object' ? seam.languageForPath : undefined;
154
+ if (typeof read !== 'function') return undefined;
155
+ const language = read(path);
156
+ return typeof language === 'string' && language.length > 0 ? language : undefined;
157
+ } catch {
158
+ return undefined;
159
+ }
160
+ }
161
+
162
+ /**
163
+ * `text` as the host's own highlighter paints it — one string per line, the theme's roles already
164
+ * applied — or `undefined` when there is no highlighter, it throws, or it hands back different text
165
+ * than it was given. A paint never changes what the row says, so a line count or a text that
166
+ * disagrees is not a paint and the caller draws plain text instead.
167
+ *
168
+ * S1: NOT memoized, deliberately. The host's highlighter resolves the ACTIVE theme on every call, so
169
+ * its answer is a function of the theme as well as of the text — and a theme is a live object Pi can
170
+ * switch under a renderer, with roles this module cannot enumerate to fingerprint. A cache keyed on
171
+ * (seam, language, text) would therefore hand a switched theme the syntax escapes of the old one,
172
+ * which is the one thing this card exists to get right. The card re-renders only while a call streams
173
+ * or when something repaints, so correctness is cheaper than the stale colour.
174
+ */
175
+ function highlightLines(text, language, seam) {
176
+ const plain = String(text).split('\n');
177
+ try {
178
+ const highlight = seam !== null && typeof seam === 'object' ? seam.highlight : undefined;
179
+ if (typeof highlight !== 'function') return undefined;
180
+ const answer = highlight(String(text), language);
181
+ const usable = Array.isArray(answer)
182
+ && answer.length === plain.length
183
+ && answer.every((line, index) => typeof line === 'string' && plainOf(line) === plain[index]);
184
+ return usable ? answer : undefined;
185
+ } catch {
186
+ return undefined;
187
+ }
188
+ }
189
+
190
+ // ---- the `write` pane ----
191
+
192
+ /** The content a write draws, tabs expanded and trailing blank lines dropped, exactly as the host does. */
193
+ function contentLines(content) {
194
+ const expanded = String(content).replace(/\t/g, ' ');
195
+ const lines = expanded.split('\n');
196
+ let end = lines.length;
197
+ while (end > 0 && lines[end - 1] === '') end -= 1;
198
+ return lines.slice(0, end);
199
+ }
200
+
201
+ /** The pane's width, or `undefined` when the host gave none to draw at. */
202
+ function paneWidth(width) {
203
+ if (typeof width !== 'number' || !Number.isFinite(width)) return undefined;
204
+ const target = Math.floor(width);
205
+ return target > 0 ? target : undefined;
206
+ }
207
+
208
+ /**
209
+ * The heading row: the tool and the path it wrote, with the file's line count right-aligned when
210
+ * the columns are there. Composed as plain text, clipped as plain text, painted afterwards.
211
+ */
212
+ function headingRow(path, total, width, theme) {
213
+ const head = `✎ ${WRITE_TOOL}`;
214
+ const count = `${total} ${total === 1 ? 'line' : 'lines'}`;
215
+ const countColumns = textColumns(count);
216
+ const keepsCount = textColumns(head) + 1 + 1 + countColumns + 2 <= width;
217
+ const pathRoom = width - textColumns(head) - 1 - (keepsCount ? countColumns + 2 : 0);
218
+ const shownPath = typeof path === 'string' && path.length > 0 && pathRoom >= 1 ? clipPlain(path, pathRoom) : '';
219
+ let row = paint(theme, 'toolTitle', head);
220
+ let used = textColumns(head);
221
+ if (shownPath !== '') {
222
+ row += ` ${paint(theme, 'accent', shownPath)}`;
223
+ used += 1 + textColumns(shownPath);
224
+ }
225
+ if (keepsCount) {
226
+ const gap = Math.max(1, width - used - countColumns);
227
+ row += `${' '.repeat(gap)}${paint(theme, 'muted', count)}`;
228
+ used += gap + countColumns;
229
+ }
230
+ return row + ' '.repeat(Math.max(0, width - used));
231
+ }
232
+
233
+ /**
234
+ * One body row: the line-number gutter and the code. `painted` is the highlighter's own line for
235
+ * this code, used only when the whole line fits — the clip is a PLAIN measurement, so a clipped
236
+ * line is drawn as plain text in the theme's `text` role rather than cut out of a painted string.
237
+ */
238
+ function codeRow(spec) {
239
+ const number = String(spec.number).padStart(spec.numberWidth);
240
+ const gutterPlain = `${number} │ `;
241
+ const room = spec.width - textColumns(gutterPlain);
242
+ let code = spec.code;
243
+ let painted = spec.painted;
244
+ if (room <= 0) {
245
+ code = '';
246
+ painted = undefined;
247
+ } else if (textColumns(code) > room) {
248
+ code = clipPlain(code, room);
249
+ painted = undefined;
250
+ }
251
+ const gutter = `${paint(spec.theme, 'muted', number)} ${paint(spec.theme, 'dim', '│')} `;
252
+ const body = typeof painted === 'string' ? painted : paint(spec.theme, 'text', code);
253
+ const used = textColumns(gutterPlain) + textColumns(code);
254
+ return `${gutter}${body}${' '.repeat(Math.max(0, spec.width - used))}`;
255
+ }
256
+
257
+ /** The row that states how much of a collapsed body is folded away. */
258
+ function foldRow(remaining, numberWidth, width, theme) {
259
+ const plain = `${' '.repeat(numberWidth)} … +${remaining} ${remaining === 1 ? 'line' : 'lines'}`;
260
+ const shown = clipPlain(plain, width);
261
+ return `${paint(theme, 'muted', shown)}${' '.repeat(Math.max(0, width - textColumns(shown)))}`;
262
+ }
263
+
264
+ // A cell the host's own card draws around its body. Its first non-space column is one of these on
265
+ // every row of a framed card, and on no row of Pi's renderer output (whose shell is drawn outside).
266
+ const FRAME_CELLS = new Set(['╭', '╰', '│', '▎']);
267
+ // The words the host's own affordance states in its own row: `ctrl+o to expand` / `… to collapse`.
268
+ const EXPAND_HINT = /to (?:expand|collapse)\b/iu;
269
+ // The rows a framed card's frame cells may stand on, once the row's leading margin is skipped.
270
+ const FRAME_LEADS = [
271
+ ['│', ' ', 2],
272
+ [' ', '▎', 3],
273
+ ['▎', ' ', 2],
274
+ ];
275
+
276
+ /** Whether the host drew its frame AROUND these rows, rather than outside them. */
277
+ function framed(lines) {
278
+ return lines.some((row) => {
279
+ if (typeof row !== 'string') return false;
280
+ const first = visibleChars(row).find((entry) => entry.char !== ' ');
281
+ return first !== undefined && FRAME_CELLS.has(first.char);
282
+ });
283
+ }
284
+
285
+ /**
286
+ * The frame one host BODY row wears, as the host's OWN bytes: the leading cells (margin, side and
287
+ * lead) and the same number of trailing columns — the space before the rail, the rail and the
288
+ * margin — which is where the host's background reset lives. `undefined` when the row wears no
289
+ * frame, so a host that draws its frame outside its renderer is never treated as if it did.
290
+ */
291
+ function frameOf(row) {
292
+ if (typeof row !== 'string') return undefined;
293
+ const chars = visibleChars(row);
294
+ const lead = FRAME_LEADS.find(([first, second]) => chars[0]?.char === first && chars[1]?.char === second);
295
+ if (lead === undefined) return undefined;
296
+ const columns = lead[2];
297
+ if (chars[columns - 1]?.char !== ' ' || chars.length < columns * 2) return undefined;
298
+ const lastPrefix = chars[columns - 1];
299
+ const beforeSuffix = chars[chars.length - columns - 1];
300
+ return {
301
+ columns,
302
+ prefix: row.slice(0, lastPrefix.raw + lastPrefix.char.length),
303
+ tail: row.slice(beforeSuffix.raw + beforeSuffix.char.length),
304
+ };
305
+ }
306
+
307
+ /** Whether a framed row carries no body content of its own — the band row a float card pads with. */
308
+ function bandRow(row, frame) {
309
+ if (typeof row !== 'string') return false;
310
+ const chars = visibleChars(row);
311
+ if (chars.length < frame.columns * 2) return false;
312
+ return chars.slice(frame.columns, chars.length - frame.columns).every((entry) => entry.char === ' ');
313
+ }
314
+
315
+ /**
316
+ * The pane's body rows at `width` columns: the numbered lines and — collapsed, with more content
317
+ * than the host's budget — the fold row. No heading: a framed host's own frame already states the
318
+ * call, and the unframed caller composes its heading beside this.
319
+ */
320
+ function bodyPane(body, highlighted, expanded, numberWidth, width, theme) {
321
+ const shown = expanded ? body.length : Math.min(body.length, COLLAPSED_LINES);
322
+ const out = [];
323
+ for (let index = 0; index < shown; index += 1) {
324
+ out.push(codeRow({
325
+ number: index + 1,
326
+ numberWidth,
327
+ code: body[index],
328
+ painted: highlighted === undefined ? undefined : highlighted[index],
329
+ width,
330
+ theme,
331
+ }));
332
+ }
333
+ if (shown < body.length) out.push(foldRow(body.length - shown, numberWidth, width, theme));
334
+ return out;
335
+ }
336
+
337
+ /** The body one call's pane draws, or `undefined` when there is nothing to draw at `width`. */
338
+ function paneBody(render, seam, width) {
339
+ if (typeof width !== 'number' || width <= 0) return undefined;
340
+ const content = render?.args?.content;
341
+ if (typeof content !== 'string' || content.length === 0) return undefined;
342
+ const body = contentLines(content);
343
+ if (body.length === 0) return undefined;
344
+ const numberWidth = Math.max(MIN_NUMBER_WIDTH, String(body.length).length);
345
+ if (width < numberWidth + 3 + MIN_CODE_COLUMNS) return undefined;
346
+ const highlighted = highlightLines(body.join('\n'), languageOf(callPath(render?.args), seam), seam);
347
+ return { body, highlighted, numberWidth };
348
+ }
349
+
350
+ /**
351
+ * The pane painted INSIDE the host's own frame, for the half of the card that draws the body: the
352
+ * host's leading band row and its closing rule come back byte for byte, the pane takes the place of
353
+ * the body rows between them, and every pane row reuses the host's own frame cells so the tone paint
354
+ * and the background reset stay exactly where the host put them.
355
+ *
356
+ * `undefined` when these rows wear no frame, the call failed (its error rows ARE the card), or there
357
+ * is nothing to draw — the host's card is then drawn as it is.
358
+ */
359
+ function framedPane(lines, ctx, render, seam) {
360
+ if (render?.isError === true) return undefined;
361
+ const closing = lines.length - 1;
362
+ if (closing < 1) return undefined;
363
+ const frame = frameOf(lines[closing - 1]);
364
+ if (frame === undefined) return undefined;
365
+ const width = paneWidth(ctx.width);
366
+ if (width === undefined) return undefined;
367
+ const inner = width - frame.columns * 2;
368
+ const pane = paneBody(render, seam, inner);
369
+ if (pane === undefined) return undefined;
370
+ const rows = bodyPane(pane.body, pane.highlighted, render?.expanded === true, pane.numberWidth, inner, ctx.theme);
371
+ const lead = bandRow(lines[0], frame) ? [lines[0]] : [];
372
+ return [...lead, ...rows.map((row) => `${frame.prefix}${row}${frame.tail}`), lines[closing]];
373
+ }
374
+
375
+ /** The host's own expand-affordance rows, exactly as it drew them. */
376
+ function hintRows(lines) {
377
+ return lines.filter((row) => typeof row === 'string' && EXPAND_HINT.test(plainOf(row)));
378
+ }
379
+
380
+ /**
381
+ * The whole pane, heading included, for a host whose renderer output carries no frame (Pi draws its
382
+ * own shell AROUND the renderer, so a design sees the body alone there). The host's own expand-hint
383
+ * row, when it drew one, follows the fold row exactly as drawn; when it drew none, none is invented.
384
+ */
385
+ function unframedPane(lines, ctx, render, seam) {
386
+ const width = paneWidth(ctx.width);
387
+ if (width === undefined) return undefined;
388
+ const pane = paneBody(render, seam, width);
389
+ if (pane === undefined) return undefined;
390
+ const out = [headingRow(callPath(render?.args), pane.body.length, width, ctx.theme)];
391
+ out.push(...bodyPane(pane.body, pane.highlighted, render?.expanded === true, pane.numberWidth, width, ctx.theme));
392
+ return [...out, ...hintRows(lines)];
393
+ }
394
+
395
+ /**
396
+ * The call half of a `write`. A framed host owns this half — its top rule, the heading and its own
397
+ * `ctrl+o to expand` hint ride it — so it comes back byte for byte. An unframed host draws the whole
398
+ * card here, so the pane is drawn here and any hint row it drew is kept after the fold row.
399
+ */
400
+ function writeCallRows(lines, ctx, render, seam) {
401
+ if (framed(lines)) return [...lines];
402
+ return unframedPane(lines, ctx, render, seam) ?? [...lines];
403
+ }
404
+
405
+ // ---- the `edit` diff, recoloured ----
406
+
407
+ const HUNK = /^@@/u;
408
+ const ADDED = /^\+(\s*\d*)\s/u;
409
+ const REMOVED = /^-(\s*\d*)\s/u;
410
+ const CONTEXT = /^(\d+)\s/u;
411
+ const HUNK_TOKEN = /^@@.*?@@/u;
412
+ // The cells a diff row's own text is padded by on the left: the frame's sides and its spaces.
413
+ const LEADING_CHROME = new Set([' ', '│', '▎', '|', '┃', '║']);
414
+ // A run of SGR sequences at one EDGE of the bytes a row keeps: the paint standing immediately
415
+ // before the span this design repaints, and the one immediately after it. Both govern only that
416
+ // span, which is rebuilt from the row's plain text, so dropping them is what makes a second pass a
417
+ // no-op (S8b) — and a row that never wore this paint loses nothing but the colour the host had just
418
+ // opened for the marker, which is repainted in this design's own role.
419
+ const TRAILING_SGR = /(?:\u001b\[[0-9;]*m)+$/u;
420
+ const LEADING_SGR = /^(?:\u001b\[[0-9;]*m)+/u;
421
+
422
+ /** The last character of a row's own TEXT, or `-1` when the row is chrome alone. */
423
+ function contentLast(chars) {
424
+ let last = chars.length - 1;
425
+ const trim = () => {
426
+ while (last >= 0 && chars[last].char === ' ') last -= 1;
427
+ };
428
+ trim();
429
+ for (let pass = 0; pass < 2 && last >= 0; pass += 1) {
430
+ if (!TRAILING_CHROME.has(chars[last].char)) break;
431
+ last -= 1;
432
+ trim();
433
+ }
434
+ return last;
435
+ }
436
+
437
+ /**
438
+ * The first character of a diff row's own text, or `-1` when the row states no diff line at all.
439
+ * The chrome the host draws around the row is skipped, never guessed from the tool: a heading, a
440
+ * blank row and a fold notice all answer `-1` and come back exactly as the host drew them.
441
+ */
442
+ function diffStart(chars) {
443
+ for (let index = 0; index < chars.length; index += 1) {
444
+ const char = chars[index].char;
445
+ if (LEADING_CHROME.has(char)) continue;
446
+ const rest = chars.slice(index).map((entry) => entry.char).join('');
447
+ if (HUNK.test(rest) || ADDED.test(rest) || REMOVED.test(rest) || CONTEXT.test(rest)) return index;
448
+ return -1;
449
+ }
450
+ return -1;
451
+ }
452
+
453
+ /**
454
+ * One diff row with this design's paint on it: the marker and the line number in the role its kind
455
+ * names, the code in the highlighter's own roles (or the theme's `text`), and every other cell of
456
+ * the host's row — the frame, its padding, the background — byte for byte. A row that is not a diff
457
+ * row, and one whose content this cannot read, come back untouched.
458
+ *
459
+ * S8b: the row is RECOGNISED and MEASURED through its plain text (`visibleChars` drops every SGR
460
+ * sequence), and the span that carries the marker and the code is rebuilt from that plain text. The
461
+ * two SGR runs that stand immediately beside that span therefore belong to text this function
462
+ * replaces, and are dropped: one is the host's own paint of the marker, the other is this design's
463
+ * own `theme.fg` codes when the row it is handed was already painted. Nothing this design added
464
+ * survives into the rewritten row, which is what makes a second pass a byte-identical no-op instead
465
+ * of a row carrying every escape twice.
466
+ */
467
+ function recolourDiffRow(row, spec) {
468
+ const chars = visibleChars(row);
469
+ const start = diffStart(chars);
470
+ if (start < 0) return row;
471
+ const last = contentLast(chars);
472
+ if (last < start) return row;
473
+ const rest = chars.slice(start, last + 1).map((entry) => entry.char).join('');
474
+ let token;
475
+ let role;
476
+ let code;
477
+ const hunk = HUNK_TOKEN.exec(rest);
478
+ if (HUNK.test(rest)) {
479
+ token = hunk === null ? '@@' : hunk[0];
480
+ role = 'muted';
481
+ code = rest.slice(token.length);
482
+ } else {
483
+ const match = ADDED.exec(rest) ?? REMOVED.exec(rest) ?? CONTEXT.exec(rest);
484
+ if (match === null) return row;
485
+ token = match[0];
486
+ role = ADDED.test(rest) ? 'toolDiffAdded' : REMOVED.test(rest) ? 'toolDiffRemoved' : 'muted';
487
+ code = rest.slice(token.length);
488
+ }
489
+ const language = spec.language;
490
+ const paintedCode = code === ''
491
+ ? ''
492
+ : highlightRow(code, role, language, spec.seam, spec.theme);
493
+ const before = row.slice(0, chars[start].raw).replace(TRAILING_SGR, '');
494
+ const after = row.slice(chars[last].raw + chars[last].char.length).replace(LEADING_SGR, '');
495
+ return `${before}${paint(spec.theme, role, token)}${paintedCode}${after}`;
496
+ }
497
+
498
+ /**
499
+ * The code of one diff row: the host's highlighter when it paints this exact line, else the plain
500
+ * text in `fallback` (the diff's own role for an addition or a deletion, `text` for context).
501
+ */
502
+ function highlightRow(code, fallback, language, seam, theme) {
503
+ if (language !== undefined) {
504
+ const painted = highlightLines(code, language, seam);
505
+ if (painted !== undefined && painted.length === 1) return painted[0];
506
+ }
507
+ return paint(theme, fallback === 'muted' ? 'text' : fallback, code);
508
+ }
509
+
510
+ /**
511
+ * Every row of an `edit` card, recoloured. Idempotent (S8b): each row is read as its PLAIN text and
512
+ * rebuilt from it, so a row already wearing this paint states the same visible characters and comes
513
+ * back byte for byte — never with a second copy of an escape or a reset.
514
+ */
515
+ function editRows(lines, render, ctx, seam) {
516
+ const language = languageOf(callPath(render?.args), seam);
517
+ return lines.map((row) => (typeof row === 'string'
518
+ ? recolourDiffRow(row, { theme: ctx.theme, language, seam })
519
+ : String(row)));
520
+ }
521
+
522
+ // ---- the design's entry point ----
523
+
524
+ /**
525
+ * The design's whole behaviour: the IDE pane for a `write`, the recoloured diff for an `edit`, and
526
+ * the host's rows byte for byte for anything it does not own. The bridge hands this to
527
+ * `registerToolDesign`; it is pure (the rows and the call in, rows out) and never throws.
528
+ *
529
+ * A `write` is drawn ONCE: a framed host keeps its call half (the frame top and its hint) and the
530
+ * pane goes inside the frame in the result half; an unframed host draws the pane on the call half
531
+ * and its result half is the host's.
532
+ *
533
+ * S4/S6: a call whose path the FILE card claims is that card's row, and it comes back exactly as
534
+ * the host drew it, whichever resolver runs first (the classification is `lib/skill-odd-card.js`'s,
535
+ * so the two surfaces can never disagree).
536
+ */
537
+ function applyDiffCard(lines, ctx, seam) {
538
+ const unchanged = () => (Array.isArray(lines) ? [...lines] : []);
539
+ try {
540
+ if (!Array.isArray(lines)) return [];
541
+ if (ctx === null || typeof ctx !== 'object') return unchanged();
542
+ const render = ctx.render !== null && typeof ctx.render === 'object' ? ctx.render : undefined;
543
+ if (fileCardIdentity(callPath(render?.args)) !== undefined) return unchanged();
544
+ if (ctx.tool === WRITE_TOOL) {
545
+ if (ctx.part === 'result') return framedPane(lines, ctx, render, seam) ?? unchanged();
546
+ return writeCallRows(lines, ctx, render, seam);
547
+ }
548
+ if (ctx.tool === EDIT_TOOL) return editRows(lines, render, ctx, seam);
549
+ return unchanged();
550
+ } catch {
551
+ return unchanged();
552
+ }
553
+ }
554
+
555
+ /**
556
+ * The design behind its never-throwing guard. S5: there is NO cache of the drawing. `args` arrives by
557
+ * reference and Pi rewrites `content` while a call streams, so a key built from its length (or from
558
+ * any other summary of it) would answer a brand-new body with the pane of the old one — and, as
559
+ * `highlightLines` says, a cached pane also carries the syntax escapes of whatever theme painted it.
560
+ * A caller always gets a fresh array.
561
+ */
562
+ function applyDiffDesign(lines, ctx, seam) {
563
+ try {
564
+ return applyDiffCard(lines, ctx, seam);
565
+ } catch {
566
+ return Array.isArray(lines) ? [...lines] : [];
567
+ }
568
+ }
569
+
570
+ // The read-only picture `/gentle:customize` draws while `color` is highlighted. ONE row, like every
571
+ // other Cards value: the gutter, a diff's two kinds and a hunk header on a single line.
572
+ const DIFF_DESIGN_PREVIEW = {
573
+ title: `Cards · ${DIFF_DESIGN_LABEL}`,
574
+ sample: ' 12 │ const total = items.length + 3 added − 1 removed @@ -1,4 +1,4 @@',
575
+ };
576
+
577
+ /** The one registration this line carries: `Card diff` over `write` and `edit`. */
578
+ function diffColorDesign(seam) {
579
+ return {
580
+ line: LINE_NAME,
581
+ tools: [WRITE_TOOL, EDIT_TOOL],
582
+ id: DIFF_DESIGN_ID,
583
+ name: DIFF_DESIGN_PLUGIN_NAME,
584
+ label: DIFF_DESIGN_LABEL,
585
+ description: 'draws a write as a syntax-highlighted IDE pane and an edit as a recoloured diff',
586
+ preview: () => ({ ...DIFF_DESIGN_PREVIEW }),
587
+ apply: (lines, ctx) => applyDiffDesign(lines, ctx, seam),
588
+ };
589
+ }
590
+
591
+ /**
592
+ * Whether the bridge's published release is at least `floor`, or `undefined` when the release string
593
+ * cannot be read as one. Read defensively: another copy of the bridge, or a host that publishes no
594
+ * release, is never mistaken for a newer one.
595
+ *
596
+ * S6: a release string carrying a prerelease or a build suffix (`0.9.0-rc.1`, `0.9.0+build.7`) does
597
+ * NOT meet a cutoff its own numbers equal. Semver puts a prerelease BELOW its release, and the package
598
+ * would rather miss a row than have a registration refused. Its numbers still clear a LOWER cutoff
599
+ * (`0.9.0-rc.1` is above 0.6.0), and a string that cannot be read at all stays `undefined` so the
600
+ * caller can fall back to its own capability probe.
601
+ */
602
+ function releaseAtLeast(version, floor) {
603
+ if (typeof version !== 'string') return undefined;
604
+ const parts = version.split('.').slice(0, 3).map((part) => {
605
+ const digits = /^\d+/u.exec(part);
606
+ return digits === null ? Number.NaN : Number(digits[0]);
607
+ });
608
+ if (parts.length < 2 || parts.some((part) => !Number.isFinite(part))) return undefined;
609
+ const suffixed = !/^\d+(?:\.\d+){1,2}$/u.test(version);
610
+ const [major, minor, patch = 0] = parts;
611
+ if (major !== floor[0]) return major > floor[0];
612
+ if (minor !== floor[1]) return minor > floor[1];
613
+ if (patch !== floor[2]) return patch > floor[2];
614
+ return !suffixed;
615
+ }
616
+
617
+ /**
618
+ * Whether a published bridge can take this line at all (gentle-shell-bridge 0.9.0). A release this
619
+ * cannot read answers NO: a probe would ask whether a grouped line is accepted, never whether a
620
+ * SECOND line may name `write`, and a refused registration is exactly the outcome S6 refuses.
621
+ */
622
+ function bridgeSupportsDiffLine(api) {
623
+ return releaseAtLeast(api?.VERSION, LINE_VERSION) === true;
624
+ }
625
+
626
+ /**
627
+ * Select `color` ONCE, on the first load that finds no choice. Returns whether it wrote the
628
+ * selection. A choice already stored on the line, `default` (stored `native`) included, is never
629
+ * touched, and the marker is written only after the selection, so a failed write is tried again on
630
+ * the next load. Never throws: the design is cosmetic.
631
+ */
632
+ function seedDiffDesignSelection(api) {
633
+ try {
634
+ if (api === null || typeof api !== 'object' || typeof api.createStore !== 'function') return false;
635
+ const own = api.createStore(OWN_STORE);
636
+ if (own.get(SEEDED_KEY, false) === true) return false;
637
+ const bridge = api.createStore(BRIDGE_SELECTION_STORE);
638
+ const stored = bridge.get(BRIDGE_SELECTION_KEY, {});
639
+ if (stored === null || typeof stored !== 'object' || Array.isArray(stored)) return false;
640
+ const lines = stored[BRIDGE_LINES_KEY];
641
+ if (lines !== undefined && (lines === null || typeof lines !== 'object' || Array.isArray(lines))) return false;
642
+ const line = lines === undefined ? undefined : lines[LINE_NAME];
643
+ if (line !== undefined) {
644
+ own.set(SEEDED_KEY, true);
645
+ return false;
646
+ }
647
+ bridge.set(BRIDGE_SELECTION_KEY, {
648
+ ...stored,
649
+ [BRIDGE_LINES_KEY]: { ...(lines ?? {}), [LINE_NAME]: DIFF_DESIGN_ID },
650
+ });
651
+ own.set(SEEDED_KEY, true);
652
+ return true;
653
+ } catch {
654
+ return false;
655
+ }
656
+ }
657
+
658
+ // The registration this process made: a second call is the same design, never two.
659
+ let designDisposer = null;
660
+
661
+ /**
662
+ * Register the design on a bridge that can take one and hand back the idempotent disposer, or `null`
663
+ * when the bridge is absent, older than the line, or refuses the registration. Never throws.
664
+ *
665
+ * The seed runs AFTER a registration that was accepted: unlike the `tools` line there is no legacy
666
+ * per-tool value for this one to inherit, so a refusal must not leave a value naming a design that
667
+ * nobody registered (the bridge's own report would call it `missing`).
668
+ */
669
+ function registerDiffDesign(api, seam) {
670
+ if (api === null || typeof api !== 'object' || typeof api.registerToolDesign !== 'function') return null;
671
+ if (designDisposer !== null) return designDisposer;
672
+ if (!bridgeSupportsDiffLine(api)) return null;
673
+ let registered;
674
+ try {
675
+ registered = api.registerToolDesign(diffColorDesign(seam));
676
+ } catch {
677
+ return null;
678
+ }
679
+ seedDiffDesignSelection(api);
680
+ const dispose = typeof registered === 'function' ? registered : () => {};
681
+ let disposed = false;
682
+ designDisposer = () => {
683
+ if (disposed) return;
684
+ disposed = true;
685
+ designDisposer = null;
686
+ try {
687
+ dispose();
688
+ } catch {
689
+ // A failed removal leaves the design registered; it never breaks the host.
690
+ }
691
+ };
692
+ return designDisposer;
693
+ }
694
+
695
+ module.exports = {
696
+ DIFF_DESIGN_ID,
697
+ DIFF_DESIGN_LABEL,
698
+ DIFF_DESIGN_PREVIEW,
699
+ LINE_VERSION,
700
+ applyDiffCard,
701
+ applyDiffDesign,
702
+ bridgeSupportsDiffLine,
703
+ diffColorDesign,
704
+ registerDiffDesign,
705
+ seedDiffDesignSelection,
706
+ };