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,88 @@
1
+ /**
2
+ * The shell API's programmatic entry point.
3
+ *
4
+ * odd-worktree's own extension entry (`extensions/odd-worktree-tools.ts`, the `pi.extensions`
5
+ * manifest entry) imports `./extension.ts`, which publishes the runtime handshake and arms the shell
6
+ * surfaces; these sources are the published artifact: there is no build step and no `dist/`. This
7
+ * module is the API surface for plugins: rows, sidebar sections, card styles, transcript transforms,
8
+ * per-tool card DESIGNS (one registration point for `pi.registerToolRenderer`) with the read-only
9
+ * reader that answers which design a tool draws right now, per-message card DESIGNS beside them (one
10
+ * registration point for a custom message's rows, `pi.registerMessageRenderer`'s `customType`) with
11
+ * the same kind of reader for a message, the active card-style selection a design — or a plugin
12
+ * outside one — honours (`resolveCardStyleSelection`), the optional store and the runtime handshake
13
+ * (`bridgeApi`, `onBridgeApi`, the announcement event). A message design rewrites the rows the host's
14
+ * own renderer drew, or owns the box when the type has no renderer at all, and a type nobody claimed
15
+ * is never touched. Backend internals — the capture patch, the hook registry, the arm
16
+ * lifecycle, the rail interception, the section renderer, the card-style line and transformer, the
17
+ * transform pipeline and the bus snapshots — are reached through the extension entry, not
18
+ * re-exported here. docs/shell-api/contract.md's Limits section is explicit about which names are the
19
+ * contract.
20
+ *
21
+ * Importing this module also publishes the runtime handshake (`./api.ts`), the channel a plugin
22
+ * uses when it does not import the package at all. A plugin that does import it calls
23
+ * `bridgeApi()` from its `session_start` handler — the object, or `undefined` when the bridge is
24
+ * not installed — or `onBridgeApi(handler, pi.events)`, which is the same answer plus the
25
+ * announcement form: the handler runs immediately when the object is already published, and when
26
+ * it is not, it runs when the bridge announces itself. There is no holding area either way.
27
+ */
28
+ export {
29
+ BRIDGE_READY_EVENT,
30
+ VERSION,
31
+ bridgeApi,
32
+ isBridgeApi,
33
+ onBridgeApi,
34
+ } from "./api.ts";
35
+ export type {
36
+ BridgeApi,
37
+ BridgeApiHandler,
38
+ BridgeEventBus,
39
+ BridgeEventUnsubscribe,
40
+ BridgeReadyPayload,
41
+ } from "./api.ts";
42
+ export { registerCardStyle, registerRows, registerSection, registerTransform } from "./bus.ts";
43
+ export { registerToolDesign, resolveToolDesignSelection } from "./tool-designs.ts";
44
+ export {
45
+ registerMessageDesign,
46
+ resolveMessageDesignFollow,
47
+ resolveMessageDesignSelection,
48
+ } from "./message-designs.ts";
49
+ export { resolveCardStyleSelection } from "./card-styles.ts";
50
+ export type { MessageDesignSelection } from "./message-designs.ts";
51
+ export type { ToolDesignSelection } from "./tool-designs.ts";
52
+ export { createStore, STORE_SCHEMA_VERSION } from "./store.ts";
53
+ export type { Store, StoreProblem, StoreProblemKind } from "./store.ts";
54
+ export type {
55
+ CardFrame,
56
+ CardFrameBottomContext,
57
+ CardFrameLineContext,
58
+ CardFrameTopContext,
59
+ CardStyleRegistration,
60
+ CardStyleSelection,
61
+ CustomizeRow,
62
+ InlineHelpers,
63
+ MessageDesignContext,
64
+ MessageDesignFollow,
65
+ MessageDesignFollowAnswer,
66
+ MessageDesignRegistration,
67
+ MessageDesignRender,
68
+ RowChoice,
69
+ RowContext,
70
+ RowLabel,
71
+ RowOrigin,
72
+ RowPreview,
73
+ RowProvider,
74
+ SectionContext,
75
+ SectionLine,
76
+ SectionPlacement,
77
+ SectionRow,
78
+ SidebarSection,
79
+ Tone,
80
+ ToolDesignCall,
81
+ ToolDesignContext,
82
+ ToolDesignRender,
83
+ ToolDesignRegistration,
84
+ ToolDesignScope,
85
+ TransformContext,
86
+ TransformCounts,
87
+ TranscriptTransform,
88
+ } from "./types.ts";
@@ -0,0 +1,549 @@
1
+ /**
2
+ * Adopting the custom messages Pi already mounted (S3, S4): the capture point the host actually offers.
3
+ *
4
+ * ## Why this pass exists, and why it is not an API patch
5
+ *
6
+ * `pi.registerMessageRenderer(customType, renderer)` writes into THAT extension's own map
7
+ * (`dist/core/extensions/loader.js:284-287`), and the runner answers `getMessageRenderer(customType)`
8
+ * by scanning extensions in LOAD ORDER and returning the first one that has the type
9
+ * (`dist/core/extensions/runner.js:534-540`). There is no `next()` chain, unlike tool renderers, and
10
+ * no accessor for another extension's map. Every extension holds its own `pi` object with its own
11
+ * closure, so a bridge that patched `pi.registerMessageRenderer` would capture only calls made
12
+ * through the bridge's object — that is, none.
13
+ *
14
+ * What the host does expose is the component it built: `CustomMessageComponent` keeps the renderer Pi
15
+ * resolved in `customRenderer`, re-calls it on every `rebuild()`, and falls back to its own box when
16
+ * the renderer answers `undefined`
17
+ * (`dist/modes/interactive/components/custom-message.js`, `rebuild()`). So adoption is: replace
18
+ * `customRenderer` with the design renderer (`./message-design-wiring.ts`) that delegates to the one
19
+ * the host had, then `invalidate()` so the stored renderer is re-resolved. Pi keeps its frame, its
20
+ * `box`, its padding and its theme, and only the rows change.
21
+ *
22
+ * ## Nobody claimed the type: nobody is touched (S4)
23
+ *
24
+ * A child is ours only when its `message.customType` is claimed by a live design. Everything else is
25
+ * `ignored`: no renderer replaced, no `invalidate()`, no store read. The claim test is a registry
26
+ * walk with no persistence, so a session without message designs pays one scan per render pass and
27
+ * nothing else.
28
+ *
29
+ * ## The one rebuild a switch needs
30
+ *
31
+ * The design renderer re-reads the selection on every pass, so `default` ↔ design with a host
32
+ * renderer needs no rebuild at all. A type with NO host renderer does: `undefined` (Pi's own box) and
33
+ * a component are different answers from the same renderer, so changing between them rebuilds the
34
+ * message exactly once, when the shape changes and never twice.
35
+ *
36
+ * This pass runs inside Pi's render loop, in the same conversation wrapper that adopts tool cards. It
37
+ * never throws: a container without children, a child that is not a message, a renderer that cannot be
38
+ * replaced — all are counted, and the ones the user should know about are reported through the design
39
+ * bus's one failure channel.
40
+ *
41
+ * This module is internal: `src/index.ts` does not re-export it.
42
+ */
43
+
44
+ import {
45
+ hasMessageDesignClaims,
46
+ isMessageTypeClaimed,
47
+ recordMessageDesignFailure,
48
+ resolveMessageDesignSelection,
49
+ } from "./message-designs.ts";
50
+ import { messageDesignRenderer, type HostMessageRenderer } from "./message-design-wiring.ts";
51
+ import { isRecord } from "./rows.ts";
52
+
53
+ /** What one adoption pass did, per child. */
54
+ export interface AdoptCustomMessagesResult {
55
+ /** Children the pass looked at. */
56
+ scanned: number;
57
+ /** Messages whose renderer this pass replaced with the design renderer. */
58
+ adopted: number;
59
+ /** Messages this pass (or an earlier one) already adopted, and the rebuild it needed if any. */
60
+ already: number;
61
+ /** Messages whose host renderer this pass put back, because no live design claims them any more. */
62
+ restored: number;
63
+ /** Children that are not a message of a claimed type. */
64
+ ignored: number;
65
+ /** Messages left exactly as the host built them after a reported failure. */
66
+ failed: number;
67
+ }
68
+
69
+ /** What this pass remembers about ONE message it adopted. */
70
+ interface AdoptedMessage {
71
+ /** Whether the renderer was built while a design was selected (true) or while it was not. */
72
+ designAtBuild: boolean;
73
+ /** The renderer Pi had resolved for this message, put back the moment nobody claims its type. */
74
+ hostRenderer: unknown;
75
+ /**
76
+ * Whether the host had a renderer at all. With one, `default` and a design are the same ANSWER from
77
+ * the design renderer (a component), so a switch between them needs no rebuild. Without one they
78
+ * are different answers — `undefined` (Pi's box) or a component — so the message is rebuilt once.
79
+ */
80
+ hadHost: boolean;
81
+ /**
82
+ * The design that failed on this message. While it is the selected one, the renderer answers
83
+ * `undefined` so Pi runs its own default path: that is what populates the box Pi shows, and retrying
84
+ * a broken design on every frame would only fail again. A different selection clears it by id.
85
+ */
86
+ suppressedDesign?: string;
87
+ }
88
+
89
+ /**
90
+ * Own property on a message component this module adopted. It certifies the exact renderer installed,
91
+ * so a rebuild, a reload or a second loaded copy of this package cannot stack two design renderers on
92
+ * one message.
93
+ */
94
+ const ADOPTED_MESSAGE: unique symbol = Symbol.for(
95
+ "gentle-shell-bridge.message-designs.adopted-message.v1",
96
+ );
97
+
98
+ interface AdoptionState {
99
+ /** Per custom type, how many messages this process adopted. */
100
+ adoptedMessages: Array<{ customType: string; messages: number }>;
101
+ /**
102
+ * How many messages currently carry the design renderer. The pass answers "no claim and nothing
103
+ * adopted" BEFORE it reads a child, which is what makes an unclaimed session cost nothing per
104
+ * frame (S4). A host that drops an adopted component without a pass seeing it can only make this
105
+ * number too high, which costs a read and never a wrong answer.
106
+ */
107
+ liveAdoptions: number;
108
+ /**
109
+ * Which adopted messages belong to which conversation container, so a pass over one container never
110
+ * concludes anything about another: a pass over an unrelated (or empty) container must not "heal"
111
+ * an adoption it never saw, and a container that really lost a child must.
112
+ */
113
+ adoptedByContainer: WeakMap<object, Set<unknown>>;
114
+ }
115
+
116
+ /** Stable process-global slot, like every other piece of bridge state: two copies must agree. */
117
+ const ADOPTION_KEY = Symbol.for("gentle-shell-bridge.message-designs.adoption.v1");
118
+
119
+ function adoptionHost(): Record<symbol, AdoptionState | undefined> {
120
+ // SAFETY: only `adoptionState()` writes this key, and it re-checks the shape before trusting a
121
+ // value left behind by another copy or an older load.
122
+ return globalThis as unknown as Record<symbol, AdoptionState | undefined>;
123
+ }
124
+
125
+ function adoptionState(): AdoptionState {
126
+ const host = adoptionHost();
127
+ const existing = host[ADOPTION_KEY];
128
+ if (existing !== undefined && Array.isArray(existing.adoptedMessages)) {
129
+ if (typeof existing.liveAdoptions !== "number") existing.liveAdoptions = 0;
130
+ if (!(existing.adoptedByContainer instanceof WeakMap)) {
131
+ existing.adoptedByContainer = new WeakMap();
132
+ }
133
+ return existing;
134
+ }
135
+ const created: AdoptionState = {
136
+ adoptedMessages: [],
137
+ liveAdoptions: 0,
138
+ adoptedByContainer: new WeakMap(),
139
+ };
140
+ host[ADOPTION_KEY] = created;
141
+ return created;
142
+ }
143
+
144
+ /** What the diagnostics record reports about this pass. */
145
+ export interface MessageDesignAdoptionDiagnostics {
146
+ /** Per custom type, how many messages were adopted after construction this process. */
147
+ adoptedMessages: Array<{ customType: string; messages: number }>;
148
+ }
149
+
150
+ /** Diagnostics snapshot for the diagnostics record. */
151
+ export function getMessageDesignAdoptionDiagnostics(): MessageDesignAdoptionDiagnostics {
152
+ return {
153
+ adoptedMessages: adoptionState().adoptedMessages.map((entry) => ({ ...entry })),
154
+ };
155
+ }
156
+
157
+ /** Test-only seam; deliberately not re-exported from `src/index.ts`. */
158
+ export function resetMessageDesignAdoptionForTests(): void {
159
+ const state = adoptionState();
160
+ state.adoptedMessages.length = 0;
161
+ state.liveAdoptions = 0;
162
+ state.adoptedByContainer = new WeakMap();
163
+ }
164
+
165
+ function errorMessage(error: unknown): string {
166
+ return error instanceof Error ? error.message : String(error);
167
+ }
168
+
169
+ function recordAdoptedMessage(customType: string): void {
170
+ const state = adoptionState();
171
+ const entry = state.adoptedMessages.find((candidate) => candidate.customType === customType);
172
+ if (entry === undefined) state.adoptedMessages.push({ customType, messages: 1 });
173
+ else entry.messages += 1;
174
+ }
175
+
176
+ /**
177
+ * Whether this type draws a design RIGHT NOW. Resolved at most once per type per pass, because it is
178
+ * the only step that reads the persisted selection.
179
+ */
180
+ function designIsSelected(customType: string, perPass: Map<string, boolean>): boolean {
181
+ const cached = perPass.get(customType);
182
+ if (cached !== undefined) return cached;
183
+ let selected = false;
184
+ try {
185
+ selected = resolveMessageDesignSelection(customType).kind === "design";
186
+ } catch (error) {
187
+ recordMessageDesignFailure(customType, "(selection)", errorMessage(error));
188
+ }
189
+ perPass.set(customType, selected);
190
+ return selected;
191
+ }
192
+
193
+ /** Read a member of a host object inside the render loop without letting a throwing getter out. */
194
+ function readMember(component: Record<string, unknown>, member: string): unknown {
195
+ try {
196
+ return component[member];
197
+ } catch {
198
+ return undefined;
199
+ }
200
+ }
201
+
202
+ /**
203
+ * Adopt every custom message in a container. Called on each CONVERSATION render pass, before the host
204
+ * renders its children; safe to call on anything, and it never throws.
205
+ */
206
+ export function adoptCustomMessages(container: unknown): AdoptCustomMessagesResult {
207
+ const result: AdoptCustomMessagesResult = {
208
+ scanned: 0,
209
+ adopted: 0,
210
+ already: 0,
211
+ restored: 0,
212
+ ignored: 0,
213
+ failed: 0,
214
+ };
215
+ // S4's cost bound: with nothing claimed and nothing adopted, a message is not even looked at.
216
+ if (!hasMessageDesignClaims() && adoptionState().liveAdoptions === 0) return result;
217
+ let children: unknown;
218
+ try {
219
+ if (!isRecord(container)) return result;
220
+ children = container.children;
221
+ } catch {
222
+ // A host object whose `children` accessor throws is not a container this pass can read; the
223
+ // host's own messages stand and there is no type to attribute the failure to.
224
+ return result;
225
+ }
226
+ if (!Array.isArray(children)) return result;
227
+
228
+ const perPass = new Map<string, boolean>();
229
+ const state = adoptionState();
230
+ // What THIS container owns, reconciled against what it holds: a message the host removed is a
231
+ // message this container no longer has, while another container's adoptions are none of its
232
+ // business.
233
+ const owned = ownedBy(state, container);
234
+ const seen = new Set<unknown>();
235
+ for (const child of children) {
236
+ result.scanned += 1;
237
+ seen.add(child);
238
+ try {
239
+ result[adoptMessage(child, perPass)] += 1;
240
+ // Counted AFTER the call, from what the child really is now, so an adoption opens the fast path
241
+ // and a restoration closes it — in one place, from one fact.
242
+ if (isRecord(child) && adoptedMessage(child) !== undefined) {
243
+ if (!owned.has(child)) {
244
+ owned.add(child);
245
+ state.liveAdoptions += 1;
246
+ }
247
+ } else if (owned.delete(child)) {
248
+ state.liveAdoptions -= 1;
249
+ }
250
+ } catch (error) {
251
+ // `adoptMessage` is written not to throw; this is the last line of defence inside Pi's render
252
+ // loop, so even a host object whose every accessor throws cannot take the frame down.
253
+ result.failed += 1;
254
+ const customType = messageTypeOf(child);
255
+ if (customType !== undefined) {
256
+ recordMessageDesignFailure(customType, "(adoption)", errorMessage(error));
257
+ }
258
+ }
259
+ }
260
+ // A message this container no longer holds is a message the host removed: only THIS container may
261
+ // conclude that, which is why the ownership sets exist at all. `liveAdoptions` is the process total,
262
+ // so one container losing a child reopens the fast path and a container that never saw an adoption
263
+ // cannot close it (S4).
264
+ for (const child of owned) {
265
+ if (!seen.has(child)) {
266
+ owned.delete(child);
267
+ state.liveAdoptions -= 1;
268
+ }
269
+ }
270
+ return result;
271
+ }
272
+
273
+ /** The set of messages one container adopted, created on first use. */
274
+ function ownedBy(state: AdoptionState, container: Record<string, unknown>): Set<unknown> {
275
+ const existing = state.adoptedByContainer.get(container);
276
+ if (existing !== undefined) return existing;
277
+ const created = new Set<unknown>();
278
+ state.adoptedByContainer.set(container, created);
279
+ return created;
280
+ }
281
+
282
+ /** The custom type of a message child, or `undefined` when this child is not one. */
283
+ function messageTypeOf(child: unknown): string | undefined {
284
+ if (!isRecord(child)) return undefined;
285
+ const message = readMember(child, "message");
286
+ if (!isRecord(message)) return undefined;
287
+ const customType = readMember(message, "customType");
288
+ return typeof customType === "string" && customType !== "" ? customType : undefined;
289
+ }
290
+
291
+ type MessageOutcome = "adopted" | "already" | "restored" | "ignored" | "failed";
292
+
293
+ function adoptMessage(child: unknown, perPass: Map<string, boolean>): MessageOutcome {
294
+ if (!isRecord(child)) return "ignored";
295
+ const customType = messageTypeOf(child);
296
+ if (customType === undefined) return "ignored";
297
+ const claimed = isMessageTypeClaimed(customType);
298
+ const adopted = adoptedMessage(child);
299
+
300
+ // A message this pass adopted, whose type nobody claims any more: put the host's own renderer back
301
+ // and rebuild once. Otherwise the message would keep calling a design renderer that now answers
302
+ // `default` — and would read the store on every frame for a type nobody claims (S4).
303
+ if (adopted !== undefined && !claimed) return restore(child, customType, adopted);
304
+
305
+ // Recognition is by CLAIM, never by the drawn frame (S4): a message nobody declared a design for is
306
+ // not ours to touch, and this is the only check that keeps an unclaimed session byte-identical.
307
+ if (!claimed) return "ignored";
308
+ // A component, and nothing else: a message object that is not renderable is not a message Pi drew.
309
+ if (typeof readMember(child, "render") !== "function") return "ignored";
310
+
311
+ const design = designIsSelected(customType, perPass);
312
+ if (adopted !== undefined) {
313
+ // Already adopted. The design renderer reads the selection per pass, so a switch between `default`
314
+ // and a design with a host renderer needs NOTHING. Without a host renderer the renderer answers
315
+ // `undefined` (Pi's own box) or a component — different answers — so it rebuilds exactly once per
316
+ // shape change, and never twice for the same shape.
317
+ // When the built answer was the wrapper, it reads the selection itself and nothing is needed. It
318
+ // is needed in the two cases where the built answer was NOT the wrapper: a host-less message that
319
+ // answered `undefined` (Pi's box) and now must draw, and a host-backed one that answered the
320
+ // host's own component and now must be rewritten. Coming back to `default` from a wrapper costs
321
+ // no rebuild in either case — the wrapper returns the host's rows, or Pi's own body, unchanged.
322
+ const needsRebuild = adopted.hadHost
323
+ ? design && !adopted.designAtBuild
324
+ : adopted.designAtBuild !== design;
325
+ if (needsRebuild) {
326
+ adopted.designAtBuild = design;
327
+ invalidate(child, customType);
328
+ }
329
+ return "already";
330
+ }
331
+
332
+ const hostRenderer = readMember(child, "customRenderer");
333
+ // Pi calls its renderer as a MEMBER (`this.customRenderer(...)`), so a host renderer that is a method
334
+ // gets the component as `this`. The design renderer must call it the same way or a method renderer
335
+ // breaks the moment the bridge wraps it.
336
+ const boundHost =
337
+ typeof hostRenderer === "function"
338
+ ? (message: unknown, options: unknown, theme?: unknown): unknown =>
339
+ // SAFETY: `typeof` just proved this callable; its arguments are Pi's own, forwarded as-is.
340
+ (hostRenderer as HostMessageRenderer).call(child, message, options, theme)
341
+ : undefined;
342
+ const renderer = messageDesignRenderer(customType, boundHost, {
343
+ // A design that throws on a host-less message must not take the body with it. Pi's own box is
344
+ // right there on the component it built, so it is rendered as-is: the same bytes the user would
345
+ // have seen without a design, not a picture of them invented here.
346
+ fallbackRows: (width: number): string[] | undefined => hostBoxRows(child, width),
347
+ // What the mounted answer is, kept true across rebuilds this pass never sees: `setExpanded`, a
348
+ // session switch or a reload re-enter the renderer, and a stale record would leave the message
349
+ // on the raw host component with no design able to reach it again.
350
+ onBuild: (designSelected: boolean): void => {
351
+ record.designAtBuild = designSelected;
352
+ },
353
+ isSuppressed: (designId: string): boolean => record.suppressedDesign === designId,
354
+ onFailure: (designId: string): void => {
355
+ if (record.suppressedDesign === designId) return;
356
+ record.suppressedDesign = designId;
357
+ // One rebuild: Pi's own renderer, its own populated box, and no second failure on this frame.
358
+ invalidate(child, customType);
359
+ },
360
+ });
361
+ const record: AdoptedMessage = {
362
+ designAtBuild: design,
363
+ hostRenderer,
364
+ hadHost: typeof hostRenderer === "function",
365
+ };
366
+
367
+
368
+ // The marker goes FIRST. A component that cannot take an own symbol (a sealed one) is reported and
369
+ // never touched, because replacing its renderer without a marker would make every later pass wrap
370
+ // it again — the one failure mode that compounds.
371
+ try {
372
+ Object.defineProperty(child, ADOPTED_MESSAGE, {
373
+ value: record,
374
+ enumerable: false,
375
+ configurable: true,
376
+ });
377
+ } catch (error) {
378
+ recordMessageDesignFailure(
379
+ customType,
380
+ "(adoption)",
381
+ `the message cannot be marked as adopted (${errorMessage(error)}); Pi's own rendering stands.`,
382
+ );
383
+ return "failed";
384
+ }
385
+ if (adoptedMessage(child) !== record) {
386
+ recordMessageDesignFailure(
387
+ customType,
388
+ "(adoption)",
389
+ "the message did not take the adoption marker; Pi's own rendering stands.",
390
+ );
391
+ return "failed";
392
+ }
393
+
394
+ try {
395
+ child.customRenderer = renderer;
396
+ } catch (error) {
397
+ delete symbolSlot(child)[ADOPTED_MESSAGE];
398
+ recordMessageDesignFailure(
399
+ customType,
400
+ "(adoption)",
401
+ `the message refuses its customRenderer (${errorMessage(error)}); Pi's own rendering stands.`,
402
+ );
403
+ return "failed";
404
+ }
405
+ // A setter (or a frozen object in a non-strict host) can ignore the assignment without throwing: the
406
+ // message is only adopted when the renderer this pass installed is really the one Pi will call.
407
+ if (child.customRenderer !== renderer) {
408
+ delete symbolSlot(child)[ADOPTED_MESSAGE];
409
+ recordMessageDesignFailure(
410
+ customType,
411
+ "(adoption)",
412
+ "the message did not take the design renderer; Pi's own rendering stands.",
413
+ );
414
+ return "failed";
415
+ }
416
+
417
+ recordAdoptedMessage(customType);
418
+ // The renderer Pi stored was resolved when the message was added; `invalidate()` is what makes it
419
+ // resolve again, through the design renderer.
420
+ invalidate(child, customType);
421
+ return "adopted";
422
+ }
423
+
424
+ /**
425
+ * Put the host's own renderer back on a message no design claims any more, and rebuild it once. The
426
+ * host's value is restored VERBATIM (including `undefined` for a type with no renderer), so the message
427
+ * returns to exactly what Pi built, and no later frame pays for a surface nobody uses.
428
+ */
429
+ function restore(
430
+ child: Record<string, unknown>,
431
+ customType: string,
432
+ record: AdoptedMessage,
433
+ ): MessageOutcome {
434
+ try {
435
+ child.customRenderer = record.hostRenderer;
436
+ } catch (error) {
437
+ recordMessageDesignFailure(
438
+ customType,
439
+ "(adoption)",
440
+ `the message refuses its customRenderer while being restored (${errorMessage(error)}); ` +
441
+ "the design renderer stays, drawing `default`.",
442
+ );
443
+ return "failed";
444
+ }
445
+ if (child.customRenderer !== record.hostRenderer) {
446
+ recordMessageDesignFailure(
447
+ customType,
448
+ "(adoption)",
449
+ "the message did not take its host renderer back; the design renderer stays, drawing `default`.",
450
+ );
451
+ return "failed";
452
+ }
453
+ delete symbolSlot(child)[ADOPTED_MESSAGE];
454
+ invalidate(child, customType);
455
+ return "restored";
456
+ }
457
+
458
+ /**
459
+ * Pi's own box for this message, rendered at `width`, or `undefined` when the component has none this
460
+ * pass can read. `CustomMessageComponent` builds that box in its constructor and keeps it for exactly
461
+ * this default rendering, so asking it is reading the host's own work — never re-drawing it.
462
+ */
463
+ function hostBoxRows(child: Record<string, unknown>, width: number): string[] | undefined {
464
+ const box = readMember(child, "box");
465
+ if (!isRecord(box) || typeof readMember(box, "render") !== "function") return undefined;
466
+ // Pi applies the message's padding to that box ONLY on its default path, which a design bypasses:
467
+ // after `setOutputPad(4)` the box still carries the padding it was born with. Rendering it as the
468
+ // fallback must therefore set the CURRENT output padding first, or a failed design would answer an
469
+ // indented box that no setting asked for.
470
+ const outputPad = readMember(child, "outputPad");
471
+ const setPaddingX = readMember(box, "setPaddingX");
472
+ const currentPad = readMember(box, "paddingX");
473
+ // Only when it really changed: `setPaddingX` invalidates the box's own render cache, and paying that
474
+ // on every failed draw would make a message with a broken design rebuild its box on every frame.
475
+ if (
476
+ typeof outputPad === "number" &&
477
+ outputPad !== currentPad &&
478
+ typeof setPaddingX === "function"
479
+ ) {
480
+ try {
481
+ (setPaddingX as (padding: number) => void).call(box, outputPad);
482
+ } catch {
483
+ // A box that refuses its own padding is still a box this pass can render.
484
+ }
485
+ }
486
+ let rows: unknown;
487
+ let blank = true;
488
+ try {
489
+ // SAFETY: `typeof` just proved `render` callable, and a component's `render(width)` is the whole
490
+ // contract this reads; its answer is inspected before it is trusted.
491
+ rows = (readMember(box, "render") as (width: number) => unknown).call(box, width);
492
+ } catch {
493
+ return undefined;
494
+ }
495
+ if (!Array.isArray(rows)) return undefined;
496
+ for (let index = 0; index < rows.length; index += 1) {
497
+ const row = rows[index];
498
+ if (typeof row !== "string") return undefined;
499
+ // An EMPTY box is not a frame: Pi only populates its default box on the path a design bypasses,
500
+ // so a box that renders nothing at all must not be handed to the user as "the host's answer".
501
+ if (row.trim() !== "") blank = false;
502
+ }
503
+ return blank ? undefined : (rows as string[]);
504
+ }
505
+
506
+ /**
507
+ * The same component, read through the symbol key this module owns. One cast, in one place: the record
508
+ * lives on the host's own object, so it can only be reached through a symbol index.
509
+ */
510
+ function symbolSlot(child: Record<string, unknown>): Record<symbol, unknown> {
511
+ // SAFETY: a symbol-keyed read of the same object; `ADOPTED_MESSAGE` is the only symbol written here,
512
+ // and the value is re-checked for its shape before it is trusted.
513
+ return child as unknown as Record<symbol, unknown>;
514
+ }
515
+
516
+ /** The adoption record of a child this pass installed a renderer on, if it is really still ours. */
517
+ function adoptedMessage(child: Record<string, unknown>): AdoptedMessage | undefined {
518
+ const record = symbolSlot(child)[ADOPTED_MESSAGE];
519
+ if (!isRecord(record)) return undefined;
520
+ // SAFETY: the only writer of this symbol is `adoptMessage`, which stores an `AdoptedMessage`; a
521
+ // value left by another copy is re-checked for the fields this pass reads before it is trusted.
522
+ return typeof record.designAtBuild === "boolean" && typeof record.hadHost === "boolean"
523
+ ? (record as unknown as AdoptedMessage)
524
+ : undefined;
525
+ }
526
+
527
+ /** Rebuild one message; a throwing `invalidate` is the host's own failure and is reported once. */
528
+ function invalidate(child: Record<string, unknown>, customType: string): void {
529
+ const invalidateChild = readMember(child, "invalidate");
530
+ if (typeof invalidateChild !== "function") {
531
+ recordMessageDesignFailure(
532
+ customType,
533
+ "(adoption)",
534
+ "the message has no invalidate(), so its renderer cannot be re-resolved; Pi keeps drawing " +
535
+ "what it already drew until the message is rebuilt by the host.",
536
+ );
537
+ return;
538
+ }
539
+ try {
540
+ (invalidateChild as () => void).call(child);
541
+ } catch (error) {
542
+ recordMessageDesignFailure(
543
+ customType,
544
+ "(adoption)",
545
+ `the message threw from invalidate() after adoption (${errorMessage(error)}); its next frame ` +
546
+ "still draws through the design.",
547
+ );
548
+ }
549
+ }