pi-odd-worktree 3.15.1 → 3.16.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 (126) hide show
  1. package/README.md +48 -25
  2. package/extensions/odd-worktree-tools.ts +64 -211
  3. package/lib/shell-api/api.ts +523 -0
  4. package/lib/shell-api/arm.ts +83 -0
  5. package/lib/shell-api/bus.ts +1389 -0
  6. package/lib/shell-api/capture.ts +1340 -0
  7. package/lib/shell-api/card-style-line.ts +112 -0
  8. package/lib/shell-api/card-style-rows.ts +390 -0
  9. package/lib/shell-api/card-style-transform.ts +862 -0
  10. package/lib/shell-api/card-style-wiring.ts +477 -0
  11. package/lib/shell-api/card-styles.ts +153 -0
  12. package/lib/shell-api/config.ts +71 -0
  13. package/lib/shell-api/extension.ts +247 -0
  14. package/lib/shell-api/hook.ts +322 -0
  15. package/lib/shell-api/index.ts +88 -0
  16. package/lib/shell-api/message-design-adoption.ts +549 -0
  17. package/lib/shell-api/message-design-rows.ts +313 -0
  18. package/lib/shell-api/message-design-wiring.ts +369 -0
  19. package/lib/shell-api/message-designs.ts +746 -0
  20. package/lib/shell-api/notices.ts +137 -0
  21. package/lib/shell-api/plugin-lines.ts +877 -0
  22. package/lib/shell-api/presence.ts +258 -0
  23. package/lib/shell-api/repaint.ts +351 -0
  24. package/lib/shell-api/row-labels.ts +146 -0
  25. package/lib/shell-api/row-names.ts +273 -0
  26. package/lib/shell-api/row-origin.ts +144 -0
  27. package/lib/shell-api/rows.ts +591 -0
  28. package/lib/shell-api/section-panel.ts +378 -0
  29. package/lib/shell-api/section-pointer.ts +164 -0
  30. package/lib/shell-api/sections-preview.ts +275 -0
  31. package/lib/shell-api/sections-rows.ts +133 -0
  32. package/lib/shell-api/sidebar-render.ts +705 -0
  33. package/lib/shell-api/sidebar.ts +1126 -0
  34. package/lib/shell-api/store.ts +279 -0
  35. package/lib/shell-api/tool-design-adoption.ts +263 -0
  36. package/lib/shell-api/tool-design-rows.ts +307 -0
  37. package/lib/shell-api/tool-design-wiring.ts +481 -0
  38. package/lib/shell-api/tool-designs.ts +1411 -0
  39. package/lib/shell-api/transform-pipeline.ts +351 -0
  40. package/lib/shell-api/types.ts +803 -0
  41. package/lib/shell-api/visibility.ts +154 -0
  42. package/package.json +3 -2
  43. package/tools/files-bridge.test.js +81 -66
  44. package/tools/fixtures/load-extension.js +40 -18
  45. package/tools/issues-command.test.js +4 -7
  46. package/tools/issues-section.test.js +71 -81
  47. package/tools/odd-rail-wiring.test.js +16 -10
  48. package/tools/package-surface.test.js +42 -13
  49. package/tools/prs-command.test.js +11 -6
  50. package/tools/shell-api/api.test.ts +484 -0
  51. package/tools/shell-api/apply-on-move.test.ts +529 -0
  52. package/tools/shell-api/arm.test.ts +220 -0
  53. package/tools/shell-api/bridge-ready.test.ts +309 -0
  54. package/tools/shell-api/bus.test.ts +194 -0
  55. package/tools/shell-api/button-rows.test.ts +435 -0
  56. package/tools/shell-api/capture.test.ts +583 -0
  57. package/tools/shell-api/card-style-rows.test.ts +493 -0
  58. package/tools/shell-api/card-style-transform.test.ts +379 -0
  59. package/tools/shell-api/card-style-wiring.test.ts +258 -0
  60. package/tools/shell-api/card-styles-e2e.test.ts +502 -0
  61. package/tools/shell-api/card-styles.test.ts +324 -0
  62. package/tools/shell-api/card-transcript-path.test.ts +178 -0
  63. package/tools/shell-api/compatibility-regression.test.mjs +64 -0
  64. package/tools/shell-api/config.test.ts +93 -0
  65. package/tools/shell-api/docs-coverage.test.ts +82 -0
  66. package/tools/shell-api/e2e.test.ts +562 -0
  67. package/tools/shell-api/example-bash-identity.test.ts +372 -0
  68. package/tools/shell-api/example-bash-matrix.test.ts +856 -0
  69. package/tools/shell-api/example-designs.test.ts +737 -0
  70. package/tools/shell-api/example-neon-transform.test.ts +283 -0
  71. package/tools/shell-api/example-plain-style.test.ts +1225 -0
  72. package/tools/shell-api/extension.test.ts +157 -0
  73. package/tools/shell-api/fake-events.ts +58 -0
  74. package/tools/shell-api/fake-host.ts +211 -0
  75. package/tools/shell-api/fake-sidebar.ts +516 -0
  76. package/tools/shell-api/fake-transcript.ts +486 -0
  77. package/tools/shell-api/frame-telemetry.test.ts +317 -0
  78. package/tools/shell-api/hook.test.ts +196 -0
  79. package/tools/shell-api/manifest.test.ts +47 -0
  80. package/tools/shell-api/message-design-adoption.test.ts +611 -0
  81. package/tools/shell-api/message-design-follows.test.ts +361 -0
  82. package/tools/shell-api/message-design-pi-release.test.mjs +157 -0
  83. package/tools/shell-api/message-design-regressions.test.mjs +162 -0
  84. package/tools/shell-api/message-design-rows.test.ts +266 -0
  85. package/tools/shell-api/message-design-wiring.test.ts +362 -0
  86. package/tools/shell-api/message-designs.test.ts +339 -0
  87. package/tools/shell-api/new-category.test.ts +1101 -0
  88. package/tools/shell-api/notices.test.ts +292 -0
  89. package/tools/shell-api/plugin-integration-lines.test.ts +827 -0
  90. package/tools/shell-api/presence.test.ts +396 -0
  91. package/tools/shell-api/rail-part-hits.test.ts +281 -0
  92. package/tools/shell-api/rail-surfaces.test.ts +402 -0
  93. package/tools/shell-api/rail-width.test.ts +406 -0
  94. package/tools/shell-api/regression.test.ts +434 -0
  95. package/tools/shell-api/repaint-api.test.ts +200 -0
  96. package/tools/shell-api/reserved-categories.test.ts +250 -0
  97. package/tools/shell-api/row-labels.test.ts +261 -0
  98. package/tools/shell-api/row-names.test.ts +407 -0
  99. package/tools/shell-api/row-origin.test.ts +395 -0
  100. package/tools/shell-api/row-placement-regression.test.ts +797 -0
  101. package/tools/shell-api/row-placement.test.ts +410 -0
  102. package/tools/shell-api/section-interaction.test.ts +364 -0
  103. package/tools/shell-api/section-panel.test.ts +430 -0
  104. package/tools/shell-api/section-placement-rail.test.ts +390 -0
  105. package/tools/shell-api/section-placement.test.ts +386 -0
  106. package/tools/shell-api/sections-preview.test.ts +312 -0
  107. package/tools/shell-api/sections-rows.test.ts +293 -0
  108. package/tools/shell-api/sidebar-backend.test.ts +477 -0
  109. package/tools/shell-api/sidebar-e2e.test.ts +317 -0
  110. package/tools/shell-api/sidebar-hover.test.ts +276 -0
  111. package/tools/shell-api/sidebar-independent.test.ts +291 -0
  112. package/tools/shell-api/sidebar-render.test.ts +281 -0
  113. package/tools/shell-api/sidebar-sections.test.ts +247 -0
  114. package/tools/shell-api/store.test.ts +192 -0
  115. package/tools/shell-api/surface-repaint-cost.test.ts +520 -0
  116. package/tools/shell-api/tool-design-card-style.test.ts +308 -0
  117. package/tools/shell-api/tool-design-chain.test.ts +471 -0
  118. package/tools/shell-api/tool-design-cost.test.ts +591 -0
  119. package/tools/shell-api/tool-design-rows.test.ts +627 -0
  120. package/tools/shell-api/tool-design-scopes-audit.test.ts +212 -0
  121. package/tools/shell-api/tool-designs.test.ts +2412 -0
  122. package/tools/shell-api/transform-pipeline.test.ts +376 -0
  123. package/tools/shell-api/transforms-bus.test.ts +233 -0
  124. package/tools/shell-api/verifier-width-regressions.test.ts +147 -0
  125. package/tools/shell-api-rpc.test.js +189 -0
  126. package/tools/user-prompt-card.test.js +8 -9
