pi-odd-worktree 3.15.1 → 3.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/README.md +48 -25
  2. package/extensions/odd-worktree-tools.ts +64 -211
  3. package/lib/shell-api/api.ts +523 -0
  4. package/lib/shell-api/arm.ts +83 -0
  5. package/lib/shell-api/bus.ts +1389 -0
  6. package/lib/shell-api/capture.ts +1340 -0
  7. package/lib/shell-api/card-style-line.ts +112 -0
  8. package/lib/shell-api/card-style-rows.ts +390 -0
  9. package/lib/shell-api/card-style-transform.ts +862 -0
  10. package/lib/shell-api/card-style-wiring.ts +477 -0
  11. package/lib/shell-api/card-styles.ts +153 -0
  12. package/lib/shell-api/config.ts +71 -0
  13. package/lib/shell-api/extension.ts +247 -0
  14. package/lib/shell-api/hook.ts +322 -0
  15. package/lib/shell-api/index.ts +88 -0
  16. package/lib/shell-api/message-design-adoption.ts +549 -0
  17. package/lib/shell-api/message-design-rows.ts +313 -0
  18. package/lib/shell-api/message-design-wiring.ts +369 -0
  19. package/lib/shell-api/message-designs.ts +746 -0
  20. package/lib/shell-api/notices.ts +137 -0
  21. package/lib/shell-api/plugin-lines.ts +877 -0
  22. package/lib/shell-api/presence.ts +258 -0
  23. package/lib/shell-api/repaint.ts +351 -0
  24. package/lib/shell-api/row-labels.ts +146 -0
  25. package/lib/shell-api/row-names.ts +273 -0
  26. package/lib/shell-api/row-origin.ts +144 -0
  27. package/lib/shell-api/rows.ts +591 -0
  28. package/lib/shell-api/section-panel.ts +378 -0
  29. package/lib/shell-api/section-pointer.ts +164 -0
  30. package/lib/shell-api/sections-preview.ts +275 -0
  31. package/lib/shell-api/sections-rows.ts +133 -0
  32. package/lib/shell-api/sidebar-render.ts +705 -0
  33. package/lib/shell-api/sidebar.ts +1126 -0
  34. package/lib/shell-api/store.ts +279 -0
  35. package/lib/shell-api/tool-design-adoption.ts +263 -0
  36. package/lib/shell-api/tool-design-rows.ts +307 -0
  37. package/lib/shell-api/tool-design-wiring.ts +481 -0
  38. package/lib/shell-api/tool-designs.ts +1411 -0
  39. package/lib/shell-api/transform-pipeline.ts +351 -0
  40. package/lib/shell-api/types.ts +803 -0
  41. package/lib/shell-api/visibility.ts +154 -0
  42. package/package.json +3 -2
  43. package/tools/files-bridge.test.js +81 -66
  44. package/tools/fixtures/load-extension.js +40 -18
  45. package/tools/issues-command.test.js +4 -7
  46. package/tools/issues-section.test.js +71 -81
  47. package/tools/odd-rail-wiring.test.js +16 -10
  48. package/tools/package-surface.test.js +42 -13
  49. package/tools/prs-command.test.js +11 -6
  50. package/tools/shell-api/api.test.ts +484 -0
  51. package/tools/shell-api/apply-on-move.test.ts +529 -0
  52. package/tools/shell-api/arm.test.ts +220 -0
  53. package/tools/shell-api/bridge-ready.test.ts +309 -0
  54. package/tools/shell-api/bus.test.ts +194 -0
  55. package/tools/shell-api/button-rows.test.ts +435 -0
  56. package/tools/shell-api/capture.test.ts +583 -0
  57. package/tools/shell-api/card-style-rows.test.ts +493 -0
  58. package/tools/shell-api/card-style-transform.test.ts +379 -0
  59. package/tools/shell-api/card-style-wiring.test.ts +258 -0
  60. package/tools/shell-api/card-styles-e2e.test.ts +502 -0
  61. package/tools/shell-api/card-styles.test.ts +324 -0
  62. package/tools/shell-api/card-transcript-path.test.ts +178 -0
  63. package/tools/shell-api/compatibility-regression.test.mjs +64 -0
  64. package/tools/shell-api/config.test.ts +93 -0
  65. package/tools/shell-api/docs-coverage.test.ts +82 -0
  66. package/tools/shell-api/e2e.test.ts +562 -0
  67. package/tools/shell-api/example-bash-identity.test.ts +372 -0
  68. package/tools/shell-api/example-bash-matrix.test.ts +856 -0
  69. package/tools/shell-api/example-designs.test.ts +737 -0
  70. package/tools/shell-api/example-neon-transform.test.ts +283 -0
  71. package/tools/shell-api/example-plain-style.test.ts +1225 -0
  72. package/tools/shell-api/extension.test.ts +157 -0
  73. package/tools/shell-api/fake-events.ts +58 -0
  74. package/tools/shell-api/fake-host.ts +211 -0
  75. package/tools/shell-api/fake-sidebar.ts +516 -0
  76. package/tools/shell-api/fake-transcript.ts +486 -0
  77. package/tools/shell-api/frame-telemetry.test.ts +317 -0
  78. package/tools/shell-api/hook.test.ts +196 -0
  79. package/tools/shell-api/manifest.test.ts +47 -0
  80. package/tools/shell-api/message-design-adoption.test.ts +611 -0
  81. package/tools/shell-api/message-design-follows.test.ts +361 -0
  82. package/tools/shell-api/message-design-pi-release.test.mjs +157 -0
  83. package/tools/shell-api/message-design-regressions.test.mjs +162 -0
  84. package/tools/shell-api/message-design-rows.test.ts +266 -0
  85. package/tools/shell-api/message-design-wiring.test.ts +362 -0
  86. package/tools/shell-api/message-designs.test.ts +339 -0
  87. package/tools/shell-api/new-category.test.ts +1101 -0
  88. package/tools/shell-api/notices.test.ts +292 -0
  89. package/tools/shell-api/plugin-integration-lines.test.ts +827 -0
  90. package/tools/shell-api/presence.test.ts +396 -0
  91. package/tools/shell-api/rail-part-hits.test.ts +281 -0
  92. package/tools/shell-api/rail-surfaces.test.ts +402 -0
  93. package/tools/shell-api/rail-width.test.ts +406 -0
  94. package/tools/shell-api/regression.test.ts +434 -0
  95. package/tools/shell-api/repaint-api.test.ts +200 -0
  96. package/tools/shell-api/reserved-categories.test.ts +250 -0
  97. package/tools/shell-api/row-labels.test.ts +261 -0
  98. package/tools/shell-api/row-names.test.ts +407 -0
  99. package/tools/shell-api/row-origin.test.ts +395 -0
  100. package/tools/shell-api/row-placement-regression.test.ts +797 -0
  101. package/tools/shell-api/row-placement.test.ts +410 -0
  102. package/tools/shell-api/section-interaction.test.ts +364 -0
  103. package/tools/shell-api/section-panel.test.ts +430 -0
  104. package/tools/shell-api/section-placement-rail.test.ts +390 -0
  105. package/tools/shell-api/section-placement.test.ts +386 -0
  106. package/tools/shell-api/sections-preview.test.ts +312 -0
  107. package/tools/shell-api/sections-rows.test.ts +293 -0
  108. package/tools/shell-api/sidebar-backend.test.ts +477 -0
  109. package/tools/shell-api/sidebar-e2e.test.ts +317 -0
  110. package/tools/shell-api/sidebar-hover.test.ts +276 -0
  111. package/tools/shell-api/sidebar-independent.test.ts +291 -0
  112. package/tools/shell-api/sidebar-render.test.ts +281 -0
  113. package/tools/shell-api/sidebar-sections.test.ts +247 -0
  114. package/tools/shell-api/store.test.ts +192 -0
  115. package/tools/shell-api/surface-repaint-cost.test.ts +520 -0
  116. package/tools/shell-api/tool-design-card-style.test.ts +308 -0
  117. package/tools/shell-api/tool-design-chain.test.ts +471 -0
  118. package/tools/shell-api/tool-design-cost.test.ts +591 -0
  119. package/tools/shell-api/tool-design-rows.test.ts +627 -0
  120. package/tools/shell-api/tool-design-scopes-audit.test.ts +212 -0
  121. package/tools/shell-api/tool-designs.test.ts +2412 -0
  122. package/tools/shell-api/transform-pipeline.test.ts +376 -0
  123. package/tools/shell-api/transforms-bus.test.ts +233 -0
  124. package/tools/shell-api/verifier-width-regressions.test.ts +147 -0
  125. package/tools/shell-api-rpc.test.js +189 -0
  126. package/tools/user-prompt-card.test.js +8 -9
