pi-odd-worktree 3.15.1 → 3.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +48 -25
  2. package/extensions/odd-worktree-tools.ts +70 -212
  3. package/lib/shell-api/api.ts +523 -0
  4. package/lib/shell-api/arm.ts +83 -0
  5. package/lib/shell-api/bus.ts +1389 -0
  6. package/lib/shell-api/capture.ts +1340 -0
  7. package/lib/shell-api/card-style-line.ts +112 -0
  8. package/lib/shell-api/card-style-rows.ts +390 -0
  9. package/lib/shell-api/card-style-transform.ts +862 -0
  10. package/lib/shell-api/card-style-wiring.ts +477 -0
  11. package/lib/shell-api/card-styles.ts +153 -0
  12. package/lib/shell-api/config.ts +71 -0
  13. package/lib/shell-api/extension.ts +247 -0
  14. package/lib/shell-api/hook.ts +322 -0
  15. package/lib/shell-api/index.ts +88 -0
  16. package/lib/shell-api/message-design-adoption.ts +549 -0
  17. package/lib/shell-api/message-design-rows.ts +313 -0
  18. package/lib/shell-api/message-design-wiring.ts +369 -0
  19. package/lib/shell-api/message-designs.ts +746 -0
  20. package/lib/shell-api/notices.ts +137 -0
  21. package/lib/shell-api/plugin-lines.ts +877 -0
  22. package/lib/shell-api/presence.ts +258 -0
  23. package/lib/shell-api/repaint.ts +351 -0
  24. package/lib/shell-api/row-labels.ts +146 -0
  25. package/lib/shell-api/row-names.ts +273 -0
  26. package/lib/shell-api/row-origin.ts +144 -0
  27. package/lib/shell-api/rows.ts +591 -0
  28. package/lib/shell-api/section-panel.ts +378 -0
  29. package/lib/shell-api/section-pointer.ts +164 -0
  30. package/lib/shell-api/sections-preview.ts +275 -0
  31. package/lib/shell-api/sections-rows.ts +133 -0
  32. package/lib/shell-api/sidebar-render.ts +705 -0
  33. package/lib/shell-api/sidebar.ts +1126 -0
  34. package/lib/shell-api/store.ts +279 -0
  35. package/lib/shell-api/tool-design-adoption.ts +263 -0
  36. package/lib/shell-api/tool-design-rows.ts +307 -0
  37. package/lib/shell-api/tool-design-wiring.ts +481 -0
  38. package/lib/shell-api/tool-designs.ts +1411 -0
  39. package/lib/shell-api/transform-pipeline.ts +351 -0
  40. package/lib/shell-api/types.ts +803 -0
  41. package/lib/shell-api/visibility.ts +154 -0
  42. package/package.json +3 -2
  43. package/tools/files-bridge.test.js +81 -66
  44. package/tools/fixtures/load-extension.js +40 -18
  45. package/tools/issues-command.test.js +4 -7
  46. package/tools/issues-section.test.js +71 -81
  47. package/tools/odd-rail-wiring.test.js +16 -10
  48. package/tools/package-surface.test.js +42 -13
  49. package/tools/prs-command.test.js +11 -6
  50. package/tools/session-auto-name-wiring.test.js +39 -0
  51. package/tools/shell-api/api.test.ts +484 -0
  52. package/tools/shell-api/apply-on-move.test.ts +529 -0
  53. package/tools/shell-api/arm.test.ts +220 -0
  54. package/tools/shell-api/bridge-ready.test.ts +309 -0
  55. package/tools/shell-api/bus.test.ts +194 -0
  56. package/tools/shell-api/button-rows.test.ts +435 -0
  57. package/tools/shell-api/capture.test.ts +583 -0
  58. package/tools/shell-api/card-style-rows.test.ts +493 -0
  59. package/tools/shell-api/card-style-transform.test.ts +379 -0
  60. package/tools/shell-api/card-style-wiring.test.ts +258 -0
  61. package/tools/shell-api/card-styles-e2e.test.ts +502 -0
  62. package/tools/shell-api/card-styles.test.ts +324 -0
  63. package/tools/shell-api/card-transcript-path.test.ts +178 -0
  64. package/tools/shell-api/compatibility-regression.test.mjs +64 -0
  65. package/tools/shell-api/config.test.ts +93 -0
  66. package/tools/shell-api/docs-coverage.test.ts +82 -0
  67. package/tools/shell-api/e2e.test.ts +562 -0
  68. package/tools/shell-api/example-bash-identity.test.ts +372 -0
  69. package/tools/shell-api/example-bash-matrix.test.ts +856 -0
  70. package/tools/shell-api/example-designs.test.ts +737 -0
  71. package/tools/shell-api/example-neon-transform.test.ts +283 -0
  72. package/tools/shell-api/example-plain-style.test.ts +1225 -0
  73. package/tools/shell-api/extension.test.ts +157 -0
  74. package/tools/shell-api/fake-events.ts +58 -0
  75. package/tools/shell-api/fake-host.ts +211 -0
  76. package/tools/shell-api/fake-sidebar.ts +516 -0
  77. package/tools/shell-api/fake-transcript.ts +486 -0
  78. package/tools/shell-api/frame-telemetry.test.ts +317 -0
  79. package/tools/shell-api/hook.test.ts +196 -0
  80. package/tools/shell-api/manifest.test.ts +47 -0
  81. package/tools/shell-api/message-design-adoption.test.ts +611 -0
  82. package/tools/shell-api/message-design-follows.test.ts +361 -0
  83. package/tools/shell-api/message-design-pi-release.test.mjs +157 -0
  84. package/tools/shell-api/message-design-regressions.test.mjs +162 -0
  85. package/tools/shell-api/message-design-rows.test.ts +266 -0
  86. package/tools/shell-api/message-design-wiring.test.ts +362 -0
  87. package/tools/shell-api/message-designs.test.ts +339 -0
  88. package/tools/shell-api/new-category.test.ts +1101 -0
  89. package/tools/shell-api/notices.test.ts +292 -0
  90. package/tools/shell-api/plugin-integration-lines.test.ts +827 -0
  91. package/tools/shell-api/presence.test.ts +396 -0
  92. package/tools/shell-api/rail-part-hits.test.ts +281 -0
  93. package/tools/shell-api/rail-surfaces.test.ts +402 -0
  94. package/tools/shell-api/rail-width.test.ts +406 -0
  95. package/tools/shell-api/regression.test.ts +434 -0
  96. package/tools/shell-api/repaint-api.test.ts +200 -0
  97. package/tools/shell-api/reserved-categories.test.ts +250 -0
  98. package/tools/shell-api/row-labels.test.ts +261 -0
  99. package/tools/shell-api/row-names.test.ts +407 -0
  100. package/tools/shell-api/row-origin.test.ts +395 -0
  101. package/tools/shell-api/row-placement-regression.test.ts +797 -0
  102. package/tools/shell-api/row-placement.test.ts +410 -0
  103. package/tools/shell-api/section-interaction.test.ts +364 -0
  104. package/tools/shell-api/section-panel.test.ts +430 -0
  105. package/tools/shell-api/section-placement-rail.test.ts +390 -0
  106. package/tools/shell-api/section-placement.test.ts +386 -0
  107. package/tools/shell-api/sections-preview.test.ts +312 -0
  108. package/tools/shell-api/sections-rows.test.ts +293 -0
  109. package/tools/shell-api/sidebar-backend.test.ts +477 -0
  110. package/tools/shell-api/sidebar-e2e.test.ts +317 -0
  111. package/tools/shell-api/sidebar-hover.test.ts +276 -0
  112. package/tools/shell-api/sidebar-independent.test.ts +291 -0
  113. package/tools/shell-api/sidebar-render.test.ts +281 -0
  114. package/tools/shell-api/sidebar-sections.test.ts +247 -0
  115. package/tools/shell-api/store.test.ts +192 -0
  116. package/tools/shell-api/surface-repaint-cost.test.ts +520 -0
  117. package/tools/shell-api/tool-design-card-style.test.ts +308 -0
  118. package/tools/shell-api/tool-design-chain.test.ts +471 -0
  119. package/tools/shell-api/tool-design-cost.test.ts +591 -0
  120. package/tools/shell-api/tool-design-rows.test.ts +627 -0
  121. package/tools/shell-api/tool-design-scopes-audit.test.ts +212 -0
  122. package/tools/shell-api/tool-designs.test.ts +2412 -0
  123. package/tools/shell-api/transform-pipeline.test.ts +376 -0
  124. package/tools/shell-api/transforms-bus.test.ts +233 -0
  125. package/tools/shell-api/verifier-width-regressions.test.ts +147 -0
  126. package/tools/shell-api-rpc.test.js +189 -0
  127. package/tools/user-prompt-card.test.js +8 -9
