pi-odd-worktree 3.15.0 → 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 (127) 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/lib/user-prompt-card.js +48 -2
  43. package/package.json +3 -2
  44. package/tools/files-bridge.test.js +81 -66
  45. package/tools/fixtures/load-extension.js +40 -18
  46. package/tools/issues-command.test.js +4 -7
  47. package/tools/issues-section.test.js +71 -81
  48. package/tools/odd-rail-wiring.test.js +16 -10
  49. package/tools/package-surface.test.js +42 -13
  50. package/tools/prs-command.test.js +11 -6
  51. package/tools/shell-api/api.test.ts +484 -0
  52. package/tools/shell-api/apply-on-move.test.ts +529 -0
  53. package/tools/shell-api/arm.test.ts +220 -0
  54. package/tools/shell-api/bridge-ready.test.ts +309 -0
  55. package/tools/shell-api/bus.test.ts +194 -0
  56. package/tools/shell-api/button-rows.test.ts +435 -0
  57. package/tools/shell-api/capture.test.ts +583 -0
  58. package/tools/shell-api/card-style-rows.test.ts +493 -0
  59. package/tools/shell-api/card-style-transform.test.ts +379 -0
  60. package/tools/shell-api/card-style-wiring.test.ts +258 -0
  61. package/tools/shell-api/card-styles-e2e.test.ts +502 -0
  62. package/tools/shell-api/card-styles.test.ts +324 -0
  63. package/tools/shell-api/card-transcript-path.test.ts +178 -0
  64. package/tools/shell-api/compatibility-regression.test.mjs +64 -0
  65. package/tools/shell-api/config.test.ts +93 -0
  66. package/tools/shell-api/docs-coverage.test.ts +82 -0
  67. package/tools/shell-api/e2e.test.ts +562 -0
  68. package/tools/shell-api/example-bash-identity.test.ts +372 -0
  69. package/tools/shell-api/example-bash-matrix.test.ts +856 -0
  70. package/tools/shell-api/example-designs.test.ts +737 -0
  71. package/tools/shell-api/example-neon-transform.test.ts +283 -0
  72. package/tools/shell-api/example-plain-style.test.ts +1225 -0
  73. package/tools/shell-api/extension.test.ts +157 -0
  74. package/tools/shell-api/fake-events.ts +58 -0
  75. package/tools/shell-api/fake-host.ts +211 -0
  76. package/tools/shell-api/fake-sidebar.ts +516 -0
  77. package/tools/shell-api/fake-transcript.ts +486 -0
  78. package/tools/shell-api/frame-telemetry.test.ts +317 -0
  79. package/tools/shell-api/hook.test.ts +196 -0
  80. package/tools/shell-api/manifest.test.ts +47 -0
  81. package/tools/shell-api/message-design-adoption.test.ts +611 -0
  82. package/tools/shell-api/message-design-follows.test.ts +361 -0
  83. package/tools/shell-api/message-design-pi-release.test.mjs +157 -0
  84. package/tools/shell-api/message-design-regressions.test.mjs +162 -0
  85. package/tools/shell-api/message-design-rows.test.ts +266 -0
  86. package/tools/shell-api/message-design-wiring.test.ts +362 -0
  87. package/tools/shell-api/message-designs.test.ts +339 -0
  88. package/tools/shell-api/new-category.test.ts +1101 -0
  89. package/tools/shell-api/notices.test.ts +292 -0
  90. package/tools/shell-api/plugin-integration-lines.test.ts +827 -0
  91. package/tools/shell-api/presence.test.ts +396 -0
  92. package/tools/shell-api/rail-part-hits.test.ts +281 -0
  93. package/tools/shell-api/rail-surfaces.test.ts +402 -0
  94. package/tools/shell-api/rail-width.test.ts +406 -0
  95. package/tools/shell-api/regression.test.ts +434 -0
  96. package/tools/shell-api/repaint-api.test.ts +200 -0
  97. package/tools/shell-api/reserved-categories.test.ts +250 -0
  98. package/tools/shell-api/row-labels.test.ts +261 -0
  99. package/tools/shell-api/row-names.test.ts +407 -0
  100. package/tools/shell-api/row-origin.test.ts +395 -0
  101. package/tools/shell-api/row-placement-regression.test.ts +797 -0
  102. package/tools/shell-api/row-placement.test.ts +410 -0
  103. package/tools/shell-api/section-interaction.test.ts +364 -0
  104. package/tools/shell-api/section-panel.test.ts +430 -0
  105. package/tools/shell-api/section-placement-rail.test.ts +390 -0
  106. package/tools/shell-api/section-placement.test.ts +386 -0
  107. package/tools/shell-api/sections-preview.test.ts +312 -0
  108. package/tools/shell-api/sections-rows.test.ts +293 -0
  109. package/tools/shell-api/sidebar-backend.test.ts +477 -0
  110. package/tools/shell-api/sidebar-e2e.test.ts +317 -0
  111. package/tools/shell-api/sidebar-hover.test.ts +276 -0
  112. package/tools/shell-api/sidebar-independent.test.ts +291 -0
  113. package/tools/shell-api/sidebar-render.test.ts +281 -0
  114. package/tools/shell-api/sidebar-sections.test.ts +247 -0
  115. package/tools/shell-api/store.test.ts +192 -0
  116. package/tools/shell-api/surface-repaint-cost.test.ts +520 -0
  117. package/tools/shell-api/tool-design-card-style.test.ts +308 -0
  118. package/tools/shell-api/tool-design-chain.test.ts +471 -0
  119. package/tools/shell-api/tool-design-cost.test.ts +591 -0
  120. package/tools/shell-api/tool-design-rows.test.ts +627 -0
  121. package/tools/shell-api/tool-design-scopes-audit.test.ts +212 -0
  122. package/tools/shell-api/tool-designs.test.ts +2412 -0
  123. package/tools/shell-api/transform-pipeline.test.ts +376 -0
  124. package/tools/shell-api/transforms-bus.test.ts +233 -0
  125. package/tools/shell-api/verifier-width-regressions.test.ts +147 -0
  126. package/tools/shell-api-rpc.test.js +189 -0
  127. package/tools/user-prompt-card.test.js +80 -10
