pi-odd-worktree 2.1.0 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +54 -319
  2. package/extensions/odd-worktree-tools.ts +4182 -2539
  3. package/lib/bash-activity.js +1166 -0
  4. package/lib/bash-design.js +684 -0
  5. package/lib/bash-destructive.js +559 -0
  6. package/lib/bash-frame.js +205 -0
  7. package/lib/card-content.js +23 -0
  8. package/lib/card-style.js +175 -0
  9. package/lib/checkout-facts.js +30 -70
  10. package/lib/codegraph-card-preview.js +628 -0
  11. package/lib/codegraph-card.js +515 -0
  12. package/lib/codegraph-compaction.js +76 -0
  13. package/lib/codegraph-daemon.js +246 -0
  14. package/lib/codegraph-edit-sync.js +182 -0
  15. package/lib/codegraph-guard-target.js +337 -0
  16. package/lib/codegraph-guard.js +211 -0
  17. package/lib/codegraph-index.js +1020 -0
  18. package/lib/codegraph-lock.js +607 -0
  19. package/lib/codegraph-mcp-config.js +134 -0
  20. package/lib/codegraph-mcp.js +123 -0
  21. package/lib/codegraph-paths.js +69 -0
  22. package/lib/codegraph-prompt/explore.md +11 -0
  23. package/lib/codegraph-prompt/fix.md +6 -0
  24. package/lib/codegraph-prompt/generic.md +8 -0
  25. package/lib/codegraph-prompt/judge.md +9 -0
  26. package/lib/codegraph-prompt/orchestrator.md +17 -0
  27. package/lib/codegraph-prompt/verify.md +10 -0
  28. package/lib/codegraph-prompt/worker.md +7 -0
  29. package/lib/codegraph-role.js +55 -0
  30. package/lib/codegraph-rules.js +146 -0
  31. package/lib/codegraph-session.js +303 -383
  32. package/lib/codegraph-warmup.js +139 -0
  33. package/lib/file-card-markdown.js +141 -0
  34. package/lib/file-card-resolver.js +245 -0
  35. package/lib/file-card.js +659 -0
  36. package/lib/files-index.js +387 -0
  37. package/lib/files-insert.js +81 -0
  38. package/lib/files-orders.js +326 -0
  39. package/lib/files-picker-view.js +1421 -0
  40. package/lib/files-preview.js +338 -0
  41. package/lib/files-scope-detail.js +171 -0
  42. package/lib/files-scope-view.js +507 -0
  43. package/lib/gh-issues.js +323 -15
  44. package/lib/issue-preview.js +26 -7
  45. package/lib/issues-bash-mutation.js +206 -0
  46. package/lib/issues-cache-store.js +261 -0
  47. package/lib/issues-section.js +710 -0
  48. package/lib/issues-view.js +649 -52
  49. package/lib/odd-prompt/odd-worktrees.md +21 -0
  50. package/lib/odd-worktrees-prompt.js +10 -28
  51. package/lib/related-issues-cache.js +210 -0
  52. package/lib/shell-card.js +825 -0
  53. package/lib/skill-odd-card.js +183 -0
  54. package/lib/tui-paint.js +4 -5
  55. package/lib/warp-create-panel.js +538 -250
  56. package/lib/warp-create-picker.js +56 -9
  57. package/lib/warp-delete-confirm.js +19 -28
  58. package/lib/warp-selector-view.js +160 -82
  59. package/lib/which-command.js +90 -0
  60. package/lib/worktree-card.js +267 -897
  61. package/lib/worktree-cards.js +383 -0
  62. package/lib/worktree-create.js +287 -0
  63. package/lib/worktree-git.js +3 -3
  64. package/lib/worktree-guard.js +548 -0
  65. package/lib/worktree-hooks.js +421 -712
  66. package/lib/worktree-list.js +120 -0
  67. package/lib/worktree-registry.js +162 -879
  68. package/lib/{worktree-close-herdr.js → worktree-remove.js} +9 -11
  69. package/lib/worktree-setup-runner.js +376 -0
  70. package/lib/worktree-setup.js +140 -0
  71. package/lib/worktree-warp-busy.js +462 -85
  72. package/lib/worktree-warp-sessions.js +1 -2
  73. package/package.json +2 -2
  74. package/tools/bash-activity.test.js +1420 -0
  75. package/tools/bash-design.test.js +1093 -0
  76. package/tools/bash-destructive.test.js +139 -0
  77. package/tools/card-content.test.js +44 -0
  78. package/tools/card-style.test.js +298 -0
  79. package/tools/codegraph-card-preview.test.js +254 -0
  80. package/tools/codegraph-card.test.js +1080 -0
  81. package/tools/codegraph-compaction.test.js +378 -0
  82. package/tools/codegraph-daemon.test.js +248 -0
  83. package/tools/codegraph-edit-sync.test.js +295 -0
  84. package/tools/codegraph-guard-target.test.js +174 -0
  85. package/tools/codegraph-guard.test.js +238 -0
  86. package/tools/codegraph-index.test.js +1948 -0
  87. package/tools/codegraph-lock.test.js +932 -0
  88. package/tools/codegraph-mcp-config.test.js +181 -0
  89. package/tools/codegraph-mcp.test.js +194 -0
  90. package/tools/codegraph-paths.test.js +44 -0
  91. package/tools/codegraph-role.test.js +30 -0
  92. package/tools/codegraph-rules.test.js +250 -0
  93. package/tools/codegraph-session.test.js +660 -391
  94. package/tools/codegraph-warmup.test.js +316 -0
  95. package/tools/commands.test.js +510 -31
  96. package/tools/file-card-markdown.test.js +188 -0
  97. package/tools/file-card.test.js +1289 -0
  98. package/tools/files-bridge.test.js +575 -0
  99. package/tools/files-command.test.js +613 -0
  100. package/tools/files-index.test.js +473 -0
  101. package/tools/files-insert.test.js +139 -0
  102. package/tools/files-orders.test.js +597 -0
  103. package/tools/files-picker-view.test.js +1889 -0
  104. package/tools/files-preview.test.js +452 -0
  105. package/tools/files-scope-detail.test.js +264 -0
  106. package/tools/files-scope-view.test.js +614 -0
  107. package/tools/fixtures/card-codegraph-outputs.js +110 -0
  108. package/tools/fixtures/codegraph-cli-stub.js +16 -0
  109. package/tools/fixtures/codegraph-init-process.js +28 -0
  110. package/tools/fixtures/codegraph-lock-worker.js +117 -0
  111. package/tools/fixtures/daemon-fake.js +98 -0
  112. package/tools/fixtures/daemon-mcp-server.js +39 -0
  113. package/tools/fixtures/daemon-warmup-worker.js +12 -0
  114. package/tools/fixtures/load-extension.js +136 -3
  115. package/tools/gh-issues-feedback.test.js +31 -7
  116. package/tools/gh-issues.test.js +417 -1
  117. package/tools/issue-preview.test.js +44 -7
  118. package/tools/issues-bash-mutation.test.js +101 -0
  119. package/tools/issues-cache-store.test.js +222 -0
  120. package/tools/issues-command.test.js +1517 -67
  121. package/tools/issues-open-guard.test.js +1096 -0
  122. package/tools/issues-section.test.js +4235 -0
  123. package/tools/issues-seed-query-regression.test.js +67 -0
  124. package/tools/issues-view.test.js +1489 -60
  125. package/tools/odd-worktrees-prompt.test.js +98 -65
  126. package/tools/package-surface.test.js +431 -36
  127. package/tools/related-issues-cache.test.js +324 -0
  128. package/tools/shell-card.test.js +834 -0
  129. package/tools/skill-odd-card.test.js +200 -0
  130. package/tools/t5-session-identity.test.js +44 -22
  131. package/tools/warp-busy-guard.test.js +2565 -309
  132. package/tools/warp-create-panel.test.js +499 -74
  133. package/tools/warp-create-picker.test.js +101 -5
  134. package/tools/warp-delete-confirm.test.js +49 -15
  135. package/tools/warp-empty-session.test.js +0 -1
  136. package/tools/warp-fallback-regression.test.js +533 -0
  137. package/tools/warp-selector-view.test.js +460 -196
  138. package/tools/which-command.test.js +126 -0
  139. package/tools/worktree-card.test.js +551 -0
  140. package/tools/worktree-cards.test.js +845 -0
  141. package/tools/worktree-changes.test.js +4 -5
  142. package/tools/worktree-create.test.js +489 -0
  143. package/tools/worktree-guard.test.js +823 -0
  144. package/tools/worktree-hooks.test.js +905 -0
  145. package/tools/worktree-list.test.js +170 -0
  146. package/tools/worktree-registry.test.js +89 -230
  147. package/tools/worktree-remove-async.test.js +318 -0
  148. package/tools/worktree-setup-runner.test.js +276 -0
  149. package/tools/worktree-setup.test.js +140 -0
  150. package/tools/worktree-tools.test.js +419 -199
  151. package/lib/codegraph-commands.js +0 -165
  152. package/lib/odd-prompt/odd-worktrees.with-codegraph.md +0 -19
  153. package/lib/odd-prompt/odd-worktrees.without-codegraph.md +0 -15
  154. package/lib/worktree-model-result.js +0 -291
  155. package/tools/codegraph-commands.test.js +0 -371
  156. package/tools/herdr-free-create.test.js +0 -161
  157. package/tools/worktree-close-herdr-async.test.js +0 -204
  158. package/tools/worktree-odd-migration.test.js +0 -224
  159. package/tools/worktree-registry-cache.test.js +0 -163
  160. package/tools/worktree-registry-odd.test.js +0 -231
