pi-odd-worktree 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +54 -311
  2. package/extensions/odd-worktree-tools.ts +4149 -2447
  3. package/lib/bash-activity.js +1164 -0
  4. package/lib/bash-design.js +684 -0
  5. package/lib/bash-destructive.js +559 -0
  6. package/lib/bash-frame.js +205 -0
  7. package/lib/card-content.js +23 -0
  8. package/lib/card-style.js +175 -0
  9. package/lib/checkout-facts.js +30 -70
  10. package/lib/codegraph-card-preview.js +628 -0
  11. package/lib/codegraph-card.js +515 -0
  12. package/lib/codegraph-compaction.js +76 -0
  13. package/lib/codegraph-daemon.js +246 -0
  14. package/lib/codegraph-edit-sync.js +182 -0
  15. package/lib/codegraph-guard-target.js +337 -0
  16. package/lib/codegraph-guard.js +211 -0
  17. package/lib/codegraph-index.js +1020 -0
  18. package/lib/codegraph-lock.js +607 -0
  19. package/lib/codegraph-mcp-config.js +134 -0
  20. package/lib/codegraph-mcp.js +123 -0
  21. package/lib/codegraph-paths.js +69 -0
  22. package/lib/codegraph-prompt/explore.md +11 -0
  23. package/lib/codegraph-prompt/fix.md +6 -0
  24. package/lib/codegraph-prompt/generic.md +8 -0
  25. package/lib/codegraph-prompt/judge.md +9 -0
  26. package/lib/codegraph-prompt/orchestrator.md +17 -0
  27. package/lib/codegraph-prompt/verify.md +10 -0
  28. package/lib/codegraph-prompt/worker.md +7 -0
  29. package/lib/codegraph-role.js +55 -0
  30. package/lib/codegraph-rules.js +146 -0
  31. package/lib/codegraph-session.js +303 -383
  32. package/lib/codegraph-warmup.js +139 -0
  33. package/lib/file-card-markdown.js +141 -0
  34. package/lib/file-card-resolver.js +245 -0
  35. package/lib/file-card.js +659 -0
  36. package/lib/files-index.js +387 -0
  37. package/lib/files-insert.js +81 -0
  38. package/lib/files-orders.js +326 -0
  39. package/lib/files-picker-view.js +1416 -0
  40. package/lib/files-preview.js +338 -0
  41. package/lib/files-scope-detail.js +171 -0
  42. package/lib/files-scope-view.js +507 -0
  43. package/lib/gh-issues.js +308 -14
  44. package/lib/issue-preview.js +26 -7
  45. package/lib/issues-bash-mutation.js +206 -0
  46. package/lib/issues-cache-store.js +261 -0
  47. package/lib/issues-section.js +710 -0
  48. package/lib/issues-view.js +649 -52
  49. package/lib/odd-prompt/odd-worktrees.md +21 -0
  50. package/lib/odd-worktrees-prompt.js +10 -28
  51. package/lib/related-issues-cache.js +210 -0
  52. package/lib/shell-card.js +825 -0
  53. package/lib/skill-odd-card.js +183 -0
  54. package/lib/tui-paint.js +4 -5
  55. package/lib/warp-create-panel.js +538 -250
  56. package/lib/warp-create-picker.js +56 -9
  57. package/lib/warp-delete-confirm.js +19 -28
  58. package/lib/warp-selector-view.js +160 -82
  59. package/lib/which-command.js +90 -0
  60. package/lib/worktree-card.js +267 -897
  61. package/lib/worktree-cards.js +383 -0
  62. package/lib/worktree-create.js +287 -0
  63. package/lib/worktree-git.js +3 -3
  64. package/lib/worktree-guard.js +548 -0
  65. package/lib/worktree-hooks.js +421 -711
  66. package/lib/worktree-list.js +120 -0
  67. package/lib/worktree-registry.js +162 -879
  68. package/lib/{worktree-close-herdr.js → worktree-remove.js} +9 -11
  69. package/lib/worktree-setup-runner.js +376 -0
  70. package/lib/worktree-setup.js +140 -0
  71. package/lib/worktree-warp-busy.js +462 -85
  72. package/lib/worktree-warp-sessions.js +1 -2
  73. package/package.json +2 -2
  74. package/tools/bash-activity.test.js +1419 -0
  75. package/tools/bash-design.test.js +1091 -0
  76. package/tools/bash-destructive.test.js +139 -0
  77. package/tools/card-content.test.js +44 -0
  78. package/tools/card-style.test.js +298 -0
  79. package/tools/codegraph-card-preview.test.js +254 -0
  80. package/tools/codegraph-card.test.js +1080 -0
  81. package/tools/codegraph-compaction.test.js +378 -0
  82. package/tools/codegraph-daemon.test.js +248 -0
  83. package/tools/codegraph-edit-sync.test.js +295 -0
  84. package/tools/codegraph-guard-target.test.js +174 -0
  85. package/tools/codegraph-guard.test.js +238 -0
  86. package/tools/codegraph-index.test.js +1948 -0
  87. package/tools/codegraph-lock.test.js +932 -0
  88. package/tools/codegraph-mcp-config.test.js +181 -0
  89. package/tools/codegraph-mcp.test.js +194 -0
  90. package/tools/codegraph-paths.test.js +44 -0
  91. package/tools/codegraph-role.test.js +30 -0
  92. package/tools/codegraph-rules.test.js +250 -0
  93. package/tools/codegraph-session.test.js +660 -391
  94. package/tools/codegraph-warmup.test.js +316 -0
  95. package/tools/commands.test.js +510 -31
  96. package/tools/file-card-markdown.test.js +188 -0
  97. package/tools/file-card.test.js +1289 -0
  98. package/tools/files-bridge.test.js +575 -0
  99. package/tools/files-command.test.js +610 -0
  100. package/tools/files-index.test.js +473 -0
  101. package/tools/files-insert.test.js +139 -0
  102. package/tools/files-orders.test.js +597 -0
  103. package/tools/files-picker-view.test.js +1871 -0
  104. package/tools/files-preview.test.js +452 -0
  105. package/tools/files-scope-detail.test.js +264 -0
  106. package/tools/files-scope-view.test.js +614 -0
  107. package/tools/fixtures/card-codegraph-outputs.js +110 -0
  108. package/tools/fixtures/codegraph-cli-stub.js +16 -0
  109. package/tools/fixtures/codegraph-init-process.js +28 -0
  110. package/tools/fixtures/codegraph-lock-worker.js +117 -0
  111. package/tools/fixtures/daemon-fake.js +98 -0
  112. package/tools/fixtures/daemon-mcp-server.js +39 -0
  113. package/tools/fixtures/daemon-warmup-worker.js +12 -0
  114. package/tools/fixtures/load-extension.js +136 -3
  115. package/tools/gh-issues-feedback.test.js +31 -7
  116. package/tools/gh-issues.test.js +391 -1
  117. package/tools/issue-preview.test.js +44 -7
  118. package/tools/issues-bash-mutation.test.js +101 -0
  119. package/tools/issues-cache-store.test.js +222 -0
  120. package/tools/issues-command.test.js +1512 -66
  121. package/tools/issues-open-guard.test.js +1096 -0
  122. package/tools/issues-section.test.js +4195 -0
  123. package/tools/issues-seed-query-regression.test.js +67 -0
  124. package/tools/issues-view.test.js +1489 -60
  125. package/tools/odd-worktrees-prompt.test.js +98 -65
  126. package/tools/package-surface.test.js +431 -36
  127. package/tools/related-issues-cache.test.js +324 -0
  128. package/tools/shell-card.test.js +834 -0
  129. package/tools/skill-odd-card.test.js +200 -0
  130. package/tools/t5-session-identity.test.js +44 -22
  131. package/tools/warp-busy-guard.test.js +2569 -308
  132. package/tools/warp-create-panel.test.js +499 -74
  133. package/tools/warp-create-picker.test.js +101 -5
  134. package/tools/warp-delete-confirm.test.js +49 -15
  135. package/tools/warp-empty-session.test.js +0 -1
  136. package/tools/warp-fallback-regression.test.js +533 -0
  137. package/tools/warp-selector-view.test.js +460 -196
  138. package/tools/which-command.test.js +126 -0
  139. package/tools/worktree-card.test.js +551 -0
  140. package/tools/worktree-cards.test.js +845 -0
  141. package/tools/worktree-changes.test.js +4 -5
  142. package/tools/worktree-create.test.js +489 -0
  143. package/tools/worktree-guard.test.js +823 -0
  144. package/tools/worktree-hooks.test.js +905 -0
  145. package/tools/worktree-list.test.js +170 -0
  146. package/tools/worktree-registry.test.js +89 -230
  147. package/tools/worktree-remove-async.test.js +318 -0
  148. package/tools/worktree-setup-runner.test.js +276 -0
  149. package/tools/worktree-setup.test.js +140 -0
  150. package/tools/worktree-tools.test.js +477 -93
  151. package/lib/codegraph-commands.js +0 -165
  152. package/lib/odd-prompt/odd-worktrees.with-codegraph.md +0 -19
  153. package/lib/odd-prompt/odd-worktrees.without-codegraph.md +0 -15
  154. package/lib/worktree-model-result.js +0 -291
  155. package/tools/codegraph-commands.test.js +0 -371
  156. package/tools/herdr-free-create.test.js +0 -161
  157. package/tools/worktree-close-herdr-async.test.js +0 -204
  158. package/tools/worktree-odd-migration.test.js +0 -224
  159. package/tools/worktree-registry-cache.test.js +0 -163
  160. package/tools/worktree-registry-odd.test.js +0 -231
