gentle-shell-bridge 0.0.0-stage → 0.3.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 (112) hide show
  1. package/.codegraph/.gitignore +5 -0
  2. package/PRD.md +144 -0
  3. package/README.md +745 -2
  4. package/docs/architecture.md +981 -0
  5. package/docs/contract.md +1266 -0
  6. package/docs/state.md +251 -0
  7. package/examples/bash-card.ts +1694 -0
  8. package/gentle-shell-bridge-0.3.0.tgz +0 -0
  9. package/odd/tasks/palette-sections.md +30 -0
  10. package/odd/tasks/plugin-keymap.md +32 -0
  11. package/odd/tasks/plugin-surface-contract.md +55 -0
  12. package/package.json +35 -4
  13. package/src/api.ts +492 -0
  14. package/src/arm.ts +83 -0
  15. package/src/bus.ts +558 -0
  16. package/src/capture.ts +886 -0
  17. package/src/card-style-line.ts +112 -0
  18. package/src/card-style-rows.ts +390 -0
  19. package/src/card-style-transform.ts +862 -0
  20. package/src/card-style-wiring.ts +472 -0
  21. package/src/card-styles.ts +159 -0
  22. package/src/config.ts +71 -0
  23. package/src/extension.ts +271 -0
  24. package/src/hook.ts +310 -0
  25. package/src/index.ts +71 -0
  26. package/src/notices.ts +137 -0
  27. package/src/plugin-lines.ts +865 -0
  28. package/src/plugin-surface.ts +218 -0
  29. package/src/presence.ts +259 -0
  30. package/src/repaint.ts +351 -0
  31. package/src/row-labels.ts +146 -0
  32. package/src/row-names.ts +273 -0
  33. package/src/row-origin.ts +144 -0
  34. package/src/rows.ts +248 -0
  35. package/src/section-panel.ts +378 -0
  36. package/src/section-pointer.ts +164 -0
  37. package/src/sections-rows.ts +128 -0
  38. package/src/sidebar-render.ts +535 -0
  39. package/src/sidebar.ts +919 -0
  40. package/src/status.ts +1161 -0
  41. package/src/store.ts +279 -0
  42. package/src/tool-design-adoption.ts +263 -0
  43. package/src/tool-design-rows.ts +246 -0
  44. package/src/tool-design-wiring.ts +428 -0
  45. package/src/tool-designs.ts +402 -0
  46. package/src/transform-pipeline.ts +351 -0
  47. package/src/types.ts +442 -0
  48. package/src/visibility.ts +154 -0
  49. package/test/api.test.ts +395 -0
  50. package/test/apply-on-move.test.ts +477 -0
  51. package/test/arm.test.ts +220 -0
  52. package/test/bridge-ready.test.ts +309 -0
  53. package/test/bus.test.ts +165 -0
  54. package/test/button-rows.test.ts +409 -0
  55. package/test/capture.test.ts +356 -0
  56. package/test/card-style-rows.test.ts +510 -0
  57. package/test/card-style-transform.test.ts +379 -0
  58. package/test/card-style-wiring.test.ts +258 -0
  59. package/test/card-styles-e2e.test.ts +491 -0
  60. package/test/card-styles.test.ts +324 -0
  61. package/test/card-transcript-path.test.ts +178 -0
  62. package/test/config.test.ts +93 -0
  63. package/test/e2e.test.ts +443 -0
  64. package/test/example-bash-identity.test.ts +372 -0
  65. package/test/example-bash-matrix.test.ts +856 -0
  66. package/test/example-designs.test.ts +734 -0
  67. package/test/example-neon-transform.test.ts +283 -0
  68. package/test/example-plain-style.test.ts +1268 -0
  69. package/test/extension.test.ts +160 -0
  70. package/test/fake-events.ts +58 -0
  71. package/test/fake-host.ts +211 -0
  72. package/test/fake-sidebar.ts +516 -0
  73. package/test/fake-transcript.ts +486 -0
  74. package/test/frame-telemetry.test.ts +417 -0
  75. package/test/hook.test.ts +196 -0
  76. package/test/manifest.test.ts +105 -0
  77. package/test/new-category.test.ts +979 -0
  78. package/test/notices.test.ts +328 -0
  79. package/test/plugin-integration-lines.test.ts +979 -0
  80. package/test/plugin-surface.test.ts +152 -0
  81. package/test/presence.test.ts +459 -0
  82. package/test/rail-surfaces.test.ts +457 -0
  83. package/test/rail-width.test.ts +423 -0
  84. package/test/regression.test.ts +483 -0
  85. package/test/repaint-api.test.ts +200 -0
  86. package/test/reserved-categories.test.ts +361 -0
  87. package/test/row-labels.test.ts +284 -0
  88. package/test/row-names.test.ts +473 -0
  89. package/test/row-origin.test.ts +395 -0
  90. package/test/section-interaction.test.ts +364 -0
  91. package/test/section-panel.test.ts +403 -0
  92. package/test/sections-rows.test.ts +291 -0
  93. package/test/sidebar-backend.test.ts +471 -0
  94. package/test/sidebar-e2e.test.ts +331 -0
  95. package/test/sidebar-hover.test.ts +276 -0
  96. package/test/sidebar-independent.test.ts +349 -0
  97. package/test/sidebar-render.test.ts +281 -0
  98. package/test/sidebar-sections.test.ts +245 -0
  99. package/test/status-card-styles.test.ts +201 -0
  100. package/test/status-section-frame.test.ts +181 -0
  101. package/test/status-sections.test.ts +243 -0
  102. package/test/status.test.ts +209 -0
  103. package/test/store.test.ts +192 -0
  104. package/test/surface-repaint-cost.test.ts +520 -0
  105. package/test/tool-design-chain.test.ts +483 -0
  106. package/test/tool-design-cost.test.ts +473 -0
  107. package/test/tool-design-rows.test.ts +359 -0
  108. package/test/tool-designs.test.ts +745 -0
  109. package/test/transform-pipeline.test.ts +465 -0
  110. package/test/transforms-bus.test.ts +233 -0
  111. package/test/verifier-width-regressions.test.ts +164 -0
  112. package/tsconfig.json +18 -0