@@ -0,0 +1,659 @@
1
+ 'use strict';
2
+ // T3 (S1/S2): the file card — a `read`, `edit` or `write` call whose `path` names a
3
+ // customized skill (`…/skills/<name>/SKILL.md`) or an ODD artifact (any file below an
4
+ // `odd/tasks/` folder) heads as that file, on the same substrate as this package's
5
+ // other cards (`lib/shell-card.js`), exactly as `lib/bash-card.js` heads a `bash` call
6
+ // as the activity its own command names.
7
+ //
8
+ // Ported from the user's gentle-shell PR #3061 (`lib/skill-odd-card.ts` and the
9
+ // `read`/`edit`/`write` heading in `extensions/quiet-tools.ts`, read read-only, L3),
10
+ // split so classification and drawing never share a decision: `lib/skill-odd-card.js`
11
+ // says WHICH card a path wears and which call shape it states (the file's name, the
12
+ // range only a read asked for, the Markdown document an expanded read or write draws);
13
+ // this module only dresses that answer.
14
+ //
15
+ // What the card never decides:
16
+ // * COLOUR. Every cell is a theme role — the identity's own `titleRole`
17
+ // (`mdHeading` for both identities), the tone's frame role, `muted`, `accent`,
18
+ // `warning`, `text`, `error`, `dim` — handed to the injected `theme.fg`. No hex
19
+ // value, no palette and no raw escape sequence is written down here, and the frame
20
+ // keeps the TONE's role whenever the tone owns the box (invariant 16), so a running
21
+ // or failed call is never painted in an identity colour. The heading states one role
22
+ // per element (S2): glyph and label in the identity's own role, the label
23
+ // additionally bold, the `·` in `muted`, the tool name in `dim`, the path in
24
+ // `accent`, a read's line range in `warning`. The card's whole closed box wears the
25
+ // identity's role too, so the title and the border read as one card.
26
+ // * MEASUREMENT. The substrate wraps, clips and pads the rows as PLAIN text and
27
+ // paints each one afterwards (invariant 17), so nothing painted is ever measured
28
+ // twice. The ODD mark is an emoji two columns wide, and only the injected metrics
29
+ // counts it: this module never hand-counts a glyph. A document body is the one
30
+ // exception, and it is the host's own: Pi's Markdown renderer hands back rows it
31
+ // ALREADY painted, so those rows are placed with the injected ANSI-aware width and
32
+ // never re-painted with a body role of ours (S5).
33
+ // * STATE. The tone follows the host's own flags (`isPartial`, `isError`), the
34
+ // expanded view is the host's own `expanded`, and the elapsed time is the host's
35
+ // own `durationMs`.
36
+ // * THE TOOL. Nothing is registered, executed or shadowed here: the resolver
37
+ // (`lib/file-card-resolver.js`) only chooses renderers for `read`, `edit` and
38
+ // `write`, and hands every row it does not own back exactly as the chain resolved
39
+ // it.
40
+ // * THE SWITCH (S1, read through `lib/card-tools-switch.js`) and the conversation's
41
+ // content level (S2, read through `lib/card-content.js`). Both are read on EVERY
42
+ // paint, inside the component's build, so flipping one repaints a row already on
43
+ // screen (L6).
44
+ //
45
+ // Rendering never throws: a theme, a host renderer or an argument that fails draws no
46
+ // rows instead of breaking the session's transcript.
47
+
48
+ const {
49
+ CARD_TONE,
50
+ cardAwaitingResult,
51
+ cardBodyRows,
52
+ cardBottom,
53
+ cardElapsed,
54
+ cardInnerWidth,
55
+ cardPaintedRows,
56
+ cardRunningLine,
57
+ cardTopLine,
58
+ cardTopRows,
59
+ floatRows,
60
+ markCardResult,
61
+ } = require('./shell-card.js');
62
+ const { CARD_CONTENT, cardContentLevel } = require('./card-content.js');
63
+ // The document body, drawn by Pi's own Markdown renderer (S3) with one theme role per
64
+ // element. Its rows arrive PAINTED, which is what the pre-painted row shape is for.
65
+ const { markdownRows } = require('./file-card-markdown.js');
66
+ const {
67
+ FILE_CARD_IDENTITY,
68
+ FILE_CARD_TOOLS,
69
+ fileCardIdentity,
70
+ fileCardLineRange,
71
+ fileCardName,
72
+ fileCardSkillPath,
73
+ markdownDocumentSource,
74
+ } = require('./skill-odd-card.js');
75
+ // `cardText` is the one reader of a tool's text as a card draws it (what it printed,
76
+ // without the terminal sequences around it), so this card reuses it rather than
77
+ // keeping a second, differently-behaved copy of the same three regexes.
78
+ const { cardText } = require('./codegraph-card-preview.js');
79
+
80
+ /** The three tools this card owns, from the one place that states the claim. Nothing else is ever claimed. */
81
+ const FILE_TOOLS = FILE_CARD_TOOLS;
82
+ const EDIT_TOOL = 'edit';
83
+ const WRITE_TOOL = 'write';
84
+ const BODY_ROLE = 'text';
85
+ const ERROR_ROLE = 'error';
86
+
87
+ // The collapsed preview budget, in printed rows. A document previews from its TOP:
88
+ // the first rows are what a reader recognises a file by, unlike a command's output,
89
+ // whose summary is written last.
90
+ const PREVIEW_ROWS = 3;
91
+
92
+ // The host keybinding the expand affordance is bound to, and the two verbs the
93
+ // heading offers for it. The host paints the hint itself; this module only places it.
94
+ const EXPAND_KEYBINDING = 'app.tools.expand';
95
+ const EXPAND_TEXT = { collapsed: 'to expand', expanded: 'to collapse' };
96
+
97
+ // The blank lines a trailing newline leaves at the end of a document.
98
+ const TRAILING_BLANK = /(?:\n[ \t]*)+$/;
99
+
100
+ // The three background roles the host's own outer shell wears, and the one column of
101
+ // horizontal padding it defaults to.
102
+ const HOST_BOX = Object.freeze({
103
+ PENDING: 'toolPendingBg',
104
+ ERROR: 'toolErrorBg',
105
+ SUCCESS: 'toolSuccessBg',
106
+ });
107
+ const HOST_BOX_PAD = 1;
108
+ // The two shells a tool renderer can declare. The host reads `renderShell ?? 'default'`,
109
+ // so anything that is not the literal `self` is the default shell.
110
+ const HOST_SHELL = Object.freeze({ DEFAULT: 'default', SELF: 'self' });
111
+
112
+ // A component that draws nothing: the answer of every path that cannot draw.
113
+ const EMPTY_COMPONENT = { render: () => [], invalidate() {} };
114
+ // No injected theme, and a host that passed none: text is drawn plain rather than not at all.
115
+ const PLAIN_THEME = { fg: (_role, text) => text };
116
+
117
+ const asObject = (value) => (value !== null && typeof value === 'object' ? value : {});
118
+ const hasFunction = (value, name) => value !== null && typeof value === 'object' && typeof value[name] === 'function';
119
+
120
+ /**
121
+ * The tone one call or result is drawn in: the host's own flags decide it — a failure
122
+ * is the error tone, anything still running the warning one, everything else info.
123
+ */
124
+ function cardTone(failed, running) {
125
+ if (failed) return CARD_TONE.ERROR;
126
+ return running ? CARD_TONE.WARNING : CARD_TONE.INFO;
127
+ }
128
+
129
+ // ---- the heading ----
130
+
131
+ /**
132
+ * The heading one call wears, or undefined when the path names no card identity (then
133
+ * the row is the chain's, untouched).
134
+ *
135
+ * The heading is the identity's mark and label, then the tool, the path and — for a
136
+ * read only — the line range the call asked for (L3). Collapsed, an ODD artifact is
137
+ * named by its file, because its folder is long (`odd/tasks/…`) and the file's own name
138
+ * is what a reader looks for, while a skill is named from its own folder down, because
139
+ * the folders above `skills` say nothing a reader of the workspace does not know.
140
+ * Expanding the call states the whole path in both cases, so nothing is lost.
141
+ *
142
+ * Beside the plain text, the heading states the roles each element wears (S2), because
143
+ * the substrate measures plain text and paints afterwards: `subtitleSegments` is that
144
+ * list, and `subtitle` is exactly its text.
145
+ */
146
+ function fileCardHeading(tool, args, expanded) {
147
+ const call = asObject(args);
148
+ const path = typeof call.path === 'string' ? call.path : '';
149
+ const identity = fileCardIdentity(path);
150
+ if (identity === undefined) return undefined;
151
+ const range = fileCardLineRange(tool, args) ?? '';
152
+ const whole = headingSegments(tool, path, range);
153
+ const file = identity.identity === FILE_CARD_IDENTITY.ODD ? fileCardName(path) : fileCardSkillPath(path);
154
+ const named = headingSegments(tool, file, range);
155
+ const segments = expanded === true ? whole : named;
156
+ return {
157
+ identity: identity.identity,
158
+ glyph: identity.glyph,
159
+ title: identity.title,
160
+ titleRole: identity.titleRole,
161
+ subtitle: segmentsText(segments),
162
+ collapsed: segmentsText(named),
163
+ // The label is bolded inside the identity's own role (S2), never the glyph.
164
+ labelBold: true,
165
+ subtitleSegments: segments,
166
+ };
167
+ }
168
+
169
+ /**
170
+ * The heading's detail as the segments it is made of: the tool name in `dim`, a space,
171
+ * the path in `accent` and a read's range in `warning`. The `·` between the label and
172
+ * this detail is the substrate's own `muted` separator, so it is not one of them.
173
+ */
174
+ function headingSegments(tool, name, range) {
175
+ const segments = [];
176
+ if (tool !== '') segments.push({ text: tool, role: 'dim' });
177
+ if (name !== '') {
178
+ if (segments.length > 0) segments.push({ text: ' ' });
179
+ segments.push({ text: name, role: 'accent' });
180
+ }
181
+ if (range !== '') segments.push({ text: range, role: 'warning' });
182
+ return segments;
183
+ }
184
+
185
+ /** The plain text a segment list states — what the substrate measures. */
186
+ const segmentsText = (segments) => segments.map((segment) => segment.text).join('');
187
+
188
+ // ---- the drawing ----
189
+
190
+ /** The theme a render is painted with: the host's own when it has one, else the injected fallback. */
191
+ function themeFor(theme, fallback) {
192
+ if (hasFunction(theme, 'fg')) return theme;
193
+ if (hasFunction(fallback, 'fg')) return fallback;
194
+ return PLAIN_THEME;
195
+ }
196
+
197
+ /** The text of a tool result: the host's `content` parts, or the `{text}` a forwarded result carries. */
198
+ function resultText(result) {
199
+ const value = asObject(result);
200
+ if (typeof value.text === 'string') return value.text;
201
+ const parts = Array.isArray(value.content) ? value.content : [];
202
+ return parts
203
+ .map((part) => (typeof asObject(part).text === 'string' ? asObject(part).text : ''))
204
+ .filter((text) => text.length > 0)
205
+ .join('\n');
206
+ }
207
+
208
+ /**
209
+ * What one result states as rows: an edit is its DIFF (the change the host carries),
210
+ * never the file read back as a document; every other call is the text the result
211
+ * reported — and a write's document comes from its call, not from here.
212
+ */
213
+ function fileResultText(tool, result) {
214
+ const value = asObject(result);
215
+ if (tool === EDIT_TOOL) {
216
+ const diff = asObject(value.details).diff;
217
+ if (typeof diff === 'string') return diff;
218
+ }
219
+ return resultText(result);
220
+ }
221
+
222
+ /**
223
+ * The document a write's own CALL carries — the file it wrote. The result only reports how
224
+ * many bytes landed, so it is never a write's body (S3): when the host's renderer cannot
225
+ * draw the document, this is the plain source the card falls back to, which is what the
226
+ * baseline showed. A call carrying no content states nothing rather than the byte count.
227
+ */
228
+ function writtenContent(args) {
229
+ const content = asObject(args).content;
230
+ return typeof content === 'string' ? content : '';
231
+ }
232
+
233
+ /** The result's text as a card draws it: terminal sequences gone, line endings normalized, trailing blanks dropped. */
234
+ function plainText(text) {
235
+ return cardText(text).replace(/\r\n/g, '\n').replace(TRAILING_BLANK, '');
236
+ }
237
+
238
+ function optionFlag(options, context, key) {
239
+ return asObject(options)[key] === true || asObject(context)[key] === true;
240
+ }
241
+
242
+ /** The right-aligned dim hint the heading offers: the host's own keybinding text for expanding (or collapsing) the card. */
243
+ function expandHint(context, expanded) {
244
+ const keyHint = asObject(context).keyHint;
245
+ if (typeof keyHint !== 'function') return undefined;
246
+ try {
247
+ const text = keyHint(EXPAND_KEYBINDING, expanded ? EXPAND_TEXT.expanded : EXPAND_TEXT.collapsed);
248
+ return typeof text === 'string' && text.length > 0 ? text : undefined;
249
+ } catch {
250
+ return undefined;
251
+ }
252
+ }
253
+
254
+ /**
255
+ * A component whose rows are built again on every paint, so the host's own width, both
256
+ * switches, the content level and the card style all apply to the card already on
257
+ * screen. Rendering never throws: a failure draws no rows instead of breaking the
258
+ * transcript.
259
+ */
260
+ function component(build) {
261
+ return {
262
+ render(width) {
263
+ try {
264
+ return build(Math.max(0, Math.floor(Number.isFinite(width) ? width : 0)));
265
+ } catch {
266
+ return [];
267
+ }
268
+ },
269
+ invalidate() {
270
+ // Nothing is cached: there is no measurement and no row to invalidate.
271
+ },
272
+ };
273
+ }
274
+
275
+ /** One slot of the host's own drawing, called exactly as the host would have called it. */
276
+ function forwardedComponent(inherited, slot, args) {
277
+ try {
278
+ const renderer = asObject(inherited)[slot];
279
+ if (typeof renderer !== 'function') return EMPTY_COMPONENT;
280
+ const drawn = renderer(...args);
281
+ return hasFunction(drawn, 'render') ? drawn : EMPTY_COMPONENT;
282
+ } catch {
283
+ return EMPTY_COMPONENT;
284
+ }
285
+ }
286
+
287
+ /** The renderers the rest of the resolver chain would use for this row, resolved once. */
288
+ function inheritedRenderers(next) {
289
+ try {
290
+ return typeof next === 'function' ? next() : undefined;
291
+ } catch {
292
+ return undefined;
293
+ }
294
+ }
295
+
296
+ // ---- the host's own outer box, for the rows this card hands back ----
297
+ //
298
+ // `pi.registerToolRenderer` resolvers run per TOOL NAME — the host resolves
299
+ // `resolveToolRenderers(toolName, base)` — so a resolver never sees a call's arguments
300
+ // and its `renderShell` is fixed for every call of that tool. This package claims
301
+ // read/edit/write so it can draw the file card, and it declares `renderShell: 'self'`,
302
+ // which REMOVES the host's own shell: right for the rows this card draws (they carry
303
+ // their own frame), wrong for the rows it forwards. The host's own `read` and `write`
304
+ // renderers are the DEFAULT shell, which the host wraps in `new Box(1, 1, bgFn)` —
305
+ // `outputPad` columns of horizontal padding, ONE painted blank row above the call and
306
+ // one below the result, all painted `toolPendingBg` while the call streams,
307
+ // `toolErrorBg` once its result failed and `toolSuccessBg` otherwise
308
+ // (`ToolExecutionComponent`). Without reproducing that box, every ordinary
309
+ // read/write row this card hands back would lose the box it has always had — a visual
310
+ // regression the request never asked for. So the rows we do not draw are drawn exactly
311
+ // as the host would have drawn them, and the `self` shell still applies only to our own
312
+ // card.
313
+
314
+ /**
315
+ * The shell the chain's own renderer draws in, read ONCE at resolver time: only the
316
+ * literal `self` is one, exactly as the host decides (`renderShell ?? 'default'`). A
317
+ * `self` renderer frames itself and the host draws NO box around it — Pi's `edit` is
318
+ * one — so its rows are handed back untouched instead of inside a box the host never
319
+ * draws.
320
+ */
321
+ function inheritedShell(inherited) {
322
+ return asObject(inherited).renderShell === HOST_SHELL.SELF ? HOST_SHELL.SELF : HOST_SHELL.DEFAULT;
323
+ }
324
+
325
+ /**
326
+ * The background role the host's own outer box wears for one state, resolved in the
327
+ * host's own order: still streaming, then failed, then success.
328
+ */
329
+ function hostBoxRole(context) {
330
+ const ctx = asObject(context);
331
+ if (ctx.isPartial !== false) return HOST_BOX.PENDING;
332
+ if (ctx.isError === true) return HOST_BOX.ERROR;
333
+ return HOST_BOX.SUCCESS;
334
+ }
335
+
336
+ /** The host box's horizontal padding: the render context's own `outputPad`, else one column. */
337
+ function hostBoxPad(context) {
338
+ const value = asObject(context).outputPad;
339
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.floor(value) : HOST_BOX_PAD;
340
+ }
341
+
342
+ /** One finished row painted with the host box's background; a theme that cannot paint one keeps the row plain. */
343
+ function paintBackground(paint, role, text) {
344
+ try {
345
+ if (!hasFunction(paint, 'bg')) return text;
346
+ const painted = paint.bg(role, text);
347
+ return typeof painted === 'string' ? painted : text;
348
+ } catch {
349
+ return text;
350
+ }
351
+ }
352
+
353
+ /**
354
+ * One row inside the host's box, exactly as `Box.applyBg` draws it: the left pad, the
355
+ * row, the plain fill to the asked width, and then the background painted over the
356
+ * whole padded row. A row wider than the budget keeps every column and loses only the
357
+ * fill; a row this module cannot pad is handed back as the chain drew it.
358
+ */
359
+ function hostBoxRow(row, width, pad, role, paint, metrics) {
360
+ const text = typeof row === 'string' ? row : '';
361
+ try {
362
+ const padded = `${' '.repeat(pad)}${text}`;
363
+ const fill = Math.max(0, Math.floor(width) - metrics.visibleWidth(padded));
364
+ return paintBackground(paint, role, padded + ' '.repeat(fill));
365
+ } catch {
366
+ return text;
367
+ }
368
+ }
369
+
370
+ /**
371
+ * The rows of one of the chain's own components, inside the box the host would have
372
+ * wrapped them in — or exactly as drawn, when the chain's renderer frames itself.
373
+ *
374
+ * `layout` says which side of the box this group carries: `leading` (the blank row
375
+ * above the call), `trailing` (the blank row below the result — or below an awaiting
376
+ * call, because the host paints a complete box before the result lands), and the
377
+ * `shell` read once at resolver time. A flag may be a function, so the closing blank
378
+ * is re-decided on every paint.
379
+ *
380
+ * Never throws and never loses content: no measurement seam (so no box this module can
381
+ * size) or a component that fails to render draws nothing at all — the host's own box
382
+ * draws nothing around a child with no rows either.
383
+ *
384
+ * The width of an inherited row is measured with the injected ANSI-aware seam: these
385
+ * rows arrive PAINTED from the host's own renderer, so this is the same one exception
386
+ * invariant 17 grants the host's own key hint — nothing this repo painted is measured
387
+ * here, and only the padded row is painted afterwards.
388
+ */
389
+ function hostShellRows(drawn, width, context, paint, seams, layout) {
390
+ try {
391
+ const target = Math.max(0, Math.floor(Number.isFinite(width) ? width : 0));
392
+ if (target === 0) return [];
393
+ // A renderer that frames itself is drawn by the host with no box at all: no pad,
394
+ // no blank rows and no background paint.
395
+ if (asObject(layout).shell === HOST_SHELL.SELF) {
396
+ const own = drawn.render(target);
397
+ return Array.isArray(own) ? own : [];
398
+ }
399
+ const metrics = seams.metrics();
400
+ if (metrics === undefined) return drawn.render(target);
401
+ const pad = hostBoxPad(context);
402
+ // The host's own `Box` renders its children at `max(1, width - paddingX * 2)`.
403
+ const rows = drawn.render(Math.max(1, target - pad * 2));
404
+ if (!Array.isArray(rows) || rows.length === 0) return [];
405
+ const role = hostBoxRole(context);
406
+ // The box's own padding rows are `applyBg('', width)`: full-width spaces, painted.
407
+ const blank = paintBackground(paint, role, ' '.repeat(target));
408
+ return [
409
+ ...(asObject(layout).leading === true ? [blank] : []),
410
+ ...rows.map((row) => hostBoxRow(row, target, pad, role, paint, metrics)),
411
+ ...(layoutFlag(layout, 'trailing') ? [blank] : []),
412
+ ];
413
+ } catch {
414
+ return [];
415
+ }
416
+ }
417
+
418
+ /** A layout flag, which the caller may decide per paint (an awaiting call's closing blank). */
419
+ function layoutFlag(layout, key) {
420
+ const value = asObject(layout)[key];
421
+ return typeof value === 'function' ? value() === true : value === true;
422
+ }
423
+
424
+ /** A component that draws the chain's own row inside the host's box, rebuilt on every paint. */
425
+ function hostShellComponent(drawn, context, paint, seams, layout) {
426
+ return {
427
+ render(width) {
428
+ return hostShellRows(drawn, width, context, paint, seams, layout);
429
+ },
430
+ invalidate() {
431
+ try {
432
+ if (hasFunction(drawn, 'invalidate')) drawn.invalidate();
433
+ } catch {
434
+ // Nothing is cached here, so a component that cannot be invalidated leaves no stale row.
435
+ }
436
+ },
437
+ };
438
+ }
439
+
440
+ /**
441
+ * The rows of a call card: the identity's heading over the file's own call line. Plain
442
+ * rows, built for one width, so the caller can rebuild them on every frame.
443
+ *
444
+ * `detail` is what the collapsed row states and `subtitle` what the expanded one does,
445
+ * which is how an ODD call names its file while collapsed and its whole path once the
446
+ * reader opens it.
447
+ */
448
+ function fileCallRows(tool, args, context, paint, metrics, width) {
449
+ const ctx = asObject(context);
450
+ const expanded = ctx.expanded === true;
451
+ const heading = fileCardHeading(tool, args, expanded);
452
+ if (heading === undefined) return [];
453
+ const pending = ctx.isPartial !== false;
454
+ const failed = ctx.isError === true;
455
+ const tone = cardTone(failed, pending);
456
+ // A running or failed call offers no expand affordance: there is nothing settled
457
+ // behind it to reveal, exactly as the bash and CodeGraph cards decide.
458
+ const hint = pending || failed ? undefined : expandHint(ctx, expanded);
459
+ const card = {
460
+ glyph: heading.glyph,
461
+ title: heading.title,
462
+ subtitle: heading.subtitle,
463
+ subtitleSegments: heading.subtitleSegments,
464
+ labelBold: heading.labelBold,
465
+ tone,
466
+ titleRole: heading.titleRole,
467
+ // The identity's role around the whole closed box, not only its label: the corners,
468
+ // the rules and the sides of an idle card are the same colour as its title. The tone
469
+ // still speaks first (`TONE_OWNS_BOX`), so a running or failed call keeps its own.
470
+ railRole: heading.titleRole,
471
+ };
472
+ return floatRows(tone, paint, width, (inner) => {
473
+ // Collapsed, the heading is one row and a detail too wide ends in an ellipsis;
474
+ // expanded, the whole path continues on the rows below, so a deep path is never
475
+ // lost behind a truncation.
476
+ const head = expanded
477
+ ? cardTopRows(card, paint, inner, hint, metrics)
478
+ : [cardTopLine(card, paint, inner, hint, () => heading.collapsed, metrics)];
479
+ const body = pending && !failed ? [cardRunningLine(tone, paint, inner, metrics)] : [];
480
+ // The result that follows owns the closing rule; a call still waiting for it
481
+ // closes its own frame, so a running row never floats outside one.
482
+ const bottom = cardAwaitingResult(ctx) ? cardBottom(tone, paint, inner, undefined, metrics) : undefined;
483
+ return { head, body, bottom };
484
+ }, card.railRole);
485
+ }
486
+
487
+ /**
488
+ * The rows a result body draws, before the card paints them.
489
+ *
490
+ * `content` is the level in force: `minimal` draws the call alone — with no body until
491
+ * the reader expands it — and `default` the bounded preview. A failure still says why
492
+ * at either level, because a card that hid the reason would report a call that failed
493
+ * as one that did nothing.
494
+ *
495
+ * A document is drawn by Pi's own Markdown renderer (S3) and arrives as rows it already
496
+ * painted, in the theme roles the substrate must not paint over (S5); the preview is
497
+ * the first `PREVIEW_ROWS` of exactly those rows (S4). When the renderer yields nothing
498
+ * — no TUI package, a theme it cannot paint, a document it refuses — the source is the
499
+ * card's answer, wrapped and unstyled by the plain path below.
500
+ */
501
+ function fileResultRows(input) {
502
+ const value = asObject(input);
503
+ const failed = value.failed === true;
504
+ const expanded = value.expanded === true;
505
+ if (value.content === CARD_CONTENT.MINIMAL && !expanded && !failed) return [];
506
+ const role = failed ? ERROR_ROLE : BODY_ROLE;
507
+ const markdown = typeof value.markdown === 'string' ? value.markdown : undefined;
508
+ // A host with no renderer of its own draws no document: the plain path below answers.
509
+ if (markdown !== undefined && typeof value.markdownClass === 'function') {
510
+ const painted = markdownRows(markdown, value.theme, value.width, value.markdownClass);
511
+ if (painted.length > 0) return [{ painted }];
512
+ }
513
+ const text = plainText(value.text);
514
+ // Whitespace alone states nothing: a blank body row would claim the file had content
515
+ // the card could show.
516
+ if (text.trim().length === 0) return [];
517
+ const shown = expanded ? text : text.split('\n').slice(0, PREVIEW_ROWS).join('\n');
518
+ return [{ text: shown, role }];
519
+ }
520
+
521
+ /**
522
+ * The call slot. The identity and the ONE switch are both decided INSIDE the
523
+ * component's build, so the host's `render(width)` re-reads them on every frame: a card
524
+ * already on screen repaints when the bridge's `Card tools` line changes (L6), and the
525
+ * measurement seam is asked for at paint time rather than at construction.
526
+ *
527
+ * A path that names neither identity returns the chain's own component straight away,
528
+ * because no switch could ever make that row this card's.
529
+ */
530
+ function fileCallSlot(tool, inherited, seams, shell) {
531
+ return (args, theme, context) => {
532
+ try {
533
+ const ctx = asObject(context);
534
+ const callArgs = args === undefined ? ctx.args : args;
535
+ const identity = fileCardIdentity(asObject(callArgs).path);
536
+ const paint = themeFor(theme, seams.theme);
537
+ // The host's box opens above the call, and closes below the call while it still
538
+ // awaits its result: the host paints a complete box before the result lands, and
539
+ // the result then supplies the same closing blank in its place.
540
+ const layout = { shell, leading: true, trailing: () => cardAwaitingResult(ctx) || ctx.isPartial !== false };
541
+ // No identity means no switch could ever make this row the card's: the chain's own
542
+ // component, drawn inside the host's box, is the answer for every frame.
543
+ if (identity === undefined) {
544
+ return hostShellComponent(forwardedComponent(inherited, 'renderCall', [args, theme, context]), ctx, paint, seams, layout);
545
+ }
546
+ return component((width) => {
547
+ if (!seams.enabled(tool)) {
548
+ return hostShellRows(forwardedComponent(inherited, 'renderCall', [args, theme, context]), width, ctx, paint, seams, layout);
549
+ }
550
+ const metrics = seams.metrics();
551
+ if (metrics === undefined) {
552
+ return hostShellRows(forwardedComponent(inherited, 'renderCall', [args, theme, context]), width, ctx, paint, seams, layout);
553
+ }
554
+ return fileCallRows(tool, callArgs, ctx, paint, metrics, width);
555
+ });
556
+ } catch {
557
+ return EMPTY_COMPONENT;
558
+ }
559
+ };
560
+ }
561
+
562
+ /**
563
+ * The result slot. Like the call slot it decides nothing at construction: the switch,
564
+ * the level and the seam are read inside the build, so a card already on screen
565
+ * repaints when either changes.
566
+ */
567
+ function fileResultSlot(tool, inherited, seams, shell) {
568
+ return (result, options, theme, context) => {
569
+ try {
570
+ const ctx = asObject(context);
571
+ const slotArgs = [result, options, theme, context];
572
+ const args = ctx.args;
573
+ const identity = fileCardIdentity(asObject(args).path);
574
+ const paint = themeFor(theme, seams.theme);
575
+ // The state the host's box is painted in, decided once per render exactly as the
576
+ // host decides its own background: still streaming, then failed, then success.
577
+ const failed = asObject(result).isError === true || optionFlag(options, ctx, 'isError');
578
+ const partial = optionFlag(options, ctx, 'isPartial');
579
+ const boxContext = { ...ctx, isPartial: partial, isError: failed };
580
+ // The box's closing blank belongs to the result, which follows the call above it.
581
+ const layout = { shell, leading: false, trailing: true };
582
+ if (identity === undefined) {
583
+ return hostShellComponent(forwardedComponent(inherited, 'renderResult', slotArgs), boxContext, paint, seams, layout);
584
+ }
585
+ return component((width) => {
586
+ if (!seams.enabled(tool)) {
587
+ return hostShellRows(forwardedComponent(inherited, 'renderResult', slotArgs), width, boxContext, paint, seams, layout);
588
+ }
589
+ const metrics = seams.metrics();
590
+ if (metrics === undefined) {
591
+ return hostShellRows(forwardedComponent(inherited, 'renderResult', slotArgs), width, boxContext, paint, seams, layout);
592
+ }
593
+ const expanded = optionFlag(options, ctx, 'expanded');
594
+ const tone = cardTone(failed, partial);
595
+ // A write states the document its call carried; its result says how many bytes
596
+ // landed, which is no body at all. Every other tool states what its result
597
+ // reported, and a FAILED write still states its error.
598
+ const text = tool === WRITE_TOOL && !failed ? writtenContent(args) : fileResultText(tool, result);
599
+ // One frame: from here on the call above is a heading and this card closes it.
600
+ markCardResult(ctx.state);
601
+ return floatRows(tone, paint, width, (inner) => {
602
+ // The level is asked for on every paint, so a preference switched on screen
603
+ // repaints the rows it decides.
604
+ const rows = fileResultRows({
605
+ text,
606
+ // A read draws the text it read; a write the content its call carries. An
607
+ // edit is declined by that rule, because an edit's rows are its diff. The
608
+ // document is asked for whatever the expansion — the collapsed card shows
609
+ // its first rows (S4), the expanded one the whole of it.
610
+ markdown: markdownDocumentSource(tool, args, resultText(result), { expanded: true, isError: failed }),
611
+ expanded,
612
+ failed,
613
+ content: seams.content(),
614
+ width: cardInnerWidth(inner),
615
+ theme: paint,
616
+ markdownClass: seams.markdownClass(),
617
+ });
618
+ const painted = rows.length > 0 && Array.isArray(rows[0].painted);
619
+ const role = rows.length > 0 ? rows[0].role : undefined;
620
+ // The document's own rows are placed as they were painted (S5): measured with
621
+ // the ANSI-aware seam and never handed the body role again.
622
+ const body = rows.length === 0
623
+ ? []
624
+ : painted
625
+ ? cardPaintedRows(rows[0].painted, tone, paint, inner, expanded ? { expanded: true } : { previewRows: PREVIEW_ROWS }, metrics)
626
+ : cardBodyRows(
627
+ rows.map((row) => row.text),
628
+ tone,
629
+ paint,
630
+ inner,
631
+ expanded ? { expanded: true, role } : { previewRows: PREVIEW_ROWS, role },
632
+ metrics,
633
+ );
634
+ // A streamed result is not finished: the closing rule (and the time on it)
635
+ // belongs to the final one, which the host renders when the call settles.
636
+ const bottom = partial ? undefined : cardBottom(tone, paint, inner, cardElapsed(ctx.durationMs), metrics);
637
+ // The call above owns the heading, so the float style still sets this body
638
+ // off from it with its separator row.
639
+ return { body, bottom, afterHeading: true };
640
+ }, identity.titleRole);
641
+ });
642
+ } catch {
643
+ return EMPTY_COMPONENT;
644
+ }
645
+ };
646
+ }
647
+
648
+ module.exports = {
649
+ FILE_TOOLS,
650
+ PREVIEW_ROWS,
651
+ fileCallRows,
652
+ fileCallSlot,
653
+ fileCardHeading,
654
+ fileResultRows,
655
+ fileResultSlot,
656
+ fileResultText,
657
+ inheritedRenderers,
658
+ inheritedShell,
659
+ };