@@ -0,0 +1,1289 @@
1
+ 'use strict';
2
+ // T3 (S1/S2): the file card — a `read`, `edit` or `write` call whose path names a
3
+ // customized skill or an ODD artifact heads as that file, on this package's card
4
+ // substrate (`lib/shell-card.js`), through the host's `registerToolRenderer` hook.
5
+ //
6
+ // Every case goes through the public surface: the resolver's slots, the heading and
7
+ // row helpers the module exports, and the lines a component draws for a width.
8
+ // Nothing reads module-internal state, a repository or a terminal, and no case spawns
9
+ // anything.
10
+ //
11
+ // The text seam and the themes are the fakes `tools/bash-card.test.js` uses: this
12
+ // package has no node_modules, so width measurement, truncation and wrapping are
13
+ // injected, and colour only ever arrives as `theme.fg(role, text)`. The one switch is
14
+ // the bridge's published reader (`api.resolveToolDesignSelection`), a process-wide slot
15
+ // this file publishes and withdraws; the content level is the shell's own slot.
16
+ const assert = require('node:assert/strict');
17
+ const { readFileSync } = require('node:fs');
18
+ const { join } = require('node:path');
19
+ const { after, afterEach, beforeEach, test } = require('node:test');
20
+
21
+ const {
22
+ FILE_TOOLS,
23
+ PREVIEW_ROWS,
24
+ fileCardHeading,
25
+ fileResultRows,
26
+ } = require('../lib/file-card.js');
27
+ const { createFileCardResolver, registerFileCard } = require('../lib/file-card-resolver.js');
28
+ // The design this package registers on the bridge's `Card tools` line: the card's one
29
+ // switch is that line's answer for the tool being drawn, so the card is only painted
30
+ // for a tool the line actually covers.
31
+ const { toolsActivityDesign } = require('../lib/bash-design.js');
32
+ const { CARD_CONTENT_SLOT } = require('../lib/card-content.js');
33
+ const { CARD_STYLE, CARD_STYLE_SLOT } = require('../lib/card-style.js');
34
+
35
+ // ---- the injected text seam (fakes: plain ASCII, each character one column) ----
36
+
37
+ const ANSI = /\x1b\[[0-9;]*m/g;
38
+ const stripAnsi = (value) => value.replace(ANSI, '');
39
+ const chars = (value) => [...stripAnsi(value)];
40
+
41
+ const metrics = {
42
+ visibleWidth(value) {
43
+ return chars(value).length;
44
+ },
45
+ truncateToWidth(value, width, ellipsis = '') {
46
+ if (width <= 0) return '';
47
+ if (this.visibleWidth(value) <= width) return value;
48
+ const tail = ellipsis ?? '';
49
+ const keep = Math.max(0, width - [...tail].length);
50
+ return chars(value).slice(0, keep).join('') + tail;
51
+ },
52
+ wrapTextWithAnsi(value, width) {
53
+ const text = stripAnsi(value);
54
+ if (width <= 0) return [text];
55
+ return text.split('\n').flatMap((line) => {
56
+ const lines = [];
57
+ let current = '';
58
+ for (const word of line.split(' ')) {
59
+ const candidate = current === '' ? word : `${current} ${word}`;
60
+ if ([...candidate].length <= width) {
61
+ current = candidate;
62
+ continue;
63
+ }
64
+ if (current !== '') {
65
+ lines.push(current);
66
+ current = '';
67
+ }
68
+ if ([...word].length <= width) {
69
+ current = word;
70
+ continue;
71
+ }
72
+ const rest = [...word];
73
+ while (rest.length > width) lines.push(rest.splice(0, width).join(''));
74
+ current = rest.join('');
75
+ }
76
+ lines.push(current);
77
+ return lines;
78
+ });
79
+ },
80
+ };
81
+
82
+ const plainTheme = { fg: (_role, value) => value };
83
+
84
+ /** A theme that tags every painted cell, so a case can see which role painted what. */
85
+ const taggedTheme = {
86
+ fg(role, value) {
87
+ return `<${role}>${value}</${role}>`;
88
+ },
89
+ };
90
+
91
+ /** A theme that can paint the float band (a `bg` that returns its own reset). */
92
+ const bandTheme = {
93
+ fg: (_role, value) => value,
94
+ bg: (_role, value) => `\x1b[48;5;240m${value}\x1b[49m`,
95
+ };
96
+
97
+ // The two slots the shell publishes, and the bridge's own published object.
98
+ const BRIDGE_API_SLOT = Symbol.for('gentle-shell-bridge/api/v1');
99
+
100
+ beforeEach(() => {
101
+ globalThis[CARD_STYLE_SLOT] = CARD_STYLE.NEON;
102
+ delete globalThis[CARD_CONTENT_SLOT];
103
+ delete globalThis[BRIDGE_API_SLOT];
104
+ });
105
+
106
+ afterEach(() => {
107
+ delete globalThis[BRIDGE_API_SLOT];
108
+ });
109
+
110
+ after(() => {
111
+ delete globalThis[CARD_STYLE_SLOT];
112
+ delete globalThis[CARD_CONTENT_SLOT];
113
+ delete globalThis[BRIDGE_API_SLOT];
114
+ });
115
+
116
+ // ---- the bridge's one switch (S1/S7) ----
117
+
118
+ const ACTIVITY = Object.freeze({ kind: 'design', design: { id: 'odd-worktree.bash-activity' } });
119
+ const NATIVE = Object.freeze({ kind: 'native' });
120
+
121
+ /**
122
+ * A published bridge object, exactly as the host hands it over: identity, major version,
123
+ * its release, and the ONE optional reader this card asks. `selection` is an answer or a
124
+ * function of the tool being drawn; `asked` collects every question.
125
+ */
126
+ function publishedBridge(selection, asked) {
127
+ return {
128
+ schema: 'gentle-shell-bridge/api',
129
+ version: 1,
130
+ VERSION: '0.7.0',
131
+ registerToolDesign: () => () => {},
132
+ resolveToolDesignSelection(tool) {
133
+ if (asked !== undefined) asked.push(tool);
134
+ return typeof selection === 'function' ? selection(tool) : selection;
135
+ },
136
+ };
137
+ }
138
+
139
+ /** Publish a bridge on the slot the host publishes it on, and hand it back. */
140
+ function publishBridge(selection, asked) {
141
+ const api = publishedBridge(selection, asked);
142
+ globalThis[BRIDGE_API_SLOT] = api;
143
+ return api;
144
+ }
145
+
146
+ // ---- the resolver under test ----
147
+
148
+ function fileResolver(options) {
149
+ const registered = [];
150
+ const cards = createFileCardResolver({
151
+ metrics,
152
+ theme: plainTheme,
153
+ registerToolRenderer: (resolver) => registered.push(resolver),
154
+ ...options,
155
+ });
156
+ assert.equal(cards.registered, true, 'the probe accepted the resolver');
157
+ assert.equal(registered.length, 1, 'exactly one resolver reached the host hook');
158
+ return registered[0];
159
+ }
160
+
161
+ /** A host that draws the three file tools itself, in the DEFAULT shell: Pi's `read` and `write` renderers declare no shell, so the host wraps them in its own box. */
162
+ const HOST = {
163
+ renderCall: () => ({ render: () => ['host read call'], invalidate() {} }),
164
+ renderResult: () => ({ render: () => ['host read result'], invalidate() {} }),
165
+ };
166
+
167
+ /** A host renderer that frames itself: Pi's `edit` declares `renderShell: 'self'`, and the host draws NO box around it. */
168
+ const HOST_EDIT = {
169
+ renderShell: 'self',
170
+ renderCall: () => ({ render: () => ['host edit call'], invalidate() {} }),
171
+ renderResult: () => ({ render: () => ['host edit result'], invalidate() {} }),
172
+ };
173
+
174
+ /** The rows that carry content: the host box's own padding rows are blank. */
175
+ const boxedContent = (rows) => rows.filter((row) => unpaint(row).trim() !== '');
176
+
177
+ /** The text of the rows a forwarded group contributes, blanks aside. */
178
+ const forwardedText = (rows) => boxedContent(rows).map(unbox);
179
+
180
+ /** A background-painted blank row: the full width, and nothing on it. */
181
+ function assertBlankRow(row, width) {
182
+ assert.equal(metrics.visibleWidth(unpaint(row)), width, `the blank row is not ${width} wide: ${JSON.stringify(unpaint(row))}`);
183
+ assert.equal(unpaint(row).trim(), '', 'the blank row carries no text');
184
+ assert.ok(row.length > 0, 'the blank row is drawn, not omitted');
185
+ }
186
+
187
+ const SKILL = 'lib/skills/one/SKILL.md';
188
+ const ODD = 'odd/tasks/cards-skill-odd.md';
189
+
190
+ function callRows(resolver, tool, args, theme, width = 60, context = { isPartial: false }) {
191
+ return resolver(tool, () => HOST).renderCall(args, theme, context).render(width);
192
+ }
193
+
194
+ const callRow = (resolver, tool, args, theme, context = { isPartial: false }) => callRows(resolver, tool, args, theme, 60, context)[0];
195
+
196
+ function resultRows(resolver, tool, args, result, options = { isPartial: false }, theme = plainTheme, width = 60, context = {}) {
197
+ return resolver(tool, () => HOST).renderResult(result, options, theme, { args, ...context }).render(width);
198
+ }
199
+
200
+ const textResult = (text, extra) => ({ content: [{ type: 'text', text }], details: {}, ...(extra ?? {}) });
201
+
202
+ /** The visible text of a cell, with the ANSI a real theme paints and the tags the fake theme wraps it in removed. */
203
+ const unpaint = (value) => stripAnsi(value).replace(/<\/?[a-zA-Z][a-zA-Z0-9]*>/g, '');
204
+
205
+ /** The visible content of a body row, without the neon frame. */
206
+ const bodyText = (row) => unpaint(row).replace(/^│ /, '').replace(/ +│$/, '');
207
+
208
+ /**
209
+ * One body row's CONTENT as painted: the card's own frame cells — its side and its rail —
210
+ * removed, the content's own roles kept. The frame wears the identity's role, so a case
211
+ * about what a document's rows wear has to look past it.
212
+ */
213
+ const bodyPaint = (rows) => rows
214
+ .replace(/^<[A-Za-z]+>(?:│|▎)<\/[A-Za-z]+> /gmu, '')
215
+ .replace(/ +<[A-Za-z]+>(?:│|▎)<\/[A-Za-z]+>$/gmu, '');
216
+
217
+ /**
218
+ * The content of a row inside the host's own outer box: the box's left pad and the
219
+ * width fill removed, so a case can compare it with the row the chain itself drew.
220
+ */
221
+ const unbox = (row) => unpaint(row).replace(/^ /u, '').replace(/ +$/u, '');
222
+
223
+ /**
224
+ * A theme that records the background roles it is asked for, painted as the ANSI the
225
+ * fake metrics strips, so a case can see the host box's role and measure its width.
226
+ */
227
+ function boxTheme() {
228
+ const roles = [];
229
+ const codes = { toolPendingBg: 33, toolErrorBg: 1, toolSuccessBg: 2 };
230
+ return {
231
+ roles,
232
+ fg: (_role, value) => value,
233
+ bg(role, value) {
234
+ roles.push(role);
235
+ return `\x1b[48;5;${codes[role] ?? 9}m${value}\x1b[49m`;
236
+ },
237
+ };
238
+ }
239
+
240
+ /** Every row the card draws must be exactly the width the host asked for. */
241
+ function assertFramed(rows, width) {
242
+ for (const row of rows) assert.equal(metrics.visibleWidth(unpaint(row)), width, `"${unpaint(row)}" is not ${width} wide`);
243
+ }
244
+
245
+ // ---- the heading ----
246
+
247
+ test('a skill call heads with its mark, its label, the tool and the path', () => {
248
+ const resolver = fileResolver();
249
+ const row = callRow(resolver, 'read', { path: SKILL }, taggedTheme);
250
+ const text = unpaint(row);
251
+ assert.match(text, /▤ skill · read one\/SKILL\.md/u, text);
252
+ assert.ok(row.includes('<mdHeading>▤</mdHeading> <mdHeading>skill</mdHeading>'), 'the glyph and the label wear the theme\'s mdHeading role');
253
+ assert.ok(row.includes('<muted>·</muted>'), 'the one separator is painted muted');
254
+ assert.equal(text.split('·').length - 1, 1, 'exactly one separator');
255
+ assert.match(text, /[^ ] · [^ ]/u, 'one space on each side of the separator');
256
+ assert.match(text, /^╭─ /, 'the collapsed call is the card\'s own top rule');
257
+ assert.match(text, /╮$/, 'the row is framed');
258
+ assertFramed([row], 60);
259
+ });
260
+
261
+ // The convention is the folder, and it holds for every tool the card claims: a reference
262
+ // file below a `skills` folder is that skill's, so reading, writing or editing it heads as
263
+ // that skill, and anything below an `odd` folder heads as that ODD whatever it is called.
264
+ test('read, write and edit all wear the identity of the folder their file lives in', () => {
265
+ const resolver = fileResolver();
266
+ for (const tool of ['read', 'write', 'edit']) {
267
+ const skill = unpaint(callRow(resolver, tool, { path: 'skills/merge-pr/references/commands.md' }, plainTheme));
268
+ assert.match(skill, new RegExp(`▤ skill · ${tool} merge-pr/references/commands\\.md`, 'u'), skill);
269
+ const odd = unpaint(callRow(resolver, tool, { path: 'odd/design/notes.md' }, plainTheme));
270
+ assert.match(odd, new RegExp(`📑 odd · ${tool} notes\\.md`, 'u'), odd);
271
+ }
272
+ });
273
+
274
+ test('an odd call names its file while collapsed and its whole path once expanded', () => {
275
+ const resolver = fileResolver();
276
+ const args = { path: ODD };
277
+ const collapsed = unpaint(callRow(resolver, 'read', args, taggedTheme));
278
+ assert.match(collapsed, /📑 odd · read cards-skill-odd\.md/u, collapsed);
279
+ assert.equal(collapsed.includes('odd/tasks'), false, 'the collapsed heading names the file, not its folder');
280
+ assert.ok(
281
+ callRow(resolver, 'read', args, taggedTheme).includes('<mdHeading>📑</mdHeading> <mdHeading>odd</mdHeading>'),
282
+ 'the ODD mark and label wear the theme\'s mdHeading role',
283
+ );
284
+
285
+ const expanded = callRows(resolver, 'read', args, plainTheme, 80, { isPartial: false, expanded: true }).map(bodyText).join('\n');
286
+ assert.match(expanded, /📑 odd · read odd\/tasks\/cards-skill-odd\.md/u, expanded);
287
+ assert.match(unpaint(collapsed), /^╭─ /u);
288
+
289
+ // The heading is the classifier's answer, never a guess: a path it declines is
290
+ // undefined, which is what keeps the chain's own row.
291
+ assert.equal(fileCardHeading('read', { path: 'src/app.js' }, false), undefined);
292
+ assert.equal(fileCardHeading('read', { path: ODD }, true).identity, 'odd');
293
+ assert.equal(fileCardHeading('read', { path: SKILL }, false).identity, 'skill');
294
+ });
295
+
296
+ test('the heading wears one theme role per element (S2)', () => {
297
+ const resolver = fileResolver();
298
+ const row = callRow(resolver, 'read', { path: SKILL, offset: 2, limit: 3 }, taggedTheme);
299
+
300
+ // The glyph AND the label wear the identity's own role (`mdHeading` for both
301
+ // identities); the label is the only one bolded, and the glyph is never bold.
302
+ assert.equal(row.includes('<mdHeading>▤</mdHeading>'), true, `the glyph wears the title role: ${row}`);
303
+ assert.equal(row.includes('<mdHeading>skill</mdHeading>'), true, 'the label wears the title role');
304
+ // The `·` separator in `muted`, the tool name in `dim`, the path in `accent`, the
305
+ // range in `warning` — in that order, on one row.
306
+ assert.equal(row.includes('<muted>·</muted> <dim>read</dim> <accent>one/SKILL.md</accent><warning>:2-4</warning>'), true, row);
307
+ assert.equal(row.includes('<accent>one/SKILL.md</accent>'), true, 'the path is the accent role');
308
+ assert.equal(row.includes('<dim>read</dim>'), true, 'the tool name is the dim role');
309
+
310
+ // A theme with a bold attribute: the label carries it, inside the role.
311
+ const boldTheme = { fg: (role, value) => `<${role}>${value}</${role}>`, bold: (value) => `*${value}*` };
312
+ const bolded = callRow(resolver, 'read', { path: SKILL }, boldTheme);
313
+ assert.equal(bolded.includes('<mdHeading>*skill*</mdHeading>'), true, `the label is bold: ${bolded}`);
314
+ assert.equal(bolded.includes('<mdHeading>*▤*</mdHeading>'), false, 'the glyph is not bold');
315
+
316
+ // An ODD artifact heads in the theme's own `mdHeading`, and while collapsed it names its
317
+ // file, in the accent role like every path.
318
+ const odd = callRow(resolver, 'read', { path: ODD, offset: 10, limit: 30 }, taggedTheme);
319
+ assert.equal(odd.includes('<mdHeading>📑</mdHeading>'), true, odd);
320
+ assert.equal(odd.includes('<mdHeading>odd</mdHeading>'), true, odd);
321
+ assert.equal(odd.includes('<dim>read</dim> <accent>cards-skill-odd.md</accent><warning>:10-39</warning>'), true, odd);
322
+ });
323
+
324
+ // The title role of BOTH identities is the theme's `mdHeading`: the card carries no
325
+ // colour of its own, so the theme decides what a skill and an ODD artifact look like.
326
+ test('both identities head in the theme\'s mdHeading role', () => {
327
+ const resolver = fileResolver();
328
+ for (const [path, head] of [[SKILL, '<mdHeading>▤</mdHeading> <mdHeading>skill</mdHeading>'], [ODD, '<mdHeading>📑</mdHeading> <mdHeading>odd</mdHeading>']]) {
329
+ const row = callRow(resolver, 'read', { path }, taggedTheme);
330
+ assert.equal(row.includes(head), true, `${path}: ${row}`);
331
+ assert.equal(/<toolTitle>/u.test(row), false, `no cell wears the old skill role: ${row}`);
332
+ }
333
+ });
334
+
335
+ // The tool name is the theme's `dim` grey: the call is the quiet part of the heading,
336
+ // the path is what the card is about.
337
+ test('the tool name is painted in dim, for a read and for a write', () => {
338
+ const resolver = fileResolver();
339
+ for (const tool of ['read', 'write']) {
340
+ const row = callRow(resolver, tool, { path: ODD, content: '# a\n' }, taggedTheme);
341
+ assert.equal(row.includes(`<dim>${tool}</dim>`), true, `${tool}: ${row}`);
342
+ assert.equal(row.includes(`<muted>·</muted> <dim>${tool}</dim> <accent>cards-skill-odd.md</accent>`), true, `${tool}: ${row}`);
343
+ }
344
+ });
345
+
346
+ // A collapsed skill names the path from the skill's own folder down; expanding it
347
+ // states the whole path, so nothing is lost, it is only deferred.
348
+ test('a collapsed skill names its path from its skill folder down, expanded states all of it', () => {
349
+ const resolver = fileResolver();
350
+ const path = '/home/dev/lib/skills/one/SKILL.md';
351
+ const collapsed = callRow(resolver, 'read', { path }, taggedTheme);
352
+ const text = unpaint(collapsed);
353
+ assert.match(text, /▤ skill · read one\/SKILL\.md/u, text);
354
+ assert.equal(text.includes('/home/dev'), false, 'the folders above the skill are not named while collapsed');
355
+ assert.equal(collapsed.includes('<accent>one/SKILL.md</accent>'), true, `the named path is the accent role: ${collapsed}`);
356
+
357
+ const expanded = callRows(resolver, 'read', { path }, plainTheme, 120, { isPartial: false, expanded: true })
358
+ .map(unpaint)
359
+ .join('\n');
360
+ assert.match(expanded, /read \/home\/dev\/lib\/skills\/one\/SKILL\.md/u, expanded);
361
+ });
362
+
363
+ // The whole frame is the identity's: an idle call's corners, rules, sides and closing
364
+ // rule wear the same role as its label. A live call keeps its tone, because the state
365
+ // speaks first (`TONE_OWNS_BOX`).
366
+ test('an idle file card wears its identity role around the whole frame', () => {
367
+ const resolver = fileResolver();
368
+ for (const path of [SKILL, ODD]) {
369
+ const call = callRow(resolver, 'read', { path }, taggedTheme);
370
+ assert.ok(call.startsWith('<mdHeading>╭</mdHeading>'), `${path}: the top-left corner wears the identity role: ${call}`);
371
+ assert.ok(call.endsWith('<mdHeading>╮</mdHeading>'), `${path}: the top-right corner too: ${call}`);
372
+
373
+ const closed = resultRows(resolver, 'read', { path }, textResult('body line'), { isPartial: false }, taggedTheme);
374
+ assert.ok(closed[0].startsWith('<mdHeading>│</mdHeading>'), `${path}: the sides wear it: ${closed[0]}`);
375
+ assert.ok(closed[0].endsWith('<mdHeading>│</mdHeading>'), `${path}: both sides: ${closed[0]}`);
376
+ assert.ok(closed.at(-1).startsWith('<mdHeading>╰</mdHeading>'), `${path}: the closing rule too: ${closed.at(-1)}`);
377
+ }
378
+
379
+ // A running call and a failed one keep their own tone: the state speaks first.
380
+ const running = callRow(resolver, 'read', { path: SKILL }, taggedTheme, { isPartial: true });
381
+ assert.ok(running.startsWith('<warning>╭</warning>'), `a running call keeps the warning tone: ${running}`);
382
+ const failed = resultRows(resolver, 'read', { path: SKILL }, textResult('ENOENT', { isError: true }), { isPartial: false }, taggedTheme);
383
+ assert.ok(failed[0].startsWith('<error>│</error>'), `a failed call keeps the error tone: ${failed[0]}`);
384
+ });
385
+
386
+ test('a heading that fits keeps every role through the expansion too', () => {
387
+ const resolver = fileResolver();
388
+ const rows = callRows(resolver, 'read', { path: ODD, offset: 2, limit: 3 }, taggedTheme, 80, { isPartial: false, expanded: true });
389
+ const heading = rows[0];
390
+ // Expanded states the whole path, and the whole path is still the accent role.
391
+ assert.equal(heading.includes('<accent>odd/tasks/cards-skill-odd.md</accent>'), true, heading);
392
+ assert.equal(heading.includes('<warning>:2-4</warning>'), true, heading);
393
+ assert.equal(heading.includes('<mdHeading>odd</mdHeading>'), true, heading);
394
+ });
395
+
396
+ test('an expanded heading that overflows states its identity on the rule and its path once', () => {
397
+ const resolver = fileResolver();
398
+ const rows = callRows(resolver, 'read', { path: ODD }, plainTheme, 40, { isPartial: false, expanded: true });
399
+ const text = rows.map(unpaint).join('\n');
400
+ // The continued layout drops the detail AND the segments it is drawn from: the rule
401
+ // states the identity alone, exactly as the baseline did, and the full detail follows
402
+ // on the rows below it.
403
+ assert.equal(unpaint(rows[0]), `╭─ 📑 odd ${'─'.repeat(30)}╮`, `the identity alone on the rule: ${unpaint(rows[0])}`);
404
+ assert.equal(text.includes('odd/tasks'), true, 'the whole path is stated below');
405
+ assert.equal(text.split('odd/tasks/cards-skill-odd.md').length - 1, 1, `the path is stated once: ${text}`);
406
+ assert.equal(text.split('·').length - 1, 1, `one separator, never two: ${text}`);
407
+ assert.match(unpaint(rows[1]), /^│ · read odd\/tasks\/cards-skill-odd\.md +│$/u, `the detail continues once: ${unpaint(rows[1])}`);
408
+ assertFramed(rows, 40);
409
+ });
410
+
411
+ test('only a read names a line range', () => {
412
+ const resolver = fileResolver();
413
+ assert.match(unpaint(callRow(resolver, 'read', { path: ODD, offset: 10, limit: 30 }, plainTheme)), /read cards-skill-odd\.md:10-39/u);
414
+ assert.match(unpaint(callRow(resolver, 'read', { path: ODD, offset: 7 }, plainTheme)), /read cards-skill-odd\.md:7\b/u);
415
+ for (const tool of ['write', 'edit']) {
416
+ const text = unpaint(callRow(resolver, tool, { path: ODD, offset: 10, limit: 30, content: '# a\n' }, plainTheme));
417
+ assert.match(text, new RegExp(`${tool} cards-skill-odd\\.md`, 'u'), text);
418
+ assert.doesNotMatch(text, /:\d/u, `${tool} states no line range`);
419
+ }
420
+ });
421
+
422
+ // ---- the rows the card does not own ----
423
+
424
+ test('a path that names neither a skill nor an ODD artifact is the chain\'s own drawing', () => {
425
+ const resolver = fileResolver();
426
+ const slot = resolver('read', () => HOST);
427
+ assert.equal(slot.renderShell, 'self', 'the card frames itself, so the host draws no filled box under it');
428
+ assert.deepEqual(forwardedText(slot.renderCall({ path: 'src/app.js' }, plainTheme, { isPartial: false }).render(60)), ['host read call']);
429
+ assert.deepEqual(
430
+ forwardedText(slot.renderResult(textResult('code'), { isPartial: false }, plainTheme, { args: { path: 'src/app.js' } }).render(60)),
431
+ ['host read result'],
432
+ );
433
+ // A folder that merely holds the word is no identity either, and neither is a
434
+ // document called SKILL.md outside a `skills` folder.
435
+ for (const path of ['lib/skillset/notes.md', 'docs/oddity.md', 'odd-work/a.md', 'notes/SKILL.md', '', undefined, 42]) {
436
+ assert.deepEqual(forwardedText(slot.renderCall({ path }, plainTheme, { isPartial: false }).render(60)), ['host read call'], String(path));
437
+ }
438
+ // A detail too long for the row is forwarded as the chain drew it, never clipped by us.
439
+ assert.deepEqual(forwardedText(slot.renderCall({ path: 'src/app.js' }, plainTheme, { isPartial: true }).render(20)), ['host read call']);
440
+ });
441
+
442
+ test('every tool this card does not own is handed back exactly as the chain resolved it', () => {
443
+ const resolver = fileResolver();
444
+ const hostRenderers = { renderShell: 'self', renderCall: () => 'host call', renderResult: () => 'host result' };
445
+ for (const toolName of ['bash', 'grep', 'find', 'ls', 'cat', 'codegraph', 'mcp__codegraph__codegraph_explore', 'worktree_create', 'worktree_list', 'READ', undefined, 42]) {
446
+ assert.equal(resolver(toolName, () => hostRenderers), hostRenderers, `${String(toolName)} is the host's own row, byte for byte`);
447
+ }
448
+ assert.equal(resolver('grep', () => undefined), undefined, 'a chain that resolves nothing stays nothing');
449
+ // A chain whose next() throws is never a lost row: an owned tool with an identity
450
+ // still draws its card, and one without an identity has nothing to forward.
451
+ const broken = resolver('read', () => {
452
+ throw new Error('chain exploded');
453
+ });
454
+ assert.equal(broken.renderShell, 'self');
455
+ assert.deepEqual(broken.renderCall({ path: 'src/app.js' }, plainTheme, { isPartial: false }).render(60), []);
456
+ assert.match(unpaint(broken.renderCall({ path: ODD }, plainTheme, { isPartial: false }).render(60)[0]), /📑 odd/u);
457
+ // The three owned tool names, and no fourth.
458
+ assert.deepEqual([...FILE_TOOLS].sort(), ['edit', 'read', 'write']);
459
+ });
460
+
461
+ // ---- S1/S7: one switch, asked of the bridge on every paint ----
462
+
463
+ test('the bridge\'s answer decides, and asking it per paint repaints a drawn row', () => {
464
+ const resolver = fileResolver();
465
+ const asked = [];
466
+ const call = resolver('read', () => HOST).renderCall({ path: SKILL }, plainTheme, { isPartial: false });
467
+
468
+ // A bridge that names another value (the reserved `default`, a design of the line that
469
+ // has left it, or one that does not cover this tool) means the host's own card.
470
+ publishBridge(NATIVE, asked);
471
+ assert.deepEqual(forwardedText(call.render(60)), ['host read call'], 'native: the chain draws the row');
472
+ assert.deepEqual(asked, ['read'], 'the question names the tool being painted');
473
+
474
+ // The same component is asked again on the next frame: a mid-session switch reaches a
475
+ // card already on screen.
476
+ genActivity();
477
+ assert.match(unpaint(call.render(60)[0]), /▤ skill/u, 'activity: the card repaints itself');
478
+ assert.deepEqual(asked, ['read', 'read'], 'one question per paint, never cached');
479
+
480
+ function genActivity() {
481
+ globalThis[BRIDGE_API_SLOT] = publishedBridge(ACTIVITY, asked);
482
+ }
483
+ });
484
+
485
+ test('every answer that is not this package\'s activity design is the host\'s own card', () => {
486
+ const resolver = fileResolver();
487
+ const cases = [
488
+ ['native', NATIVE],
489
+ ['missing', { kind: 'missing', id: 'gone.design' }],
490
+ ['not-covered', { kind: 'not-covered', id: 'other.design' }],
491
+ ['another design', { kind: 'design', design: { id: 'someone-else.bash-design' } }],
492
+ ];
493
+ for (const [label, answer] of cases) {
494
+ publishBridge(answer);
495
+ assert.deepEqual(
496
+ forwardedText(resolver('read', () => HOST).renderCall({ path: ODD }, plainTheme, { isPartial: false }).render(60)),
497
+ ['host read call'],
498
+ label,
499
+ );
500
+ assert.deepEqual(
501
+ forwardedText(resolver('read', () => HOST).renderResult(textResult('# x'), { isPartial: false }, plainTheme, { args: { path: ODD } }).render(60)),
502
+ ['host read result'],
503
+ `${label} (result)`,
504
+ );
505
+ }
506
+ });
507
+
508
+ test('the question is asked per painted tool: one tool can be carded while another is not', () => {
509
+ const resolver = fileResolver();
510
+ const asked = [];
511
+ publishBridge((tool) => (tool === 'read' ? ACTIVITY : NATIVE), asked);
512
+ assert.match(
513
+ unpaint(resolver('read', () => HOST).renderCall({ path: SKILL }, plainTheme, { isPartial: false }).render(60)[0]),
514
+ /▤ skill/u,
515
+ 'read is covered by the activity design',
516
+ );
517
+ assert.deepEqual(
518
+ forwardedText(resolver('write', () => HOST).renderCall({ path: ODD, content: '# x' }, plainTheme, { isPartial: false }).render(60)),
519
+ ['host read call'],
520
+ 'write is not: the host draws that row',
521
+ );
522
+ assert.deepEqual(asked, ['read', 'write'], 'each paint asked about the tool it draws');
523
+ });
524
+
525
+ test('no bridge and a bridge older than the reader both paint the card, never hide it', () => {
526
+ // The resolver-absence case this feature pins: a host whose published object has no
527
+ // `resolveToolDesignSelection` (gentle-shell-bridge before 0.7.0), and no bridge at
528
+ // all. Neither may hide the card, because neither can answer the question.
529
+ const resolver = fileResolver();
530
+ delete globalThis[BRIDGE_API_SLOT];
531
+ assert.match(
532
+ unpaint(resolver('read', () => HOST).renderCall({ path: SKILL }, plainTheme, { isPartial: false }).render(60)[0]),
533
+ /▤ skill/u,
534
+ 'no bridge: the card paints, exactly as before the switch was joined',
535
+ );
536
+
537
+ globalThis[BRIDGE_API_SLOT] = { schema: 'gentle-shell-bridge/api', version: 1, VERSION: '0.6.0', registerToolDesign: () => () => {} };
538
+ assert.match(
539
+ unpaint(resolver('read', () => HOST).renderCall({ path: ODD }, plainTheme, { isPartial: false }).render(60)[0]),
540
+ /📑 odd/u,
541
+ 'an older bridge: the card still paints',
542
+ );
543
+ assert.match(
544
+ unpaint(resolver('read', () => HOST).renderResult(textResult('# Design'), { isPartial: false }, plainTheme, { args: { path: ODD } }).render(60)[0]),
545
+ /^│ /u,
546
+ 'and so does its body',
547
+ );
548
+ });
549
+
550
+ test('a foreign, hostile or unreadable bridge never hides the card', () => {
551
+ const resolver = fileResolver();
552
+ const draw = () => unpaint(resolver('read', () => HOST).renderCall({ path: ODD }, plainTheme, { isPartial: false }).render(60)[0]);
553
+
554
+ // Another library on the same slot: its gate fails, and this package still paints.
555
+ globalThis[BRIDGE_API_SLOT] = { schema: 'someone-else/api', version: 1, resolveToolDesignSelection: () => NATIVE };
556
+ assert.match(draw(), /📑 odd/u, 'a foreign object on the slot is no bridge');
557
+
558
+ // A reader that throws breaks the bridge's own contract; the card stays visible.
559
+ globalThis[BRIDGE_API_SLOT] = { ...publishedBridge(NATIVE), resolveToolDesignSelection: () => { throw new Error('boom'); } };
560
+ assert.match(draw(), /📑 odd/u, 'a reader that throws never hides a row');
561
+
562
+ // An answer in a shape this build does not know is unreadable, not a refusal.
563
+ globalThis[BRIDGE_API_SLOT] = publishedBridge({ kind: 'future-kind' });
564
+ assert.match(draw(), /📑 odd/u, 'an unknown kind keeps the card');
565
+ });
566
+
567
+ test('S1: a write is covered by the Card tools line, so its file card paints and `default` restores the host row', () => {
568
+ // A bridge answers from the design's own `tools` list, exactly as it resolves
569
+ // coverage: a tool the line does not name is `not-covered`, which is the host's own
570
+ // card. `write` is declared on that line so the file card can be asked about it.
571
+ const design = toolsActivityDesign();
572
+ const asked = [];
573
+ publishBridge((tool) => (design.tools.includes(tool) ? { kind: 'design', design } : { kind: 'not-covered' }), asked);
574
+ const resolver = fileResolver();
575
+ for (const tool of ['read', 'write']) {
576
+ assert.equal(design.tools.includes(tool), true, `${tool} is covered by the Card tools line`);
577
+ const row = callRow(resolver, tool, { path: ODD, content: '# x\n' }, plainTheme);
578
+ assert.match(unpaint(row), /📑 odd/u, `${tool}: the file card paints its heading`);
579
+ assert.match(unpaint(row), new RegExp(`${tool} cards-skill-odd\\.md`, 'u'), `${tool}: and names the call`);
580
+ }
581
+ // A tool the line does not cover is still the host's row: a write is declared, but
582
+ // nothing else is.
583
+ const edit = resolver('edit', () => HOST).renderCall({ path: ODD }, plainTheme, { isPartial: false }).render(60);
584
+ assert.deepEqual(forwardedText(edit), ['host read call'], 'an uncovered tool keeps the host card');
585
+ assert.deepEqual(asked, ['read', 'write', 'edit'], 'each paint asked about the tool it draws');
586
+
587
+ // `default` is the bridge's `native`: the host draws every row again.
588
+ publishBridge(NATIVE);
589
+ assert.deepEqual(
590
+ forwardedText(resolver('write', () => HOST).renderCall({ path: ODD, content: '# x\n' }, plainTheme, { isPartial: false }).render(60)),
591
+ ['host read call'],
592
+ 'default: no write file card',
593
+ );
594
+ });
595
+
596
+ // ---- the host's own outer box, reproduced for every row this card hands back ----
597
+
598
+ test('a forwarded read call draws the host box\'s own blank rows around its rows', () => {
599
+ const resolver = fileResolver();
600
+ const width = 40;
601
+ const settled = boxTheme();
602
+ const rows = resolver('read', () => HOST).renderCall({ path: 'src/app.js' }, settled, { isPartial: false }).render(width);
603
+ assert.equal(rows.length, 2, 'the box opens with one blank row, then the call the host drew');
604
+ assertBlankRow(rows[0], width);
605
+ assert.deepEqual([...new Set(settled.roles)], ['toolSuccessBg'], 'a settled call is the settled background, blank row included');
606
+
607
+ const text = unpaint(rows[1]);
608
+ assert.equal(metrics.visibleWidth(text), width, 'the box pads the row to the width the host asked for');
609
+ assert.equal(text.startsWith(' host read call'), true, `exactly one column of padding on the left: ${JSON.stringify(text)}`);
610
+ assert.equal(text.endsWith(' '), true, 'the row is filled on the right, never cut');
611
+
612
+ // `outputPad` is the host's own padding, and one column is only the default.
613
+ const widePad = boxTheme();
614
+ const padded = resolver('read', () => HOST).renderCall({ path: 'src/app.js' }, widePad, { isPartial: false, outputPad: 3 }).render(width);
615
+ assert.match(unpaint(padded[1]), /^ {3}host read call/u, 'the host pad is the one the context states');
616
+ assert.equal(metrics.visibleWidth(unpaint(padded[1])), width);
617
+ assertBlankRow(padded[0], width);
618
+ });
619
+
620
+ test('an awaiting call carries the box\'s closing blank and loses it once the result arrives', () => {
621
+ const resolver = fileResolver();
622
+ const width = 30;
623
+ const awaiting = resolver('read', () => HOST).renderCall({ path: 'src/app.js' }, boxTheme(), { isPartial: true }).render(width);
624
+ assert.equal(awaiting.length, 3, 'blank, the call, blank: the host paints a complete box before the result');
625
+ assertBlankRow(awaiting[0], width);
626
+ assertBlankRow(awaiting[2], width);
627
+
628
+ // The host re-renders the call when the result lands, and the result then owns the
629
+ // closing blank.
630
+ const settled = resolver('read', () => HOST).renderCall({ path: 'src/app.js' }, boxTheme(), { isPartial: false }).render(width);
631
+ assert.equal(settled.length, 2, 'the call no longer closes the box');
632
+ assertBlankRow(settled[0], width);
633
+ const result = resolver('read', () => HOST).renderResult(textResult('code'), { isPartial: false }, boxTheme(), { args: { path: 'src/app.js' } }).render(width);
634
+ assert.equal(result.length, 2, 'the result rows, then the box\'s closing blank');
635
+ assertBlankRow(result.at(-1), width);
636
+ });
637
+
638
+ test('a forwarded result closes the box with the background its state names', () => {
639
+ const resolver = fileResolver();
640
+ const args = { path: 'src/app.js' };
641
+ const width = 40;
642
+ const settled = boxTheme();
643
+ const settledRows = resolver('read', () => HOST).renderResult(textResult('code'), { isPartial: false }, settled, { args }).render(width);
644
+ assert.deepEqual([...new Set(settled.roles)], ['toolSuccessBg'], 'a settled result is the success background');
645
+ assert.equal(unbox(settledRows[0]), 'host read result', 'the chain\'s own row is kept');
646
+ assertBlankRow(settledRows.at(-1), width);
647
+
648
+ const failed = boxTheme();
649
+ resolver('read', () => HOST).renderResult(textResult('boom', { isError: true }), { isPartial: false }, failed, { args }).render(width);
650
+ assert.deepEqual([...new Set(failed.roles)], ['toolErrorBg'], 'a failed result is the error background');
651
+
652
+ // `isError` stated in the render options is the same state as the result flag.
653
+ const fromOptions = boxTheme();
654
+ resolver('read', () => HOST).renderResult(textResult('boom'), { isPartial: false, isError: true }, fromOptions, { args }).render(width);
655
+ assert.deepEqual([...new Set(fromOptions.roles)], ['toolErrorBg']);
656
+
657
+ // A streamed result is the pending background, from the context's own flag.
658
+ const partial = boxTheme();
659
+ resolver('read', () => HOST).renderResult(textResult('code'), { isPartial: true }, partial, { args }).render(width);
660
+ assert.deepEqual([...new Set(partial.roles)], ['toolPendingBg']);
661
+ });
662
+
663
+ test('a forwarded edit row is returned exactly as the chain drew it', () => {
664
+ const resolver = fileResolver();
665
+ const args = { path: 'src/app.js' };
666
+ for (const partial of [true, false]) {
667
+ const theme = boxTheme();
668
+ const rows = resolver('edit', () => HOST_EDIT).renderCall(args, theme, { isPartial: partial }).render(40);
669
+ // Pi's edit renderer declares `renderShell: 'self'`: the host draws NO box around
670
+ // it, so this card adds none — no blank, no pad, no background.
671
+ assert.deepEqual(rows, ['host edit call'], 'exactly the chain\'s rows');
672
+ assert.equal(rows[0].startsWith(' '), false, 'no left pad');
673
+ assert.equal(rows[0].includes(String.fromCharCode(27)), false, 'no background paint');
674
+ assert.deepEqual(theme.roles, [], 'the box asks the theme for no background at all');
675
+ }
676
+ const resultTheme = boxTheme();
677
+ const result = resolver('edit', () => HOST_EDIT).renderResult(textResult('Edited'), { isPartial: false }, resultTheme, { args }).render(40);
678
+ assert.deepEqual(result, ['host edit result']);
679
+ assert.deepEqual(resultTheme.roles, []);
680
+ });
681
+
682
+ test('a chain renderer that declares no shell is the default shell, like the host', () => {
683
+ const resolver = fileResolver();
684
+ const UNDECLARED = {
685
+ renderCall: () => ({ render: () => ['host call'], invalidate() {} }),
686
+ renderResult: () => ({ render: () => ['host result'], invalidate() {} }),
687
+ };
688
+ const DECLARED = {
689
+ renderShell: 'default',
690
+ renderCall: () => ({ render: () => ['host call'], invalidate() {} }),
691
+ renderResult: () => ({ render: () => ['host result'], invalidate() {} }),
692
+ };
693
+ for (const inherited of [UNDECLARED, DECLARED]) {
694
+ const rows = resolver('read', () => inherited).renderCall({ path: 'src/app.js' }, plainTheme, { isPartial: false }).render(24);
695
+ assert.equal(rows.length, 2, 'the default shell opens with a blank row');
696
+ assertBlankRow(rows[0], 24);
697
+ assert.equal(rows[1].startsWith(' '), true, 'and pads the chain\'s row horizontally');
698
+ assert.equal(unbox(rows[1]), 'host call');
699
+ }
700
+ });
701
+
702
+ test('the forwarded text is byte-identical to the row the chain drew, and is never cut', () => {
703
+ const resolver = fileResolver();
704
+ const width = 40;
705
+ const pad = 1;
706
+ const hostCallRows = HOST.renderCall({ path: 'src/app.js' }, plainTheme, {}).render(width - pad * 2);
707
+ const forwardedCall = resolver('read', () => HOST).renderCall({ path: 'src/app.js' }, plainTheme, { isPartial: false }).render(width);
708
+ assert.deepEqual(forwardedText(forwardedCall), hostCallRows.map(stripAnsi), 'the same text the chain drew, at the box\'s inner width');
709
+
710
+ // A row wider than the box budget is kept, not clipped: the outer box loses its fill,
711
+ // never a character.
712
+ const long = 'x'.repeat(120);
713
+ const LONG = { renderCall: () => ({ render: () => [long], invalidate() {} }) };
714
+ const longRows = resolver('read', () => LONG).renderCall({ path: 'src/app.js' }, plainTheme, { isPartial: false }).render(20);
715
+ assert.equal(unbox(boxedContent(longRows)[0]), long, 'a row too wide for the box keeps every column');
716
+
717
+ // The result slot reproduces the same box: the host's own renderer is asked for the
718
+ // inner width and its rows come back padded to the outer one.
719
+ const hostResultRows = HOST.renderResult(textResult('code'), { isPartial: false }, plainTheme, { args: { path: 'src/app.js' } }).render(width - pad * 2);
720
+ const forwardedResult = resolver('read', () => HOST)
721
+ .renderResult(textResult('code'), { isPartial: false }, plainTheme, { args: { path: 'src/app.js' } })
722
+ .render(width);
723
+ assert.deepEqual(forwardedText(forwardedResult), hostResultRows.map(stripAnsi));
724
+ });
725
+
726
+ test('a chain row that cannot be drawn adds nothing and never throws', () => {
727
+ const resolver = fileResolver();
728
+ const THROWING_COMPONENT = {
729
+ renderCall: () => ({
730
+ render: () => {
731
+ throw new Error('render exploded');
732
+ },
733
+ invalidate() {},
734
+ }),
735
+ renderResult: () => {
736
+ throw new Error('renderer exploded');
737
+ },
738
+ };
739
+ // No row means no box either: the blank rows only accompany rows that were drawn.
740
+ const slot = resolver('read', () => THROWING_COMPONENT);
741
+ assert.deepEqual(slot.renderCall({ path: 'src/app.js' }, plainTheme, { isPartial: false }).render(40), []);
742
+ assert.doesNotThrow(() => slot.renderCall({ path: 'src/app.js' }, boxTheme(), { isPartial: true }).render(40));
743
+ assert.deepEqual(slot.renderResult(textResult('code'), { isPartial: false }, plainTheme, { args: { path: 'src/app.js' } }).render(40), []);
744
+
745
+ // The same for a renderer that frames itself.
746
+ const selfSlot = resolver('read', () => ({ renderShell: 'self', renderCall: () => ({ render: () => { throw new Error('nope'); } }), renderResult: () => ({ render: () => { throw new Error('nope'); } }) }));
747
+ assert.deepEqual(selfSlot.renderCall({ path: 'src/app.js' }, boxTheme(), { isPartial: false }).render(40), []);
748
+
749
+ // No inherited slot at all is no box either, and no throw.
750
+ const nothing = resolver('read', () => undefined);
751
+ assert.deepEqual(nothing.renderCall({ path: 'src/app.js' }, plainTheme, { isPartial: false }).render(40), []);
752
+ assert.doesNotThrow(() => nothing.renderResult(textResult('code'), { isPartial: false }, plainTheme, { args: { path: 'src/app.js' } }).render(40));
753
+
754
+ // A theme that cannot paint a background still draws the box's padding and blanks.
755
+ const bare = resolver('read', () => HOST).renderCall({ path: 'src/app.js' }, plainTheme, { isPartial: true }).render(40);
756
+ assertBlankRow(bare[0], 40);
757
+ assert.match(unpaint(bare[1]), /^ host read call +$/u, 'a theme without bg keeps the box\'s padding');
758
+ });
759
+
760
+ test('a row the bridge\'s answer withholds is the same boxed row as a path with no identity', () => {
761
+ const resolver = fileResolver();
762
+ const plain = boxTheme();
763
+ const withheld = boxTheme();
764
+ const plainRows = resolver('read', () => HOST).renderCall({ path: 'src/app.js' }, plain, { isPartial: false }).render(40);
765
+ publishBridge(NATIVE);
766
+ const withheldRows = resolver('read', () => HOST).renderCall({ path: ODD }, withheld, { isPartial: false }).render(40);
767
+ assert.deepEqual(withheldRows, plainRows, 'both are the host\'s own boxed row');
768
+ assert.deepEqual(withheld.roles, plain.roles);
769
+ });
770
+
771
+ // ---- S2: the content level, read per paint ----
772
+
773
+ test('the content level is read per paint: `minimal` is the call alone, `default` the bounded preview', () => {
774
+ const resolver = fileResolver();
775
+ const args = { path: 'odd/tasks/notes.json' };
776
+ const result = textResult(['one', 'two', 'three', 'four', 'five', 'six'].join('\n'));
777
+ const component = resolver('read', () => HOST).renderResult(result, { isPartial: false }, plainTheme, { args });
778
+
779
+ const defaultRows = component.render(60);
780
+ assert.equal(defaultRows.length, PREVIEW_ROWS + 1, 'three preview rows and the closing rule');
781
+ assert.deepEqual(defaultRows.slice(0, PREVIEW_ROWS).map(bodyText), ['one', 'two', 'three'], 'a document previews from its top');
782
+ assert.match(unpaint(defaultRows.at(-1)), /^╰/u);
783
+
784
+ globalThis[CARD_CONTENT_SLOT] = 'minimal';
785
+ try {
786
+ const minimalRows = component.render(60);
787
+ assert.equal(minimalRows.length, 1, 'a minimized card is the call alone plus its closing rule');
788
+ assert.match(unpaint(minimalRows[0]), /^╰/u, 'the one row is the closing rule');
789
+ } finally {
790
+ delete globalThis[CARD_CONTENT_SLOT];
791
+ }
792
+ assert.deepEqual(component.render(60), defaultRows, 'flipping the level back repaints the same rows');
793
+
794
+ const expanded = resolver('read', () => HOST)
795
+ .renderResult(result, { expanded: true, isPartial: false }, plainTheme, { args })
796
+ .render(60);
797
+ assert.equal(expanded.length, 7, 'expanding is the reader\'s own ask: the whole result');
798
+ assert.deepEqual(expanded.slice(0, 6).map(bodyText), ['one', 'two', 'three', 'four', 'five', 'six']);
799
+ });
800
+
801
+ test('the row decision itself says which level withholds a body, and a failure still says why', () => {
802
+ assert.deepEqual(fileResultRows({ content: 'minimal', text: 'a\nb', failed: false, expanded: false }), []);
803
+ assert.equal(fileResultRows({ content: 'default', text: 'a\nb\nc\nd', failed: false, expanded: false })[0].text, 'a\nb\nc');
804
+ const failed = fileResultRows({ content: 'minimal', text: 'ENOENT', failed: true, expanded: false });
805
+ assert.deepEqual(failed, [{ text: 'ENOENT', role: 'error' }], 'a minimized failure keeps its reason');
806
+ assert.deepEqual(fileResultRows({ content: 'default', text: ' ', failed: false, expanded: false }), [], 'no output draws no row');
807
+ });
808
+
809
+ // ---- S2: both styles, read per paint ----
810
+
811
+ test('the same card is drawn in both styles, and the style is read on every paint', () => {
812
+ const resolver = fileResolver();
813
+ const draw = (style, run) => {
814
+ globalThis[CARD_STYLE_SLOT] = style;
815
+ try {
816
+ return run();
817
+ } finally {
818
+ globalThis[CARD_STYLE_SLOT] = CARD_STYLE.NEON;
819
+ }
820
+ };
821
+ const call = (style) => draw(style, () => callRows(resolver, 'read', { path: SKILL }, bandTheme, 60));
822
+ const result = (style) => draw(style, () => resultRows(resolver, 'read', { path: SKILL }, textResult('a\nb\nc\nd'), { isPartial: false }, bandTheme));
823
+
824
+ const neon = call(CARD_STYLE.NEON);
825
+ const float = call(CARD_STYLE.FLOAT);
826
+ assert.match(unpaint(neon[0]), /^╭─/u, 'neon draws its rounded frame');
827
+ assert.ok(float.some((row) => unpaint(row).includes('▎')), 'float draws its rail');
828
+ assert.equal(float.some((row) => /[╭╮╰╯]/u.test(unpaint(row))), false, 'float draws no box');
829
+
830
+ // One card's content, two chromes: the same words in both styles.
831
+ const content = (rows) => rows
832
+ .map((row) => unpaint(row).replace(/[╭╮╰╯─│▎]/gu, ' ').replace(/\s+/gu, ' ').trim())
833
+ .filter((text) => text.length > 0)
834
+ .join(' | ');
835
+ assert.equal(content(neon), content(float));
836
+ assert.equal(content(result(CARD_STYLE.FLOAT)), content(result(CARD_STYLE.NEON)), 'the body is the same in both styles');
837
+ });
838
+
839
+ // ---- S3/S4/S5: the document body, drawn by Pi's own Markdown renderer ----
840
+
841
+ /**
842
+ * A stand-in for Pi's `Markdown` component that behaves the way the real one does where
843
+ * this card depends on it: it asks the theme TABLE it was handed for every element, and
844
+ * every row it returns is already PAINTED. A heading goes through `heading`, a bullet
845
+ * through `listBullet`, inline code through `code`, a fence through `codeBlockBorder` and
846
+ * `codeBlock`, a quote through `quoteBorder` and `quote`, and a rule through `hr`.
847
+ */
848
+ class OutlineMarkdown {
849
+ constructor(source, paddingX, paddingY, theme) {
850
+ this.source = source;
851
+ this.theme = theme;
852
+ this.padding = { paddingX, paddingY };
853
+ }
854
+
855
+ render() {
856
+ const theme = this.theme;
857
+ let fenced = false;
858
+ return this.source.split('\n').map((line) => {
859
+ if (line.startsWith('```')) {
860
+ fenced = !fenced;
861
+ return theme.codeBlockBorder(line);
862
+ }
863
+ if (fenced) return theme.codeBlock(line);
864
+ if (line.startsWith('# ')) return theme.heading(line.slice(2));
865
+ if (line.startsWith('- ')) return `${theme.listBullet('-')} ${line.slice(2)}`;
866
+ if (line.startsWith('> ')) return `${theme.quoteBorder('>')} ${theme.quote(line.slice(2))}`;
867
+ if (line === '---') return theme.hr('────');
868
+ return line.replace(/`([^`]+)`/gu, (_match, code) => theme.code(code));
869
+ });
870
+ }
871
+
872
+ invalidate() {}
873
+ }
874
+
875
+ // A document with every element S3 names, one per row.
876
+ const DOCUMENT = [
877
+ '# Design',
878
+ '- one',
879
+ 'Some `inline` code',
880
+ '```',
881
+ 'const a = 1;',
882
+ '```',
883
+ '> quoted',
884
+ '---',
885
+ ].join('\n');
886
+
887
+ const documentResolver = () => fileResolver({ markdownClass: OutlineMarkdown });
888
+
889
+ test('the document is drawn by the host renderer, one theme role per element (S3)', () => {
890
+ const resolver = documentResolver();
891
+ const rows = resultRows(resolver, 'read', { path: ODD }, textResult(DOCUMENT), { expanded: true, isPartial: false }, taggedTheme, 60);
892
+ // The raw rows: `bodyText` strips the very tags these cases read.
893
+ const body = rows.slice(0, -1).join('\n');
894
+
895
+ assert.equal(body.includes('<mdHeading>Design</mdHeading>'), true, `a heading wears mdHeading: ${body}`);
896
+ assert.equal(body.includes('<mdListBullet>-</mdListBullet>'), true, 'a bullet wears mdListBullet');
897
+ assert.equal(body.includes('<mdCode>inline</mdCode>'), true, 'inline code wears mdCode');
898
+ assert.equal(body.includes('<mdCodeBlockBorder>```</mdCodeBlockBorder>'), true, 'a fence wears mdCodeBlockBorder');
899
+ assert.equal(body.includes('<mdCodeBlock>const a = 1;</mdCodeBlock>'), true, 'fenced content wears mdCodeBlock');
900
+ assert.equal(body.includes('<mdQuoteBorder>></mdQuoteBorder>'), true, 'a quote border wears mdQuoteBorder');
901
+ assert.equal(body.includes('<mdQuote>quoted</mdQuote>'), true, 'quoted text wears mdQuote');
902
+ assert.equal(body.includes('<mdHr>'), true, 'a rule wears mdHr');
903
+ });
904
+
905
+ // A theme that paints real, zero-width ANSI and records the roles it was asked for: the
906
+ // fake metrics strips ANSI, so its widths are the host's own visible widths.
907
+ function ansiRoles() {
908
+ const roles = [];
909
+ return {
910
+ roles,
911
+ fg(role, value) {
912
+ roles.push(role);
913
+ return `\x1b[36m${value}\x1b[39m`;
914
+ },
915
+ bold: (value) => `\x1b[1m${value}\x1b[22m`,
916
+ };
917
+ }
918
+
919
+ test('S5: the document\'s painted rows are placed, never painted again', () => {
920
+ const resolver = documentResolver();
921
+ const rows = resultRows(resolver, 'read', { path: ODD }, textResult(DOCUMENT), { expanded: true, isPartial: false }, taggedTheme, 60);
922
+ const body = rows.slice(0, -1).join('\n');
923
+ // The body role is the one this card paints its own rows with; the document's rows keep
924
+ // exactly the paint they arrived with, so none of them carries it.
925
+ assert.equal(body.includes('<text>'), false, `the body role is never applied over the document: ${body}`);
926
+ assert.equal(body.split('<mdHeading>Design</mdHeading>').length - 1, 1, 'each painted cell is placed once');
927
+
928
+ // The same document with a theme that paints real, zero-width ANSI: the sequences survive,
929
+ // and each row is still exactly the width the host asked for — proof that the placement
930
+ // measured it with the ANSI-aware seam and not with a codepoint count.
931
+ const ansiTheme = ansiRoles();
932
+ const ansiRows = resultRows(resolver, 'read', { path: ODD }, textResult(DOCUMENT), { expanded: true, isPartial: false }, ansiTheme, 60);
933
+ assert.equal(ansiRows.slice(0, -1).join('\n').includes('\x1b[36m'), true, 'the document keeps the host paint');
934
+ for (const row of ansiRows) assert.equal(metrics.visibleWidth(row), 60, `"${row}" is not 60 columns`);
935
+ });
936
+
937
+ test('S4: the collapsed preview is the first drawn rows of the same document, with its roles', () => {
938
+ const resolver = documentResolver();
939
+ const collapsed = resultRows(resolver, 'read', { path: ODD }, textResult(DOCUMENT), { isPartial: false }, taggedTheme, 60);
940
+ assert.equal(collapsed.length, PREVIEW_ROWS + 1, 'three preview rows and the closing rule');
941
+ const preview = collapsed.slice(0, PREVIEW_ROWS).join('\n');
942
+ assert.equal(preview.includes('<mdHeading>Design</mdHeading>'), true, `the first drawn row is the heading: ${preview}`);
943
+ assert.equal(preview.includes('<mdListBullet>-</mdListBullet>'), true);
944
+ assert.equal(preview.includes('<mdCode>inline</mdCode>'), true);
945
+ assert.equal(preview.includes('<mdCodeBlock>const a = 1;</mdCodeBlock>'), false, 'the preview stops at its budget');
946
+ // Not the raw source: no heading is typed out while the renderer can draw it.
947
+ assert.doesNotMatch(unpaint(preview), /^# Design$/mu, 'a preview is not the file\'s own text');
948
+
949
+ // `minimal` still suppresses the whole body, preview included.
950
+ globalThis[CARD_CONTENT_SLOT] = 'minimal';
951
+ try {
952
+ const minimal = resultRows(resolver, 'read', { path: ODD }, textResult(DOCUMENT), { isPartial: false }, taggedTheme, 60);
953
+ assert.equal(minimal.length, 1, 'the closing rule alone');
954
+ assert.match(unpaint(minimal[0]), /^╰/u);
955
+ } finally {
956
+ delete globalThis[CARD_CONTENT_SLOT];
957
+ }
958
+
959
+ // A write previews the document it wrote, exactly as a read previews the one it read.
960
+ const written = resultRows(
961
+ resolver,
962
+ 'write',
963
+ { path: ODD, content: '# Task\n\n- one\n' },
964
+ textResult('Wrote 20 bytes'),
965
+ { isPartial: false },
966
+ taggedTheme,
967
+ 60,
968
+ );
969
+ const writtenBody = written.slice(0, -1).join('\n');
970
+ assert.equal(writtenBody.includes('<mdHeading>Task</mdHeading>'), true, writtenBody);
971
+ assert.equal(written.slice(0, -1).length, PREVIEW_ROWS, 'the preview budget is the same');
972
+ });
973
+
974
+ test('a document the renderer cannot draw falls back to the plain source, unstyled', () => {
975
+ const source = ['# Design', '', '## Specs', '', 'Body text'].join('\n');
976
+ const drawsNothing = class { render() { return []; } invalidate() {} };
977
+ const throws = class { render() { throw new Error('renderer exploded'); } invalidate() {} };
978
+ const blanks = class { render() { return ['', ' ']; } invalidate() {} };
979
+ const cases = [
980
+ ['no renderer', null],
981
+ ['a renderer that throws', throws],
982
+ ['a renderer that draws nothing', drawsNothing],
983
+ ['a renderer that draws only blanks', blanks],
984
+ ];
985
+ for (const [label, markdownClass] of cases) {
986
+ const resolver = fileResolver({ markdownClass });
987
+ const rows = resultRows(resolver, 'read', { path: ODD }, textResult(source), { expanded: true, isPartial: false }, taggedTheme, 60);
988
+ const body = rows.slice(0, -1).join('\n');
989
+ assert.equal(body.includes('# Design'), true, `${label}: the source is shown`);
990
+ assert.equal(body.includes('## Specs'), true, `${label}: every line of it`);
991
+ assert.equal(bodyPaint(rows.slice(0, -1).join('\n')).includes('<mdHeading>'), false, `${label}: in no Markdown role`);
992
+ }
993
+ });
994
+
995
+ test('a write whose document cannot be drawn shows the document it wrote, never the result (S3)', () => {
996
+ const source = ['# Design', '', '## Specs', '', 'Body text'].join('\n');
997
+ const drawsNothing = class { render() { return []; } invalidate() {} };
998
+ const throws = class { render() { throw new Error('renderer exploded'); } invalidate() {} };
999
+ const cases = [
1000
+ ['no renderer', null],
1001
+ ['a renderer that throws', throws],
1002
+ ['a renderer that draws nothing', drawsNothing],
1003
+ ];
1004
+ for (const [label, markdownClass] of cases) {
1005
+ const resolver = fileResolver({ markdownClass });
1006
+ const args = { path: ODD, content: source };
1007
+ const result = textResult('Successfully wrote 42 bytes');
1008
+ for (const options of [{ isPartial: false }, { expanded: true, isPartial: false }]) {
1009
+ const written = resultRows(resolver, 'write', args, result, options, taggedTheme, 60);
1010
+ const body = written.slice(0, -1).join('\n');
1011
+ assert.equal(unpaint(body).includes('Successfully wrote'), false, `${label}: the result is never a write's body`);
1012
+ assert.equal(body.includes('# Design'), true, `${label}: the document is`);
1013
+ // Expanded, the whole document; collapsed, its first rows, exactly as a read's.
1014
+ assert.equal(body.includes('Body text'), options.expanded === true, `${label}: ${JSON.stringify(options)}`);
1015
+ assert.equal(bodyPaint(body).includes('<mdHeading>'), false, `${label}: and it is drawn as plain source`);
1016
+ }
1017
+ // A read keeps the text it read, exactly as before.
1018
+ const read = resultRows(resolver, 'read', { path: ODD }, textResult(source), { expanded: true, isPartial: false }, taggedTheme, 60);
1019
+ assert.equal(read.slice(0, -1).join('\n').includes('## Specs'), true, `${label}: a read keeps its result text`);
1020
+ }
1021
+ });
1022
+
1023
+ test('the real host renderer draws the document with the theme roles (S3)', (t) => {
1024
+ let Markdown;
1025
+ try {
1026
+ ({ Markdown } = require('@earendil-works/pi-tui'));
1027
+ } catch {
1028
+ t.skip('requires @earendil-works/pi-tui');
1029
+ return;
1030
+ }
1031
+ const resolver = fileResolver({ markdownClass: Markdown });
1032
+ const source = ['# Design', '', '## Specs', '', 'Some **bold** text and `code`', '', '- one', ''].join('\n');
1033
+ const theme = ansiRoles();
1034
+ const rows = resultRows(resolver, 'read', { path: ODD }, textResult(source), { expanded: true, isPartial: false }, theme, 60);
1035
+ const body = rows.slice(0, -1).join('\n');
1036
+ assert.doesNotMatch(body, /## Specs/u, `a heading is drawn, not typed: ${JSON.stringify(rows.map(unpaint))}`);
1037
+ assert.equal(theme.roles.includes('mdHeading'), true, 'headings wear mdHeading');
1038
+ assert.equal(theme.roles.includes('mdListBullet'), true, 'bullets wear mdListBullet');
1039
+ assert.equal(theme.roles.includes('mdCode'), true, 'inline code wears mdCode');
1040
+ assert.match(body, /Design/u);
1041
+ assertFramed(rows, 60);
1042
+ });
1043
+
1044
+ test('a failed call and a non-Markdown file keep their plain rows (S8)', () => {
1045
+ const resolver = documentResolver();
1046
+ const source = ['# Design', '', '## Specs'].join('\n');
1047
+
1048
+ const failed = resultRows(resolver, 'read', { path: ODD }, textResult(source, { isError: true }), { expanded: true, isPartial: false }, taggedTheme, 60);
1049
+ assert.match(unpaint(failed[0]), /^│ # Design/u, 'a failure keeps its rows as they were reported');
1050
+ assert.equal(failed.slice(0, -1).join('\n').includes('<mdHeading>'), false, 'a failure is never a document');
1051
+
1052
+ const json = resultRows(resolver, 'read', { path: 'odd/tasks/data.json' }, textResult('{"a":1}'), { expanded: true, isPartial: false }, taggedTheme, 60);
1053
+ assert.deepEqual(json.slice(0, -1).map(bodyText), ['{"a":1}'], 'a non-Markdown file is drawn as it is');
1054
+ });
1055
+
1056
+ test('an edit draws its diff and is never rendered as a document', () => {
1057
+ const resolver = fileResolver();
1058
+ const diff = ['@@ -1,2 +1,2 @@', '-**old**', '+**new**'].join('\n');
1059
+ const args = { path: ODD, old_string: '**old**', new_string: '**new**' };
1060
+ const collapsed = resultRows(resolver, 'edit', args, textResult('Edited', { details: { diff } }), { isPartial: false }, plainTheme, 60);
1061
+ assert.deepEqual(collapsed.slice(0, -1).map(bodyText), ['@@ -1,2 +1,2 @@', '-**old**', '+**new**'], 'the diff is the edit\'s rows');
1062
+
1063
+ const expanded = resultRows(resolver, 'edit', args, textResult('Edited', { details: { diff } }), { expanded: true, isPartial: false }, plainTheme, 60);
1064
+ const body = expanded.slice(0, -1).map(bodyText).join('\n');
1065
+ assert.equal(body, diff, 'expanding an edit shows the whole diff, not a document');
1066
+ assert.doesNotMatch(body, /▌/u, 'a Markdown path does not turn an edit into a document');
1067
+
1068
+ // A result that carries no diff is its own text.
1069
+ const plain = resultRows(resolver, 'edit', args, textResult('Edited 2 lines'), { isPartial: false }, plainTheme, 60);
1070
+ assert.deepEqual(plain.slice(0, -1).map(bodyText), ['Edited 2 lines']);
1071
+ });
1072
+
1073
+ test('a failed result keeps its error rows and the error tone', () => {
1074
+ const resolver = fileResolver();
1075
+ const rows = resultRows(resolver, 'read', { path: ODD }, textResult('ENOENT: no such file', { isError: true }), { isPartial: false }, taggedTheme);
1076
+ assert.match(rows[0], /^<error>│<\/error>/u, 'a failure paints its frame in the error role');
1077
+ assert.match(rows[0], /<error>ENOENT: no such file<\/error>/u, 'and its reason too');
1078
+ assert.match(rows.at(-1), /^<error>╰/u);
1079
+ assertFramed(rows, 60);
1080
+
1081
+ // The host's own `isError` in the render options is the same flag.
1082
+ const fromOptions = resultRows(resolver, 'read', { path: ODD }, textResult('boom'), { isPartial: false, isError: true }, taggedTheme);
1083
+ assert.match(fromOptions[0], /^<error>│/u);
1084
+ });
1085
+
1086
+ test('a call still running is the warning tone and closes its own frame', () => {
1087
+ const resolver = fileResolver();
1088
+ const rows = callRows(resolver, 'read', { path: ODD }, taggedTheme, 40, { isPartial: true });
1089
+ assert.equal(rows.length, 3, 'a heading, the running row and the closed frame');
1090
+ assert.match(rows[0], /^<warning>╭<\/warning>/u, 'pending is the warning tone');
1091
+ assert.match(rows[1], /^<warning>│<\/warning> <muted>running…<\/muted>/u);
1092
+ assert.match(rows[2], /^<warning>╰/u);
1093
+ assertFramed(rows, 40);
1094
+ assert.equal(callRows(resolver, 'read', { path: ODD }, plainTheme, 40, { isPartial: false }).length, 1, 'a settled call leaves the closing rule to its result');
1095
+ });
1096
+
1097
+ // ---- the identity's two columns are the metrics', never a hand count ----
1098
+
1099
+ test('the ODD mark\'s two columns are measured by the injected seam', () => {
1100
+ // The same seam, counting the artifact mark as the two columns it occupies. A card
1101
+ // that hand-counted the glyph would pad a column off.
1102
+ const wide = (value) => [...stripAnsi(value)].reduce((total, char) => total + (char === '📑' ? 2 : 1), 0);
1103
+ const wideMetrics = {
1104
+ visibleWidth: wide,
1105
+ truncateToWidth(value, width, ellipsis = '') {
1106
+ if (width <= 0) return '';
1107
+ if (wide(value) <= width) return value;
1108
+ const keep = Math.max(0, width - [...ellipsis].length);
1109
+ return [...stripAnsi(value)].slice(0, keep).join('') + ellipsis;
1110
+ },
1111
+ wrapTextWithAnsi: metrics.wrapTextWithAnsi,
1112
+ };
1113
+ const resolver = fileResolver({ metrics: wideMetrics });
1114
+ for (const width of [20, 40, 60, 80]) {
1115
+ const call = callRows(resolver, 'read', { path: ODD, offset: 3, limit: 7 }, plainTheme, width);
1116
+ for (const row of call) assert.equal(wide(row), width, `"${row}" is not ${width} columns`);
1117
+ const result = resultRows(resolver, 'read', { path: ODD }, textResult('a\nb'), { isPartial: false }, plainTheme, width);
1118
+ for (const row of result) assert.equal(wide(row), width, `"${row}" is not ${width} columns`);
1119
+ }
1120
+ });
1121
+
1122
+ // ---- paint last: no row of OURS is ever measured after it was painted ----
1123
+
1124
+ test('the plain body is measured and clipped as plain text, and painted only afterwards', () => {
1125
+ const seen = [];
1126
+ const spyMetrics = {
1127
+ visibleWidth(value) {
1128
+ seen.push(value);
1129
+ return metrics.visibleWidth(value);
1130
+ },
1131
+ truncateToWidth(value, width, ellipsis) {
1132
+ seen.push(value);
1133
+ return metrics.truncateToWidth(value, width, ellipsis);
1134
+ },
1135
+ wrapTextWithAnsi(value, width) {
1136
+ seen.push(value);
1137
+ return metrics.wrapTextWithAnsi(value, width);
1138
+ },
1139
+ };
1140
+ // No document renderer: every row below takes the plain path this card owns.
1141
+ const resolver = fileResolver({ metrics: spyMetrics, markdownClass: null });
1142
+ for (const style of [CARD_STYLE.NEON, CARD_STYLE.FLOAT]) {
1143
+ globalThis[CARD_STYLE_SLOT] = style;
1144
+ try {
1145
+ const call = callRows(resolver, 'read', { path: ODD, offset: 1, limit: 9 }, taggedTheme, 44);
1146
+ const result = resultRows(resolver, 'read', { path: ODD }, textResult('# Title\n\n## Specs\n\nBody text'), { expanded: true, isPartial: false }, taggedTheme, 44);
1147
+ const edit = resultRows(resolver, 'edit', { path: ODD }, textResult('Edited', { details: { diff: '-a\n+b' } }), { isPartial: false }, taggedTheme, 44);
1148
+ assert.ok([...call, ...result, ...edit].some((row) => row.includes('<')), `${style}: the rows were painted`);
1149
+ } finally {
1150
+ globalThis[CARD_STYLE_SLOT] = CARD_STYLE.NEON;
1151
+ }
1152
+ }
1153
+ assert.ok(seen.length > 0, 'the seams were used');
1154
+ for (const value of seen) {
1155
+ assert.equal(typeof value, 'string');
1156
+ assert.equal(value.includes(String.fromCharCode(27)), false, `a painted string reached the measurement seam: ${JSON.stringify(value)}`);
1157
+ assert.doesNotMatch(value, /<\/?[a-zA-Z][a-zA-Z0-9]*>/u, `a painted row reached the measurement seam: ${JSON.stringify(value)}`);
1158
+ }
1159
+ });
1160
+
1161
+ test('the document\'s rows reach the seam PAINTED, and the ANSI-aware width is what measures them', () => {
1162
+ // S5: the one exception to "paint last", and the host's own: Pi's renderer hands back
1163
+ // painted rows, so they are measured as they are (with a visible width, never a codepoint
1164
+ // count) and no role of ours is applied over them.
1165
+ const seen = [];
1166
+ const spyMetrics = {
1167
+ visibleWidth(value) {
1168
+ seen.push(value);
1169
+ return metrics.visibleWidth(value);
1170
+ },
1171
+ truncateToWidth(value, width, ellipsis) {
1172
+ seen.push(value);
1173
+ return metrics.truncateToWidth(value, width, ellipsis);
1174
+ },
1175
+ wrapTextWithAnsi(value, width) {
1176
+ seen.push(value);
1177
+ return metrics.wrapTextWithAnsi(value, width);
1178
+ },
1179
+ };
1180
+ const resolver = fileResolver({ metrics: spyMetrics, markdownClass: OutlineMarkdown });
1181
+ const theme = ansiRoles();
1182
+ const rows = resultRows(resolver, 'read', { path: ODD }, textResult(DOCUMENT), { expanded: true, isPartial: false }, theme, 44);
1183
+ assert.ok(seen.includes('\x1b[36mDesign\x1b[39m'), 'the document\'s own painted heading reached the seam, escape and all');
1184
+ assertFramed(rows, 44);
1185
+ });
1186
+
1187
+ // ---- geometry ----
1188
+
1189
+ test('the card draws at every width the host may ask for', () => {
1190
+ const resolver = documentResolver();
1191
+ for (const width of [0, 1, 2, 3, 5, 9, 10, 12, 16, 61]) {
1192
+ for (const drawn of [
1193
+ callRows(resolver, 'read', { path: ODD }, plainTheme, width, { isPartial: true }),
1194
+ callRows(resolver, 'read', { path: ODD, offset: 2, limit: 4 }, plainTheme, width, { isPartial: false, expanded: true }),
1195
+ resultRows(resolver, 'read', { path: SKILL }, textResult('a\nb\nc\nd'), { isPartial: false }, plainTheme, width),
1196
+ resultRows(resolver, 'read', { path: ODD }, textResult(DOCUMENT), { isPartial: false }, plainTheme, width),
1197
+ resultRows(resolver, 'read', { path: ODD }, textResult(DOCUMENT), { expanded: true, isPartial: false }, plainTheme, width),
1198
+ resultRows(resolver, 'write', { path: ODD }, textResult('# T\n\n## S'), { expanded: true, isPartial: false }, plainTheme, width),
1199
+ ]) {
1200
+ for (const row of drawn) assert.ok(metrics.visibleWidth(unpaint(row)) <= width, `"${unpaint(row)}" overflows ${width}`);
1201
+ }
1202
+ }
1203
+ });
1204
+
1205
+ // ---- the factory's contract ----
1206
+
1207
+ test('the factory registers through the host hook when it can, and fails open when it cannot', () => {
1208
+ const seen = [];
1209
+ const registered = createFileCardResolver({
1210
+ metrics,
1211
+ theme: plainTheme,
1212
+ registerToolRenderer: (resolver) => seen.push(resolver),
1213
+ });
1214
+ assert.equal(registered.registered, true);
1215
+ assert.equal(seen[0], registered.resolver);
1216
+
1217
+ // No hook is an older host: nothing of ours is drawn, and nothing throws.
1218
+ const none = createFileCardResolver({ metrics, theme: plainTheme });
1219
+ assert.equal(none.registered, false);
1220
+ assert.doesNotThrow(() => none.resolver('read', () => undefined));
1221
+
1222
+ // A hook that throws is the same as none.
1223
+ const hostile = createFileCardResolver({
1224
+ metrics,
1225
+ theme: plainTheme,
1226
+ registerToolRenderer: () => {
1227
+ throw new Error('hook refused');
1228
+ },
1229
+ });
1230
+ assert.equal(hostile.registered, false);
1231
+ assert.match(unpaint(hostile.resolver('read', () => HOST).renderCall({ path: ODD }, plainTheme, { isPartial: false }).render(60)[0]), /📑 odd/u);
1232
+
1233
+ // The measurement seam is part of the contract, and the factory says which one is missing.
1234
+ assert.throws(() => createFileCardResolver(), /metrics/u);
1235
+ const broken = { ...metrics, wrapTextWithAnsi: undefined };
1236
+ assert.throws(() => createFileCardResolver({ metrics: broken }), /wrapTextWithAnsi/u);
1237
+
1238
+ // A seam resolved late (the host's TUI package is loaded inside the hook) is read per paint.
1239
+ const late = createFileCardResolver({
1240
+ metrics: () => metrics,
1241
+ theme: plainTheme,
1242
+ registerToolRenderer: (resolver) => seen.push(resolver),
1243
+ });
1244
+ assert.equal(late.resolver('read', () => HOST).renderShell, 'self');
1245
+ // A seam that resolves to nothing leaves the row to the host.
1246
+ const absent = createFileCardResolver({
1247
+ metrics: () => undefined,
1248
+ theme: plainTheme,
1249
+ registerToolRenderer: (resolver) => seen.push(resolver),
1250
+ });
1251
+ assert.equal(absent.resolver('read', () => HOST), HOST, 'the host\'s own row keeps the row');
1252
+ });
1253
+
1254
+ test('registerFileCard wires the Pi host in, and a host without the hook loses nothing', () => {
1255
+ const registered = [];
1256
+ const outcome = registerFileCard({ registerToolRenderer: (resolver) => registered.push(resolver) }, { metrics, theme: plainTheme });
1257
+ assert.equal(outcome.registered, true);
1258
+ assert.equal(registered.length, 1, 'exactly one resolver reached the host');
1259
+ assert.equal(registered[0], outcome.resolver);
1260
+
1261
+ assert.deepEqual(registerFileCard(undefined, { metrics, theme: plainTheme }), { registered: false, resolver: undefined });
1262
+ assert.deepEqual(registerFileCard({}, { metrics, theme: plainTheme }), { registered: false, resolver: undefined });
1263
+ // A host whose hook throws, and a missing seam: the card is cosmetic, so both fail open.
1264
+ const hostile = registerFileCard({ registerToolRenderer: () => { throw new Error('no'); } }, { metrics, theme: plainTheme });
1265
+ assert.equal(hostile.registered, false);
1266
+ assert.equal(registerFileCard({ registerToolRenderer: () => {} }, {}).registered, false);
1267
+ });
1268
+
1269
+ // ---- purity ----
1270
+
1271
+ test('the card modules carry no colour, no escape and no host package', () => {
1272
+ for (const file of ['file-card.js', 'file-card-resolver.js']) {
1273
+ const source = readFileSync(join(__dirname, '..', 'lib', file), 'utf8');
1274
+ assert.doesNotMatch(source, /@earendil-works/u, `${file} requires no host package`);
1275
+ assert.doesNotMatch(source, /\\u001b|\\x1b|String\.fromCharCode\(27\)/u, `${file} writes no escape sequence down`);
1276
+ assert.doesNotMatch(source, /#[0-9a-fA-F]{6}\b/u, `${file} writes no hexadecimal colour`);
1277
+ assert.doesNotMatch(source, /require\(['"](?!\.\/|node:)/u, `${file} imports only its own modules and Node builtins`);
1278
+ assert.doesNotMatch(source, /registerTool\(|\.execute\b|registerCommand\(/u, `${file} registers and runs nothing`);
1279
+ }
1280
+ // This card's own tone table is `lib/shell-card.js`'s alone. The ONLY background
1281
+ // roles named here are the host's own box roles, reproduced for the rows this card
1282
+ // hands back (a resolver cannot see a call's args, so it cannot tell the host's
1283
+ // default-shell read/write rows apart at claim time).
1284
+ const card = readFileSync(join(__dirname, '..', 'lib', 'file-card.js'), 'utf8');
1285
+ const named = [...card.matchAll(/\btool[A-Za-z]+Bg\b/gu)].map((match) => match[0]);
1286
+ assert.deepEqual([...new Set(named)].sort(), ['toolErrorBg', 'toolPendingBg', 'toolSuccessBg'], 'only the host box\'s three roles are named');
1287
+ const resolver = readFileSync(join(__dirname, '..', 'lib', 'file-card-resolver.js'), 'utf8');
1288
+ assert.doesNotMatch(resolver, /tool(?:Success|Pending|Error)Bg/u, 'the resolver names no background role at all');
1289
+ });