@@ -0,0 +1,705 @@
1
+ /**
2
+ * Section rendering (S3, S7, S8; N10–N14): the bridge's half of the sidebar surface, contributed
3
+ * through the rail backend's `setRailContributor` extension point (`./sidebar.ts`).
4
+ *
5
+ * ## The host draws the frame, we supply the header and the rows
6
+ *
7
+ * A section must look like `AGENTS` / `CHANGES` / `STATS`, and those are drawn by the host's own
8
+ * card frame — so the bridge never draws a box. It contributes two things per frame: the part's
9
+ * rows, and the card groups over them. The group shape mirrors
10
+ * `lib/shell-sidebar-layout.ts:392-410`: a group's `start` is the row that carries the card heading
11
+ * (`▾ TITLE`, plus the count right-aligned) and `end` is one past the last body row, both indices
12
+ * into the part's `render(width)` output, which is also what the group shape in
13
+ * `test/fake-sidebar.ts` models. That is the contract T3 offsets and this module fills; the host
14
+ * calls `sectionCardRows(headerParts(lines[start]), lines.slice(start + 1, end))` on it.
15
+ *
16
+ * ## The header and the rows are the host's own drawing (N11)
17
+ *
18
+ * The header comes from `./section-panel.ts`'s `renderSectionHeader` — caret from the section's own
19
+ * collapse state, uppercase title, the right-aligned `meta`, the host's hover role — and a
20
+ * structured row from `renderSectionRow`, composed the way `lib/agents-widget.ts:400-407` composes an
21
+ * `AGENTS` row. Both use the host's builders when a host publishes them and the byte-identical local
22
+ * port otherwise; the diagnostics record reports which.
23
+ *
24
+ * ## A plain string row is untouched (N10)
25
+ *
26
+ * `lines()` may return a string or a `SectionRow`. A string keeps the exact bytes the author wrote —
27
+ * no indent, no padding, no styling — so no existing plugin's card changes appearance. Only a
28
+ * structured row gets the panel treatment, because only a structured row asked for it.
29
+ *
30
+ * ## Interaction (N12, N13)
31
+ *
32
+ * The host's own click model is POSITIONAL: it maps a pointer event into the part's frame and calls
33
+ * the part's `handleMouse` (`lib/shell-sidebar-layout.ts:245-259`), so this module records which of
34
+ * its own rows is the header and which are clickable, and answers only those events. A row without
35
+ * `onClick` is inert: it never highlights and never answers. The header toggles the section; the
36
+ * collapse flag lives in the bridge's store, like visibility (`./visibility.ts`), and the frame is
37
+ * requested synchronously (`./repaint.ts`).
38
+ *
39
+ * ## What a section costs
40
+ *
41
+ * `lines(ctx)` and `meta(ctx)` run per frame, so a plugin's content is honest without a redraw API.
42
+ * A hidden section is not built at all (S7), a COLLAPSED one is not built either (N13): no rows, and
43
+ * neither function is called for the body. A throwing function, or a return that is not the
44
+ * documented shape, drops that section's body, records the failure for the diagnostics record and leaves
45
+ * every other section and every native card rendering (S8).
46
+ *
47
+ * This module is internal: `src/index.ts` does not re-export it.
48
+ */
49
+
50
+ import { resolveSectionPlacements, snapshotSections } from "./bus.ts";
51
+ import { hostColumns } from "./card-style-transform.ts";
52
+ import { requestSurfaceRepaint } from "./repaint.ts";
53
+ import { createRowContext } from "./rows.ts";
54
+ import {
55
+ checkSectionRows,
56
+ clipSectionRow,
57
+ getSectionTheme,
58
+ getPanelReport,
59
+ renderSectionHeader,
60
+ renderSectionRow,
61
+ type AcceptedRow,
62
+ type PanelTheme,
63
+ } from "./section-panel.ts";
64
+ import { claimSectionHover, releaseSectionHover } from "./section-pointer.ts";
65
+ import type {
66
+ RailContribution,
67
+ RailContributor,
68
+ RailContributorContext,
69
+ RailContributionPosition,
70
+ RailMouseResult,
71
+ RailPartContribution,
72
+ RailRowRange,
73
+ } from "./sidebar.ts";
74
+ import { setRailContributor } from "./sidebar.ts";
75
+ import { RAIL_PARTS } from "./types.ts";
76
+ import type { RailPart, SectionContext, SidebarSection } from "./types.ts";
77
+ import {
78
+ getSectionCollapsed,
79
+ getSectionVisibility,
80
+ isSectionCollapsed,
81
+ isSectionVisible,
82
+ setSectionCollapsed,
83
+ } from "./visibility.ts";
84
+
85
+ /** Rows a section body may occupy before the rest is elided. */
86
+ export const MAX_SECTION_BODY_ROWS = 8;
87
+
88
+ /** The row that marks an elided body; it always fits a sane rail width. */
89
+ const ELISION = (hidden: number): string => `… +${hidden} more`;
90
+
91
+ /** A section whose `lines()` or `meta()` misbehaved in the most recent frame. */
92
+ export interface SectionRenderFailure {
93
+ sectionId: string;
94
+ phase: "meta" | "lines" | "onClick";
95
+ message: string;
96
+ }
97
+
98
+ /**
99
+ * One physical row of the last contribution, so a pointer event can be mapped to what the user sees
100
+ * (N12). `y` in a part's mouse event counts the PART's rows; `row` counts this contribution's,
101
+ * which is why the backend hands us the offset (`RailContributionPosition`).
102
+ */
103
+ export interface SectionRowHit {
104
+ /** Index within the contribution (not the part's frame). */
105
+ row: number;
106
+ sectionId: string;
107
+ kind: "header" | "body";
108
+ /** The hover identity, for a row that can be highlighted; absent for an inert row. */
109
+ key?: string;
110
+ /** What a click on this row does; absent for an inert row. */
111
+ activate?: () => void;
112
+ }
113
+
114
+ /** Where the most recent render stood on width (N20): what it was given, and its widest row. */
115
+ interface SectionFrame {
116
+ width: number;
117
+ /** The widest row any part produced at this width, measured the way the host measures (N20). */
118
+ widest: number;
119
+ }
120
+
121
+ /** The rows this contributor drew for ONE part, at the width they were drawn at (S3). */
122
+ interface SectionPartRanges {
123
+ width: number;
124
+ /** One block per side of the part's own rows, so a pointer event can be mapped to what it hit. */
125
+ blocks: SectionBlock[];
126
+ }
127
+
128
+ /** One block of contributed rows: the rows this contributor drew on one side of one part. */
129
+ interface SectionBlock {
130
+ side: "before" | "after";
131
+ hits: SectionRowHit[];
132
+ }
133
+
134
+ // Bumped to v2 with the per-part ranges: a copy at 0.16.1 shares this slot, and its single wide
135
+ // `frame.blocks` is not the shape read below, so the two versions must not read one another's state.
136
+ const SECTION_RENDER_STATE = Symbol.for("gentle-shell-bridge.sections.render.v2");
137
+
138
+ interface SectionRenderState {
139
+ /** What the most recent frame failed on, so the diagnostics record reports the latest frame. */
140
+ lastFailures: SectionRenderFailure[];
141
+ /** The most recent render's width and its widest row (N20). */
142
+ frame?: SectionFrame;
143
+ /**
144
+ * The rows of the most recent contribution of EACH part, for pointer hit-testing. Replaced
145
+ * wholesale when that part renders, so a part re-rendered inside one pass cannot double count and a
146
+ * part that lost every section loses its ranges — and a part re-rendered on its own, which is what
147
+ * the host's memo does, leaves every other part's ranges alone (S1, S3).
148
+ */
149
+ partRanges?: Map<RailPart, SectionPartRanges>;
150
+ /** The hovered row's key, or absent when the pointer is not on one of ours. */
151
+ hovered?: string;
152
+ /**
153
+ * The paint index of the part rendered last. The layout renders the parts in paint order, so a
154
+ * part at or before the previous index means a NEW pass began — which is how one report of
155
+ * failures survives across the four parts of the same pass.
156
+ */
157
+ lastPartIndex?: number;
158
+ }
159
+
160
+ function renderStateHost(): Record<symbol, SectionRenderState | undefined> {
161
+ // SAFETY: only `sectionRenderState()` writes this slot, and it validates the shape before use, so
162
+ // a foreign or partial value is replaced rather than trusted.
163
+ return globalThis as unknown as Record<symbol, SectionRenderState | undefined>;
164
+ }
165
+
166
+ function sectionRenderState(): SectionRenderState {
167
+ const host = renderStateHost();
168
+ const existing = host[SECTION_RENDER_STATE];
169
+ if (existing !== undefined && Array.isArray(existing.lastFailures)) return existing;
170
+ const created: SectionRenderState = { lastFailures: [] };
171
+ host[SECTION_RENDER_STATE] = created;
172
+ return created;
173
+ }
174
+
175
+ /** Sections that failed in the most recent frame, for the diagnostics record (T6). */
176
+ export function getSectionFailures(): SectionRenderFailure[] {
177
+ return sectionRenderState().lastFailures.map((failure) => ({ ...failure }));
178
+ }
179
+
180
+ /**
181
+ * The width the last frame was handed and the widest row the bridge produced at it (N20), both in
182
+ * the host's own columns. `undefined` until a frame contributed rows, so a report of a session whose
183
+ * rail never painted stays exactly as it was.
184
+ */
185
+ export interface SectionFrameWidth {
186
+ /** The width the host handed this part. */
187
+ given: number;
188
+ /** The widest contributed row, as the host measures it; always `<= given` when N17 holds. */
189
+ widest: number;
190
+ }
191
+
192
+ /** N20: the last render's given width and the widest line the bridge produced, host-measured. */
193
+ export function getSectionFrameWidth(): SectionFrameWidth | undefined {
194
+ const frame = sectionRenderState().frame;
195
+ if (frame === undefined) return undefined;
196
+ return { given: frame.width, widest: frame.widest };
197
+ }
198
+
199
+ /**
200
+ * Test-only seam; drops the last frame, the per-part ranges and the hover too, so one test cannot
201
+ * leak into another.
202
+ */
203
+ export function resetSectionFailuresForTests(): void {
204
+ const state = sectionRenderState();
205
+ state.lastFailures = [];
206
+ delete state.frame;
207
+ delete state.partRanges;
208
+ delete state.hovered;
209
+ }
210
+
211
+ /**
212
+ * Build one part's contribution: its cards, in the order the placement resolver decided, split into
213
+ * the block ABOVE the host's own rows and the block below them (S1–S3, S5).
214
+ *
215
+ * The placement list is recomputed per part from the registry and the painted parts, so no frame
216
+ * state can make one part disagree with another: the same registrations and the same painted set
217
+ * always produce the same rows in the same place.
218
+ */
219
+ export function buildSectionContribution(
220
+ width: number,
221
+ ctx: SectionContext,
222
+ rail: RailContributorContext,
223
+ ): RailPartContribution | undefined {
224
+ // A part rendered at zero width has no room for a heading or a body row. Contributing nothing
225
+ // keeps the host's own shape untouched instead of returning a row wider than the width.
226
+ if (!Number.isFinite(width) || width < 1) return undefined;
227
+
228
+ const state = sectionRenderState();
229
+ const frame = beginPartFrame(state, rail.part, width);
230
+ const visibility = getSectionVisibility();
231
+ const collapsedMap = getSectionCollapsed();
232
+ const theme = getSectionTheme();
233
+ const hovered = state.hovered;
234
+ const placements = resolveSectionPlacements(snapshotSections(), rail.painted);
235
+
236
+ const blocks: SectionBlock[] = [];
237
+ const contribution: RailPartContribution = {};
238
+ for (const side of ["before", "after"] as const) {
239
+ const sections = placements
240
+ .filter((entry) => entry.part === rail.part && entry.side === side)
241
+ .map((entry) => entry.section);
242
+ if (sections.length === 0) continue;
243
+ const built = buildBlock(sections, {
244
+ width,
245
+ theme,
246
+ hovered,
247
+ visibility,
248
+ collapsedMap,
249
+ ctx,
250
+ });
251
+ if (built === undefined) continue;
252
+ blocks.push({ side, hits: built.hits });
253
+ contribution[side] = built.contribution;
254
+ }
255
+
256
+ // This part's ranges are REPLACED, never merged: a part re-rendered inside the same pass must not
257
+ // be counted twice, a part that lost every section must lose its row ranges too, and a part
258
+ // re-rendered on its own must leave every other part's ranges untouched (S1, S3).
259
+ partRanges(state).set(rail.part, { width, blocks });
260
+ if (contribution.before === undefined && contribution.after === undefined) return undefined;
261
+ return contribution;
262
+ }
263
+
264
+ /** The per-part row ranges, created on first use. */
265
+ function partRanges(state: SectionRenderState): Map<RailPart, SectionPartRanges> {
266
+ const existing = state.partRanges;
267
+ if (existing !== undefined) return existing;
268
+ const created = new Map<RailPart, SectionPartRanges>();
269
+ state.partRanges = created;
270
+ return created;
271
+ }
272
+
273
+ /**
274
+ * Start (or continue) one part's place in the pass. The layout renders the parts in paint order, so a
275
+ * part whose index is not after the previous one belongs to a NEW pass: that is where the failure
276
+ * list restarts, once per pass instead of once per part. The row ranges are NOT part of that reset —
277
+ * they are recorded per part and replaced only when that part renders.
278
+ */
279
+ function beginPartFrame(
280
+ state: SectionRenderState,
281
+ part: RailPart,
282
+ width: number,
283
+ ): SectionFrame {
284
+ const index = RAIL_PARTS.indexOf(part);
285
+ const frame = state.frame;
286
+ const newPass =
287
+ frame === undefined ||
288
+ frame.width !== width ||
289
+ state.lastPartIndex === undefined ||
290
+ index <= state.lastPartIndex;
291
+ if (newPass) {
292
+ // Failures describe the pass, not history: a section that stops throwing stops being reported.
293
+ state.lastFailures = [];
294
+ state.frame = { width, widest: 0 };
295
+ }
296
+ state.lastPartIndex = index;
297
+ // SAFETY: every branch above leaves a frame in place.
298
+ return state.frame as SectionFrame;
299
+ }
300
+
301
+ /** One block of sections: their rows, their card groups and the pointer map over them. */
302
+ function buildBlock(
303
+ sections: readonly SidebarSection[],
304
+ frame: {
305
+ width: number;
306
+ theme: PanelTheme | undefined;
307
+ hovered: string | undefined;
308
+ visibility: ReturnType<typeof getSectionVisibility>;
309
+ collapsedMap: ReturnType<typeof getSectionCollapsed>;
310
+ ctx: SectionContext;
311
+ },
312
+ ): { contribution: RailContribution; hits: SectionRowHit[] } | undefined {
313
+ const lines: string[] = [];
314
+ const hits: SectionRowHit[] = [];
315
+ const groups: Array<{ start: number; end: number }> = [];
316
+
317
+ for (const section of sections) {
318
+ // Hidden means NOT BUILT (S7): no rows, no `lines()`, no `meta()`. Hiding is a user choice, not
319
+ // a request to compute something nobody will see — and it does NOT move the sections placed
320
+ // after this one, because their slot was decided from the registration, not from these rows.
321
+ if (!isSectionVisible(frame.visibility, section)) continue;
322
+
323
+ const collapsed = isSectionCollapsed(frame.collapsedMap, section);
324
+ const meta = readMeta(section, frame.ctx);
325
+ // A meta failure drops the body too (S8's rule is about the section's BODY), while a body
326
+ // failure keeps the heading so the user can still see that the section exists. A collapsed
327
+ // section builds no body at all (N13) — folding must not cost the work of drawing.
328
+ const body = meta.ok && !collapsed ? readBody(section, frame.ctx) : [];
329
+ const start = lines.length;
330
+ const headerKey = `${section.id}#header`;
331
+ const headerHovered = frame.hovered === headerKey;
332
+ lines.push(
333
+ renderSectionHeader(frame.theme, frame.width, {
334
+ title: section.title,
335
+ ...(meta.text === undefined ? {} : { count: meta.text }),
336
+ open: !collapsed,
337
+ hovered: headerHovered,
338
+ }),
339
+ );
340
+ hits.push({
341
+ row: start,
342
+ sectionId: section.id,
343
+ kind: "header",
344
+ key: headerKey,
345
+ activate: () => toggleSectionCollapsed(section),
346
+ });
347
+ // Isolation is per SECTION, not per frame (S8): one section must never be able to throw away
348
+ // its siblings' rows or its own heading. The validation in `readBody` catches the cases we know
349
+ // about; this guard covers the ones we do not.
350
+ try {
351
+ appendBody(section, body, {
352
+ theme: frame.theme,
353
+ width: frame.width,
354
+ hovered: frame.hovered,
355
+ lines,
356
+ hits,
357
+ });
358
+ } catch (error) {
359
+ recordFailure(section.id, "lines", error);
360
+ lines.length = start + 1; // keep the heading, drop the broken body
361
+ hits.length = start + 1;
362
+ }
363
+ groups.push({ start, end: lines.length });
364
+ }
365
+
366
+ if (lines.length === 0) return undefined;
367
+ // The frame's widest row, measured the way the host measures (N20).
368
+ const frameState = sectionRenderState().frame;
369
+ if (frameState !== undefined) {
370
+ for (const line of lines) frameState.widest = Math.max(frameState.widest, hostColumns(line));
371
+ }
372
+ return { contribution: { lines, groups }, hits };
373
+ }
374
+
375
+ /** One section's body rows, each recorded for the pointer map as it is drawn. */
376
+ function appendBody(
377
+ section: SidebarSection,
378
+ body: readonly AcceptedRow[],
379
+ frame: {
380
+ theme: PanelTheme | undefined;
381
+ width: number;
382
+ hovered: string | undefined;
383
+ lines: string[];
384
+ hits: SectionRowHit[];
385
+ },
386
+ ): void {
387
+ body.forEach((entry, index) => {
388
+ const row = frame.lines.length;
389
+ if (typeof entry === "string") {
390
+ // Byte-identical (N10): a plain row is the author's text, clipped to the width and nothing
391
+ // else — no indent, no padding, no styling, no hit target.
392
+ frame.lines.push(clipRow(entry, frame.width));
393
+ frame.hits.push({ row, sectionId: section.id, kind: "body" });
394
+ return;
395
+ }
396
+ const key = entry.onClick === undefined ? undefined : `${section.id}#${index}`;
397
+ frame.lines.push(
398
+ renderSectionRow(frame.theme, frame.width, entry, key !== undefined && frame.hovered === key),
399
+ );
400
+ frame.hits.push({
401
+ row,
402
+ sectionId: section.id,
403
+ kind: "body",
404
+ ...(key === undefined ? {} : { key }),
405
+ ...(entry.onClick === undefined ? {} : { activate: entry.onClick }),
406
+ });
407
+ });
408
+ }
409
+
410
+ /**
411
+ * The contributor T3 calls once per frame. It resolves the same context a row provider gets — the
412
+ * theme Pi handed the widget factory (so a section can paint with the host's own roles, N11) and the
413
+ * resolved gentle-shell config home — so a section never re-derives a path.
414
+ */
415
+ export const sectionRailContributor: RailContributor = {
416
+ render: (width, rail) =>
417
+ buildSectionContribution(width, createRowContext(getSectionTheme()), rail),
418
+ // N14: the layout re-renders a part only when its digest moves, so the built rows are what the
419
+ // signature is made of. Reading `meta()`/`lines()` here is the same trade the host's own parts
420
+ // make (`extensions/gentle-agents.ts:2255-2260`): a live field has to be read to be noticed.
421
+ digest: (rail) => sectionRailDigest(createRowContext(getSectionTheme()), rail),
422
+ handleMouse: (event, position) => handleSectionMouse(event, position),
423
+ };
424
+
425
+ /**
426
+ * A cheap signature of everything a frame would draw: the sections, their header counts, their
427
+ * collapse flags, their rows and the hover state. Two frames that would draw the same rows have the
428
+ * same signature, so a change anywhere in it — a `meta` that moved (N14), a collapse, a hover —
429
+ * reaches the host's memo as a new digest and repaints.
430
+ */
431
+ export function sectionRailDigest(ctx: SectionContext, rail: RailContributorContext): string {
432
+ const visibility = getSectionVisibility();
433
+ const collapsedMap = getSectionCollapsed();
434
+ const state = sectionRenderState();
435
+ const sections: unknown[] = [];
436
+ for (const resolved of resolveSectionPlacements(snapshotSections(), rail.painted)) {
437
+ const section = resolved.section;
438
+ // Where the card goes is part of what the frame draws: a new anchor or a native part that stops
439
+ // being painted has to reach the host's memo as a new signature, or the rows never move.
440
+ const slot = [section.id, resolved.part, resolved.side];
441
+ if (!isSectionVisible(visibility, section)) {
442
+ sections.push([...slot, false]);
443
+ continue;
444
+ }
445
+ const collapsed = isSectionCollapsed(collapsedMap, section);
446
+ const meta = readMeta(section, ctx);
447
+ const body = meta.ok && !collapsed ? readBody(section, ctx) : [];
448
+ sections.push([
449
+ ...slot,
450
+ section.title,
451
+ meta.text ?? null,
452
+ collapsed,
453
+ body.map(rowSignature),
454
+ ]);
455
+ }
456
+ const panel = getPanelReport();
457
+ return JSON.stringify([
458
+ sections,
459
+ rail.part,
460
+ rail.painted,
461
+ state.hovered ?? null,
462
+ panel.source,
463
+ themeSignature(),
464
+ ]);
465
+ }
466
+
467
+ /** One body row, flattened into a comparable string for the digest (N14). */
468
+ function rowSignature(row: AcceptedRow): string {
469
+ if (typeof row === "string") return `s:${row}`;
470
+ const parts = [row.label, row.meta ?? "", row.glyph ?? "", row.tone ?? ""];
471
+ return `r:${JSON.stringify(parts)}:${row.onClick === undefined ? "inert" : "acts"}`;
472
+ }
473
+
474
+ /**
475
+ * What the current theme paints with. Pi hands extensions ONE live theme proxy, so identity never
476
+ * changes on a theme switch; how the roles paint does. The host's memo keys on the same idea
477
+ * (`lib/shell-sidebar-layout.ts:123-124`), which is why a themed row repaints when the theme changes.
478
+ */
479
+ function themeSignature(): string {
480
+ const theme = getSectionTheme();
481
+ if (theme === undefined) return "no-theme";
482
+ const roles = ["accent", "dim", "error", "muted", "success", "text", "warning"];
483
+ try {
484
+ return roles.map((role) => theme.fg(role, ".")).join("");
485
+ } catch {
486
+ return "theme-throws";
487
+ }
488
+ }
489
+
490
+ /**
491
+ * Answer a pointer event the host mapped into the part's frame (N12). Only our own rows answer, and
492
+ * only where they act: the header always does (it folds the section), a body row only when it
493
+ * carries `onClick`.
494
+ *
495
+ * The position the backend hands over is the set of ROW RANGES of this part's frame, so a block may
496
+ * sit above the host's rows as well as below them (S7): the event is matched against the block that
497
+ * contains it, and never against "everything after the host's rows".
498
+ *
499
+ * The ranges belong to ONE part and to the width that part was rendered at (S1, S3): the host's memo
500
+ * re-renders a single part when its digest moves, and an event mapped at another width has no ranges
501
+ * to be mapped onto, so both mismatches decline instead of guessing an offset.
502
+ */
503
+ export function handleSectionMouse(
504
+ event: unknown,
505
+ position?: RailContributionPosition,
506
+ ): RailMouseResult | undefined {
507
+ if (position === undefined) return undefined;
508
+ const state = sectionRenderState();
509
+ const part = railPartNamed(position.part);
510
+ const ranges = part === undefined ? undefined : state.partRanges?.get(part);
511
+ if (ranges === undefined || ranges.width !== position.width) return undefined;
512
+ const pointer = readPointer(event);
513
+ if (pointer === undefined) return undefined;
514
+ const block = blockAt(position, pointer.y);
515
+ if (block === undefined) return undefined;
516
+ const hits = ranges.blocks.find((candidate) => candidate.side === block.side)?.hits;
517
+ if (hits === undefined) return undefined;
518
+ const hit = hits.find((candidate) => candidate.row === pointer.y - block.start);
519
+ if (hit === undefined) return undefined;
520
+
521
+ if (pointer.type === "move") {
522
+ if (hit.key === undefined) {
523
+ // An inert row: never highlight, and let the host's own dispatch continue.
524
+ return state.hovered === undefined ? undefined : clearHover();
525
+ }
526
+ if (state.hovered === hit.key) return { handled: true };
527
+ state.hovered = hit.key;
528
+ claimSectionHover(() => {
529
+ clearHover();
530
+ });
531
+ requestSurfaceRepaint({
532
+ cause: `section ${JSON.stringify(hit.sectionId)} ${hit.kind} hover`,
533
+ surfaces: ["rail"],
534
+ });
535
+ return { handled: true, render: true };
536
+ }
537
+
538
+ if (pointer.type === "click") {
539
+ if (pointer.button !== "left") return undefined;
540
+ if (hit.activate === undefined) return undefined;
541
+ // One click, one action (N12): the pointer stops hovering and the row's own work runs once. The
542
+ // drop is silent — the action below asks for the frame, so a click costs one request, not two.
543
+ dropHover();
544
+ runActivate(hit);
545
+ return { handled: true, render: true };
546
+ }
547
+
548
+ return undefined;
549
+ }
550
+
551
+ /** The painted part a position names, or `undefined` for a part the rail never wraps. */
552
+ function railPartNamed(part: string): RailPart | undefined {
553
+ return RAIL_PARTS.find((candidate) => candidate === part);
554
+ }
555
+
556
+ /** Which of this contributor's two blocks the event's row falls in, and where that block starts. */
557
+ function blockAt(
558
+ position: RailContributionPosition,
559
+ y: number,
560
+ ): { side: "before" | "after"; start: number } | undefined {
561
+ const inRange = (range: RailRowRange | undefined): boolean =>
562
+ range !== undefined && y >= range.start && y < range.end;
563
+ if (position.before !== undefined && inRange(position.before)) {
564
+ return { side: "before", start: position.before.start };
565
+ }
566
+ if (position.after !== undefined && inRange(position.after)) {
567
+ return { side: "after", start: position.after.start };
568
+ }
569
+ return undefined;
570
+ }
571
+
572
+ function runActivate(hit: SectionRowHit): void {
573
+ const activate = hit.activate;
574
+ if (activate === undefined) return;
575
+ try {
576
+ activate();
577
+ } catch (error) {
578
+ // A plugin's `onClick` that throws must not escape into the host's pointer dispatch.
579
+ recordFailure(hit.sectionId, "onClick", error);
580
+ }
581
+ }
582
+
583
+ /** Drop the hover state and release the shared pointer, without asking for a frame. */
584
+ function dropHover(): void {
585
+ sectionRenderState().hovered = undefined;
586
+ releaseSectionHover();
587
+ }
588
+
589
+ /** Drop the hover and repaint — the path the host's own "pointer left" calls. */
590
+ function clearHover(): RailMouseResult {
591
+ const state = sectionRenderState();
592
+ const wasHovered = state.hovered !== undefined;
593
+ dropHover();
594
+ if (wasHovered) requestSurfaceRepaint({ cause: "section hover cleared", surfaces: ["rail"] });
595
+ return { handled: true, render: true };
596
+ }
597
+
598
+ /** Fold or unfold one section (N13): persist first, then ask for the frame in the same call. */
599
+ function toggleSectionCollapsed(section: SidebarSection): void {
600
+ const collapsed = isSectionCollapsed(getSectionCollapsed(), section);
601
+ setSectionCollapsed(section.id, !collapsed);
602
+ requestSurfaceRepaint({
603
+ cause: `section ${JSON.stringify(section.id)} → ${collapsed ? "expanded" : "collapsed"}`,
604
+ surfaces: ["rail"],
605
+ });
606
+ }
607
+
608
+ /**
609
+ * The one contributor the backend holds. Idempotent by construction: it stores one function in the
610
+ * backend's state, so a second arm or a second package copy never doubles a card.
611
+ */
612
+ export function installSectionRail(): void {
613
+ setRailContributor(sectionRailContributor);
614
+ }
615
+
616
+ interface MetaResult {
617
+ /** False when `meta()` threw or returned the wrong type: the whole body is dropped. */
618
+ ok: boolean;
619
+ /** Trimmed, non-empty text; absent when the section has no meta or it is blank. */
620
+ text?: string;
621
+ }
622
+
623
+ function readMeta(section: SidebarSection, ctx: SectionContext): MetaResult {
624
+ if (section.meta === undefined) return { ok: true };
625
+ let value: unknown;
626
+ try {
627
+ value = section.meta(ctx);
628
+ } catch (error) {
629
+ recordFailure(section.id, "meta", error);
630
+ return { ok: false };
631
+ }
632
+ if (value === undefined) return { ok: true };
633
+ if (typeof value !== "string") {
634
+ recordFailure(section.id, "meta", new Error("meta() must return a string or undefined"));
635
+ return { ok: false };
636
+ }
637
+ const text = value.trim();
638
+ return text === "" ? { ok: true } : { ok: true, text };
639
+ }
640
+
641
+ function readBody(section: SidebarSection, ctx: SectionContext): AcceptedRow[] {
642
+ let value: unknown;
643
+ try {
644
+ value = section.lines(ctx);
645
+ } catch (error) {
646
+ recordFailure(section.id, "lines", error);
647
+ return [];
648
+ }
649
+ // A non-array, a hole or a malformed row is a failure, never coerced: a coerced row would show
650
+ // garbage as if the plugin had meant it. The row rules live in one place (`./section-panel.ts`).
651
+ const checked = checkSectionRows(value);
652
+ if (!checked.ok) {
653
+ recordFailure(section.id, "lines", new Error(checked.message));
654
+ return [];
655
+ }
656
+ return capBody(checked.rows);
657
+ }
658
+
659
+ /** Keep the body inside the row budget, marking the elision visibly. */
660
+ function capBody(rows: readonly AcceptedRow[]): AcceptedRow[] {
661
+ if (rows.length <= MAX_SECTION_BODY_ROWS) return [...rows];
662
+ const kept = rows.slice(0, MAX_SECTION_BODY_ROWS - 1);
663
+ // The marker occupies one of the budgeted rows and says how many are not shown. It is a plain
664
+ // string, so it is drawn exactly as the author's own plain rows are.
665
+ return [...kept, ELISION(rows.length - kept.length)];
666
+ }
667
+
668
+ /** The pointer fields of a mouse event, when it has the shape the host dispatches. */
669
+ function readPointer(event: unknown): { type: string; button?: string; y: number } | undefined {
670
+ if (typeof event !== "object" || event === null) return undefined;
671
+ const candidate = event as { type?: unknown; button?: unknown; y?: unknown };
672
+ if (typeof candidate.type !== "string") return undefined;
673
+ if (typeof candidate.y !== "number" || !Number.isFinite(candidate.y)) return undefined;
674
+ return {
675
+ type: candidate.type,
676
+ ...(typeof candidate.button === "string" ? { button: candidate.button } : {}),
677
+ y: candidate.y,
678
+ };
679
+ }
680
+
681
+ /**
682
+ * Clamp one plain row to the width the host passes, with a visible marker instead of a silent cut.
683
+ *
684
+ * Measured the way the HOST measures a row (N17) — `./section-panel.ts`'s `clipSectionRow`, over
685
+ * `hostColumns`: ANSI is zero columns, a TAB is three, and a grapheme cluster is charged as a whole —
686
+ * so a CJK glyph, an emoji or a tab cannot make the row wider than the width it was fitted to. A row
687
+ * that already fits keeps its exact bytes (N10). A STRUCTURED row is drawn by the panel builder,
688
+ * which measures the same way.
689
+ */
690
+ function clipRow(row: string, width: number): string {
691
+ return clipSectionRow(row, width);
692
+ }
693
+
694
+ function recordFailure(
695
+ sectionId: string,
696
+ phase: SectionRenderFailure["phase"],
697
+ error: unknown,
698
+ ): void {
699
+ const state = sectionRenderState();
700
+ state.lastFailures.push({ sectionId, phase, message: errorMessage(error) });
701
+ }
702
+
703
+ function errorMessage(error: unknown): string {
704
+ return error instanceof Error ? error.message : String(error);
705
+ }