@@ -0,0 +1,258 @@
1
+ /**
2
+ * T12/S9 — runtime presence of the REQUIRED host package, `gentle-pi`.
3
+ *
4
+ * The bridge exists to feed gentle-pi's `/gentle:customize` surface, so without gentle-pi it has
5
+ * nothing to feed: no rows, no sections, no card styles, no tool designs, no wrappers. The answer is
6
+ * never read from disk — a path can name one checkout on one machine — and never from
7
+ * `gentle-pi.card-style`, which `setCardStyle` writes lazily (its absence proves nothing).
8
+ *
9
+ * The sanctioned runtime check is `pi.getCommands()` including the command gentle-pi registers:
10
+ * gentle-shell itself asks the same question the same way
11
+ * (`extensions/gentle-design.ts:137`, `extensions/gentle-guide.ts:62`). Every extension is loaded
12
+ * before Pi fires `session_start`, so that event is the first moment the answer is real, and it is
13
+ * asked again on every later `session_start` so a host that appears late is picked up.
14
+ *
15
+ * ## The three things this module owns
16
+ *
17
+ * 1. **The predicate** (`hasGentlePi`): true only for a command list that names
18
+ * `gentle:customize`. A missing `getCommands`, a throwing one, a non-array result, an entry
19
+ * without a name and an unrelated list all mean MISSING. It never throws: a broken host must not
20
+ * take the session handler with it.
21
+ * 2. **The process-global record** (`getGentlePiPresence`): the answer the check left behind. It is
22
+ * `undefined` until the first check, so a report for a process that never ran a session keeps its
23
+ * historical output byte for byte. The slot is keyed by a `Symbol.for` for the same reason as the
24
+ * bus and the notice buffer: Pi loads every extension with `moduleCache: false`, so module scope
25
+ * is per-copy while the answer belongs to the process.
26
+ * 3. **The warning budget** (`checkGentlePi`): ONE `ctx.ui.notify` warning per absence, and a fresh
27
+ * one if the host disappears again after having been present. Repeated `session_start` events for
28
+ * the same absence deliver nothing, so a re-bind cannot spam the user.
29
+ *
30
+ * Nothing here arms or disarms anything: the extension decides what to do with the answer, and the
31
+ * disabled path simply never reaches the arming code.
32
+ */
33
+
34
+ /** The command `gentle-pi` registers; its presence in `pi.getCommands()` is the runtime answer. */
35
+ export const GENTLE_PI_COMMAND = "gentle:customize";
36
+
37
+ /**
38
+ * Why a host does not count as gentle-pi. The text is user-facing (it is the tail of
39
+ * `gentle-pi: missing — <reason>` and of the warning), so it names what was actually observed.
40
+ */
41
+ export type GentlePiAbsenceReason =
42
+ | "the host has no getCommands()"
43
+ | "getCommands() returned no command list"
44
+ | `getCommands() threw: ${string}`
45
+ | `getCommands() lists no ${typeof GENTLE_PI_COMMAND}`;
46
+
47
+ /** The verdict, with the reason carried only when the host is missing. */
48
+ export type GentlePiPresence =
49
+ | { present: true }
50
+ | { present: false; reason: GentlePiAbsenceReason };
51
+
52
+ /** What one check concluded, and whether it owes the one warning for a new absence. */
53
+ export interface GentlePiCheck {
54
+ present: boolean;
55
+ /** Present only when missing: why the host does not count as gentle-pi. */
56
+ reason?: GentlePiAbsenceReason;
57
+ /**
58
+ * `true` exactly for the check that STARTS an absence. The caller delivers the one warning when it
59
+ * is `true` and stays silent otherwise, so repeated `session_start` events cannot repeat it while a
60
+ * later disappearance does warn again.
61
+ */
62
+ warnNow: boolean;
63
+ }
64
+
65
+ /** The record the check leaves behind; see `getGentlePiPresence`. */
66
+ export interface GentlePiPresenceRecord {
67
+ present: boolean;
68
+ /** Present only when missing. */
69
+ reason?: GentlePiAbsenceReason;
70
+ }
71
+
72
+ /** The process-global slot. `v1` is part of the key, like the API, the bus and the notice buffer. */
73
+ const PRESENCE_KEY: symbol = Symbol.for("gentle-shell-bridge/presence/v1");
74
+
75
+ interface PresenceState {
76
+ /** `false` until the first check, which is why the report has no presence line before then. */
77
+ checked: boolean;
78
+ present: boolean;
79
+ reason?: GentlePiAbsenceReason;
80
+ /** An absence warning is outstanding: one per absence, re-armed by a present check. */
81
+ warningOutstanding: boolean;
82
+ }
83
+
84
+ function presenceHost(): Record<symbol, PresenceState | undefined> {
85
+ // SAFETY: this module is the only writer of the slot, and `presenceState()` re-checks the shape
86
+ // before trusting a value left by another copy or an older load.
87
+ return globalThis as unknown as Record<symbol, PresenceState | undefined>;
88
+ }
89
+
90
+ /** The process-global state, created on first use; a foreign value is replaced. */
91
+ function presenceState(): PresenceState {
92
+ const host = presenceHost();
93
+ const existing = host[PRESENCE_KEY];
94
+ if (
95
+ existing !== undefined &&
96
+ typeof existing.checked === "boolean" &&
97
+ typeof existing.present === "boolean" &&
98
+ typeof existing.warningOutstanding === "boolean"
99
+ ) {
100
+ return existing;
101
+ }
102
+ const created: PresenceState = { checked: false, present: false, warningOutstanding: false };
103
+ host[PRESENCE_KEY] = created;
104
+ return created;
105
+ }
106
+
107
+ /** The message of a thrown value, without trusting it to be an `Error`. */
108
+ function messageOf(error: unknown): string {
109
+ if (error instanceof Error) return error.message;
110
+ try {
111
+ return String(error);
112
+ } catch {
113
+ return "an unprintable error";
114
+ }
115
+ }
116
+
117
+ /** The `name` of one command entry, or `undefined` when the entry has none (or reading it throws). */
118
+ function commandName(entry: unknown): string | undefined {
119
+ if (typeof entry !== "object" || entry === null) return undefined;
120
+ try {
121
+ const name = (entry as { name?: unknown }).name;
122
+ return typeof name === "string" ? name : undefined; // a non-string name is "no name"
123
+ } catch {
124
+ return undefined; // a throwing accessor is "no name", never a crash
125
+ }
126
+ }
127
+
128
+ /** The command list `pi.getCommands()` returned, or why there is none. */
129
+ function readCommands(
130
+ pi: unknown,
131
+ ): { kind: "listed"; commands: readonly unknown[] } | { kind: "absent"; reason: GentlePiAbsenceReason } {
132
+ if (typeof pi !== "object" || pi === null) {
133
+ return { kind: "absent", reason: "the host has no getCommands()" };
134
+ }
135
+ let member: unknown;
136
+ try {
137
+ member = (pi as { getCommands?: unknown }).getCommands;
138
+ } catch (error) {
139
+ // Reading the accessor is the host's code too: it is reported like a throwing call.
140
+ return { kind: "absent", reason: `getCommands() threw: ${messageOf(error)}` };
141
+ }
142
+ if (typeof member !== "function") {
143
+ return { kind: "absent", reason: "the host has no getCommands()" };
144
+ }
145
+ let value: unknown;
146
+ try {
147
+ // `this` matters: `getCommands` is a method on Pi's extension API.
148
+ value = (member as () => unknown).call(pi);
149
+ } catch (error) {
150
+ return { kind: "absent", reason: `getCommands() threw: ${messageOf(error)}` };
151
+ }
152
+ if (!Array.isArray(value)) {
153
+ return { kind: "absent", reason: "getCommands() returned no command list" };
154
+ }
155
+ return { kind: "listed", commands: value };
156
+ }
157
+
158
+ /**
159
+ * The presence verdict for this host, right now.
160
+ *
161
+ * True only when `pi.getCommands()` is an array with an entry whose `name` is exactly
162
+ * `gentle:customize`. Every other shape — no member, a non-function member, a throw, a non-array
163
+ * result, an entry without a name, a non-string name — is MISSING. Never throws.
164
+ */
165
+ export function gentlePiPresence(pi: unknown): GentlePiPresence {
166
+ const read = readCommands(pi);
167
+ if (read.kind === "absent") return { present: false, reason: read.reason };
168
+ for (const command of read.commands) {
169
+ if (commandName(command) === GENTLE_PI_COMMAND) return { present: true };
170
+ }
171
+ return { present: false, reason: `getCommands() lists no ${GENTLE_PI_COMMAND}` };
172
+ }
173
+
174
+ /** The runtime predicate (S9). `true` only when the host advertises gentle-pi's command. */
175
+ export function hasGentlePi(pi: unknown): boolean {
176
+ return gentlePiPresence(pi).present;
177
+ }
178
+
179
+ /**
180
+ * Ask the host, record the answer in the process-global slot and decide the warning budget.
181
+ *
182
+ * This is the function `session_start` calls. It arms nothing and notifies nothing: the caller owns
183
+ * the UI, and `warnNow` keeps the one-warning-per-absence rule in the process, not in one copy of the
184
+ * module or one session handler.
185
+ */
186
+ export function checkGentlePi(pi: unknown): GentlePiCheck {
187
+ const verdict = gentlePiPresence(pi);
188
+ const state = presenceState();
189
+ state.checked = true;
190
+ state.present = verdict.present;
191
+ if (verdict.present) {
192
+ state.reason = undefined;
193
+ // The next absence is a NEW absence and owes its own warning.
194
+ state.warningOutstanding = false;
195
+ return { present: true, warnNow: false };
196
+ }
197
+ state.reason = verdict.reason;
198
+ const warnNow = !state.warningOutstanding;
199
+ state.warningOutstanding = true;
200
+ return { present: false, reason: verdict.reason, warnNow };
201
+ }
202
+
203
+ /**
204
+ * What the last check concluded, or `undefined` when no check has run in this process.
205
+ *
206
+ * `undefined` is the whole reason a process that never reached `session_start` has no presence
207
+ * answer: no check, no record.
208
+ */
209
+ export function getGentlePiPresence(): GentlePiPresenceRecord | undefined {
210
+ const state = presenceState();
211
+ if (!state.checked) return undefined;
212
+ return state.present ? { present: true } : { present: false, reason: state.reason };
213
+ }
214
+
215
+ /** The one warning text, so the test and the report can quote what the user was shown. */
216
+ export function missingGentlePiWarning(reason: GentlePiAbsenceReason | string): string {
217
+ return (
218
+ `odd-worktree: gentle-pi is missing (${reason}), so the sidebar sections, the Customize ` +
219
+ "rows and the card designs are off until it is installed."
220
+ );
221
+ }
222
+
223
+ /**
224
+ * Deliver the one warning for a new absence through `ctx.ui.notify`.
225
+ *
226
+ * Returns whether the message was handed to a UI. A context without `notify` (or with one that
227
+ * throws) is a reported `false`, never an exception inside Pi's event handler: the absence is still
228
+ * recorded, so the answer survives even when the terminal never showed it.
229
+ */
230
+ export function warnMissingGentlePi(ui: unknown, reason: GentlePiAbsenceReason | string): boolean {
231
+ if (typeof ui !== "object" || ui === null) return false;
232
+ let notify: unknown;
233
+ try {
234
+ notify = (ui as { notify?: unknown }).notify;
235
+ } catch {
236
+ return false;
237
+ }
238
+ if (typeof notify !== "function") return false;
239
+ try {
240
+ // `this` matters: Pi's notify is a method on the UI context.
241
+ (notify as (message: string, level?: "warning") => void).call(
242
+ ui,
243
+ missingGentlePiWarning(reason),
244
+ "warning",
245
+ );
246
+ return true;
247
+ } catch {
248
+ return false;
249
+ }
250
+ }
251
+
252
+ /**
253
+ * Test-only seam: forget the process-global record and the warning budget. The extension never calls
254
+ * this — a presence answer is a fact about the process, not per-session state.
255
+ */
256
+ export function resetPresenceForTests(): void {
257
+ delete presenceHost()[PRESENCE_KEY];
258
+ }
@@ -0,0 +1,351 @@
1
+ /**
2
+ * Repaint triggers (R3) and per-surface bookkeeping (R4): the half of a bridge-owned write that
3
+ * makes it visible.
4
+ *
5
+ * ## Why a write needs to ask for a frame
6
+ *
7
+ * The bridge owns state that a HOST surface draws: a section's visibility (the rail paints the
8
+ * section) and the card-style selection (both surfaces paint chrome from it). The bridge persists
9
+ * that state synchronously — the host's row renderer re-reads `current()` when it repaints — but
10
+ * persistence alone changes nothing on screen: gentle-shell re-renders a rail part only when its
11
+ * digest changes or when the layout's own revision counter moves
12
+ * (`lib/shell-sidebar-layout.ts:310-350`). That counter is what a part OWNER bumps:
13
+ *
14
+ * ```ts
15
+ * if (sidebarTui) invalidateSidebar(sidebarTui); // lib/shell-sidebar-layout.ts:105-107
16
+ * host?.requestRender(); // extensions/gentle-agents.ts:2147-2148
17
+ * ```
18
+ *
19
+ * Both calls are the host's documented contract for "I changed what your rail shows". This package
20
+ * cannot import gentle-shell's modules (Pi loads every extension through its own jiti loader with
21
+ * `moduleCache: false`), so the two steps are performed against the same published state the host
22
+ * itself uses:
23
+ *
24
+ * 1. `invalidateSidebar(tui)` is exactly `tui.terminal[CACHE].revision++`, where `CACHE` is
25
+ * `Symbol.for("gentle-pi.experimental-sidebar.cache")` — the symbol the host declares and reads
26
+ * (`lib/shell-sidebar-layout.ts:97-107`, `symbol.for` so every loaded copy shares it);
27
+ * 2. `tui.requestRender()`: one differential frame (`tui.js:665-672`), which draws the rows that
28
+ * changed and leaves every other component's cache — and the terminal's differential state —
29
+ * alone.
30
+ *
31
+ * ## Why the tree is never invalidated (S19/T35-T36)
32
+ *
33
+ * T4 also called `tui.invalidate()` and forced the frame. Measuring both halves on real pi
34
+ * components says neither is needed by EITHER kind of caller, and that they are what the freeze
35
+ * was:
36
+ *
37
+ * | 600 children, one switch | bridge row, today | differential only | invalidate + force |
38
+ * | ------------------------------- | ----------------- | ----------------- | ------------------ |
39
+ * | card style → example `plain` | 697 ms | 420 ms | 721 ms |
40
+ * | card style → the host's `float` | 306 ms | 16 ms | 307 ms |
41
+ * | section hidden, then a frame | 99 ms | 3 ms | 100 ms |
42
+ *
43
+ * The invalidation is the expensive half: it drops every mounted component's frame cache, so the
44
+ * next frame re-parses every Markdown message of the transcript. The force is the other half: it
45
+ * resets the renderer's differential state and rewrites the whole buffer.
46
+ *
47
+ * Neither buys the bridge anything, proven per surface (S19/T35, `test/surface-repaint-cost.ts`):
48
+ *
49
+ * - the CONVERSATION repaints the selected style in the wrapper, on the host's ALREADY rendered
50
+ * rows, on every pass (`./card-style-wiring.ts` → `./card-style-transform.ts`), so a cache that
51
+ * hands back the previous frame's rows is restyled just the same — the rows are byte-identical
52
+ * with and without the invalidation at 50, 200 and 600 children;
53
+ * - the RAIL is framed the same way, by the same wrapper over the host's rail component
54
+ * (`transformCardLines(..., "rail")`), so a host memo that answers from its own cache is
55
+ * restyled too; and a SECTION toggle moves the bridge's own section digest, which the host's memo
56
+ * already keys on (`./sidebar-render.ts` `sectionRailDigest`), while the revision bumped below is
57
+ * the host's documented part-owner step for a digest that does not move;
58
+ * - a style that came from the HOST (pressing `neon`/`float`) is inside the host card's own frame
59
+ * key (`cards-bash-v2` `extensions/quiet-tools.ts:942-965`), which is why the host's own setter
60
+ * never invalidates either (`extensions/gentle-shell.ts:3431-3437`).
61
+ *
62
+ * The control that proves this is not vacuous: with a host frame key that does NOT include the
63
+ * style, the differential path draws the previous card and only the invalidation repairs it
64
+ * (`test/surface-repaint-cost.test.ts` counts that case). So a future surface that genuinely caches
65
+ * its own value can be given a LOCAL invalidate of that component — never the whole tree, and not
66
+ * without the measured byte comparison this module's history records.
67
+ *
68
+ * Nothing else: no timer, no poll, no retry. A repaint that cannot happen is RECORDED and reported
69
+ * by the diagnostics record , because "the toggle did nothing" must always have an answer.
70
+ *
71
+ * ## Surfaces
72
+ *
73
+ * Two surfaces paint bridge-owned chrome: the conversation (the component
74
+ * `./card-style-wiring.ts` wraps) and the rail (the host's rail component, wrapped the same way).
75
+ * The reach of each is recorded where the attach is attempted, so a report can say "the rail was
76
+ * never reached, and why" instead of only "no frame".
77
+ *
78
+ * This module is internal: `src/index.ts` does not re-export it.
79
+ */
80
+
81
+ import { isRecord } from "./rows.ts";
82
+
83
+ /** What a plugin-facing repaint records as its cause, so the diagnostics record reads as a sentence. */
84
+ const PLUGIN_REPAINT_CAUSE = "a plugin asked for a repaint";
85
+
86
+ /** Why nothing could be repainted: no host was captured at all. */
87
+ const NO_HOST_REASON = "no tui has been captured, so no surface can be repainted";
88
+
89
+ /** Why nothing could be repainted: the captured host has no frame request on it. */
90
+ const NO_FRAME_REQUEST_REASON =
91
+ "the captured tui has no requestRender(), so no frame can be asked for";
92
+
93
+ /** The surfaces a card style can paint. Order is the order the report prints. */
94
+ export const PAINT_SURFACES = ["conversation", "rail"] as const;
95
+
96
+ export type PaintSurface = (typeof PAINT_SURFACES)[number];
97
+
98
+ /**
99
+ * The host's terminal-side frame cache (`lib/shell-sidebar-layout.ts:97-107`). Symbol-keyed, so
100
+ * every separately loaded copy of the host shares one counter per terminal.
101
+ */
102
+ export const HOST_SIDEBAR_CACHE: symbol = Symbol.for("gentle-pi.experimental-sidebar.cache");
103
+
104
+ /** Whether a surface's repaint path was reached, and why not when it was not. */
105
+ export interface SurfaceReach {
106
+ reached: boolean;
107
+ /** Only when `reached` is false: the attach outcome, e.g. `no-layout-root`. */
108
+ reason?: string;
109
+ }
110
+
111
+ /** What one `action()` did about the screen, as the diagnostics record prints it. */
112
+ export interface RepaintTrigger {
113
+ /** What changed, as a person reads it: `section "loon.music" → hidden`. */
114
+ cause: string;
115
+ /** The surfaces that display it, and whose repaint was requested. */
116
+ surfaces: PaintSurface[];
117
+ outcome: "repainted" | "unavailable";
118
+ /** Only for `unavailable`: why no frame could be requested. */
119
+ reason?: string;
120
+ }
121
+
122
+ export interface RepaintDiagnostics {
123
+ /** Whether a `tui` has been captured yet; without one nothing can be repainted. */
124
+ hostCaptured: boolean;
125
+ reach: Partial<Record<PaintSurface, SurfaceReach>>;
126
+ lastTrigger?: RepaintTrigger;
127
+ }
128
+
129
+ /** The host object Pi hands the widget factory, as far as this module reads it. */
130
+ export type RepaintHost = Record<string, unknown>;
131
+
132
+ interface RepaintState {
133
+ tui?: unknown;
134
+ reach: Partial<Record<PaintSurface, SurfaceReach>>;
135
+ lastTrigger?: RepaintTrigger;
136
+ }
137
+
138
+ /** Process-global, like every other piece of bridge state (`./bus.ts` explains why). */
139
+ const REPAINT_STATE = Symbol.for("gentle-shell-bridge.repaint.state.v1");
140
+
141
+ function repaintHost(): Record<symbol, RepaintState | undefined> {
142
+ // SAFETY: only `repaintState()` writes this key, and it re-checks the shape it finds.
143
+ return globalThis as unknown as Record<symbol, RepaintState | undefined>;
144
+ }
145
+
146
+ /**
147
+ * The slot's shape, checked before use so a value another copy or an older load left behind is
148
+ * replaced rather than trusted. `tui` and `lastTrigger` are only ever copied or replaced wholesale,
149
+ * and both readers re-validate what they read.
150
+ */
151
+ function isRepaintStateLike(value: unknown): value is RepaintState {
152
+ return isRecord(value) && isRecord(value.reach);
153
+ }
154
+
155
+ function repaintState(): RepaintState {
156
+ const host = repaintHost();
157
+ const existing = host[REPAINT_STATE];
158
+ if (isRepaintStateLike(existing)) return existing;
159
+ const created: RepaintState = { reach: {} };
160
+ host[REPAINT_STATE] = created;
161
+ return created;
162
+ }
163
+
164
+ /**
165
+ * Remember the `tui` Pi handed the widget factory (`./extension.ts`): the one documented hand-out,
166
+ * and the only object whose `requestRender()` reaches the host's render loop.
167
+ */
168
+ export function setRepaintHost(tui: unknown): void {
169
+ repaintState().tui = tui;
170
+ }
171
+
172
+ /** The captured `tui`, for a caller that must attempt an attach before asking for a frame. */
173
+ export function getRepaintHost(): RepaintHost | undefined {
174
+ const tui = repaintState().tui;
175
+ return isRecord(tui) ? tui : undefined;
176
+ }
177
+
178
+ /** Record whether one surface's repaint path was reached (called where the attach is attempted). */
179
+ export function recordSurfaceReach(surface: PaintSurface, reach: SurfaceReach): void {
180
+ repaintState().reach[surface] =
181
+ reach.reached || reach.reason === undefined
182
+ ? { reached: reach.reached }
183
+ : { reached: false, reason: reach.reason };
184
+ }
185
+
186
+ /** The reach last recorded for one surface. */
187
+ export function getSurfaceReach(surface: PaintSurface): SurfaceReach | undefined {
188
+ const reach = repaintState().reach[surface];
189
+ return reach === undefined ? undefined : { ...reach };
190
+ }
191
+
192
+ /** Diagnostics snapshot for the diagnostics record (R4) and for this module's own tests. */
193
+ export function getRepaintDiagnostics(): RepaintDiagnostics {
194
+ const state = repaintState();
195
+ const reach: Partial<Record<PaintSurface, SurfaceReach>> = {};
196
+ for (const surface of PAINT_SURFACES) {
197
+ const recorded = state.reach[surface];
198
+ if (recorded !== undefined) reach[surface] = { ...recorded };
199
+ }
200
+ return {
201
+ hostCaptured: state.tui !== undefined,
202
+ reach,
203
+ ...(state.lastTrigger === undefined ? {} : { lastTrigger: { ...state.lastTrigger } }),
204
+ };
205
+ }
206
+
207
+ /** Test-only seam; deliberately not re-exported from `src/index.ts`. */
208
+ export function resetRepaintForTests(): void {
209
+ const state = repaintState();
210
+ delete state.tui;
211
+ state.reach = {};
212
+ delete state.lastTrigger;
213
+ }
214
+
215
+ function errorMessage(error: unknown): string {
216
+ return error instanceof Error ? error.message : String(error);
217
+ }
218
+
219
+ /**
220
+ * Bump the host's cache revision exactly as `invalidateSidebar(tui)` does
221
+ * (`lib/shell-sidebar-layout.ts:105-107`): `tui.terminal[CACHE].revision++`, creating the slot the
222
+ * host creates on its first invalidate. Never throws: a terminal that cannot carry the slot is a
223
+ * non-host object, and the `requestRender()` that follows is still worth attempting.
224
+ */
225
+ function invalidateHostSidebar(tui: Record<string, unknown>): void {
226
+ try {
227
+ const terminal = tui.terminal;
228
+ if (!isRecord(terminal)) return;
229
+ // SAFETY: the host stores a `{ revision: number }` object under this symbol on the terminal
230
+ // (`lib/shell-sidebar-layout.ts:99-107`); a value of any other shape is replaced by the same
231
+ // default the host itself uses, never trusted.
232
+ const slot = terminal as Record<symbol, unknown>;
233
+ const existing = slot[HOST_SIDEBAR_CACHE];
234
+ if (isRecord(existing) && typeof existing.revision === "number") {
235
+ existing.revision += 1;
236
+ return;
237
+ }
238
+ slot[HOST_SIDEBAR_CACHE] = { revision: 1 };
239
+ } catch {
240
+ // A frozen terminal cannot be invalidated; the frame request below is still honest.
241
+ }
242
+ }
243
+
244
+ /**
245
+ * The one place a frame is asked for, shared by every repaint path (T4, S19/T36).
246
+ *
247
+ * One kind of caller, both kinds of value: a BRIDGE-owned row (`./card-style-rows.ts`,
248
+ * `./sections-rows.ts`) and a plugin's own (`api.requestRepaint()`). Both change a value that a
249
+ * wrapper re-reads on top of the host's rows on every pass, so one differential frame
250
+ * (`requestRender()`, `tui.js:665-672`) draws the changed rows and leaves every other component's
251
+ * cache — and the terminal's differential state — alone. Measuring the two halves that used to be
252
+ * here is why (the table at the top of this module): `tui.invalidate()` re-parsed every Markdown
253
+ * message of the transcript and `requestRender(true)` rewrote the whole buffer, and neither changed
254
+ * a single row the switch had not already changed.
255
+ *
256
+ * Order matters and is asserted by the tests: the host's terminal-side cache revision is bumped
257
+ * first, then the frame is asked for. Returns the trigger it recorded, including the reason the
258
+ * frame could not be asked for.
259
+ */
260
+ function requestFrame(input: {
261
+ cause: string;
262
+ surfaces: readonly PaintSurface[];
263
+ }): RepaintTrigger {
264
+ const state = repaintState();
265
+ const record = (outcome: RepaintTrigger["outcome"], reason?: string): RepaintTrigger => {
266
+ const trigger: RepaintTrigger = {
267
+ cause: input.cause,
268
+ surfaces: [...input.surfaces],
269
+ outcome,
270
+ ...(reason === undefined ? {} : { reason }),
271
+ };
272
+ state.lastTrigger = trigger;
273
+ return { ...trigger, surfaces: [...trigger.surfaces] };
274
+ };
275
+
276
+ const tui = state.tui;
277
+ if (!isRecord(tui)) return record("unavailable", NO_HOST_REASON);
278
+ const requestRender = tui.requestRender;
279
+ if (typeof requestRender !== "function") return record("unavailable", NO_FRAME_REQUEST_REASON);
280
+
281
+ invalidateHostSidebar(tui);
282
+ try {
283
+ requestRender.call(tui);
284
+ } catch (error) {
285
+ // A host that refuses a frame is reported, never swallowed: the write DID land, the screen did
286
+ // not change, and only a report can distinguish that from "the toggle is broken".
287
+ return record("unavailable", `requestRender threw: ${errorMessage(error)}`);
288
+ }
289
+ return record("repainted");
290
+ }
291
+
292
+ /**
293
+ * Ask the host for a frame after a write to bridge-owned state (R3), retuned by S19/T36.
294
+ *
295
+ * Runs synchronously, before the caller's action returns: the host's sidebar revision is bumped
296
+ * exactly as `invalidateSidebar(tui)` does (`lib/shell-sidebar-layout.ts:105-107`) and one
297
+ * DIFFERENTIAL frame is requested. T4 also dropped every mounted component's frame cache and forced
298
+ * the frame; measuring the restored example `plain` style, the way back to a host style, and a
299
+ * section toggle on real pi-tui and pi's `ToolExecutionComponent` (50/200/600 children) says those
300
+ * two halves cost 697/306/99 ms against 420/16/3 ms, and that the rows they draw are byte-identical
301
+ * on the conversation, on a rail host panel, and on a bridge section collapsed, expanded and hidden
302
+ * (`test/surface-repaint-cost.test.ts` bounds the work; the tables in this module's header record
303
+ * the numbers).
304
+ *
305
+ * Records the trigger — cause, surfaces, outcome — so the diagnostics record can report the last one,
306
+ * including the reason a repaint could not happen.
307
+ */
308
+ export function requestSurfaceRepaint(input: {
309
+ cause: string;
310
+ surfaces: readonly PaintSurface[];
311
+ }): RepaintTrigger {
312
+ return requestFrame(input);
313
+ }
314
+
315
+ /**
316
+ * Ask for a repaint of everything the host draws (T4), retuned from measurements (S13/T23): the
317
+ * plugin-facing request behind `api.requestRepaint()`.
318
+ *
319
+ * T4 assumed a plugin's setting could only reach the cards already on screen through
320
+ * `tui.invalidate()` + `requestRender(force = true)`. Measuring real pi-tui and pi's
321
+ * `ToolExecutionComponent` on transcripts of 50/200/600 children says those two calls ARE the cost,
322
+ * and that a plugin whose wrapper reads its value on every render pass does not need them:
323
+ *
324
+ * | 600 children, one switch | frame | written |
325
+ * | ------------------------------ | ----- | ------- |
326
+ * | `requestRender()` (this path) | 21 ms | 0 B (only the rows the diff finds) |
327
+ * | `tui.invalidate()` + frame | 730 ms | 0 B (every Markdown message re-parsed) |
328
+ * | `requestRender(true)` | 33 ms | 6.9 MB (whole buffer cleared and rewritten) |
329
+ * | invalidate + force (old T4) | 753 ms | 6.9 MB |
330
+ *
331
+ * A bridge-owned row makes the same claim, and measuring it is what S19/T35 added: the rows it
332
+ * changes are repainted by the same wrapper, on top of the host's already rendered rows, so the
333
+ * drawn card changes without any cache being dropped either — and the one cache that could replay
334
+ * old chrome, the host card's `ToolCardRows`, is keyed on the HOST's own style
335
+ * (`cards-bash-v2` `extensions/quiet-tools.ts:942-965`), which a bridge style never touches.
336
+ *
337
+ * The host's own `Card style` switch is the precedent its user compares with: it writes the value,
338
+ * bumps the sidebar revision and calls `requestRender()` with no argument
339
+ * (`extensions/gentle-shell.ts:3431-3437`) — no tree invalidation, no forced frame. `requestRepaint`
340
+ * and `requestSurfaceRepaint` are that same two-step.
341
+ *
342
+ * Both surfaces are named, because both paint chrome from a plugin's value. Safe with no host
343
+ * captured yet (a plugin may ask from its own `session_start`): the request is REPORTED as
344
+ * `unavailable` with its reason, never thrown, and never queued for a host that may never arrive.
345
+ */
346
+ export function requestRepaint(): RepaintTrigger {
347
+ return requestFrame({
348
+ cause: PLUGIN_REPAINT_CAUSE,
349
+ surfaces: PAINT_SURFACES,
350
+ });
351
+ }