@@ -0,0 +1,477 @@
1
+ /**
2
+ * Wiring the transform to a live TUI (S5, S4): the only way in, done once, with the same marker and
3
+ * generation discipline the sidebar backend already uses (`./sidebar.ts:52-90`).
4
+ *
5
+ * ## The path, and why it is walked here
6
+ *
7
+ * `./card-styles.ts` §1 records the evidence: Pi hands an extension a real `tui` only through
8
+ * `ctx.ui.setWidget`, and from there the conversation component is reachable in two ways —
9
+ *
10
+ * 1. `tui.children[0]` → the document container → `children[2]` (the chat container). `children` is
11
+ * a declared member of the public `TUI` interface (`pi-tui/dist/tui.d.ts:223-231`) and Pi fills
12
+ * it in both renderer modes, document first (`interactive-mode.js:623-625,722-731`), so this is
13
+ * the primary hop.
14
+ * 2. `tui.layoutRoot` → its layout entries → `entries[0].component` (the primary `ScrollView`) →
15
+ * the scroll view's child (`[LAYOUT_NODE]().component`, `scroll-view.d.ts:57`) → the document →
16
+ * `children[2]`. `layoutRoot` is TypeScript-`private` and exists only on the fullscreen renderer,
17
+ * so this is the secondary hop, tried when the first one does not land.
18
+ *
19
+ * Both end at the same component, and the marker below certifies the exact wrapper installed on it,
20
+ * read as an OWN property, so a rebind, a second arm or a second copy of this package reports
21
+ * `already-wrapped` instead of stacking a second transform.
22
+ *
23
+ * ## What the wrapper does
24
+ *
25
+ * It calls the host's own `render(width)` first (the host's failure path stays the host's), and then
26
+ * hands the rows to the pipeline: `transformCardLines` repaints the selected card style (a
27
+ * pass-through unless a style is selected, and it never throws), and `applyTransforms` then runs the
28
+ * registered transcript transforms in order over that output (`./transform-pipeline.ts`). With no
29
+ * style selected and no transform registered the host's own array is what the wrapper returns, so a
30
+ * session that uses neither is byte-identical. The wrapper captures the generation it was created
31
+ * in: once `disableCardStyleTransform()` (or a reset) bumps it, a wrapper foreign code kept a
32
+ * reference to is a plain pass-through, not an injector.
33
+ *
34
+ * ## The rail surface (R1, R3)
35
+ *
36
+ * The second surface is gentle-shell's fullscreen rail. On a transparent rail the host re-frames
37
+ * every section itself — `sectionCardRows`/`headerParts` through `floatRows`/`cardTop`/`cardLine`
38
+ * (`lib/shell-sidebar-layout.ts:36-47,392-410`), host sections and contributed ones alike — and the
39
+ * FRAMED rows are the child of the rail's `ScrollView` in the layout tree
40
+ * (`lib/shell-sidebar-layout.ts:486-499`): the root's layout node is a `vstack` holding an `hstack`
41
+ * whose SECOND entry is that scroll view, and `ScrollView[LAYOUT_NODE]()` reports its child
42
+ * (`pi-tui/dist/components/scroll-view.js:191-192`). That child renders the whole rail, so wrapping
43
+ * its `render(width)` is the one place that sees every rail frame AFTER the host framed it — which
44
+ * is exactly what a repaint needs, and why a style reaches host sections and bridge sections
45
+ * without the bridge drawing either frame.
46
+ *
47
+ * The rail wrapper runs ONLY the card-style transform (`transformCardLines(..., "rail")`): the
48
+ * registered transcript transforms are the conversation's extension point, and handing a plugin's
49
+ * conversation rows for the rail would let it corrupt a surface it never asked for. Every absence is
50
+ * an outcome here too (`no-layout-root`, `no-sidebar`, `no-rail`), and each attempt records the
51
+ * surface's reach for the diagnostics record (`./repaint.ts`).
52
+ *
53
+ * ## Every absence is a reported state
54
+ *
55
+ * The `tui` is host state, so the walk never assumes a shape and never creates one: no tui, no
56
+ * children, a first child that is not the document, a document without a third child, a third child
57
+ * that cannot render, an accessor that throws — each is an outcome recorded for the diagnostics record
58
+ * (`no-tui`, `no-children`, `no-document`, `no-conversation`, `render-missing`, `wrong-shape`), and
59
+ * none of them throws. A session that never got a `tui` keeps `lastOutcome` undefined, which is
60
+ * reported as "not armed" rather than as a failure.
61
+ *
62
+ * This module is internal: `src/index.ts` does not re-export it.
63
+ */
64
+
65
+ import { transformCardLines } from "./card-style-transform.ts";
66
+ import { getRepaintHost, recordSurfaceReach, type PaintSurface } from "./repaint.ts";
67
+ import { isRecord } from "./rows.ts";
68
+ import { rowOrigins } from "./row-origin.ts";
69
+ import { adoptCustomMessages } from "./message-design-adoption.ts";
70
+ import { adoptToolCards } from "./tool-design-adoption.ts";
71
+ import { applyTransforms } from "./transform-pipeline.ts";
72
+
73
+ /** The layout protocol symbol, exactly as `pi-tui` defines it (`layout-node.js:1`). */
74
+ const LAYOUT_NODE: symbol = Symbol.for("@earendil-works/pi-tui/layout-node");
75
+
76
+ /** Own property on a wrapped component → the exact wrapper function this module installed. */
77
+ const TRANSFORM_WRAPPED: symbol = Symbol.for("gentle-shell-bridge.card-style-transform.wrapped.v1");
78
+
79
+ /** Process-global, like every other piece of bridge state (`./bus.ts` explains why). */
80
+ const WIRING_STATE: symbol = Symbol.for("gentle-shell-bridge.card-style-wiring.state.v1");
81
+
82
+ /** Why the transform is (or is not) attached. Every value is reported, none is a throw. */
83
+ export type CardStyleInstallOutcome =
84
+ | "wrapped"
85
+ | "already-wrapped"
86
+ | "no-tui"
87
+ | "no-children"
88
+ | "no-document"
89
+ | "no-conversation"
90
+ | "render-missing"
91
+ | "no-layout-root"
92
+ | "no-sidebar"
93
+ | "no-rail"
94
+ | "wrong-shape";
95
+
96
+ export interface InstallCardStyleResult {
97
+ installed: boolean;
98
+ outcome: CardStyleInstallOutcome;
99
+ /** The component the wrapper landed on, when it landed. */
100
+ component?: "chat" | "rail";
101
+ /** Only for `wrong-shape`: the message a host accessor threw. */
102
+ reason?: string;
103
+ }
104
+
105
+ export interface CardStyleWiringDiagnostics {
106
+ /** Conversation components currently wrapped in this process. */
107
+ wrapped: number;
108
+ /** Present when at least one conversation component is wrapped. */
109
+ component?: "chat";
110
+ /** The most recent conversation install attempt's outcome; absent when never attempted. */
111
+ lastOutcome?: CardStyleInstallOutcome;
112
+ /** Only for `wrong-shape`: the reason, verbatim. */
113
+ lastReason?: string;
114
+ /** Rail components currently wrapped in this process (R1); absent when a rail was never reached. */
115
+ railWrapped?: number;
116
+ /** The most recent rail install attempt's outcome; absent when never attempted. */
117
+ lastRailOutcome?: CardStyleInstallOutcome;
118
+ /** Only for a rail `wrong-shape`: the reason, verbatim. */
119
+ lastRailReason?: string;
120
+ }
121
+
122
+ /** The part of a component this module needs: Pi's `Component.render(width): string[]`. */
123
+ interface Renderable {
124
+ render(width: number): readonly string[];
125
+ }
126
+
127
+ /** What a host-shaped component's `render` may be, before the wrapper checks it at runtime. */
128
+ type RenderFunction = Renderable["render"];
129
+
130
+ /** A walk's answer: the component, or the hop that failed. */
131
+ type ConversationFound =
132
+ | { found: true; component: Renderable }
133
+ | { found: false; outcome: CardStyleInstallOutcome };
134
+
135
+ interface WrappedRecord {
136
+ component: Renderable;
137
+ original: RenderFunction;
138
+ wrapper: RenderFunction;
139
+ /** Which surface this record serves; one wrapper draws one surface. */
140
+ surface: PaintSurface;
141
+ }
142
+
143
+ interface WiringState {
144
+ /** Bumped by a disable/reset; a wrapper from an older generation is a pass-through. */
145
+ generation: number;
146
+ wrapped: WrappedRecord[];
147
+ lastOutcome?: CardStyleInstallOutcome;
148
+ lastReason?: string;
149
+ lastRailOutcome?: CardStyleInstallOutcome;
150
+ lastRailReason?: string;
151
+ }
152
+
153
+ function wiringHost(): Record<symbol, WiringState | undefined> {
154
+ // SAFETY: only `wiringState()` writes this key, and it re-checks the shape before trusting it.
155
+ return globalThis as unknown as Record<symbol, WiringState | undefined>;
156
+ }
157
+
158
+ function wiringState(): WiringState {
159
+ const host = wiringHost();
160
+ const existing = host[WIRING_STATE];
161
+ if (
162
+ existing !== undefined &&
163
+ typeof existing.generation === "number" &&
164
+ Array.isArray(existing.wrapped)
165
+ ) {
166
+ return existing;
167
+ }
168
+ const created: WiringState = { generation: 0, wrapped: [] };
169
+ host[WIRING_STATE] = created;
170
+ return created;
171
+ }
172
+
173
+ /** Diagnostics snapshot for the diagnostics record (T4) and for this module's own tests. */
174
+ export function getCardStyleWiringDiagnostics(): CardStyleWiringDiagnostics {
175
+ const state = wiringState();
176
+ const chat = state.wrapped.filter((record) => record.surface === "conversation").length;
177
+ const rail = state.wrapped.filter((record) => record.surface === "rail").length;
178
+ return {
179
+ wrapped: chat,
180
+ ...(chat === 0 ? {} : { component: "chat" as const }),
181
+ ...(state.lastOutcome === undefined ? {} : { lastOutcome: state.lastOutcome }),
182
+ ...(state.lastReason === undefined ? {} : { lastReason: state.lastReason }),
183
+ ...(rail === 0 ? {} : { railWrapped: rail }),
184
+ ...(state.lastRailOutcome === undefined ? {} : { lastRailOutcome: state.lastRailOutcome }),
185
+ ...(state.lastRailReason === undefined ? {} : { lastRailReason: state.lastRailReason }),
186
+ };
187
+ }
188
+
189
+ /** Test-only seam: forget every record, so one test cannot leak into another. */
190
+ export function resetCardStyleWiringForTests(): void {
191
+ const state = wiringState();
192
+ state.wrapped.length = 0;
193
+ delete state.lastOutcome;
194
+ delete state.lastReason;
195
+ delete state.lastRailOutcome;
196
+ delete state.lastRailReason;
197
+ // Bump so a wrapper a previous test retained becomes a pass-through instead of injecting.
198
+ state.generation += 1;
199
+ }
200
+
201
+ /** Read `[LAYOUT_NODE]()` from a component, if it exposes it. */
202
+ interface LayoutNode {
203
+ type?: unknown;
204
+ entries?: ReadonlyArray<{ component?: unknown }>;
205
+ component?: unknown;
206
+ }
207
+
208
+ function layoutNodeOf(value: unknown): LayoutNode | undefined {
209
+ if (value === null || typeof value !== "object") return undefined;
210
+ const read = (value as Record<symbol, unknown>)[LAYOUT_NODE];
211
+ if (typeof read !== "function") return undefined;
212
+ const node: unknown = read.call(value);
213
+ // SAFETY: the layout protocol's node is `{ type, entries?, component? }` (`pi-tui`
214
+ // `layout-node.d.ts`); every member this module reads is re-validated at the point of use.
215
+ return isRecord(node) ? (node as LayoutNode) : undefined;
216
+ }
217
+
218
+ /**
219
+ * The conversation component inside a document container: `children[2]`
220
+ * (`interactive-mode.js:404-407`). Returns why it is not, when it is not.
221
+ */
222
+ function conversationOf(document: unknown): ConversationFound {
223
+ if (!isRecord(document)) return { found: false, outcome: "no-document" };
224
+ const children = document.children;
225
+ if (!Array.isArray(children)) return { found: false, outcome: "no-document" };
226
+ const candidate = children[2];
227
+ if (!isRecord(candidate)) return { found: false, outcome: "no-conversation" };
228
+ if (typeof candidate.render !== "function") return { found: false, outcome: "render-missing" };
229
+ // SAFETY: `render` is verified callable above, and it is the only member this module reads;
230
+ // everything a foreign object might carry instead is irrelevant to the wrapper it gets.
231
+ return { found: true, component: candidate as unknown as Renderable };
232
+ }
233
+
234
+ /**
235
+ * Walk `tui` down to the conversation component: primary through `children`, secondary through the
236
+ * layout root. The outcome names the FIRST hop that failed, so the diagnostics record can say which shape
237
+ * was not what this host promised.
238
+ */
239
+ function findConversation(tui: Record<string, unknown>): ConversationFound {
240
+ const children = tui.children;
241
+ const primary: ConversationFound =
242
+ Array.isArray(children) && children.length > 0
243
+ ? conversationOf(children[0])
244
+ : { found: false, outcome: "no-children" };
245
+ if (primary.found) return primary;
246
+
247
+ // The secondary hop exists because a host may not have mounted its children yet (or at all) while
248
+ // its layout root still carries the transcript. It is tried whenever the primary hop failed.
249
+ const root = tui.layoutRoot;
250
+ if (root !== undefined) {
251
+ const entries = layoutNodeOf(root)?.entries;
252
+ const scroll = Array.isArray(entries) ? entries[0]?.component : undefined;
253
+ const document = layoutNodeOf(scroll)?.component;
254
+ if (document !== undefined) {
255
+ const secondary = conversationOf(document);
256
+ if (secondary.found) return secondary;
257
+ }
258
+ }
259
+ return primary;
260
+ }
261
+
262
+ /** The component name each surface reports when its wrapper lands. */
263
+ const SURFACE_COMPONENT: Record<PaintSurface, "chat" | "rail"> = {
264
+ conversation: "chat",
265
+ rail: "rail",
266
+ };
267
+
268
+ /**
269
+ * Find the rail component behind `tui`: the child of the rail `ScrollView` in the host's layout tree
270
+ * (`lib/shell-sidebar-layout.ts:486-499`, `pi-tui/dist/components/scroll-view.js:191-192`).
271
+ *
272
+ * The tree is walked by SHAPE, not by index into the root: the root's layout node is a `vstack`
273
+ * whose entries include the `hstack` host, and that hstack is `[conversation, rail ScrollView]`
274
+ * (`lib/shell-sidebar-layout.ts:490-497`). A second entry qualifies only when its own layout node is
275
+ * a `scroll` AND the component that node reports has a `render`, so neither the transcript's scroll
276
+ * view nor an unrelated stack can be mistaken for the rail.
277
+ */
278
+ function findRail(tui: Record<string, unknown>): ConversationFound {
279
+ const root = tui.layoutRoot;
280
+ if (root === undefined) return { found: false, outcome: "no-layout-root" };
281
+ const scroll = findRailScroll(layoutNodeOf(root), 0);
282
+ if (scroll === undefined) return { found: false, outcome: "no-sidebar" };
283
+ const rail = layoutNodeOf(scroll)?.component;
284
+ if (!isRecord(rail) || typeof rail.render !== "function") {
285
+ return { found: false, outcome: "no-rail" };
286
+ }
287
+ // SAFETY: `render` is verified callable above, and it is the only member this module reads; the
288
+ // rail's other fields (`digest`, `cardGroups`, `surface`, ...) stay on the host's own object
289
+ // because the wrapper replaces only `render`.
290
+ return { found: true, component: rail as unknown as Renderable };
291
+ }
292
+
293
+ /** The rail `ScrollView` of the host's `hstack`, found in the small tree the layout root publishes. */
294
+ function findRailScroll(node: LayoutNode | undefined, depth: number): Record<string, unknown> | undefined {
295
+ if (node === undefined || depth > 3) return undefined;
296
+ if (node.type === "hstack") {
297
+ // entries[0] is the conversation's host, entries[1] the rail (`lib/shell-sidebar-layout.ts:493-496`).
298
+ const candidate = node.entries?.[1]?.component;
299
+ if (isRecord(candidate) && layoutNodeOf(candidate)?.type === "scroll") return candidate;
300
+ }
301
+ for (const entry of node.entries ?? []) {
302
+ const found = findRailScroll(layoutNodeOf(entry.component), depth + 1);
303
+ if (found !== undefined) return found;
304
+ }
305
+ return undefined;
306
+ }
307
+
308
+ /** Wrap one component, once, with a marker that certifies the exact function installed. */
309
+ function wrapComponent(component: Renderable, surface: PaintSurface): InstallCardStyleResult {
310
+ const current = component.render;
311
+ // SAFETY: a component is an object (verified by `isRecord` before it gets here) and the marker is
312
+ // the only symbol-keyed property this module writes on it, so reading it through a widened record
313
+ // is exact.
314
+ const marked = component as unknown as Record<symbol, unknown>;
315
+ if (Object.hasOwn(component, TRANSFORM_WRAPPED) && marked[TRANSFORM_WRAPPED] === current) {
316
+ return { installed: true, outcome: "already-wrapped", component: SURFACE_COMPONENT[surface] };
317
+ }
318
+
319
+ const state = wiringState();
320
+ const generation = state.generation;
321
+ const wrapper = function (this: unknown, width: number): readonly string[] {
322
+ // S10: a tool design is adopted AFTER construction, on every conversation pass, BEFORE the host
323
+ // renders its children. That is the path that survives the resolver order: when an earlier
324
+ // resolver answers a tool without calling `next()`, the bridge's resolver never runs, but this
325
+ // wrapper already holds the container whose children are the cards. Adoption stamps its own
326
+ // marker, so the resolver path and this path never stack on one card. A disabled transform (an
327
+ // older generation) is a pass-through and adopts nothing, exactly as it transforms nothing.
328
+ if (surface === "conversation" && wiringState().generation === generation) {
329
+ try {
330
+ adoptToolCards(component);
331
+ // The message designs' capture point, on the same pass and for the same reason: Pi holds a
332
+ // custom message's renderer on the component it built, and this is the only place the bridge
333
+ // can reach it. It touches a message only when a live design claims its type (S4).
334
+ adoptCustomMessages(component);
335
+ } catch {
336
+ // `adoptToolCards` is written not to throw, and this is the last line of defence: a failure
337
+ // in the adoption path must never take the host's render loop down. The host's own rows are
338
+ // drawn exactly as they would have been.
339
+ }
340
+ }
341
+ // The host's own render always runs first: a host failure stays the host's to report.
342
+ const lines = current.call(component, width);
343
+ if (wiringState().generation !== generation) return lines;
344
+ if (!Array.isArray(lines)) return lines;
345
+ // SAFETY: `Array.isArray` just proved this is the host's own `string[]`; the card-style
346
+ // transformer and the transform pipeline only ever read it and return either that instance or a
347
+ // new array of strings.
348
+ const rows = lines as string[];
349
+ // R1: ONE repaint for every surface. The rail stops after the card style — the registered
350
+ // transcript transforms belong to the conversation, and a plugin's conversation rows must never
351
+ // be handed the rail. That is also why the rail needs no origin map: it runs no transform, so
352
+ // there is nothing to attribute rows to.
353
+ if (surface !== "conversation") return transformCardLines(rows, width, "rail");
354
+ // S1: the origin map is read from the layout the host's OWN render pass just published
355
+ // (`mouseLayout`, `pi-tui/dist/tui.js:136-149`) — no second render, no takeover of
356
+ // `Container.render`, one entry per row of `rows`. A host that published no layout hands the
357
+ // transform an empty map rather than a guess (`./row-origin.ts`), so the frame is still drawn.
358
+ const origins = rowOrigins(component, width, rows.length);
359
+ return applyTransforms(
360
+ transformCardLines(rows, width, "conversation"),
361
+ width,
362
+ origins.rows,
363
+ );
364
+ };
365
+
366
+ component.render = wrapper;
367
+ Object.defineProperty(component, TRANSFORM_WRAPPED, {
368
+ value: wrapper,
369
+ enumerable: false,
370
+ configurable: true,
371
+ });
372
+ // Reconfiguring a component we already wrapped (a foreign rebind kept the marker but replaced
373
+ // `render`) replaces the record instead of adding a second one.
374
+ const previous = state.wrapped.findIndex((record) => record.component === component);
375
+ const record: WrappedRecord = { component, original: current, wrapper, surface };
376
+ if (previous === -1) state.wrapped.push(record);
377
+ else state.wrapped[previous] = record;
378
+ return { installed: true, outcome: "wrapped", component: SURFACE_COMPONENT[surface] };
379
+ }
380
+
381
+ /**
382
+ * Attach the transform to the live conversation component behind `tui`.
383
+ *
384
+ * Called from the one place this package receives a real `tui` (`./extension.ts`'s widget factory),
385
+ * never at module load. Safe to call repeatedly: a second call on the same component reports
386
+ * `already-wrapped` and installs nothing. Any absence is an outcome, never a throw — this runs
387
+ * inside the host's widget factory, where an exception would take the sidebar and the rows with it.
388
+ */
389
+ export function installCardStyleTransform(tui: unknown): InstallCardStyleResult {
390
+ const result = attemptInstall(tui, "conversation");
391
+ const state = wiringState();
392
+ state.lastOutcome = result.outcome;
393
+ if (result.reason === undefined) delete state.lastReason;
394
+ else state.lastReason = result.reason;
395
+ return result;
396
+ }
397
+
398
+ /**
399
+ * Attach the same transform to the host's rail component (R1). Called from the widget factory, and
400
+ * re-attempted by `refreshCardStyleSurfaces()` because the host's fullscreen layout may not be
401
+ * mounted at the moment the factory runs — a reported outcome, never a timer.
402
+ */
403
+ export function installRailCardStyleTransform(tui: unknown): InstallCardStyleResult {
404
+ const result = attemptInstall(tui, "rail");
405
+ const state = wiringState();
406
+ state.lastRailOutcome = result.outcome;
407
+ if (result.reason === undefined) delete state.lastRailReason;
408
+ else state.lastRailReason = result.reason;
409
+ return result;
410
+ }
411
+
412
+ /**
413
+ * Re-attempt every surface whose repaint path was not reached, against the `tui` the bridge captured.
414
+ *
415
+ * Not a retry loop and not a poll: this runs exactly once per bridge-owned write, at the moment that
416
+ * write needs its surface repainted. The host's rail is mounted by the time a user can open the
417
+ * customize menu, which is why that moment is the reliable one; when even then no rail is reachable,
418
+ * the outcome stays recorded for the diagnostics record.
419
+ */
420
+ export function refreshCardStyleSurfaces(): void {
421
+ const tui = getRepaintHost();
422
+ if (tui === undefined) return;
423
+ // Re-attempting an attached surface is free (`already-wrapped`), and it keeps a reloaded host's
424
+ // new component wrapped without another entry point.
425
+ installCardStyleTransform(tui);
426
+ installRailCardStyleTransform(tui);
427
+ }
428
+
429
+ function attemptInstall(tui: unknown, surface: PaintSurface): InstallCardStyleResult {
430
+ if (!isRecord(tui)) {
431
+ recordSurfaceReach(surface, { reached: false, reason: "no-tui" });
432
+ return { installed: false, outcome: "no-tui" };
433
+ }
434
+ let result: InstallCardStyleResult;
435
+ try {
436
+ const found = surface === "conversation" ? findConversation(tui) : findRail(tui);
437
+ result = found.found
438
+ ? wrapComponent(found.component, surface)
439
+ : { installed: false, outcome: found.outcome };
440
+ } catch (error) {
441
+ // A host accessor that throws is a shape problem, not a crash: report it and stay inert.
442
+ result = {
443
+ installed: false,
444
+ outcome: "wrong-shape",
445
+ reason: error instanceof Error ? error.message : String(error),
446
+ };
447
+ }
448
+ recordSurfaceReach(surface, result.installed ? { reached: true } : { reached: false, reason: result.outcome });
449
+ return result;
450
+ }
451
+
452
+ /**
453
+ * Restore every wrapped component's own `render` and bump the generation, so a wrapper retained by
454
+ * foreign code becomes a pass-through. Returns how many components were restored.
455
+ */
456
+ export function disableCardStyleTransform(): number {
457
+ const state = wiringState();
458
+ let restored = 0;
459
+ for (const record of state.wrapped.splice(0)) {
460
+ try {
461
+ if (record.component.render === record.wrapper) {
462
+ record.component.render = record.original;
463
+ }
464
+ if (Object.hasOwn(record.component, TRANSFORM_WRAPPED)) {
465
+ // SAFETY: the marker is the only symbol-keyed property this module writes on a component,
466
+ // and this only removes it; the widened record is how a `symbol` key is deleted.
467
+ delete (record.component as unknown as Record<PropertyKey, unknown>)[TRANSFORM_WRAPPED];
468
+ }
469
+ restored += 1;
470
+ } catch {
471
+ // A component that refuses the assignment keeps its wrapper; the generation still makes it
472
+ // a pass-through, so the transform is off either way.
473
+ }
474
+ }
475
+ state.generation += 1;
476
+ return restored;
477
+ }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Card styles (S1–S4, S12): the bridge's selection, and the facts a repaint depends on.
3
+ *
4
+ * This module buys nothing from the host and asks it for nothing. A registered style is chrome the
5
+ * bridge paints over the frames gentle-shell already drew, which only works if two things are
6
+ * PROVEN rather than assumed: the path from the `tui` this package captures to the component that
7
+ * renders the conversation, and the exact grammar of the lines a `float` card is drawn with. Both
8
+ * follow, with citations. The fixtures that pin them live in `test/fake-transcript.ts`, and
9
+ * `test/card-transcript-path.test.ts` walks the path end to end.
10
+ *
11
+ * ## 1. The path: `tui` → the conversation component
12
+ *
13
+ * Where the `tui` comes from: Pi exposes no `tui` getter, so the only hand-out is the widget
14
+ * factory `ctx.ui.setWidget(key, (tui, theme) => Component)`. This package already captures it
15
+ * (`./extension.ts:108-109`, `docs/contract.md` §9).
16
+ *
17
+ * From there, three candidates, in the order this bridge trusts them. All of them end at the same
18
+ * live object, so the walk can try them in sequence without guessing:
19
+ *
20
+ * a. **`tui.layoutRoot` → its layout entries → the primary `ScrollView` → its child.** Pi mounts
21
+ * the fullscreen tree by calling `tui.setLayoutRoot(fullscreenLayoutRoot)`
22
+ * (`pi-coding-agent/dist/modes/interactive/interactive-mode.js:623-629`), and that root is a
23
+ * `VStack` whose FIRST entry is the transcript `ScrollView`
24
+ * (`dist/modes/interactive/chat-viewport.js:4-11,22-25`). The root's entries are readable
25
+ * through the layout protocol, `LAYOUT_NODE()` (`pi-tui/dist/layout-node.d.ts:2,36-38`, the
26
+ * symbol being `Symbol.for("@earendil-works/pi-tui/layout-node")`), and the `ScrollView`
27
+ * reports its own child the same way (`pi-tui/dist/components/scroll-view.d.ts:57`).
28
+ * **Limit:** `layoutRoot` is a TypeScript-`private` class field
29
+ * (`pi-tui/dist/tui-alt-screen.d.ts:44`) with only a setter in the public interface
30
+ * (`tui.d.ts:253-256`), so it must be read through a widened cast. It exists only on the
31
+ * fullscreen renderer (`TuiAltScreen`, `mode === "fullscreen"`); the regular renderer
32
+ * (`TuiMainScreen`) has no such field and mounts its children directly.
33
+ * b. **`tui.children[0]` → the document `Container`.** `children` IS public
34
+ * (`pi-tui/dist/tui.d.ts:223-231`) and Pi fills it in BOTH renderer modes, in a fixed order,
35
+ * with `documentContainer` first (`interactive-mode.js:623-625,722-731`). This is the most
36
+ * stable hop, because it uses only a declared member of the public `TUI` interface.
37
+ * c. **`tui.children[0].children[2]` = the chat container.** The document container's children are
38
+ * `[headerContainer, loadedResourcesContainer, chatContainer]`
39
+ * (`interactive-mode.js:404-407`), so index 2 is the component that renders the conversation
40
+ * cards. A downstream post-processor that re-frames the conversation uses exactly this.
41
+ * **Least
42
+ * stable:** the index is insertion order, not a contract.
43
+ *
44
+ * `tui.render(width)` itself, `tui.getScreenLines()` and `tui.getPrimaryScrollView()` are NOT
45
+ * candidates: the first two hand back the composited screen (rail, editor, scrollbar column)
46
+ * rather than the conversation, and the third is `private` and caches a layout, so it can be stale
47
+ * between frames.
48
+ *
49
+ * **When it is absent** every hop simply fails: no `layoutRoot` in regular mode, no `children`
50
+ * before Pi mounts (`interactive-mode.js:623` runs during `init`), a non-`ScrollView` first entry,
51
+ * or a document without a third child. Then there is no transcript, and the feature must report
52
+ * `unstyled (no-transcript)` and stay inert (S4) — inventing a component or creating the state
53
+ * would fabricate host state and mask the wiring mistake (same rule as `./sidebar.ts:264-274`).
54
+ *
55
+ * ## 2. The `float` grammar (`gentle-shell/lib/shell-card.ts`, read-only)
56
+ *
57
+ * `cardStyle()` returns `"neon"` only when the global slot is exactly `"neon"` and `"float"`
58
+ * otherwise (`:43-45`), so an unknown style degrades to float instead of breaking: that is what
59
+ * lets a third style exist at all. Float applies only when the style is float AND
60
+ * `width >= FLOAT_MIN_WIDTH` (10) AND the theme can paint a background (`:275-276,336-338`).
61
+ *
62
+ * A float card at width W, in order (`:314-333`, chars at `:105-108`):
63
+ *
64
+ * 1. one-column transparent margin, then the tone background opener, on EVERY row (`:343-346`);
65
+ * 2. a padding row: `▎` + spaces, i.e. `cardBottom` with no content (`:186-196`);
66
+ * 3. the header row: `▎` + one space + `✿ <title>` (title role) + `· <subtitle>` when present,
67
+ * then spaces (float's "rule" is a space, `:108`), then ` <hint> ` right-aligned in the dim role
68
+ * when it fits, then two spaces (`cardTop`, `:141-160`);
69
+ * 4. a padding row between header and body — ONLY when a body exists (`:314-333`);
70
+ * 5. body rows: `▎` + one space + text + padding + one space (the float "right rail" is a space),
71
+ * where the text was wrapped to `W - 6` columns by the caller (`cardLine`, `:172-184`;
72
+ * wrapping: `:203-215`) and is TRUNCATED with `…` if it still overflows;
73
+ * 6. the closing rule: a padding row, identical to row 2.
74
+ *
75
+ * So: opener = padding, header = bar + `✿ `, closer = padding after the body; body rows are the
76
+ * only rows carrying text besides the header, and an empty body is just `padding, header,
77
+ * padding` (3 rows). A card with no hint ends the header row with spaces and no dim segment: the
78
+ * hint is painted `HINT_ROLE` = `"dim"` (`:84,157`) while the title is painted the tone's title
79
+ * role (`:78-83,148`), which is the only unambiguous separator between the two — they are both
80
+ * followed by runs of spaces at the character level.
81
+ *
82
+ * `neon` (`OUTLINE_CHROME`, `:105`) differs in every chrome character and paints no background
83
+ * and no margin: `╭─ ✿ title ──── hint ╮` / `│ text │` / `╰──────╯`. A detection pass must
84
+ * therefore classify by position, not by "contains a box character": a float row starts with
85
+ * `" ▎"` (margin, then the accent bar) and a neon row starts with `╭`, `│` or `╰`.
86
+ *
87
+ * ## 3. What is NOT proven
88
+ *
89
+ * - That a `float` conversation card is always drawn through `floatRows`: the callers observed in
90
+ * gentle-shell pass `previewRows` or use their own component
91
+ * (`extensions/quiet-tools.ts:649,678`, `lib/gentle-ai-renderer.ts:120,218`). The frames are
92
+ * produced by `shell-card.ts` in every case observed, but the fixture reproduces `floatRows`
93
+ * output only.
94
+ * - Whether the host will draw a card at a width below 10 (it draws the outline frame instead,
95
+ * `:336-338`).
96
+ * - Whether a widget component that renders zero rows leaves the editor area untouched; that is
97
+ * the sidebar's open question (`./sidebar.ts:80-90`), inherited unchanged.
98
+ *
99
+ * ## 4. The selection
100
+ *
101
+ * `native` by default, keyed by the bridge's own plugin id (`bridge-card-style`), never the host's
102
+ * `visual-customization.json`. The stored value is a style id, and it resolves to three answers —
103
+ * `native`, the live `style`, or `missing` when the style it names was disposed — without ever
104
+ * throwing, because that answer is what the transformer degrades from (S12).
105
+ */
106
+
107
+ import { snapshotCardStyles } from "./bus.ts";
108
+ import { CARD_STYLE_NATIVE } from "./card-style-line.ts";
109
+ import { createStore } from "./store.ts";
110
+ import type { CardStyleSelection } from "./types.ts";
111
+
112
+ /**
113
+ * The bridge's own plugin id for the selection: one namespaced file, never the host's
114
+ * `visual-customization.json` (whose key list is closed, see `./visibility.ts` for the same
115
+ * reasoning about sections).
116
+ */
117
+ export const CARD_STYLE_STORE_ID = "bridge-card-style";
118
+
119
+ /** The one key in that file. */
120
+ export const CARD_STYLE_STORE_KEY = "cardStyle";
121
+
122
+ /**
123
+ * The persisted selection: a style id, or `native` for "the bridge does not touch the
124
+ * conversation". Anything unreadable or not a string falls back to `native` — a hand-edited file
125
+ * can never select a style the user did not choose, and `native` is always safe.
126
+ */
127
+ export function getCardStyleSelection(): string {
128
+ const stored = createStore(CARD_STYLE_STORE_ID).get<unknown>(CARD_STYLE_STORE_KEY, CARD_STYLE_NATIVE);
129
+ return typeof stored === "string" && stored.trim() !== "" ? stored : CARD_STYLE_NATIVE;
130
+ }
131
+
132
+ /**
133
+ * Persist the selection, FIRST and synchronously: the host repaints after an action returns and
134
+ * re-reads `current()` when it does, so the bullet cannot land on a value that was never written.
135
+ */
136
+ export function setCardStyleSelection(id: string): void {
137
+ createStore(CARD_STYLE_STORE_ID).set(CARD_STYLE_STORE_KEY, id);
138
+ }
139
+
140
+ /**
141
+ * What the stored selection means right now: defined with the other registrations in
142
+ * `./types.ts`, because a tool design reads it from its own context (S22); re-exported here so the
143
+ * card-style module keeps answering with one name.
144
+ */
145
+ export type { CardStyleSelection } from "./types.ts";
146
+
147
+ /** Resolve the persisted selection against the live registry. */
148
+ export function resolveCardStyleSelection(): CardStyleSelection {
149
+ const id = getCardStyleSelection();
150
+ if (id === CARD_STYLE_NATIVE) return { kind: "native" };
151
+ const style = snapshotCardStyles().find((candidate) => candidate.id === id);
152
+ return style === undefined ? { kind: "missing", id } : { kind: "style", style };
153
+ }