pi-odd-worktree 3.15.1 → 3.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +48 -25
  2. package/extensions/odd-worktree-tools.ts +70 -212
  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/session-auto-name-wiring.test.js +39 -0
  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 +8 -9
@@ -0,0 +1,279 @@
1
+ /**
2
+ * Optional namespaced store (S5, S8; docs/state.md).
3
+ *
4
+ * `<bridge config home>/<pluginId>.json`, one file per plugin, written atomically. The bridge
5
+ * composes rows; it does not own preferences, so this is a convenience for a plugin that has no
6
+ * file of its own. `registerRows` never reads or writes these files.
7
+ *
8
+ * Document shape:
9
+ *
10
+ * ```json
11
+ * { "schemaVersion": 1, "values": { "bannerSource": "output" } }
12
+ * ```
13
+ *
14
+ * `values` is an envelope so a plugin key can never collide with `schemaVersion`.
15
+ *
16
+ * Malformed files: a file that is not valid JSON, does not parse to an object, or carries an
17
+ * unknown `schemaVersion` is reported through `status`, never repaired and never deleted. Reads
18
+ * fall back to the caller's default.
19
+ *
20
+ * A later `set` writes a valid `schemaVersion: 1` document. Existing `values` are carried forward
21
+ * ONLY when the file was a usable `schemaVersion: 1` document, so a partially written file keeps
22
+ * its other keys. For an unknown `schemaVersion` the write stores only the keys the caller sets —
23
+ * re-labelling a future payload as schema 1 would be a lie about its format — and the discarded
24
+ * payload is recorded as a store problem so the diagnostics record shows what happened. Foreign
25
+ * top-level keys are always dropped, because the bridge cannot know what they mean.
26
+ */
27
+
28
+ import { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
29
+ import { dirname, join } from "node:path";
30
+
31
+ import { getBridgeConfigHome } from "./config.ts";
32
+ import { isRecord } from "./rows.ts";
33
+
34
+ /** Current document schema, an integer so a later shape change can migrate. */
35
+ export const STORE_SCHEMA_VERSION = 1;
36
+
37
+ export type StoreProblemKind =
38
+ | "invalid-json"
39
+ | "not-an-object"
40
+ | "unsupported-schema-version"
41
+ | "unreadable";
42
+
43
+ /** A store file the bridge could not use, surfaced by `status` (S6). */
44
+ export interface StoreProblem {
45
+ pluginId: string;
46
+ path: string;
47
+ kind: StoreProblemKind;
48
+ message: string;
49
+ }
50
+
51
+ /** One plugin's file. Every accessor is scoped to that file. */
52
+ export interface Store {
53
+ readonly pluginId: string;
54
+ readonly path: string;
55
+ /** The stored value, or `fallback` when the key is absent or the file is unusable. */
56
+ get<T>(key: string, fallback: T): T;
57
+ /** Persist one key atomically. Throws before writing if the value is not JSON-serialisable. */
58
+ set(key: string, value: unknown): void;
59
+ }
60
+
61
+ const STORE_STATE = Symbol.for("gentle-shell-bridge.store.state.v1");
62
+
63
+ interface StoreState {
64
+ /** Latest problem per plugin id, in first-report order. */
65
+ problems: StoreProblem[];
66
+ }
67
+
68
+ function storeHost(): Record<symbol, unknown> {
69
+ // SAFETY: `globalThis` accepts symbol keys, and the only write to this slot is `storeState()`
70
+ // below; a foreign value is rejected there before use.
71
+ return globalThis as unknown as Record<symbol, unknown>;
72
+ }
73
+
74
+ function storeState(): StoreState {
75
+ const host = storeHost();
76
+ const existing = host[STORE_STATE];
77
+ if (isStoreState(existing)) return existing;
78
+ const created: StoreState = { problems: [] };
79
+ host[STORE_STATE] = created;
80
+ return created;
81
+ }
82
+
83
+ function isStoreState(value: unknown): value is StoreState {
84
+ return isRecord(value) && Array.isArray(value.problems);
85
+ }
86
+
87
+ /** Problems from the most recent read or write of each store file. */
88
+ export function getStoreDiagnostics(): StoreProblem[] {
89
+ return storeState().problems.map((problem) => ({ ...problem }));
90
+ }
91
+
92
+ /** Test-only seam; deliberately not re-exported from `src/index.ts`. */
93
+ export function resetStoreStateForTests(): void {
94
+ storeState().problems = [];
95
+ }
96
+
97
+ function recordProblem(problem: StoreProblem): void {
98
+ const state = storeState();
99
+ const index = state.problems.findIndex((existing) => existing.pluginId === problem.pluginId);
100
+ if (index === -1) state.problems.push(problem);
101
+ else state.problems[index] = problem;
102
+ }
103
+
104
+ function clearProblem(pluginId: string): void {
105
+ const state = storeState();
106
+ state.problems = state.problems.filter((problem) => problem.pluginId !== pluginId);
107
+ }
108
+
109
+ /**
110
+ * Create the store for one plugin. The id is validated before any filesystem access: it must be a
111
+ * non-empty single path segment, so it can never name a file outside the bridge directory.
112
+ * Invalid ids throw; they are never silently sanitised.
113
+ */
114
+ export function createStore(pluginId: string): Store {
115
+ const path = resolveStorePath(pluginId);
116
+
117
+ return {
118
+ pluginId,
119
+ path,
120
+ get<T>(key: string, fallback: T): T {
121
+ const read = readValues(pluginId, path);
122
+ if (read.problem !== undefined) {
123
+ // An unusable file reads as empty. Its `values` are kept only so a later `set` can carry
124
+ // them over — an unknown or future schema must never serve foreign data to the caller.
125
+ // A reported problem stays on record until a write resolves it, so a read of a usable
126
+ // file cannot silently erase what the diagnostics record is supposed to show.
127
+ recordProblem(read.problem);
128
+ return fallback;
129
+ }
130
+ return Object.hasOwn(read.values, key) ? (read.values[key] as T) : fallback;
131
+ },
132
+ set(key: string, value: unknown): void {
133
+ const read = readValues(pluginId, path);
134
+ // Serialise before touching the disk so an unserialisable value cannot truncate the file.
135
+ const document = {
136
+ schemaVersion: STORE_SCHEMA_VERSION,
137
+ // Only a usable schema-1 document contributes existing values to the write.
138
+ values: { ...(read.carriesValues ? read.values : {}), [key]: value },
139
+ };
140
+ const serialised = `${JSON.stringify(document, null, 2)}\n`;
141
+
142
+ mkdirSync(dirname(path), { recursive: true });
143
+ const tempPath = `${path}.${process.pid}.${Date.now().toString(36)}.${writeCounter++}.tmp`;
144
+ try {
145
+ writeFileSync(tempPath, serialised, "utf8");
146
+ // Same directory, so the rename is atomic on one filesystem.
147
+ renameSync(tempPath, path);
148
+ } catch (error) {
149
+ // Never leave a partial temp file behind if the rename failed.
150
+ try {
151
+ unlinkSync(tempPath);
152
+ } catch {
153
+ // Already renamed, or never created: nothing to clean.
154
+ }
155
+ throw error;
156
+ }
157
+ if (
158
+ !read.carriesValues &&
159
+ read.problem !== undefined &&
160
+ read.problem.kind === "unsupported-schema-version"
161
+ ) {
162
+ // The write dropped a payload the bridge could not interpret; keep that fact visible.
163
+ recordProblem({
164
+ ...read.problem,
165
+ message: `${read.problem.message}; its payload was discarded by this write, which stored only the keys set afterwards`,
166
+ });
167
+ } else {
168
+ clearProblem(pluginId);
169
+ }
170
+ },
171
+ };
172
+ }
173
+
174
+ let writeCounter = 0;
175
+
176
+ function resolveStorePath(pluginId: string): string {
177
+ const reject = (reason: string): never => {
178
+ throw new Error(
179
+ `gentle-shell-bridge: invalid plugin id ${JSON.stringify(pluginId)}: ${reason}. ` +
180
+ "A plugin id must be one non-empty path segment (no separators, no '.' or '..').",
181
+ );
182
+ };
183
+
184
+ if (typeof pluginId !== "string" || pluginId.length === 0) reject("it is empty");
185
+ if (pluginId.includes("\0")) reject("it contains a NUL byte");
186
+ if (pluginId === "." || pluginId === "..") reject("it is a directory reference");
187
+ if (pluginId.includes("/") || pluginId.includes("\\")) reject("it contains a path separator");
188
+ if (pluginId.includes("..")) reject("it contains '..'");
189
+
190
+ const directory = getBridgeConfigHome();
191
+ const path = join(directory, `${pluginId}.json`);
192
+ // Defence in depth: even a future id rule cannot place the file outside the bridge directory.
193
+ if (dirname(path) !== directory) reject("it resolves outside the bridge directory");
194
+ return path;
195
+ }
196
+
197
+ interface ReadResult {
198
+ values: Record<string, unknown>;
199
+ /** Existing values may be carried into a write: only for a usable `schemaVersion: 1` document. */
200
+ carriesValues: boolean;
201
+ problem?: StoreProblem;
202
+ }
203
+
204
+ function readValues(pluginId: string, path: string): ReadResult {
205
+ let raw: string;
206
+ try {
207
+ raw = readFileSync(path, "utf8");
208
+ } catch (error) {
209
+ if (isNotFound(error)) return { values: {}, carriesValues: false };
210
+ return {
211
+ values: {},
212
+ carriesValues: false,
213
+ problem: {
214
+ pluginId,
215
+ path,
216
+ kind: "unreadable",
217
+ message: error instanceof Error ? error.message : String(error),
218
+ },
219
+ };
220
+ }
221
+
222
+ let parsed: unknown;
223
+ try {
224
+ parsed = JSON.parse(raw);
225
+ } catch (error) {
226
+ return {
227
+ values: {},
228
+ carriesValues: false,
229
+ problem: {
230
+ pluginId,
231
+ path,
232
+ kind: "invalid-json",
233
+ message: error instanceof Error ? error.message : String(error),
234
+ },
235
+ };
236
+ }
237
+
238
+ if (!isRecord(parsed)) {
239
+ return {
240
+ values: {},
241
+ carriesValues: false,
242
+ problem: { pluginId, path, kind: "not-an-object", message: "document is not a JSON object" },
243
+ };
244
+ }
245
+
246
+ if (parsed.schemaVersion !== STORE_SCHEMA_VERSION) {
247
+ return {
248
+ // An unknown schema's payload is NOT carried forward: the bridge cannot know its meaning,
249
+ // so a write must not re-label it as schema 1. It is reported instead (see `set`).
250
+ values: {},
251
+ carriesValues: false,
252
+ problem: {
253
+ pluginId,
254
+ path,
255
+ kind: "unsupported-schema-version",
256
+ message: `schemaVersion is ${String(parsed.schemaVersion)}, expected ${STORE_SCHEMA_VERSION}`,
257
+ },
258
+ };
259
+ }
260
+
261
+ if (!isRecord(parsed.values)) {
262
+ return {
263
+ values: {},
264
+ carriesValues: false,
265
+ problem: {
266
+ pluginId,
267
+ path,
268
+ kind: "not-an-object",
269
+ message: "schemaVersion is 1 but values is not an object",
270
+ },
271
+ };
272
+ }
273
+
274
+ return { values: parsed.values, carriesValues: true };
275
+ }
276
+
277
+ function isNotFound(error: unknown): boolean {
278
+ return isRecord(error) && error.code === "ENOENT";
279
+ }
@@ -0,0 +1,263 @@
1
+ /**
2
+ * Adopting tool cards AFTER construction (S10, T14–T16): the path that survives the resolver order.
3
+ *
4
+ * ## Why a second path exists at all
5
+ *
6
+ * Pi composes every extension's `ToolRendererResolver` in EXTENSION LOAD ORDER
7
+ * (`dist/core/extensions/runner.js:550-553`) and offers no way to reorder them
8
+ * (`dist/core/extensions/loader.js:298-302` only pushes). So a resolver loaded before this package
9
+ * decides first, and a resolver that answers WITHOUT calling `next()` — the host's own quiet bash
10
+ * resolver does exactly that while `Card content` is `minimal`
11
+ * (`extensions/quiet-tools.ts:910-914`) — means the bridge's resolver is never consulted. The user's
12
+ * live report (L3) is that picture: a design is selected, the `Cards` row and the sidebar say so, and
13
+ * every bash card still draws `$ …`.
14
+ *
15
+ * `./tool-design-wiring.ts` stays exactly as it is: when this package happens to be ahead in the
16
+ * chain, its wrapper is the cheaper path and needs no second pass. This module is the other path,
17
+ * for when it is behind: it adopts the card AFTER Pi constructed it.
18
+ *
19
+ * ## The card's own contract is enough
20
+ *
21
+ * The bridge already holds the conversation component (`./card-style-wiring.ts`'s
22
+ * `findConversation`), and its children are Pi's `ToolExecutionComponent`s. Each one carries
23
+ * `toolName` and the `toolDefinition` Pi resolved for it
24
+ * (`dist/modes/interactive/components/tool-execution.js`, constructor near line 37-45), and
25
+ * `invalidate()` re-invokes the stored `renderCall`/`renderResult` through `updateDisplay()`
26
+ * (`tool-execution.js:64-68,164-175`). So adopting a card is: replace its `toolDefinition` with the
27
+ * SAME wrapper the resolver path uses (`wrapRenderers`), then invalidate it so its stored renderer
28
+ * is rebuilt through that wrapper. No second wrapper, no fork of the render rule.
29
+ *
30
+ * The pass runs on every conversation render, BEFORE the host renders its children
31
+ * (`./card-style-wiring.ts`), so:
32
+ *
33
+ * - a card drawn before the design existed is adopted the first time it is rendered;
34
+ * - a card Pi rebuilds (reload, `/tree`, session switch) is a NEW child and is adopted on the next
35
+ * pass;
36
+ * - the wrapper re-reads the live selection on every frame, so selecting a design repaints the
37
+ * adopted card and selecting `native` restores the host's own bytes (S2).
38
+ *
39
+ * ## A marker, so the two paths cannot stack
40
+ *
41
+ * `wrapRenderers` stamps the wrapper it returns with one symbol
42
+ * (`TOOL_RENDERERS_WRAPPED`), and both paths check it. Resolver first: the card's
43
+ * `toolDefinition` is already stamped, so adoption reports `already` and does not wrap again.
44
+ * Adoption first: a later resolver call on that same object returns it untouched for the same
45
+ * reason. The design therefore applies exactly once, whichever path got there first.
46
+ *
47
+ * ## Every absence is a reported outcome, never a throw
48
+ *
49
+ * This runs inside Pi's render loop. A container without `children`, a child that is not a card, a
50
+ * `toolName` that is not a string, a tool with no designs: all are silently not-ours (`ignored`) —
51
+ * the host's rows stand. A card of an adopted tool whose `toolDefinition` is missing, not a record,
52
+ * has nothing to wrap, or cannot be reassigned is REPORTED through the design bus's one failure
53
+ * channel (`recordToolDesignFailure`, deduplicated) and left exactly as the host built it. A
54
+ * throwing `invalidate` is reported too, and the wrapped definition still applies on the next frame.
55
+ */
56
+
57
+ import { isRecord } from "./rows.ts";
58
+ import { designsOfTool, recordToolDesignFailure } from "./tool-designs.ts";
59
+ import {
60
+ TOOL_RENDERERS_WRAPPED,
61
+ wrapRenderers,
62
+ type ToolRenderersLike,
63
+ } from "./tool-design-wiring.ts";
64
+
65
+ /** What one adoption pass did, per child. */
66
+ export interface AdoptToolCardsResult {
67
+ /** Children the pass looked at. */
68
+ scanned: number;
69
+ /** Cards whose `toolDefinition` this pass wrapped. */
70
+ adopted: number;
71
+ /** Cards already carrying the wrapper (this path or the resolver's). */
72
+ already: number;
73
+ /** Children that are not a card of a tool with designs. */
74
+ ignored: number;
75
+ /** Cards left exactly as the host built them after a reported failure. */
76
+ failed: number;
77
+ }
78
+
79
+ interface AdoptedEntry {
80
+ tool: string;
81
+ cards: number;
82
+ }
83
+
84
+ interface AdoptionState {
85
+ adoptedCards: AdoptedEntry[];
86
+ }
87
+
88
+ /** Stable process-global slot, like every other piece of bridge state: two copies must agree. */
89
+ const ADOPTION_STATE: symbol = Symbol.for("gentle-shell-bridge.tool-designs.adoption.v1");
90
+
91
+ function adoptionHost(): Record<symbol, AdoptionState | undefined> {
92
+ // SAFETY: only `adoptionState()` writes this key, and it re-checks the shape before trusting a
93
+ // value left behind by another copy or an older load.
94
+ return globalThis as unknown as Record<symbol, AdoptionState | undefined>;
95
+ }
96
+
97
+ function adoptionState(): AdoptionState {
98
+ const host = adoptionHost();
99
+ const existing = host[ADOPTION_STATE];
100
+ if (existing !== undefined && Array.isArray(existing.adoptedCards)) return existing;
101
+ const created: AdoptionState = { adoptedCards: [] };
102
+ host[ADOPTION_STATE] = created;
103
+ return created;
104
+ }
105
+
106
+ function errorMessage(error: unknown): string {
107
+ return error instanceof Error ? error.message : String(error);
108
+ }
109
+
110
+ /** Record one card adopted for a tool (once per card: the wrapper's marker prevents a recount). */
111
+ function recordAdoptedCard(tool: string): void {
112
+ const state = adoptionState();
113
+ const entry = state.adoptedCards.find((candidate) => candidate.tool === tool);
114
+ if (entry === undefined) state.adoptedCards.push({ tool, cards: 1 });
115
+ else entry.cards += 1;
116
+ }
117
+
118
+ /** What the diagnostics record reports about the adoption path. */
119
+ export interface ToolDesignAdoptionDiagnostics {
120
+ /** Per tool, how many card components were adopted after construction this process. */
121
+ adoptedCards: AdoptedEntry[];
122
+ }
123
+
124
+ /** Diagnostics snapshot for the diagnostics record (T16). */
125
+ export function getToolDesignAdoptionDiagnostics(): ToolDesignAdoptionDiagnostics {
126
+ return {
127
+ adoptedCards: adoptionState().adoptedCards.map((entry) => ({ ...entry })),
128
+ };
129
+ }
130
+
131
+ /** Test-only seam; deliberately not re-exported from `src/index.ts`. */
132
+ export function resetToolDesignAdoptionForTests(): void {
133
+ adoptionState().adoptedCards.length = 0;
134
+ }
135
+
136
+ const FAILURE_ID = "(adoption)";
137
+
138
+ /**
139
+ * Adopt every tool card in a container. Called on each CONVERSATION render pass, before the host
140
+ * renders its children (`./card-style-wiring.ts`); safe to call on anything, and it never throws.
141
+ */
142
+ export function adoptToolCards(container: unknown): AdoptToolCardsResult {
143
+ const result: AdoptToolCardsResult = { scanned: 0, adopted: 0, already: 0, ignored: 0, failed: 0 };
144
+ let children: unknown;
145
+ try {
146
+ if (!isRecord(container)) return result;
147
+ children = container.children;
148
+ } catch {
149
+ // A host object whose `children` accessor throws is not a container this pass can read; the
150
+ // host's own rows stand and there is no tool to attribute the failure to.
151
+ return result;
152
+ }
153
+ if (!Array.isArray(children)) return result;
154
+
155
+ for (const child of children) {
156
+ result.scanned += 1;
157
+ try {
158
+ result[adoptCard(child)] += 1;
159
+ } catch (error) {
160
+ // `adoptCard` is written not to throw; this is the last line of defence inside Pi's render
161
+ // loop, so even a host object whose every accessor throws cannot take the frame down.
162
+ result.failed += 1;
163
+ const tool = isRecord(child) ? child.toolName : undefined;
164
+ if (typeof tool === "string" && tool !== "") {
165
+ recordToolDesignFailure(tool, FAILURE_ID, errorMessage(error));
166
+ }
167
+ }
168
+ }
169
+ return result;
170
+ }
171
+
172
+ type CardOutcome = "adopted" | "already" | "ignored" | "failed";
173
+
174
+ function adoptCard(child: unknown): CardOutcome {
175
+ if (!isRecord(child)) return "ignored";
176
+ const tool = child.toolName;
177
+ // Recognition is by component identity, never by the drawn frame (S1): a child that is not a tool
178
+ // card is not ours to touch, and neither is a tool nobody declared a design for.
179
+ if (typeof tool !== "string" || tool === "") return "ignored";
180
+ if (designsOfTool(tool).length === 0) return "ignored";
181
+
182
+ const definition = child.toolDefinition;
183
+ if (definition === undefined || definition === null) {
184
+ recordToolDesignFailure(
185
+ tool,
186
+ FAILURE_ID,
187
+ `the card of tool ${JSON.stringify(tool)} carries no toolDefinition, so there are no renderers ` +
188
+ "to wrap; the host's own card is drawn.",
189
+ );
190
+ return "failed";
191
+ }
192
+ if (!isRecord(definition)) {
193
+ recordToolDesignFailure(
194
+ tool,
195
+ FAILURE_ID,
196
+ `the card of tool ${JSON.stringify(tool)} carries a toolDefinition that is not an object, so ` +
197
+ "there is nothing to wrap; the host's own card is drawn.",
198
+ );
199
+ return "failed";
200
+ }
201
+ // SAFETY: `isRecord` just proved this is an object; `toolDefinition` is structurally the renderers
202
+ // object Pi hands a resolver (`renderCall`, `renderResult`, `renderShell`, plus host extras).
203
+ const renderers = definition as ToolRenderersLike;
204
+ // The resolver path (or an earlier pass) already wrapped this card: one design applies once.
205
+ if (Object.hasOwn(renderers, TOOL_RENDERERS_WRAPPED)) return "already";
206
+
207
+ let wrapped: ToolRenderersLike;
208
+ try {
209
+ wrapped = wrapRenderers(renderers, tool, "adoption");
210
+ } catch (error) {
211
+ recordToolDesignFailure(tool, FAILURE_ID, errorMessage(error));
212
+ return "failed";
213
+ }
214
+ if (wrapped === renderers) {
215
+ recordToolDesignFailure(
216
+ tool,
217
+ FAILURE_ID,
218
+ `the card of tool ${JSON.stringify(tool)} has no renderCall/renderResult function in its ` +
219
+ "toolDefinition, so there is nothing to wrap; the host's own card is drawn.",
220
+ );
221
+ return "failed";
222
+ }
223
+
224
+ try {
225
+ child.toolDefinition = wrapped;
226
+ } catch (error) {
227
+ recordToolDesignFailure(
228
+ tool,
229
+ FAILURE_ID,
230
+ `the card of tool ${JSON.stringify(tool)} refuses its toolDefinition (${errorMessage(error)}); ` +
231
+ "the host's own card is drawn.",
232
+ );
233
+ return "failed";
234
+ }
235
+ // A setter (or a frozen object in a non-strict host) can ignore the assignment without throwing;
236
+ // the card is only adopted when the wrapper is really what the host will read.
237
+ if (child.toolDefinition !== wrapped) {
238
+ recordToolDesignFailure(
239
+ tool,
240
+ FAILURE_ID,
241
+ `the card of tool ${JSON.stringify(tool)} did not take the wrapped toolDefinition; the host's ` +
242
+ "own card is drawn.",
243
+ );
244
+ return "failed";
245
+ }
246
+
247
+ recordAdoptedCard(tool);
248
+
249
+ // The stored renderer is only rebuilt when the card invalidates; a throwing `invalidate` is the
250
+ // host's own failure, reported once, and the wrapped definition still applies on the next frame.
251
+ try {
252
+ const invalidate = child.invalidate;
253
+ if (typeof invalidate === "function") (invalidate as () => void).call(child);
254
+ } catch (error) {
255
+ recordToolDesignFailure(
256
+ tool,
257
+ FAILURE_ID,
258
+ `the card of tool ${JSON.stringify(tool)} threw from invalidate() after adoption ` +
259
+ `(${errorMessage(error)}); its next frame still draws through the design.`,
260
+ );
261
+ }
262
+ return "adopted";
263
+ }