@@ -0,0 +1,746 @@
1
+ /**
2
+ * The message-design registry (S1, S4): ONE registration point for Pi custom messages, and the
3
+ * selection the wiring resolves on every pass.
4
+ *
5
+ * ## Why this exists
6
+ *
7
+ * `bash` is drawn by gentle-shell's own renderers, so `float`/`neon` reaches it there. A custom message
8
+ * registered with `pi.registerMessageRenderer` is drawn by whoever registered it — or by Pi's default
9
+ * box when nobody did — and neither path knows about the bridge's card styles. A design is the only
10
+ * surface from which a plugin can paint one, and this module is its registry.
11
+ *
12
+ * ## One value per line, one line per type
13
+ *
14
+ * The shape is the tool designs' shape (see `./tool-designs.ts`), minus scopes: a design is declared for
15
+ * ONE custom type (its own `Message <type>` line) or joins a named line of several types. A type belongs
16
+ * to at most ONE line, so two switches can never disagree about one message; a second claim on a type is
17
+ * refused whole before anything is stored.
18
+ *
19
+ * ## The persisted value is the design id, never the label
20
+ *
21
+ * `default` (stored as `native`, the reserved identity) is the host's own output, always first and never
22
+ * registered by a plugin. Renaming a label therefore never loses a user's choice, and disposing a design
23
+ * leaves `missing` — which the wiring reads as "draw the host's own output" and says so in
24
+ * the diagnostics record, never as a silent `default`.
25
+ *
26
+ * ## Declining costs nothing
27
+ *
28
+ * With no design registered for a type the wiring never even installs a renderer for it (S4): Pi's own
29
+ * output is byte-identical and no pass pays for this surface. Resolving reads the store ONCE per call,
30
+ * never once per candidate.
31
+ *
32
+ * This module is internal: `src/index.ts` re-exports only `registerMessageDesign`,
33
+ * `resolveMessageDesignSelection` and their types.
34
+ */
35
+
36
+ import { assertRegistrationId } from "./bus.ts";
37
+ import { attributeRegistration } from "./plugin-lines.ts";
38
+ import { isRecord } from "./rows.ts";
39
+ import { createStore } from "./store.ts";
40
+ import { getToolDesignLineSelection, toolDesignLines } from "./tool-designs.ts";
41
+ import type {
42
+ MessageDesignContext,
43
+ MessageDesignFollow,
44
+ MessageDesignFollowAnswer,
45
+ MessageDesignRegistration,
46
+ } from "./types.ts";
47
+
48
+ /** The reserved value that means "the host's own output": never a design id, never selectable as one. */
49
+ export const MESSAGE_DESIGN_NATIVE = "native";
50
+
51
+ /** What the menu SHOWS for that value, exactly like `Card <line>`'s `default`. */
52
+ export const MESSAGE_DESIGN_DEFAULT_LABEL = "default";
53
+
54
+ /** The bridge's own store, namespaced: never a plugin's file. */
55
+ export const MESSAGE_DESIGN_STORE_ID = "bridge-message-designs";
56
+
57
+ /** The one key in it: the per-type selections, with the per-line map under a reserved key beside them. */
58
+ export const MESSAGE_DESIGN_STORE_KEY = "selections";
59
+
60
+ /** Reserved inside that document, so a custom type can never collide with the line map. */
61
+ export const MESSAGE_DESIGN_LINE_STORE_KEY = "$lines";
62
+
63
+ /** Which key a line uses: an ungrouped design's implicit line, or a registered line id. */
64
+ export type MessageDesignScope = "type" | "line";
65
+
66
+ /** A registration that replaced, duplicated or collided with another one, reported by the diagnostics record. */
67
+ export interface MessageDesignConflict {
68
+ /** The custom type the record is about (the first of the line's types for a line conflict). */
69
+ customType: string;
70
+ /** The id of the registration that lost or was replaced. */
71
+ id: string;
72
+ kind: "replaced" | "label" | "type";
73
+ /** One sentence naming what happened, shown verbatim. */
74
+ message: string;
75
+ }
76
+
77
+ /** A design that threw while painting, recorded once per (type, id, message). */
78
+ export interface MessageDesignFailure {
79
+ customType: string;
80
+ designId: string;
81
+ message: string;
82
+ }
83
+
84
+ /** How many failures are kept; older ones fall off the front. */
85
+ const MAX_FAILURES = 8;
86
+
87
+ /** One live registration: the line it belongs to, the types it claims, and the design itself. */
88
+ interface DesignEntry {
89
+ scope: MessageDesignScope;
90
+ line: string;
91
+ types: string[];
92
+ design: MessageDesignRegistration;
93
+ }
94
+
95
+ /** One line, as the menu and the diagnostics record read it. */
96
+ export interface MessageDesignLine {
97
+ scope: MessageDesignScope;
98
+ /** The selection key: the custom type, or the registered line id. */
99
+ line: string;
100
+ /** Every type the line covers, in first-seen order. */
101
+ types: string[];
102
+ /** The line's designs, in registration order. */
103
+ designs: MessageDesignRegistration[];
104
+ }
105
+
106
+ /** What a type's stored selection means right now. Never a throw: every value is an answer. */
107
+ export type MessageDesignSelection =
108
+ | { kind: "native" }
109
+ | { kind: "design"; design: MessageDesignRegistration }
110
+ | { kind: "missing"; id: string }
111
+ | { kind: "not-covered"; id: string };
112
+
113
+ interface MessageDesignState {
114
+ /** Every live registration, in registration order; one entry per (`scope`, `line`, `id`). */
115
+ entries: DesignEntry[];
116
+ conflicts: MessageDesignConflict[];
117
+ failures: MessageDesignFailure[];
118
+ /**
119
+ * How many times the persisted selections were read since the last reset. One read is one logical
120
+ * read of the bridge's store, which is what a cost test bounds instead of timing (S4).
121
+ */
122
+ selectionReads: number;
123
+ /**
124
+ * The rows line's installer, set by `./message-design-rows.ts` when the bridge arms. It is called
125
+ * when a design appears, so the line is registered THEN and never before: with no design there is
126
+ * no provider, no row and nothing added to the diagnostics record (S4).
127
+ */
128
+ rowsInstaller?: () => void;
129
+ }
130
+
131
+ /** Stable process-global slot: a second loaded copy of this package must see the same registry. */
132
+ const DESIGNS_KEY = Symbol.for("gentle-shell-bridge.message-designs.v1");
133
+
134
+ function designsHost(): Record<symbol, MessageDesignState | undefined> {
135
+ // SAFETY: only `messageDesignState()` writes this key, and it re-checks the shape before trusting a
136
+ // value left by another copy or by an older load.
137
+ return globalThis as unknown as Record<symbol, MessageDesignState | undefined>;
138
+ }
139
+
140
+ function messageDesignState(): MessageDesignState {
141
+ const host = designsHost();
142
+ const existing = host[DESIGNS_KEY];
143
+ if (existing !== undefined && Array.isArray(existing.entries)) {
144
+ // A slot created by a copy that predates the counters gains them in place, so two copies agree.
145
+ if (!Array.isArray(existing.conflicts)) existing.conflicts = [];
146
+ if (!Array.isArray(existing.failures)) existing.failures = [];
147
+ if (typeof existing.selectionReads !== "number") existing.selectionReads = 0;
148
+ return existing;
149
+ }
150
+ const created: MessageDesignState = { entries: [], conflicts: [], failures: [], selectionReads: 0 };
151
+ host[DESIGNS_KEY] = created;
152
+ return created;
153
+ }
154
+
155
+ /**
156
+ * Let the rows line install itself the moment a design exists (S4), and withdraw that request when
157
+ * the bridge disarms. Passing `undefined` unsubscribes. The installer is the bridge's own, never a
158
+ * plugin's, so it is never attributed and its failures are the bridge's own.
159
+ */
160
+ export function setMessageDesignRowsInstaller(installer: (() => void) | undefined): void {
161
+ messageDesignState().rowsInstaller = installer;
162
+ }
163
+
164
+ /** A value that cannot be read as text is still a value: the report must not throw on it. */
165
+ const UNPRINTABLE_THROWN_VALUE = "a value that cannot be read as text";
166
+
167
+ function errorMessage(error: unknown): string {
168
+ if (error instanceof Error && typeof error.message === "string") return error.message;
169
+ try {
170
+ const text = String(error);
171
+ return text === "" ? UNPRINTABLE_THROWN_VALUE : text;
172
+ } catch {
173
+ return UNPRINTABLE_THROWN_VALUE;
174
+ }
175
+ }
176
+
177
+ function invalid(id: unknown, problem: string): Error {
178
+ return new Error(
179
+ `gentle-shell-bridge: invalid message design ${JSON.stringify(id)}: ${problem}. ` +
180
+ "A message design is declared for ONE custom type (`customType`) or for a line of several " +
181
+ "(`line` + `types`), and carries an `id`, a `label` and an `apply`.",
182
+ );
183
+ }
184
+
185
+ /** One sentence a refusal can be quoted with, and the reason the report shows. */
186
+ function recordConflict(conflict: MessageDesignConflict): void {
187
+ const state = messageDesignState();
188
+ const duplicate = state.conflicts.find(
189
+ (existing) =>
190
+ existing.customType === conflict.customType &&
191
+ existing.id === conflict.id &&
192
+ existing.kind === conflict.kind,
193
+ );
194
+ if (duplicate !== undefined) {
195
+ duplicate.message = conflict.message;
196
+ return;
197
+ }
198
+ state.conflicts.push(conflict);
199
+ }
200
+
201
+ // ---------------------------------------------------------------------------------------------
202
+ // Validation: everything is checked BEFORE anything is stored, so a refusal never half-registers
203
+ // ---------------------------------------------------------------------------------------------
204
+
205
+ const RESERVED_LABELS = new Set([MESSAGE_DESIGN_DEFAULT_LABEL, MESSAGE_DESIGN_NATIVE]);
206
+
207
+ function assertLabel(id: string, label: unknown): void {
208
+ if (typeof label !== "string" || label.trim() === "") {
209
+ throw new Error(
210
+ `gentle-shell-bridge: invalid message design ${JSON.stringify(id)}: label must be a ` +
211
+ "non-empty string. It is the value a user reads on the line; the id stays internal.",
212
+ );
213
+ }
214
+ if (RESERVED_LABELS.has(label.trim())) {
215
+ throw new Error(
216
+ `gentle-shell-bridge: invalid message design ${JSON.stringify(id)}: label ` +
217
+ `${JSON.stringify(label)} is reserved. "default" is the bridge's own value and "native" is ` +
218
+ "its identity; register a label of your own.",
219
+ );
220
+ }
221
+ }
222
+
223
+ function assertApply(id: string, apply: unknown): void {
224
+ if (typeof apply !== "function") {
225
+ throw new Error(
226
+ `gentle-shell-bridge: invalid message design ${JSON.stringify(id)}: apply must be a function ` +
227
+ "`(lines, ctx) => rows`. It is the whole point of the registration.",
228
+ );
229
+ }
230
+ }
231
+
232
+ /**
233
+ * `follows`, when present, is exactly `{ line, id }`: both non-empty, and never the reserved `native`
234
+ * as the id it waits for — `native` means "this line answers nothing", so a design following it could
235
+ * never turn on and would be a switch the user cannot find anywhere.
236
+ */
237
+ function assertFollow(id: unknown, follow: unknown): void {
238
+ if (follow === null || typeof follow !== "object") {
239
+ throw invalid(id, "`follows` must be an object `{ line, id }`");
240
+ }
241
+ const candidate = follow as { line?: unknown; id?: unknown };
242
+ if (typeof candidate.line !== "string" || candidate.line.trim() === "") {
243
+ throw invalid(id, "`follows.line` must be a non-empty tool-design line id");
244
+ }
245
+ if (typeof candidate.id !== "string" || candidate.id.trim() === "") {
246
+ throw invalid(id, "`follows.id` must be a non-empty tool design id");
247
+ }
248
+ if (candidate.id.trim() === MESSAGE_DESIGN_NATIVE) {
249
+ throw invalid(
250
+ id,
251
+ `\`follows.id\` cannot be ${JSON.stringify(MESSAGE_DESIGN_NATIVE)}: that value means the tool ` +
252
+ "line answers nothing, so the design could never turn on. Name the tool design that should " +
253
+ "turn it on.",
254
+ );
255
+ }
256
+ }
257
+
258
+ function assertTypes(id: unknown, types: unknown): string[] {
259
+ if (!Array.isArray(types) || types.length === 0) {
260
+ throw new Error(
261
+ `gentle-shell-bridge: invalid message design ${JSON.stringify(id)}: types must be a non-empty ` +
262
+ "array of custom types; a registration that claims no message paints nothing.",
263
+ );
264
+ }
265
+ const seen = new Set<string>();
266
+ for (const type of types) {
267
+ if (typeof type !== "string" || type.trim() === "") {
268
+ throw new Error(
269
+ `gentle-shell-bridge: invalid message design ${JSON.stringify(id)}: every entry of types ` +
270
+ "must be a non-empty custom type string.",
271
+ );
272
+ }
273
+ if (seen.has(type)) {
274
+ throw new Error(
275
+ `gentle-shell-bridge: invalid message design ${JSON.stringify(id)}: types repeats ` +
276
+ `${JSON.stringify(type)}. List each type once.`,
277
+ );
278
+ }
279
+ seen.add(type);
280
+ }
281
+ return [...seen];
282
+ }
283
+
284
+ interface Normalized {
285
+ scope: MessageDesignScope;
286
+ line: string;
287
+ types: string[];
288
+ }
289
+
290
+ /** Exactly one shape: `customType`, or `line` + `types`. Never both, never neither. */
291
+ function normalizeRegistration(id: unknown, design: MessageDesignRegistration): Normalized {
292
+ if (design === null || typeof design !== "object") {
293
+ throw invalid(id, "the registration must be an object");
294
+ }
295
+ const hasType = design.customType !== undefined;
296
+ const hasLine = design.line !== undefined || design.types !== undefined;
297
+ if (hasType && hasLine) {
298
+ throw invalid(id, "`customType` and (`line` + `types`) cannot be mixed");
299
+ }
300
+ if (!hasType && !hasLine) {
301
+ throw invalid(id, "one of `customType` or (`line` + `types`) is required");
302
+ }
303
+ if (hasType) {
304
+ const type = design.customType;
305
+ if (typeof type !== "string" || type.trim() === "") {
306
+ throw invalid(id, "`customType` must be a non-empty string");
307
+ }
308
+ return { scope: "type", line: type, types: [type] };
309
+ }
310
+ const line = design.line;
311
+ if (typeof line !== "string" || line.trim() === "") {
312
+ throw invalid(id, "`line` must be a non-empty string");
313
+ }
314
+ return { scope: "line", line, types: assertTypes(id, design.types) };
315
+ }
316
+
317
+ /**
318
+ * A type belongs to ONE line. A claim from ANOTHER line — or from an ungrouped design — is refused
319
+ * whole and reported, because two switches that could both paint one message would leave the user
320
+ * with a choice that cannot be honoured.
321
+ *
322
+ * A design of the SAME line is not a competing claim: the designs of one line are the VALUES of its
323
+ * one switch, so two of them may cover the same type. Selecting either answers for that type; the
324
+ * other is simply not the current value.
325
+ */
326
+ function assertTypesAreFree(
327
+ scope: MessageDesignScope,
328
+ line: string,
329
+ id: string,
330
+ types: readonly string[],
331
+ ): void {
332
+ for (const entry of messageDesignState().entries) {
333
+ const sameLine = entry.scope === scope && entry.line === line;
334
+ if (sameLine) continue;
335
+ const shared = types.find((type) => entry.types.includes(type));
336
+ if (shared === undefined) continue;
337
+ const message =
338
+ `message ${JSON.stringify(shared)} is already claimed by ` +
339
+ `${entry.scope === "type" ? "its own line" : `line ${JSON.stringify(entry.line)}`} ` +
340
+ `(${JSON.stringify(entry.design.id)}); a custom type belongs to ONE line.`;
341
+ recordConflict({ customType: shared, id, kind: "type", message });
342
+ throw new Error(`gentle-shell-bridge: invalid message design ${JSON.stringify(id)}: ${message}`);
343
+ }
344
+ }
345
+
346
+ // ---------------------------------------------------------------------------------------------
347
+ // Registration
348
+ // ---------------------------------------------------------------------------------------------
349
+
350
+ function registerStored(design: MessageDesignRegistration): () => void {
351
+ assertRegistrationId("message design", design.id);
352
+ const { scope, line, types } = normalizeRegistration(design.id, design);
353
+ assertLabel(design.id, design.label);
354
+ assertApply(design.id, design.apply);
355
+ if (design.follows !== undefined) assertFollow(design.id, design.follows);
356
+ assertTypesAreFree(scope, line, design.id, types);
357
+
358
+ const state = messageDesignState();
359
+ const entry: DesignEntry = { scope, line, types, design };
360
+ const existing = state.entries.findIndex(
361
+ (candidate) =>
362
+ candidate.scope === scope && candidate.line === line && candidate.design.id === design.id,
363
+ );
364
+ if (existing === -1) {
365
+ state.entries.push(entry);
366
+ } else {
367
+ recordConflict({
368
+ customType: types[0],
369
+ id: design.id,
370
+ kind: "replaced",
371
+ message: `design ${JSON.stringify(design.id)} on ${scope === "type" ? "its own line" : `line ${JSON.stringify(line)}`} was replaced in place.`,
372
+ });
373
+ state.entries[existing] = entry;
374
+ }
375
+
376
+ // A design now exists, so the `Cards` line that shows it must exist too. Idempotent, and it runs
377
+ // ONLY here: with no design the bridge registers no provider at all (S4).
378
+ state.rowsInstaller?.();
379
+
380
+ let disposed = false;
381
+ return () => {
382
+ if (disposed) return;
383
+ disposed = true;
384
+ const index = state.entries.indexOf(entry);
385
+ if (index !== -1) state.entries.splice(index, 1);
386
+ };
387
+ }
388
+
389
+ /**
390
+ * Register one message design, or several as ONE all-or-nothing batch. Throws on an invalid
391
+ * registration before storing anything, and returns a disposer that withdraws exactly what it added.
392
+ */
393
+ export function registerMessageDesign(
394
+ design: MessageDesignRegistration | readonly MessageDesignRegistration[],
395
+ ): () => void {
396
+ if (!Array.isArray(design)) {
397
+ return attributeRegistration("message design", design, undefined, () =>
398
+ registerStored(design as MessageDesignRegistration),
399
+ );
400
+ }
401
+ const state = messageDesignState();
402
+ const before = [...state.entries];
403
+ const disposers: Array<() => void> = [];
404
+ try {
405
+ for (const one of design as readonly MessageDesignRegistration[]) {
406
+ disposers.push(
407
+ attributeRegistration("message design", one, undefined, () => registerStored(one)),
408
+ );
409
+ }
410
+ } catch (error) {
411
+ for (const dispose of disposers.reverse()) dispose();
412
+ // The batch is all-or-nothing, so the entries an earlier member added are withdrawn too.
413
+ state.entries.length = 0;
414
+ state.entries.push(...before);
415
+ throw error;
416
+ }
417
+ return () => {
418
+ for (const dispose of disposers) dispose();
419
+ };
420
+ }
421
+
422
+ // ---------------------------------------------------------------------------------------------
423
+ // The lines, as the menu and the diagnostics record read them
424
+ // ---------------------------------------------------------------------------------------------
425
+
426
+ /**
427
+ * Whether ANY live design exists. The conversation pass asks this before it looks at a child, so a
428
+ * session with no message design reads no message at all (S4's cost bound, not only its output).
429
+ */
430
+ export function hasMessageDesignClaims(): boolean {
431
+ return messageDesignState().entries.length > 0;
432
+ }
433
+
434
+ /**
435
+ * Whether a custom type is claimed by a live design right now. A registry walk with NO persistence
436
+ * read, which is what lets a conversation pass skip unclaimed messages for free (S4).
437
+ */
438
+ export function isMessageTypeClaimed(customType: string): boolean {
439
+ return messageDesignState().entries.some((entry) => entry.types.includes(customType));
440
+ }
441
+
442
+ /** What a follow answers when no live tool-design line has its name. */
443
+ export const MESSAGE_DESIGN_FOLLOW_NONE = "none";
444
+
445
+ /**
446
+ * What one follow answers RIGHT NOW (S1, 0.12.0): which tool-design line answered, what it answered,
447
+ * and whether that is the id this design waits for.
448
+ *
449
+ * READ ONLY. It never writes the tool document and never needs a seed: the value the user already
450
+ * picked on that line is the whole answer, and when there is no such line (a tool design that has not
451
+ * registered yet, or was disposed) the answer is `found: false` rather than a throw.
452
+ */
453
+ export function resolveMessageDesignFollow(
454
+ follow: MessageDesignFollow,
455
+ ): MessageDesignFollowAnswer {
456
+ const line = toolDesignLines().find((candidate) => candidate.line === follow.line);
457
+ if (line === undefined) {
458
+ return {
459
+ line: follow.line,
460
+ found: false,
461
+ answered: MESSAGE_DESIGN_FOLLOW_NONE,
462
+ active: false,
463
+ };
464
+ }
465
+ const answered = getToolDesignLineSelection(line.scope, line.line);
466
+ return { line: follow.line, found: true, answered, active: answered === follow.id };
467
+ }
468
+
469
+ /** Every line that has designs, in creation order, with its type set and its designs in order. */
470
+ export function messageDesignLines(): MessageDesignLine[] {
471
+ const lines: MessageDesignLine[] = [];
472
+ for (const entry of messageDesignState().entries) {
473
+ const existing = lines.find(
474
+ (line) => line.scope === entry.scope && line.line === entry.line,
475
+ );
476
+ if (existing === undefined) {
477
+ lines.push({
478
+ scope: entry.scope,
479
+ line: entry.line,
480
+ types: [...entry.types],
481
+ designs: [entry.design],
482
+ });
483
+ continue;
484
+ }
485
+ for (const type of entry.types) {
486
+ if (!existing.types.includes(type)) existing.types.push(type);
487
+ }
488
+ existing.designs.push(entry.design);
489
+ }
490
+ return lines;
491
+ }
492
+
493
+ // ---------------------------------------------------------------------------------------------
494
+ // The selection: one persisted value per line
495
+ // ---------------------------------------------------------------------------------------------
496
+
497
+ interface SelectionState {
498
+ /** The ungrouped selections: custom type -> design id. */
499
+ types: Record<string, unknown>;
500
+ /** The named lines, under the reserved key in the same document. */
501
+ lines: Record<string, unknown>;
502
+ }
503
+
504
+ function asRecord(value: unknown): Record<string, unknown> {
505
+ return isRecord(value) ? value : {};
506
+ }
507
+
508
+ /**
509
+ * The persisted selections, read live. An unreadable or malformed file reads as empty, so a hand-edited
510
+ * file can never select a design the user did not choose. ONE logical read of the bridge's store per
511
+ * call, which is what the cost bound counts (S4).
512
+ */
513
+ function readSelections(): SelectionState {
514
+ messageDesignState().selectionReads += 1;
515
+ const stored = asRecord(
516
+ createStore(MESSAGE_DESIGN_STORE_ID).get<unknown>(MESSAGE_DESIGN_STORE_KEY, {}),
517
+ );
518
+ const { [MESSAGE_DESIGN_LINE_STORE_KEY]: lines, ...types } = stored;
519
+ return { types, lines: asRecord(lines) };
520
+ }
521
+
522
+ /** The reserved key is written ONLY when a line has a value, so a session with none keeps its document. */
523
+ function writeSelections(state: SelectionState): void {
524
+ const document: Record<string, unknown> = { ...state.types };
525
+ if (Object.keys(state.lines).length > 0) {
526
+ document[MESSAGE_DESIGN_LINE_STORE_KEY] = state.lines;
527
+ }
528
+ createStore(MESSAGE_DESIGN_STORE_ID).set(MESSAGE_DESIGN_STORE_KEY, document);
529
+ }
530
+
531
+ /** A stored value that is not a usable id reads as `native`, never as a design nobody registered. */
532
+ function storedId(map: Record<string, unknown>, key: string): string {
533
+ if (!Object.hasOwn(map, key)) return MESSAGE_DESIGN_NATIVE;
534
+ const stored = map[key];
535
+ return typeof stored === "string" && stored.trim() !== "" ? stored : MESSAGE_DESIGN_NATIVE;
536
+ }
537
+
538
+ /** The design id stored for one custom type, or `native` when it has none. */
539
+ export function getMessageDesignSelection(customType: string): string {
540
+ return storedId(readSelections().types, customType);
541
+ }
542
+
543
+ /** The design id stored for one line, or `native` when it has none. */
544
+ export function getMessageDesignLineSelection(scope: MessageDesignScope, line: string): string {
545
+ const selections = readSelections();
546
+ return storedId(scope === "type" ? selections.types : selections.lines, line);
547
+ }
548
+
549
+ /**
550
+ * Persist one line's selection, FIRST and synchronously: the host re-reads `current()` when it repaints,
551
+ * so the bullet cannot land on a value that was never written.
552
+ */
553
+ export function setMessageDesignLineSelection(
554
+ scope: MessageDesignScope,
555
+ line: string,
556
+ id: string,
557
+ ): void {
558
+ const selections = readSelections();
559
+ if (scope === "type") {
560
+ writeSelections({ types: { ...selections.types, [line]: id }, lines: selections.lines });
561
+ return;
562
+ }
563
+ writeSelections({ types: selections.types, lines: { ...selections.lines, [line]: id } });
564
+ }
565
+
566
+ /** Persist one custom type's (ungrouped) selection. */
567
+ export function setMessageDesignSelection(customType: string, id: string): void {
568
+ setMessageDesignLineSelection("type", customType, id);
569
+ }
570
+
571
+ /**
572
+ * Resolve one custom type's design against the live registry. Never throws.
573
+ *
574
+ * With no live claim on the type the answer is `native` — the host's own output, untouched. A stored
575
+ * value that names no live design of its line is `missing` (a disposed design, which the wiring draws
576
+ * as the host's own output and reports), and a line whose selected design does not list THIS type is
577
+ * `not-covered`, so a grouped line never silently paints a message it never claimed.
578
+ */
579
+ export function resolveMessageDesignSelection(customType: string): MessageDesignSelection {
580
+ const state = messageDesignState();
581
+ const claim = state.entries.find((entry) => entry.types.includes(customType));
582
+ if (claim === undefined) {
583
+ // No live claim on the type. A value still stored for it names a design that was disposed, and
584
+ // saying so is what lets the wiring draw the host's own output and REPORT it instead of quietly
585
+ // reading as the host's default (S4). This is the one path that must open the document.
586
+ const orphan = storedId(readSelections().types, customType);
587
+ return orphan === MESSAGE_DESIGN_NATIVE ? { kind: "native" } : { kind: "missing", id: orphan };
588
+ }
589
+ const lineEntries = state.entries.filter(
590
+ (entry) => entry.scope === claim.scope && entry.line === claim.line,
591
+ );
592
+ // A design that FOLLOWS a tool switch is decided by that switch and by nothing else (S1). It is
593
+ // answered FIRST, before the message document is even opened, because no stored value there may
594
+ // veto it — a stale id left by a design that is gone must not turn off a design whose switch is on.
595
+ // The first active follow in registration order wins, the same rule the line's own values follow.
596
+ const activeFollow = lineEntries.find(
597
+ (entry) =>
598
+ entry.types.includes(customType) &&
599
+ entry.design.follows !== undefined &&
600
+ resolveMessageDesignFollow(entry.design.follows).active,
601
+ )?.design;
602
+ if (activeFollow !== undefined) return { kind: "design", design: activeFollow };
603
+
604
+ // Nothing but follows claims this type, and none of them is on: the host's own output, and the
605
+ // message document is never opened. That is what keeps a claimed-but-inactive alert free (S4).
606
+ const ownEntries = lineEntries.filter(
607
+ (entry) => entry.types.includes(customType) && entry.design.follows === undefined,
608
+ );
609
+ if (ownEntries.length === 0) return { kind: "native" };
610
+
611
+ // From here a value the user really chose on the message's own line decides. ONE snapshot serves
612
+ // the rest of the resolve: one logical store read per call.
613
+ const selections = readSelections();
614
+ const stored = storedId(
615
+ claim.scope === "type" ? selections.types : selections.lines,
616
+ claim.line,
617
+ );
618
+ if (stored === MESSAGE_DESIGN_NATIVE) return { kind: "native" };
619
+ // The stored value names a design of THIS line, whether or not it lists this type: a line that
620
+ // covers several types must answer `not-covered` rather than quietly painting a message it never
621
+ // claimed, and a value that names nothing live is `missing`.
622
+ const chosen = lineEntries.find(
623
+ (entry) => entry.design.id === stored && entry.design.follows === undefined,
624
+ );
625
+ if (chosen === undefined) return { kind: "missing", id: stored };
626
+ if (!chosen.types.includes(customType)) return { kind: "not-covered", id: stored };
627
+ return { kind: "design", design: chosen.design };
628
+ }
629
+
630
+ // ---------------------------------------------------------------------------------------------
631
+ // Applying a design
632
+ // ---------------------------------------------------------------------------------------------
633
+
634
+ /**
635
+ * Hand one pass's rows to a design and take back the rows to draw. `undefined` means "draw what was
636
+ * passed in": a design that throws, or that answers something which is not an array of strings, loses
637
+ * its own output only — the host's rows stay on screen and the failure is reported (S5).
638
+ */
639
+ export function applyMessageDesign(
640
+ design: MessageDesignRegistration,
641
+ lines: readonly string[],
642
+ ctx: MessageDesignContext,
643
+ ): string[] | undefined {
644
+ let applied: unknown;
645
+ try {
646
+ applied = design.apply([...lines], ctx);
647
+ } catch (error) {
648
+ recordMessageDesignFailure(ctx.customType, design.id, errorMessage(error));
649
+ return undefined;
650
+ }
651
+ // Read by INDEX, never through the value's own methods: `every` skips a sparse array's holes (so
652
+ // `Array(3)` would pass and Pi would be handed `undefined` rows) and a plugin's own `every` is a
653
+ // function this module must not call at all — calling it threw into Pi's render loop.
654
+ if (!Array.isArray(applied) || !rowsAreStrings(applied)) {
655
+ recordMessageDesignFailure(
656
+ ctx.customType,
657
+ design.id,
658
+ "apply returned something that is not an array of strings; the host's own output is drawn " +
659
+ "instead. Return the rows to draw, e.g. `return lines`.",
660
+ );
661
+ return undefined;
662
+ }
663
+ // A CLEAN copy, built here: nothing the plugin attached to the array travels into Pi's frame, and
664
+ // a plugin that later mutates the array it returned cannot change what was already drawn.
665
+ const rows: string[] = [];
666
+ for (let index = 0; index < applied.length; index += 1) rows.push(applied[index] as string);
667
+ return rows;
668
+ }
669
+
670
+ /**
671
+ * Whether every position of this array holds a string, read BY INDEX and never through the value's own
672
+ * members. A `for` over the length, so a sparse array is refused instead of silently handing Pi
673
+ * `undefined` rows, and nothing here calls a method the plugin could have replaced.
674
+ *
675
+ * What a plugin hangs off the array itself is deliberately ignored rather than refused: a value whose
676
+ * `every` was replaced is still a row array if its positions are rows, and because the accepted rows
677
+ * are copied out by index (`applyMessageDesign`), no such member can ever travel into Pi's frame.
678
+ * Refusing it would drop a design's output over a property nobody reads.
679
+ */
680
+ function rowsAreStrings(value: readonly unknown[]): boolean {
681
+ for (let index = 0; index < value.length; index += 1) {
682
+ if (typeof value[index] !== "string") return false;
683
+ }
684
+ return true;
685
+ }
686
+
687
+ // ---------------------------------------------------------------------------------------------
688
+ // Diagnostics
689
+ // ---------------------------------------------------------------------------------------------
690
+
691
+ /** Record one design that failed to paint, once per (type, id, message). Read by the diagnostics record. */
692
+ export function recordMessageDesignFailure(
693
+ customType: string,
694
+ designId: string,
695
+ message: string,
696
+ ): void {
697
+ const state = messageDesignState();
698
+ const duplicate = state.failures.some(
699
+ (failure) =>
700
+ failure.customType === customType &&
701
+ failure.designId === designId &&
702
+ failure.message === message,
703
+ );
704
+ if (duplicate) return;
705
+ state.failures.push({ customType, designId, message });
706
+ if (state.failures.length > MAX_FAILURES) {
707
+ state.failures.splice(0, state.failures.length - MAX_FAILURES);
708
+ }
709
+ }
710
+
711
+ /** The failures the last passes recorded, oldest first. */
712
+ export function getMessageDesignFailures(): MessageDesignFailure[] {
713
+ return messageDesignState().failures.map((failure) => ({ ...failure }));
714
+ }
715
+
716
+ /** The replacements and collisions the registry recorded, oldest first. */
717
+ export function getMessageDesignConflicts(): MessageDesignConflict[] {
718
+ return messageDesignState().conflicts.map((conflict) => ({ ...conflict }));
719
+ }
720
+
721
+ /** How many persisted-selection reads happened since the last reset (S4's cost bound). */
722
+ export function getMessageDesignSelectionReads(): number {
723
+ return messageDesignState().selectionReads;
724
+ }
725
+
726
+ /** Test-only seam; deliberately not re-exported from `src/index.ts`. */
727
+ export function resetMessageDesignSelectionReads(): void {
728
+ messageDesignState().selectionReads = 0;
729
+ }
730
+
731
+ /** Test-only seam: empties the registry, the conflicts and the failures in place. */
732
+ export function resetMessageDesignsForTests(): void {
733
+ const state = messageDesignState();
734
+ state.entries.length = 0;
735
+ state.conflicts.length = 0;
736
+ state.failures.length = 0;
737
+ state.selectionReads = 0;
738
+ }
739
+
740
+ /**
741
+ * The error text for a stored value the wiring cannot use, kept here so the message and the record live
742
+ * together.
743
+ */
744
+ export function messageDesignErrorMessage(error: unknown): string {
745
+ return errorMessage(error);
746
+ }