package/src/status.ts ADDED
@@ -0,0 +1,1161 @@
1
+ /**
2
+ * `status` diagnostics (S6). One command answers "why did no rows appear": providers, backend,
3
+ * last capture, last failures, store problems and conflicting settings.
4
+ *
5
+ * `collectStatus` gathers live process state (bus, capture/hook/store diagnostics) and
6
+ * `formatStatus` is a pure function over that snapshot, so the report is testable without a host
7
+ * and the command prints exactly what the snapshot says. Nothing here mutates bridge state, and
8
+ * nothing here renames or drops a row: a duplicate `category` + `setting` pair is reported, not
9
+ * fixed (docs/contract.md §6).
10
+ */
11
+
12
+ import { snapshotCardStyles, snapshotProviders, snapshotSections, snapshotTransforms } from "./bus.ts";
13
+ import {
14
+ CARD_STYLE_ROWS_PROVIDER_ID,
15
+ cardStyleRowMode,
16
+ type CardStyleRowMode,
17
+ } from "./card-style-rows.ts";
18
+ import {
19
+ getCardStyleLastOutcome,
20
+ getCardStyleTransformFailures,
21
+ type CardStyleFrameOutcome,
22
+ type CardStyleTransformFailure,
23
+ } from "./card-style-transform.ts";
24
+ import { getCardStyleWiringDiagnostics, type CardStyleWiringDiagnostics } from "./card-style-wiring.ts";
25
+ import { resolveCardStyleSelection } from "./card-styles.ts";
26
+ import { getCaptureDiagnostics, type CaptureOutcome } from "./capture.ts";
27
+ import { getHookDiagnostics } from "./hook.ts";
28
+ import { snapshotNotices, type NoticeLevel } from "./notices.ts";
29
+ import {
30
+ PAINT_SURFACES,
31
+ getRepaintDiagnostics,
32
+ getSurfaceReach,
33
+ type PaintSurface,
34
+ type RepaintTrigger,
35
+ } from "./repaint.ts";
36
+ import { getTransformFrameOutcomes, type TransformFrameCounts } from "./transform-pipeline.ts";
37
+ import { getPluginLineReport, type PluginLineReport } from "./plugin-lines.ts";
38
+ import { getGentlePiPresence } from "./presence.ts";
39
+ import { getToolDesignAdoptionDiagnostics } from "./tool-design-adoption.ts";
40
+ import {
41
+ TOOL_DESIGN_NATIVE,
42
+ getToolDesignConflicts,
43
+ getToolDesignFailures,
44
+ resolveToolDesignSelection,
45
+ snapshotToolDesigns,
46
+ toolNamesWithDesigns,
47
+ type ToolDesignConflict,
48
+ type ToolDesignFailure,
49
+ } from "./tool-designs.ts";
50
+ import { TOOL_DESIGN_ROWS_PROVIDER_ID } from "./tool-design-rows.ts";
51
+ import {
52
+ getToolDesignWiringDiagnostics,
53
+ type ToolDesignResolverOutcome,
54
+ } from "./tool-design-wiring.ts";
55
+ import { getLastRowBuild, type RowBuildRecord } from "./rows.ts";
56
+ import {
57
+ getSidebarDiagnostics,
58
+ type SidebarDiagnostics,
59
+ type SidebarFailure,
60
+ } from "./sidebar.ts";
61
+ import { getSectionFailures, getSectionFrameWidth, type SectionRenderFailure } from "./sidebar-render.ts";
62
+ import { getPanelReport } from "./section-panel.ts";
63
+ import { getSectionHoverReport } from "./section-pointer.ts";
64
+ import { SECTION_ROWS_PROVIDER_ID } from "./sections-rows.ts";
65
+ import { sectionRowLabels } from "./row-labels.ts";
66
+ import { getRowNameRejections, type RowNameRejection } from "./row-names.ts";
67
+ import { getStoreDiagnostics, type StoreProblem } from "./store.ts";
68
+ import type { RowContext, RowProvider } from "./types.ts";
69
+ import {
70
+ getSectionCollapsed,
71
+ getSectionVisibility,
72
+ isSectionCollapsed,
73
+ isSectionVisible,
74
+ } from "./visibility.ts";
75
+
76
+ export type StatusBackend = "hook" | "capture" | "none";
77
+
78
+ export interface StatusProviderEntry {
79
+ id: string;
80
+ category: string;
81
+ }
82
+
83
+ /** Two providers contribute the same `category` + `choice.setting`. */
84
+ export interface StatusDuplicate {
85
+ category: string;
86
+ setting: string;
87
+ providerIds: string[];
88
+ }
89
+
90
+ export interface StatusFailure {
91
+ providerId: string;
92
+ message: string;
93
+ rowsDropped: boolean;
94
+ }
95
+
96
+ /** One registered sidebar section, as `/bridge-status` lists it. */
97
+ export interface StatusSectionEntry {
98
+ id: string;
99
+ title: string;
100
+ /** The persisted (or default) visibility right now. */
101
+ visible: boolean;
102
+ /** Present only while the card is folded (N13); absent keeps every historical line unchanged. */
103
+ collapsed?: true;
104
+ /** The render position's source: an explicit integer, or registration order when absent. */
105
+ order: number | "registration";
106
+ /** The label the section's `Sections` row reads (N2). The id stays in `id`, never in a row. */
107
+ rowLabel: string;
108
+ /** Present when two sections wanted the same label: the label this one had to move away from. */
109
+ rowLabelCollision?: string;
110
+ }
111
+
112
+ /**
113
+ * How the section frame is drawn and how the pointer reaches it (N11, N15): the answer to "is this
114
+ * the host's own header, or a port of it, and what could the bridge not reach".
115
+ */
116
+ export interface StatusSectionFrame {
117
+ /** `host` when the host's own builders were found on an object the bridge is handed. */
118
+ source: "host" | "fallback";
119
+ /** Where they were looked for, in the order the objects were offered. */
120
+ lookedAt: string[];
121
+ /** What was missing, as a person reads it; empty when the host's builders were found. */
122
+ missing: string[];
123
+ /** Whether Pi has handed the widget factory a theme yet; without one, rows are uncoloured. */
124
+ theme: "captured" | "missing";
125
+ /** The pointer path: the host's own dispatch, and how the hover claim is carried. */
126
+ hover: "host-state" | "unavailable" | "not used";
127
+ hoverReason?: string;
128
+ /**
129
+ * N20: the width the last render was handed and the widest row the bridge produced at it, both in
130
+ * the host's own columns. Absent until a frame contributes rows, so a session whose rail never
131
+ * painted keeps its report unchanged.
132
+ */
133
+ width?: { given: number; widest: number };
134
+ }
135
+
136
+ /** One rejected row name, as `/bridge-status` lists it: the string verbatim and the rule it broke. */
137
+ export type StatusRowNameRejection = RowNameRejection;
138
+
139
+ /** One buffered notice, as `/bridge-status` lists it: still pending, or already delivered. */
140
+ export interface StatusNoticeEntry {
141
+ level: NoticeLevel;
142
+ message: string;
143
+ delivered: boolean;
144
+ }
145
+
146
+ /** Where the sidebar interception stands, so a missing section has an answer. */
147
+ export type StatusSidebarState = "intercepted" | "no-sidebar-state" | "unarmed";
148
+
149
+ export interface StatusSidebarEntry {
150
+ state: StatusSidebarState;
151
+ /** Only for `no-sidebar-state`: why nothing could be intercepted. */
152
+ reason?: string;
153
+ /** Only when intercepted: whether the part we append to is in the host's map already. */
154
+ rail?: "wrapped" | "pending";
155
+ }
156
+
157
+ /** One registered design of one tool, as `/bridge-status` lists it. */
158
+ export interface StatusToolDesignEntry {
159
+ id: string;
160
+ label: string;
161
+ description?: string;
162
+ }
163
+
164
+ /** One tool with designs, its values, and the selection in force. */
165
+ export interface StatusToolDesignTool {
166
+ tool: string;
167
+ designs: StatusToolDesignEntry[];
168
+ /** The stored value: a design id, `native`, or `<id> (missing: not registered)`. */
169
+ selection: string;
170
+ /**
171
+ * Whether a card of this tool was built through the bridge's wrapper. With no selection the
172
+ * wrapper draws the host's own rows, so `mounted` is the answer to "can a design selected now
173
+ * still repaint this card?" (S2): an unwrapped card can never change again.
174
+ */
175
+ wrapper: "mounted" | "not mounted";
176
+ /** Only when mounted: how many card components were built through the wrapper this process. */
177
+ cards?: number;
178
+ /**
179
+ * How many card components were ADOPTED after construction this process (S10): the path that
180
+ * reaches a card when a resolver ahead of the bridge answered the tool without calling `next()`.
181
+ * Absent when no card was adopted, so a resolver-only session keeps its historical line.
182
+ */
183
+ adopted?: number;
184
+ }
185
+
186
+ /** The tool-design surface, reported only when the process has something to say (see below). */
187
+ export interface StatusToolDesigns {
188
+ tools: StatusToolDesignTool[];
189
+ /** How many `pi` objects the ONE resolver was registered on; absent when never attempted. */
190
+ resolver?: { registered: number; lastOutcome?: ToolDesignResolverOutcome; reason?: string };
191
+ /** Registrations that replaced another one or were refused, and why. */
192
+ conflicts: ToolDesignConflict[];
193
+ /** Designs that failed while a card was drawn (one entry per tool, id and message). */
194
+ failures: ToolDesignFailure[];
195
+ }
196
+
197
+ /** One registered card style, as `/bridge-status` lists it: in the order its values appear. */
198
+ export interface StatusCardStyleEntry {
199
+ id: string;
200
+ label: string;
201
+ /** The value's position source: an explicit integer, or registration order when absent. */
202
+ order: number | "registration";
203
+ }
204
+
205
+ /** The persisted selection, resolved against the live registry. `missing` is a disposed style. */
206
+ export type StatusCardStyleSelection =
207
+ | { kind: "native" }
208
+ | { kind: "style"; id: string; label: string }
209
+ | { kind: "missing"; id: string };
210
+
211
+ /** One surface the card style paints, with what it last did there (R4). */
212
+ export interface StatusSurfaceEntry {
213
+ surface: PaintSurface;
214
+ /** Whether the transform was attached to this surface. */
215
+ reached: boolean;
216
+ /** Only when it was not: the attach outcome (`no-layout-root`, `no-sidebar`, `no-rail`, ...). */
217
+ reason?: string;
218
+ /** The last frame this surface painted through the transform; `none` before it ran once. */
219
+ frame: CardStyleFrameOutcome | { kind: "none" };
220
+ }
221
+
222
+ /** The card-style surface, reported only when there is something to say (see `collectStatus`). */
223
+ export interface StatusCardStyles {
224
+ /** `extended`: the host's own `Card style` line was found and grown. `separate`: the fallback. */
225
+ mode: CardStyleRowMode;
226
+ styles: StatusCardStyleEntry[];
227
+ selection: StatusCardStyleSelection;
228
+ /** The most recent CONVERSATION frame's outcome; `none` before the transform ever ran. */
229
+ frame: CardStyleFrameOutcome | { kind: "none" };
230
+ /**
231
+ * Per-surface reach and last frame (R4): the conversation and the rail are separate surfaces that
232
+ * share one transform, so "the style is selected but the sidebar looks untouched" is answerable.
233
+ */
234
+ surfaces: StatusSurfaceEntry[];
235
+ wiring: CardStyleWiringDiagnostics;
236
+ failures: CardStyleTransformFailure[];
237
+ }
238
+
239
+ /** One registered transform, as `/bridge-status` lists it: in pipeline order. */
240
+ export interface StatusTransformEntry {
241
+ id: string;
242
+ /** The position's source: an explicit integer, or registration order when absent. */
243
+ order: number | "registration";
244
+ /** What the LAST frame did with it; `not run` when no frame has reached it yet. */
245
+ outcome: "applied" | "skipped" | "failed" | "not run";
246
+ /** Only when `outcome` is `failed`: the transform's own message, verbatim. */
247
+ message?: string;
248
+ /**
249
+ * The last frame's counts (F1, F2): the lines it received and what its own grammar reported —
250
+ * candidates examined, cards recognised, cards rewritten, shapes matched by name. Absent only for
251
+ * `not run`, where no frame has asked the transform anything.
252
+ */
253
+ counts?: TransformFrameCounts;
254
+ }
255
+
256
+ export interface StatusSnapshot {
257
+ providers: StatusProviderEntry[];
258
+ backend: StatusBackend;
259
+ lastCapture?: CaptureOutcome;
260
+ failures: StatusFailure[];
261
+ storeProblems: StoreProblem[];
262
+ /** Absent until a menu build has happened: duplicates cannot be computed without rows. */
263
+ duplicates?: StatusDuplicate[];
264
+ /** Absent when no section is registered, so a row-only run keeps its historical output. */
265
+ sections?: StatusSectionEntry[];
266
+ /**
267
+ * How the section frame is drawn (N11) and what it could not reach (N15). Absent when no section
268
+ * is registered, so a row-only session keeps its historical output exactly.
269
+ */
270
+ sectionFrame?: StatusSectionFrame;
271
+ /** Absent when the most recent sidebar frame had no section failure. */
272
+ sectionFailures?: SectionRenderFailure[];
273
+ /**
274
+ * Failures the RAIL BACKEND recorded in the most recent frame (a throwing host `render`, a
275
+ * throwing contributor, a failed card-group call). Absent when there were none.
276
+ */
277
+ sidebarFailures?: SidebarFailure[];
278
+ /** Absent when the sidebar backend was never installed (reported as "not armed"). */
279
+ sidebar?: StatusSidebarEntry;
280
+ /**
281
+ * The last repaint a bridge-owned write requested (R3/R4): the surfaces, the cause and whether the
282
+ * host was actually asked for a frame. Absent until such a write happens, so a session that never
283
+ * toggled anything keeps its historical output byte for byte.
284
+ */
285
+ lastRepaint?: RepaintTrigger;
286
+ /**
287
+ * Every buffered bridge notice, delivered or still pending. Absent when there is none, so the
288
+ * report for a clean session keeps its historical output exactly.
289
+ */
290
+ notices?: StatusNoticeEntry[];
291
+ /** Messages the bounded buffer evicted before they could be shown. Absent when none were. */
292
+ noticesDropped?: number;
293
+ /**
294
+ * The card-style surface. Absent when nothing card-related exists — no style registered, the
295
+ * selection native, no transform attempt and no frame — so a row-only session keeps its output.
296
+ */
297
+ cardStyles?: StatusCardStyles;
298
+ /**
299
+ * The tool-design surface. Absent when no design is registered, so a session that never uses the
300
+ * bus keeps its historical output byte for byte.
301
+ */
302
+ toolDesigns?: StatusToolDesigns;
303
+ /**
304
+ * Plugin row names the bridge rejected for breaking the row-name shape (N8), or a row category it refused as reserved (S15): the offending
305
+ * string, verbatim, and the rule it broke. Absent when nothing was rejected, so a clean session
306
+ * keeps its historical output exactly.
307
+ */
308
+ rowNames?: StatusRowNameRejection[];
309
+ /**
310
+ * Every registered transcript transform in pipeline order, with the last frame's outcome. Absent
311
+ * when none is registered, so a session that never used the pipeline keeps its historical output
312
+ * byte for byte.
313
+ */
314
+ transforms?: StatusTransformEntry[];
315
+ /**
316
+ * The INTEGRATIONS rows this bridge paints on the plugins' behalf (I1–I7): one entry per plugin,
317
+ * the name and whether it was derived or explicit, the registrations accepted and rejected, and
318
+ * whether the host's `setStatus` was available at all. Absent when no plugin has registered, so a
319
+ * session without one keeps its historical output byte for byte.
320
+ */
321
+ pluginLines?: PluginLineReport;
322
+ /**
323
+ * The REQUIRED host package (S9/T12): whether `pi.getCommands()` advertised `gentle:customize` on
324
+ * the last `session_start`. Absent until a check has run, so a report that predates one keeps its
325
+ * historical output byte for byte.
326
+ */
327
+ gentlePi?: StatusGentlePi;
328
+ }
329
+
330
+ /** One line of the report: gentle-pi is present, or it is missing and the bridge is disabled. */
331
+ export interface StatusGentlePi {
332
+ present: boolean;
333
+ /** Present only when missing: why the host does not count as gentle-pi. */
334
+ reason?: string;
335
+ }
336
+
337
+ /**
338
+ * One snapshot of everything `status` reports. The backend is derived from real state rather than
339
+ * remembered: a hook registry in use wins, otherwise a wrapped UI target means the capture
340
+ * backend.
341
+ */
342
+ export function collectStatus(): StatusSnapshot {
343
+ const providers = snapshotProviders();
344
+ const hook = getHookDiagnostics();
345
+ const capture = getCaptureDiagnostics();
346
+ const backend: StatusBackend =
347
+ hook.installed ? "hook" : capture.armedTargets > 0 ? "capture" : "none";
348
+
349
+ // Diagnostics never run providers: duplicate detection comes from the rows the LAST menu build
350
+ // actually received, and is unknown until such a build exists.
351
+ const snapshot: StatusSnapshot = {
352
+ // The bridge's own `Sections` and card-style fallback providers are plumbing, not plugin
353
+ // providers: their effect is the tables below, and listing one would make a session report a
354
+ // provider its user never registered (B3).
355
+ providers: providers
356
+ .filter(
357
+ (provider) =>
358
+ provider.id !== SECTION_ROWS_PROVIDER_ID &&
359
+ provider.id !== CARD_STYLE_ROWS_PROVIDER_ID &&
360
+ provider.id !== TOOL_DESIGN_ROWS_PROVIDER_ID,
361
+ )
362
+ .map((provider) => ({ id: provider.id, category: provider.category })),
363
+ backend,
364
+ // Report the failures and the capture outcome of the backend that is actually in use.
365
+ failures:
366
+ backend === "hook"
367
+ ? hook.lastFailures.map(toStatusFailure)
368
+ : capture.lastFailures.map(toStatusFailure),
369
+ storeProblems: getStoreDiagnostics(),
370
+ };
371
+ const duplicates = findDuplicatesInBuilds(getLastRowBuild());
372
+ if (duplicates !== undefined) snapshot.duplicates = duplicates;
373
+ // The row-name rejections (N8). Nothing here runs a provider: the records are the ones the last
374
+ // registration or build already made, so the report matches what the menu shows.
375
+ const rowNames = getRowNameRejections();
376
+ if (rowNames.length > 0) snapshot.rowNames = rowNames;
377
+ const lastCapture = backend === "hook" ? hook.lastCapture : capture.lastOutcome;
378
+ if (lastCapture !== undefined) snapshot.lastCapture = lastCapture;
379
+
380
+ // S9/T12 — the runtime answer about the REQUIRED host package. Nothing here checks anything: the
381
+ // record is what the last `session_start` already observed. No check yet means no field and no
382
+ // line, which is what keeps the pre-feature output byte for byte.
383
+ const presence = getGentlePiPresence();
384
+ if (presence !== undefined) {
385
+ snapshot.gentlePi = presence.present
386
+ ? { present: true }
387
+ : { present: false, reason: presence.reason ?? "no reason recorded" };
388
+ }
389
+
390
+ // The sidebar surface. Nothing here runs a section: the table reports registrations and the
391
+ // persisted visibility, and the failures are the ones the last frame already recorded — `lines()`
392
+ // and `meta()` are never called by a diagnostics report.
393
+ //
394
+ // Ids belong in THIS report (N4): it is read by the plugin author diagnosing a registration, not by
395
+ // the user picking a toggle. The rows the user sees show labels only (`./row-labels.ts`), so these
396
+ // ids exist precisely to be found here. The label column is the same assignment the rows use,
397
+ // including collision disambiguation, so the report explains what the menu shows instead of
398
+ // recomputing it differently.
399
+ const sections = snapshotSections();
400
+ if (sections.length > 0) {
401
+ const visibility = getSectionVisibility();
402
+ const collapsedMap = getSectionCollapsed();
403
+ snapshot.sections = sectionRowLabels(sections).map(({ section, label, collision }) => ({
404
+ id: section.id,
405
+ title: section.title,
406
+ visible: isSectionVisible(visibility, section),
407
+ ...(isSectionCollapsed(collapsedMap, section) ? { collapsed: true as const } : {}),
408
+ order:
409
+ typeof section.order === "number" && Number.isFinite(section.order)
410
+ ? section.order
411
+ : "registration",
412
+ rowLabel: label,
413
+ ...(collision === undefined ? {} : { rowLabelCollision: collision }),
414
+ }));
415
+ snapshot.sectionFrame = describeSectionFrame();
416
+ }
417
+ const sectionFailures = getSectionFailures();
418
+ if (sectionFailures.length > 0) snapshot.sectionFailures = sectionFailures;
419
+ const sidebarDiagnostics = getSidebarDiagnostics();
420
+ if (sidebarDiagnostics.lastFailures.length > 0) {
421
+ // The rail backend's own failures are a separate class: a throwing host render, a throwing
422
+ // contributor. Without them, a frame that lost every section would report nothing (B1).
423
+ snapshot.sidebarFailures = sidebarDiagnostics.lastFailures;
424
+ }
425
+ // The notices the bridge had to report out of band (an incompatible API object). They are listed
426
+ // here so removing them from the terminal never made them invisible: after the one-time notify,
427
+ // this is where they stay.
428
+ const notices = snapshotNotices();
429
+ if (notices.entries.length > 0) {
430
+ snapshot.notices = notices.entries.map((entry) => ({
431
+ level: entry.level,
432
+ message: entry.message,
433
+ delivered: entry.emitted,
434
+ }));
435
+ if (notices.dropped > 0) snapshot.noticesDropped = notices.dropped;
436
+ }
437
+ const cardStyles = describeCardStyles();
438
+ if (cardStyles !== undefined) snapshot.cardStyles = cardStyles;
439
+ const toolDesigns = describeToolDesigns();
440
+ if (toolDesigns !== undefined) snapshot.toolDesigns = toolDesigns;
441
+ const lastRepaint = describeLastRepaint();
442
+ if (lastRepaint !== undefined) snapshot.lastRepaint = lastRepaint;
443
+ // The transform pipeline, in the order the wrapper runs it. Nothing here calls a transform: the
444
+ // outcomes are the ones the last frame already recorded.
445
+ const transforms = describeTransforms();
446
+ if (transforms !== undefined) snapshot.transforms = transforms;
447
+ // The per-plugin INTEGRATIONS rows. Nothing here calls the host: the records are the ones each
448
+ // registration (and `session_start`'s paint attempt) already made.
449
+ const pluginLines = describePluginLines();
450
+ if (pluginLines !== undefined) snapshot.pluginLines = pluginLines;
451
+ const sidebarEntry = describeSidebar(sidebarDiagnostics);
452
+ // The sidebar line is worth a line only when it explains something: a registered section that may
453
+ // not be appearing, or a rail that IS intercepted. A row-only session with no rail keeps the
454
+ // pre-feature output exactly (B3).
455
+ if (
456
+ sidebarEntry !== undefined &&
457
+ (snapshot.sections !== undefined || sidebarEntry.state === "intercepted")
458
+ ) {
459
+ snapshot.sidebar = sidebarEntry;
460
+ }
461
+
462
+ return snapshot;
463
+ }
464
+
465
+ /**
466
+ * How the section frame is drawn (N11) and what the bridge could not reach (N15).
467
+ *
468
+ * This is a REPORT of the run, not a claim in a comment: the panel source comes from looking for the
469
+ * host's builders on every object the bridge is handed, the theme from whether Pi has run the
470
+ * `setWidget` factory, and the hover mechanism from the last attempt to claim the shared pointer.
471
+ */
472
+ function describeSectionFrame(): StatusSectionFrame {
473
+ const panel = getPanelReport();
474
+ const hover = getSectionHoverReport();
475
+ const width = getSectionFrameWidth();
476
+ return {
477
+ source: panel.source,
478
+ lookedAt: panel.lookedAt,
479
+ missing: panel.missing,
480
+ theme: panel.theme === "captured" ? "captured" : "missing",
481
+ hover: hover.mechanism,
482
+ ...(hover.reason === undefined ? {} : { hoverReason: hover.reason }),
483
+ ...(width === undefined ? {} : { width }),
484
+ };
485
+ }
486
+
487
+ /**
488
+ * The card-style block, or `undefined` when the process has nothing card-related to say.
489
+ *
490
+ * The guard is what keeps a row-only session's report byte-identical: no style, a `native`
491
+ * selection, no wiring attempt and no frame means the feature was never used here.
492
+ */
493
+ function describeCardStyles(): StatusCardStyles | undefined {
494
+ const styles = snapshotCardStyles();
495
+ const selection = resolveCardStyleSelection();
496
+ const wiring = getCardStyleWiringDiagnostics();
497
+ const frame = getCardStyleLastOutcome();
498
+ const failures = getCardStyleTransformFailures();
499
+ if (styles.length === 0 && selection.kind === "native" && wiring.lastOutcome === undefined && frame === undefined) {
500
+ return undefined;
501
+ }
502
+ return {
503
+ mode: cardStyleRowMode(),
504
+ styles: styles.map((style) => ({
505
+ id: style.id,
506
+ label: style.label,
507
+ order:
508
+ typeof style.order === "number" && Number.isFinite(style.order)
509
+ ? style.order
510
+ : "registration",
511
+ })),
512
+ selection:
513
+ selection.kind === "native"
514
+ ? { kind: "native" }
515
+ : selection.kind === "missing"
516
+ ? { kind: "missing", id: selection.id }
517
+ : { kind: "style", id: selection.style.id, label: selection.style.label },
518
+ frame: frame === undefined ? { kind: "none" } : frame,
519
+ surfaces: PAINT_SURFACES.map((surface) => {
520
+ const reach = getSurfaceReach(surface);
521
+ const outcome = getCardStyleLastOutcome(surface);
522
+ return {
523
+ surface,
524
+ reached: reach?.reached === true,
525
+ ...(reach?.reason === undefined ? {} : { reason: reach.reason }),
526
+ frame: outcome === undefined ? { kind: "none" as const } : outcome,
527
+ };
528
+ }),
529
+ wiring,
530
+ failures,
531
+ };
532
+ }
533
+
534
+ /**
535
+ * The tool-design block, or `undefined` when this process registered no design.
536
+ *
537
+ * The guard is the same discipline as every other block: a session that never registered a design
538
+ * keeps its historical report exactly, including a host with no `registerToolRenderer` hook (a bare
539
+ * harness has nothing to say about designs). Once a design exists, the ONE resolver's outcome is the
540
+ * answer to "why is my design not drawing?", so it is reported right beside the registrations.
541
+ *
542
+ * Nothing here calls an `apply` or a `rows()`: the entries are the live registrations, the
543
+ * persisted selection and the records the last frames already made.
544
+ */
545
+ function describeToolDesigns(): StatusToolDesigns | undefined {
546
+ const tools = toolNamesWithDesigns();
547
+ const wiring = getToolDesignWiringDiagnostics();
548
+ const adoption = getToolDesignAdoptionDiagnostics();
549
+ const conflicts = getToolDesignConflicts();
550
+ const failures = getToolDesignFailures();
551
+ if (tools.length === 0) return undefined;
552
+ return {
553
+ tools: tools.map((tool) => {
554
+ const selection = resolveToolDesignSelection(tool);
555
+ const wrapped = wiring.wrappedCards.find((entry) => entry.tool === tool);
556
+ const adopted = adoption.adoptedCards.find((entry) => entry.tool === tool);
557
+ return {
558
+ tool,
559
+ designs: snapshotToolDesigns(tool).map((design) => ({
560
+ id: design.id,
561
+ label: design.label,
562
+ ...(design.description === undefined ? {} : { description: design.description }),
563
+ })),
564
+ selection:
565
+ selection.kind === "native"
566
+ ? TOOL_DESIGN_NATIVE
567
+ : selection.kind === "missing"
568
+ ? `${selection.id} (missing: not registered)`
569
+ : selection.design.id,
570
+ // The wrapper's identity is per CARD: a card built before the tool had a design (or before
571
+ // the bridge was armed) has none, and no later selection can repaint it.
572
+ ...(wrapped === undefined
573
+ ? { wrapper: "not mounted" as const }
574
+ : { wrapper: "mounted" as const, cards: wrapped.cards }),
575
+ ...(adopted === undefined ? {} : { adopted: adopted.cards }),
576
+ };
577
+ }),
578
+ ...(wiring.lastOutcome === undefined
579
+ ? {}
580
+ : {
581
+ resolver: {
582
+ registered: wiring.registered,
583
+ lastOutcome: wiring.lastOutcome,
584
+ ...(wiring.lastReason === undefined ? {} : { reason: wiring.lastReason }),
585
+ },
586
+ }),
587
+ conflicts,
588
+ failures,
589
+ };
590
+ }
591
+
592
+ /**
593
+ * The transform block, or `undefined` when this process registered no transform at all.
594
+ *
595
+ * The guard is what keeps a session that never used the pipeline byte-identical: the block appears
596
+ * only when a transform exists, and the outcomes are the ones the last frame recorded (a transform
597
+ * registered after that frame reads `not run` rather than borrowing another one's answer).
598
+ */
599
+ function describeTransforms(): StatusTransformEntry[] | undefined {
600
+ const registered = snapshotTransforms();
601
+ if (registered.length === 0) return undefined;
602
+ const frame = new Map(getTransformFrameOutcomes().map((outcome) => [outcome.id, outcome]));
603
+ return registered.map((transform) => {
604
+ const outcome = frame.get(transform.id);
605
+ return {
606
+ id: transform.id,
607
+ order:
608
+ typeof transform.order === "number" && Number.isFinite(transform.order)
609
+ ? transform.order
610
+ : "registration",
611
+ outcome: outcome?.status ?? "not run",
612
+ ...(outcome?.message === undefined ? {} : { message: outcome.message }),
613
+ ...(outcome?.counts === undefined ? {} : { counts: outcome.counts }),
614
+ };
615
+ });
616
+ }
617
+
618
+ /**
619
+ * The INTEGRATIONS block, or `undefined` when no plugin has registered with the bridge.
620
+ *
621
+ * The guard is the same discipline as every other block: a session with no plugin keeps its
622
+ * historical report exactly. The line's TEXT is deliberately not recomputed here — it is what the
623
+ * host was handed — but `line`/`reason` say whether a row is currently set, so a missing row is an
624
+ * answer (I6).
625
+ */
626
+ function describePluginLines(): PluginLineReport | undefined {
627
+ const report = getPluginLineReport();
628
+ return report.plugins.length === 0 ? undefined : report;
629
+ }
630
+
631
+ /** The last repaint a bridge-owned write requested (R3/R4), or `undefined` before one happened.
632
+ *
633
+ * The guard is the same discipline as every other block: a session that never toggled anything keeps
634
+ * its historical report exactly. A trigger whose outcome is `unavailable` is the interesting case —
635
+ * the write landed and the screen did not move — so its reason is reported verbatim.
636
+ */
637
+ function describeLastRepaint(): RepaintTrigger | undefined {
638
+ return getRepaintDiagnostics().lastTrigger;
639
+ }
640
+
641
+ function formatCardSelection(selection: StatusCardStyleSelection): string {
642
+ switch (selection.kind) {
643
+ case "native":
644
+ return "native";
645
+ case "style":
646
+ return `${selection.id} "${selection.label}"`;
647
+ case "missing":
648
+ return `${selection.id} (missing: not registered)`;
649
+ }
650
+ }
651
+
652
+ function formatCardFrame(frame: StatusCardStyles["frame"]): string {
653
+ switch (frame.kind) {
654
+ case "none":
655
+ return "none";
656
+ case "transformed":
657
+ return `transformed ${frame.cards} ${frame.cards === 1 ? "card" : "cards"}`;
658
+ case "pass-through":
659
+ return `pass-through (${
660
+ frame.reason === "missing" ? "missing: a disposed style" : frame.reason === "no-card" ? "no card" : "native"
661
+ })`;
662
+ case "failed":
663
+ return `failed (${frame.styleId}: ${frame.message})`;
664
+ }
665
+ }
666
+
667
+ function formatCardWiring(wiring: CardStyleWiringDiagnostics): string {
668
+ // Which COMPONENTS carry the transform. The rail is named only once it was wrapped — its failures
669
+ // have their own per-surface line below (`formatCardSurface`), so nothing is hidden by keeping this
670
+ // line about the conversation's state, which is what it has always answered.
671
+ const parts: string[] = [];
672
+ if ((wiring.railWrapped ?? 0) > 0) parts.push("rail wrapped");
673
+ if (wiring.wrapped > 0) parts.push("chat wrapped");
674
+ if (parts.length > 0) return parts.join(", ");
675
+ if (wiring.lastOutcome === undefined) return "not armed";
676
+ const reason = wiring.lastReason === undefined ? "" : `: ${wiring.lastReason}`;
677
+ return `not wrapped (${wiring.lastOutcome}${reason})`;
678
+ }
679
+
680
+ /** One surface's line: whether the style reached it, and what its last frame did there (R4). */
681
+ function formatCardSurface(entry: StatusSurfaceEntry): string {
682
+ const reached = entry.reached
683
+ ? `reached (${entry.surface === "conversation" ? "chat wrapped" : "rail wrapped"})`
684
+ : `not reached (${entry.reason ?? "not attempted"})`;
685
+ return `card style surface ${entry.surface}: ${reached}, last frame ${formatCardFrame(entry.frame)}`;
686
+ }
687
+
688
+ /**
689
+ * Map the backend's diagnostics onto the three states a user needs: intercepted, present-but-nothing
690
+ * to intercept, or previously installed and now off. Never-installed is `undefined` ("not armed").
691
+ */
692
+ function describeSidebar(diagnostics: SidebarDiagnostics): StatusSidebarEntry | undefined {
693
+ if (diagnostics.interceptedMaps > 0) {
694
+ return {
695
+ state: "intercepted",
696
+ rail: diagnostics.wrappedRails > 0 ? "wrapped" : "pending",
697
+ };
698
+ }
699
+ if (
700
+ diagnostics.lastOutcome === "no-sidebar-state" ||
701
+ diagnostics.lastOutcome === "resolver-threw"
702
+ ) {
703
+ return {
704
+ state: "no-sidebar-state",
705
+ ...(diagnostics.lastReason === undefined ? {} : { reason: diagnostics.lastReason }),
706
+ };
707
+ }
708
+ if (diagnostics.lastOutcome === "no-widget-surface") {
709
+ return {
710
+ state: "unarmed",
711
+ ...(diagnostics.lastReason === undefined ? {} : { reason: diagnostics.lastReason }),
712
+ };
713
+ }
714
+ if (diagnostics.lastOutcome !== undefined) return { state: "unarmed" };
715
+ return undefined;
716
+ }
717
+
718
+ /**
719
+ * Report every `category` + `choice.setting` pair contributed by more than one provider id.
720
+ *
721
+ * A single provider's own consecutive toggle rows share a setting by design, so they are not a
722
+ * duplicate: only a second provider id makes the pair conflict. Rows are read, never rewritten. A
723
+ * provider that throws is skipped — its failure is already its own diagnostics entry.
724
+ */
725
+ export function findDuplicateSettings(providers: RowProvider[], ctx: RowContext): StatusDuplicate[] {
726
+ const builds: RowBuildRecord[] = [];
727
+ for (const provider of providers) {
728
+ try {
729
+ builds.push({ providerId: provider.id, category: provider.category, rows: provider.rows(ctx) });
730
+ } catch {
731
+ continue;
732
+ }
733
+ }
734
+ return findDuplicatesInBuilds(builds) ?? [];
735
+ }
736
+
737
+ /**
738
+ * The same grouping over rows a build already produced, with no provider invocation. `undefined`
739
+ * means no build has happened yet, which is reported as unknown rather than as "no duplicates".
740
+ */
741
+ export function findDuplicatesInBuilds(
742
+ builds: RowBuildRecord[] | undefined,
743
+ ): StatusDuplicate[] | undefined {
744
+ if (builds === undefined) return undefined;
745
+
746
+ const groups = new Map<string, StatusDuplicate>();
747
+ const order: string[] = [];
748
+
749
+ for (const build of builds) {
750
+ for (const row of build.rows) {
751
+ const setting = row.choice?.setting;
752
+ if (setting === undefined) continue;
753
+ const category = row.category ?? build.category;
754
+ const key = `${category}\u0000${setting}`;
755
+ const existing = groups.get(key);
756
+ if (existing === undefined) {
757
+ groups.set(key, { category, setting, providerIds: [build.providerId] });
758
+ order.push(key);
759
+ continue;
760
+ }
761
+ if (!existing.providerIds.includes(build.providerId)) {
762
+ existing.providerIds.push(build.providerId);
763
+ }
764
+ }
765
+ }
766
+
767
+ const duplicates: StatusDuplicate[] = [];
768
+ for (const key of order) {
769
+ const group = groups.get(key);
770
+ if (group !== undefined && group.providerIds.length >= 2) duplicates.push(group);
771
+ }
772
+ return duplicates;
773
+ }
774
+
775
+ /** What `/bridge-status` says when the required host package is not there (S9, T12). */
776
+ const BRIDGE_DISABLED_LINE =
777
+ "bridge: disabled — gentle-pi is required; no rows, sections, card styles or tool designs are armed";
778
+
779
+ /** The report, as lines, exactly as the `status` command prints it. */
780
+ export function formatStatus(snapshot: StatusSnapshot): string[] {
781
+ const lines: string[] = ["gentle-shell-bridge status"];
782
+
783
+ // The gate answer comes first: a user whose bridge does nothing needs to know WHY before reading
784
+ // anything else. Absent only when no check has run, so the historical report is unchanged.
785
+ const presence = snapshot.gentlePi;
786
+ if (presence !== undefined) {
787
+ if (presence.present) {
788
+ lines.push("gentle-pi: present");
789
+ } else {
790
+ lines.push(`gentle-pi: missing — ${presence.reason ?? "no reason recorded"}`);
791
+ lines.push(BRIDGE_DISABLED_LINE);
792
+ // Disabled (S9): every per-surface block below would claim work that is not being done — no
793
+ // wrapper, no rows installed, no resolver, no footer line — so none is emitted. The buffered
794
+ // notices still explain the process, and the presence lines carry the reason.
795
+ lines.push(...formatNotices(snapshot));
796
+ return lines;
797
+ }
798
+ }
799
+
800
+ if (snapshot.providers.length === 0) {
801
+ lines.push("providers: none");
802
+ } else {
803
+ lines.push(`providers: ${snapshot.providers.length}`);
804
+ for (const provider of snapshot.providers) {
805
+ lines.push(` - ${provider.id} (${provider.category})`);
806
+ }
807
+ }
808
+
809
+ lines.push(`backend: ${snapshot.backend}`);
810
+ lines.push(formatCapture(snapshot.lastCapture));
811
+
812
+ if (snapshot.failures.length === 0) {
813
+ lines.push("last failures: none");
814
+ } else {
815
+ lines.push(`last failures: ${snapshot.failures.length}`);
816
+ for (const failure of snapshot.failures) {
817
+ const outcome = failure.rowsDropped ? "rows dropped" : "rows kept";
818
+ lines.push(` - ${failure.providerId}: ${failure.message} (${outcome})`);
819
+ }
820
+ }
821
+
822
+ if (snapshot.storeProblems.length === 0) {
823
+ lines.push("store problems: none");
824
+ } else {
825
+ lines.push(`store problems: ${snapshot.storeProblems.length}`);
826
+ for (const problem of snapshot.storeProblems) {
827
+ lines.push(
828
+ ` - ${problem.pluginId} (${problem.path}): ${problem.kind}: ${problem.message} ` +
829
+ "(reads fall back to defaults; the file is left as is)",
830
+ );
831
+ }
832
+ }
833
+
834
+ if (snapshot.duplicates === undefined) {
835
+ lines.push("duplicate settings: no build yet");
836
+ } else if (snapshot.duplicates.length === 0) {
837
+ lines.push("duplicate settings: none");
838
+ } else {
839
+ lines.push(`duplicate settings: ${snapshot.duplicates.length}`);
840
+ for (const duplicate of snapshot.duplicates) {
841
+ lines.push(
842
+ ` - ${duplicate.category} / "${duplicate.setting}": ${duplicate.providerIds.join(", ")}`,
843
+ );
844
+ }
845
+ }
846
+
847
+ if (snapshot.rowNames !== undefined) {
848
+ lines.push(`row rejections: ${snapshot.rowNames.length}`);
849
+ for (const rejection of snapshot.rowNames) {
850
+ // The offending string is printed EXACTLY as the author wrote it: the report is how they find
851
+ // it, and the bridge never rewrites a name it refused (N8).
852
+ lines.push(
853
+ ` - ${rejection.surface} ${JSON.stringify(rejection.id)} ${rejection.field} ` +
854
+ `${JSON.stringify(rejection.value)}: ${rejection.reason} (rejected, never rewritten)`,
855
+ );
856
+ }
857
+ }
858
+
859
+ // These blocks are emitted only when they have something to say. What is guaranteed: a session
860
+ // that registers no section and never intercepts a rail prints exactly the pre-feature output
861
+ // (proved through the real entry, not just this formatter). The sections table appears once a
862
+ // section is registered; the sidebar line appears when a section is registered — so an
863
+ // unreachable rail is an answer — or when a rail is actually intercepted.
864
+ if (snapshot.sections !== undefined) {
865
+ lines.push(`sections: ${snapshot.sections.length}`);
866
+ for (const section of snapshot.sections) {
867
+ const order =
868
+ section.order === "registration" ? "registration order" : `order ${section.order}`;
869
+ const visibility = section.visible ? "visible" : "hidden";
870
+ // The id and the title are diagnostics; `row` is what the menu actually reads, and the
871
+ // collision note says why two equal titles did not produce two equal lines (N2, N4).
872
+ const row =
873
+ section.rowLabelCollision === undefined
874
+ ? `, row "${section.rowLabel}"`
875
+ : `, row "${section.rowLabel}" (label collision with "${section.rowLabelCollision}")`;
876
+ lines.push(
877
+ ` - ${section.id} "${section.title}": ${visibility}${section.collapsed === true ? ", collapsed" : ""}, ${order}${row}`,
878
+ );
879
+ }
880
+ }
881
+
882
+ if (snapshot.sectionFrame !== undefined) {
883
+ lines.push(...formatSectionFrame(snapshot.sectionFrame));
884
+ }
885
+
886
+ if (snapshot.sectionFailures !== undefined) {
887
+ lines.push(`section failures: ${snapshot.sectionFailures.length}`);
888
+ for (const failure of snapshot.sectionFailures) {
889
+ lines.push(` - ${failure.sectionId} (${failure.phase}): ${failure.message}`);
890
+ }
891
+ }
892
+
893
+ if (snapshot.sidebarFailures !== undefined) {
894
+ lines.push(`sidebar failures: ${snapshot.sidebarFailures.length}`);
895
+ for (const failure of snapshot.sidebarFailures) {
896
+ lines.push(` - ${failure.key} (${failure.phase}): ${failure.message}`);
897
+ }
898
+ }
899
+
900
+ if (snapshot.sidebar === undefined) {
901
+ if (snapshot.sections !== undefined) lines.push("sidebar: not armed");
902
+ } else if (snapshot.sidebar.state === "intercepted") {
903
+ lines.push(`sidebar: intercepted (rail ${snapshot.sidebar.rail})`);
904
+ } else if (snapshot.sidebar.state === "no-sidebar-state") {
905
+ const reason = snapshot.sidebar.reason === undefined ? "" : ` (${snapshot.sidebar.reason})`;
906
+ lines.push(`sidebar: no-sidebar-state${reason}`);
907
+ } else {
908
+ const reason = snapshot.sidebar.reason === undefined ? "" : ` (${snapshot.sidebar.reason})`;
909
+ lines.push(`sidebar: not armed${reason}`);
910
+ }
911
+
912
+ if (snapshot.cardStyles !== undefined) {
913
+ const card = snapshot.cardStyles;
914
+ lines.push(`card styles: ${card.mode}, ${card.styles.length} registered`);
915
+ for (const entry of card.styles) {
916
+ const order = entry.order === "registration" ? "registration order" : `order ${entry.order}`;
917
+ lines.push(` - ${entry.id} "${entry.label}" (${order})`);
918
+ }
919
+ lines.push(`card style selection: ${formatCardSelection(card.selection)}`);
920
+ lines.push(`card style frame: ${formatCardFrame(card.frame)}`);
921
+ for (const surface of card.surfaces) lines.push(formatCardSurface(surface));
922
+ lines.push(`card style wiring: ${formatCardWiring(card.wiring)}`);
923
+ if (card.failures.length > 0) {
924
+ lines.push(`card style failures: ${card.failures.length}`);
925
+ for (const failure of card.failures) {
926
+ lines.push(` - ${failure.styleId}: ${failure.message}`);
927
+ }
928
+ }
929
+ // S7: a later post-processor — a component that rewrites the conversation's rows after this
930
+ // frame is drawn — can erase it. The bridge cannot prevent that, so it says so instead of
931
+ // pretending otherwise.
932
+ lines.push(
933
+ "card style note: a downstream post-processor can strip or override this frame; " +
934
+ "the bridge cannot prevent it.",
935
+ );
936
+ }
937
+
938
+ if (snapshot.toolDesigns !== undefined) {
939
+ const designs = snapshot.toolDesigns;
940
+ lines.push(`tool designs: ${designs.tools.length} tools with designs`);
941
+ for (const entry of designs.tools) {
942
+ // The tool's own line answers both questions a stuck user has: which design resolves NOW, and
943
+ // whether the cards already on screen can still be repainted at all (S2).
944
+ const wrapper =
945
+ entry.wrapper === "mounted"
946
+ ? `wrapper mounted on ${entry.cards} ${entry.cards === 1 ? "card" : "cards"}`
947
+ : "wrapper not mounted";
948
+ // S10/T16: which path reached this tool's cards — the resolver (the bridge was ahead in the
949
+ // chain) or adoption (a resolver ahead of it answered without calling next()). Both may be
950
+ // non-zero: old cards adopted after construction, new cards resolved through the wrapper.
951
+ const adopted =
952
+ entry.adopted === undefined
953
+ ? ""
954
+ : `, adopted ${entry.adopted} ${entry.adopted === 1 ? "card" : "cards"}`;
955
+ lines.push(` - ${entry.tool}: ${entry.selection}, ${wrapper}${adopted}`);
956
+ for (const design of entry.designs) {
957
+ const description = design.description === undefined ? "" : ` — ${design.description}`;
958
+ lines.push(` ${design.id} "${design.label}"${description}`);
959
+ }
960
+ }
961
+ if (designs.resolver !== undefined) {
962
+ const outcome = designs.resolver.lastOutcome ?? "registered";
963
+ const reason = designs.resolver.reason === undefined ? "" : `: ${designs.resolver.reason}`;
964
+ lines.push(
965
+ `tool design resolver: ${outcome} (${designs.resolver.registered} registered)${reason}`,
966
+ );
967
+ } else {
968
+ lines.push("tool design resolver: not attempted");
969
+ }
970
+ if (designs.conflicts.length > 0) {
971
+ lines.push(`tool design conflicts: ${designs.conflicts.length}`);
972
+ for (const conflict of designs.conflicts) {
973
+ lines.push(` - ${conflict.tool} / ${conflict.id} (${conflict.kind}): ${conflict.message}`);
974
+ }
975
+ }
976
+ if (designs.failures.length > 0) {
977
+ lines.push(`tool design failures: ${designs.failures.length}`);
978
+ for (const failure of designs.failures) {
979
+ lines.push(` - ${failure.tool} / ${failure.designId}: ${failure.message}`);
980
+ }
981
+ }
982
+ }
983
+
984
+ if (snapshot.lastRepaint !== undefined) {
985
+ const trigger = snapshot.lastRepaint;
986
+ const outcome =
987
+ trigger.outcome === "repainted" ? "repainted" : `unavailable: ${trigger.reason ?? "no reason recorded"}`;
988
+ lines.push(`last repaint: ${trigger.surfaces.join(", ")} for ${trigger.cause} (${outcome})`);
989
+ }
990
+
991
+ if (snapshot.transforms !== undefined) {
992
+ lines.push(`transforms: ${snapshot.transforms.length} registered`);
993
+ for (const entry of snapshot.transforms) {
994
+ const order = entry.order === "registration" ? "registration order" : `order ${entry.order}`;
995
+ const outcome =
996
+ entry.outcome === "failed"
997
+ ? `failed (${entry.message ?? "no message"})`
998
+ : entry.outcome;
999
+ // F2: the counts the SAME frame recorded, on the same line as the outcome: "it ran" and "it
1000
+ // recognised nothing" are one answer, and the line has to read as one.
1001
+ const counts = entry.counts === undefined ? "" : `, ${formatTransformCounts(entry.counts)}`;
1002
+ lines.push(` - ${entry.id} (${order}): ${outcome}${counts}`);
1003
+ }
1004
+ }
1005
+
1006
+ if (snapshot.pluginLines !== undefined) {
1007
+ lines.push(...formatPluginLines(snapshot.pluginLines));
1008
+ }
1009
+
1010
+ lines.push(...formatNotices(snapshot));
1011
+
1012
+ return lines;
1013
+ }
1014
+
1015
+ /**
1016
+ * The buffered bridge notices: every message the bridge had to report out of band, delivered or
1017
+ * still pending. Empty when there is none, so a clean session's report keeps its historical shape.
1018
+ */
1019
+ function formatNotices(snapshot: StatusSnapshot): string[] {
1020
+ const lines: string[] = [];
1021
+ if (snapshot.notices !== undefined) {
1022
+ lines.push(`notices: ${snapshot.notices.length}`);
1023
+ for (const notice of snapshot.notices) {
1024
+ const state = notice.delivered ? "delivered" : "pending";
1025
+ lines.push(` - ${notice.level} (${state}): ${notice.message}`);
1026
+ }
1027
+ }
1028
+ if (snapshot.noticesDropped !== undefined) {
1029
+ lines.push(`notices dropped: ${snapshot.noticesDropped}`);
1030
+ }
1031
+ return lines;
1032
+ }
1033
+
1034
+ /**
1035
+ * The counts of one transform's last frame (F1), as the report reads them: lines received,
1036
+ * candidates examined, cards recognised, cards rewritten — then the matched shapes by name, in the
1037
+ * order the transform reported them. Numbers and names only: no line of the frame is ever here.
1038
+ */
1039
+ function formatTransformCounts(counts: TransformFrameCounts): string {
1040
+ const parts = [
1041
+ `${counts.lines} ${counts.lines === 1 ? "line" : "lines"}`,
1042
+ `${counts.candidates} ${counts.candidates === 1 ? "candidate" : "candidates"}`,
1043
+ `${counts.recognised} recognised`,
1044
+ `${counts.rewritten} rewritten`,
1045
+ ];
1046
+ if (counts.shapes.length > 0) {
1047
+ parts.push(`shapes: ${counts.shapes.map((shape) => `${shape.name} ${shape.count}`).join(", ")}`);
1048
+ }
1049
+ return parts.join(", ");
1050
+ }
1051
+
1052
+ /**
1053
+ * The section-frame block: which drawing the header and rows use, how the pointer reaches them, and
1054
+ * the gap the bridge cannot close (N11, N15).
1055
+ *
1056
+ * Every fact here is a measurement of this run: the source comes from looking for the host's two
1057
+ * builder functions on the objects the bridge is actually handed, the theme from whether Pi has run
1058
+ * the widget factory, and the hover mechanism from the last claim of the shared pointer.
1059
+ */
1060
+ function formatSectionFrame(frame: StatusSectionFrame): string[] {
1061
+ const looked = frame.lookedAt.length === 0 ? "nothing yet" : frame.lookedAt.join(", ");
1062
+ const why =
1063
+ frame.source === "host"
1064
+ ? `the host's own renderPanelHeader/renderPanelRow, found on: ${looked}`
1065
+ : `looked for renderPanelHeader/renderPanelRow on: ${looked}; found none`;
1066
+ const theme =
1067
+ frame.theme === "captured"
1068
+ ? "theme captured, rows painted in the host's roles"
1069
+ : "no theme captured yet, rows drawn uncoloured";
1070
+ const hover =
1071
+ frame.hover === "not used"
1072
+ ? "hover not used yet"
1073
+ : frame.hover === "host-state"
1074
+ ? "hover owner claimed on the host's sidebar state"
1075
+ : `hover owner unavailable (${frame.hoverReason ?? "no reason recorded"})`;
1076
+ const lines = [
1077
+ `section frame: ${frame.source} (${why}; ${theme})`,
1078
+ `section interaction: rail handleMouse (the host's own dispatch), ${hover}`,
1079
+ ];
1080
+ if (frame.width !== undefined) {
1081
+ // N20: a width bug is visible from the report — the given width next to what the bridge emitted.
1082
+ lines.push(`section width: ${frame.width.given} columns given, widest row ${frame.width.widest}`);
1083
+ }
1084
+ if (frame.source === "fallback") {
1085
+ // N15: the gap, named. Not "unsupported": gentle-shell's panel module publishes no seam on any
1086
+ // object this package is given, so the header and rows are drawn by the byte-identical port.
1087
+ lines.push(
1088
+ "section frame gap: gentle-shell's lib/shell-panel.ts cannot be imported (Pi loads each " +
1089
+ "extension in its own module graph) and publishes no builder on the rail part, the Pi theme " +
1090
+ "or the terminal's sidebar state, so the header and rows are drawn by a byte-identical port",
1091
+ );
1092
+ }
1093
+ return lines;
1094
+ }
1095
+
1096
+ /** The INTEGRATIONS header's availability note: empty when the host surface is installed. */
1097
+ function formatPluginAvailability(report: PluginLineReport): string {
1098
+ if (report.availability === "installed") return "";
1099
+ const state = report.availability === "unavailable" ? "unavailable" : "not armed";
1100
+ const reason = report.reason === undefined ? "" : `: ${report.reason}`;
1101
+ return ` (status ${state}${reason})`;
1102
+ }
1103
+
1104
+ /** The per-plugin INTEGRATIONS list: the name, how it was chosen, and the registration counts. */
1105
+ function formatPluginLines(report: PluginLineReport): string[] {
1106
+ const lines = [`plugin lines: ${report.plugins.length}${formatPluginAvailability(report)}`];
1107
+ for (const plugin of report.plugins) {
1108
+ const source =
1109
+ plugin.nameSource === "explicit"
1110
+ ? "explicit name"
1111
+ : `derived from package ${JSON.stringify(plugin.packageName ?? "")}`;
1112
+ // `(no line)` is a state, not a name: a module path is diagnostics and stays on this line only,
1113
+ // never in the footer (I2).
1114
+ const label = plugin.name === undefined ? "(no line)" : `${JSON.stringify(plugin.name)} (${source})`;
1115
+ const where = plugin.name === undefined ? ` module ${plugin.modulePath}` : "";
1116
+ const state =
1117
+ plugin.line === "set"
1118
+ ? plugin.status
1119
+ : `no line set (${plugin.reason ?? "no reason recorded"})`;
1120
+ lines.push(
1121
+ ` - ${label}${where}: ${state}, ${plugin.accepted} accepted, ${plugin.rejected.length} rejected`,
1122
+ );
1123
+ for (const rejection of plugin.rejected) {
1124
+ lines.push(` - ${rejection.surface} ${JSON.stringify(rejection.id)}: ${rejection.reason}`);
1125
+ }
1126
+ for (const conflict of plugin.nameConflicts) {
1127
+ lines.push(
1128
+ ` - name conflict on ${conflict.surface} ${JSON.stringify(conflict.id)}: declared ` +
1129
+ `${JSON.stringify(conflict.name)}, kept ${JSON.stringify(conflict.kept)}`,
1130
+ );
1131
+ }
1132
+ }
1133
+ return lines;
1134
+ }
1135
+
1136
+ function formatCapture(outcome: CaptureOutcome | undefined): string {
1137
+ if (outcome === undefined) return "last capture: none";
1138
+ const rows = outcome.injectedRows === 1 ? "1 row" : `${outcome.injectedRows} rows`;
1139
+ switch (outcome.kind) {
1140
+ case "injected":
1141
+ return `last capture: injected ${rows}`;
1142
+ case "already-injected":
1143
+ return "last capture: already injected";
1144
+ case "uncaptured":
1145
+ return outcome.reason === undefined
1146
+ ? "last capture: uncaptured"
1147
+ : `last capture: uncaptured (${outcome.reason})`;
1148
+ }
1149
+ }
1150
+
1151
+ function toStatusFailure(failure: {
1152
+ providerId: string;
1153
+ message: string;
1154
+ rowsDropped: boolean;
1155
+ }): StatusFailure {
1156
+ return {
1157
+ providerId: failure.providerId,
1158
+ message: failure.message,
1159
+ rowsDropped: failure.rowsDropped,
1160
+ };
1161
+ }