pi-odd-worktree 3.15.0 → 3.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +48 -25
  2. package/extensions/odd-worktree-tools.ts +64 -211
  3. package/lib/shell-api/api.ts +523 -0
  4. package/lib/shell-api/arm.ts +83 -0
  5. package/lib/shell-api/bus.ts +1389 -0
  6. package/lib/shell-api/capture.ts +1340 -0
  7. package/lib/shell-api/card-style-line.ts +112 -0
  8. package/lib/shell-api/card-style-rows.ts +390 -0
  9. package/lib/shell-api/card-style-transform.ts +862 -0
  10. package/lib/shell-api/card-style-wiring.ts +477 -0
  11. package/lib/shell-api/card-styles.ts +153 -0
  12. package/lib/shell-api/config.ts +71 -0
  13. package/lib/shell-api/extension.ts +247 -0
  14. package/lib/shell-api/hook.ts +322 -0
  15. package/lib/shell-api/index.ts +88 -0
  16. package/lib/shell-api/message-design-adoption.ts +549 -0
  17. package/lib/shell-api/message-design-rows.ts +313 -0
  18. package/lib/shell-api/message-design-wiring.ts +369 -0
  19. package/lib/shell-api/message-designs.ts +746 -0
  20. package/lib/shell-api/notices.ts +137 -0
  21. package/lib/shell-api/plugin-lines.ts +877 -0
  22. package/lib/shell-api/presence.ts +258 -0
  23. package/lib/shell-api/repaint.ts +351 -0
  24. package/lib/shell-api/row-labels.ts +146 -0
  25. package/lib/shell-api/row-names.ts +273 -0
  26. package/lib/shell-api/row-origin.ts +144 -0
  27. package/lib/shell-api/rows.ts +591 -0
  28. package/lib/shell-api/section-panel.ts +378 -0
  29. package/lib/shell-api/section-pointer.ts +164 -0
  30. package/lib/shell-api/sections-preview.ts +275 -0
  31. package/lib/shell-api/sections-rows.ts +133 -0
  32. package/lib/shell-api/sidebar-render.ts +705 -0
  33. package/lib/shell-api/sidebar.ts +1126 -0
  34. package/lib/shell-api/store.ts +279 -0
  35. package/lib/shell-api/tool-design-adoption.ts +263 -0
  36. package/lib/shell-api/tool-design-rows.ts +307 -0
  37. package/lib/shell-api/tool-design-wiring.ts +481 -0
  38. package/lib/shell-api/tool-designs.ts +1411 -0
  39. package/lib/shell-api/transform-pipeline.ts +351 -0
  40. package/lib/shell-api/types.ts +803 -0
  41. package/lib/shell-api/visibility.ts +154 -0
  42. package/lib/user-prompt-card.js +48 -2
  43. package/package.json +3 -2
  44. package/tools/files-bridge.test.js +81 -66
  45. package/tools/fixtures/load-extension.js +40 -18
  46. package/tools/issues-command.test.js +4 -7
  47. package/tools/issues-section.test.js +71 -81
  48. package/tools/odd-rail-wiring.test.js +16 -10
  49. package/tools/package-surface.test.js +42 -13
  50. package/tools/prs-command.test.js +11 -6
  51. package/tools/shell-api/api.test.ts +484 -0
  52. package/tools/shell-api/apply-on-move.test.ts +529 -0
  53. package/tools/shell-api/arm.test.ts +220 -0
  54. package/tools/shell-api/bridge-ready.test.ts +309 -0
  55. package/tools/shell-api/bus.test.ts +194 -0
  56. package/tools/shell-api/button-rows.test.ts +435 -0
  57. package/tools/shell-api/capture.test.ts +583 -0
  58. package/tools/shell-api/card-style-rows.test.ts +493 -0
  59. package/tools/shell-api/card-style-transform.test.ts +379 -0
  60. package/tools/shell-api/card-style-wiring.test.ts +258 -0
  61. package/tools/shell-api/card-styles-e2e.test.ts +502 -0
  62. package/tools/shell-api/card-styles.test.ts +324 -0
  63. package/tools/shell-api/card-transcript-path.test.ts +178 -0
  64. package/tools/shell-api/compatibility-regression.test.mjs +64 -0
  65. package/tools/shell-api/config.test.ts +93 -0
  66. package/tools/shell-api/docs-coverage.test.ts +82 -0
  67. package/tools/shell-api/e2e.test.ts +562 -0
  68. package/tools/shell-api/example-bash-identity.test.ts +372 -0
  69. package/tools/shell-api/example-bash-matrix.test.ts +856 -0
  70. package/tools/shell-api/example-designs.test.ts +737 -0
  71. package/tools/shell-api/example-neon-transform.test.ts +283 -0
  72. package/tools/shell-api/example-plain-style.test.ts +1225 -0
  73. package/tools/shell-api/extension.test.ts +157 -0
  74. package/tools/shell-api/fake-events.ts +58 -0
  75. package/tools/shell-api/fake-host.ts +211 -0
  76. package/tools/shell-api/fake-sidebar.ts +516 -0
  77. package/tools/shell-api/fake-transcript.ts +486 -0
  78. package/tools/shell-api/frame-telemetry.test.ts +317 -0
  79. package/tools/shell-api/hook.test.ts +196 -0
  80. package/tools/shell-api/manifest.test.ts +47 -0
  81. package/tools/shell-api/message-design-adoption.test.ts +611 -0
  82. package/tools/shell-api/message-design-follows.test.ts +361 -0
  83. package/tools/shell-api/message-design-pi-release.test.mjs +157 -0
  84. package/tools/shell-api/message-design-regressions.test.mjs +162 -0
  85. package/tools/shell-api/message-design-rows.test.ts +266 -0
  86. package/tools/shell-api/message-design-wiring.test.ts +362 -0
  87. package/tools/shell-api/message-designs.test.ts +339 -0
  88. package/tools/shell-api/new-category.test.ts +1101 -0
  89. package/tools/shell-api/notices.test.ts +292 -0
  90. package/tools/shell-api/plugin-integration-lines.test.ts +827 -0
  91. package/tools/shell-api/presence.test.ts +396 -0
  92. package/tools/shell-api/rail-part-hits.test.ts +281 -0
  93. package/tools/shell-api/rail-surfaces.test.ts +402 -0
  94. package/tools/shell-api/rail-width.test.ts +406 -0
  95. package/tools/shell-api/regression.test.ts +434 -0
  96. package/tools/shell-api/repaint-api.test.ts +200 -0
  97. package/tools/shell-api/reserved-categories.test.ts +250 -0
  98. package/tools/shell-api/row-labels.test.ts +261 -0
  99. package/tools/shell-api/row-names.test.ts +407 -0
  100. package/tools/shell-api/row-origin.test.ts +395 -0
  101. package/tools/shell-api/row-placement-regression.test.ts +797 -0
  102. package/tools/shell-api/row-placement.test.ts +410 -0
  103. package/tools/shell-api/section-interaction.test.ts +364 -0
  104. package/tools/shell-api/section-panel.test.ts +430 -0
  105. package/tools/shell-api/section-placement-rail.test.ts +390 -0
  106. package/tools/shell-api/section-placement.test.ts +386 -0
  107. package/tools/shell-api/sections-preview.test.ts +312 -0
  108. package/tools/shell-api/sections-rows.test.ts +293 -0
  109. package/tools/shell-api/sidebar-backend.test.ts +477 -0
  110. package/tools/shell-api/sidebar-e2e.test.ts +317 -0
  111. package/tools/shell-api/sidebar-hover.test.ts +276 -0
  112. package/tools/shell-api/sidebar-independent.test.ts +291 -0
  113. package/tools/shell-api/sidebar-render.test.ts +281 -0
  114. package/tools/shell-api/sidebar-sections.test.ts +247 -0
  115. package/tools/shell-api/store.test.ts +192 -0
  116. package/tools/shell-api/surface-repaint-cost.test.ts +520 -0
  117. package/tools/shell-api/tool-design-card-style.test.ts +308 -0
  118. package/tools/shell-api/tool-design-chain.test.ts +471 -0
  119. package/tools/shell-api/tool-design-cost.test.ts +591 -0
  120. package/tools/shell-api/tool-design-rows.test.ts +627 -0
  121. package/tools/shell-api/tool-design-scopes-audit.test.ts +212 -0
  122. package/tools/shell-api/tool-designs.test.ts +2412 -0
  123. package/tools/shell-api/transform-pipeline.test.ts +376 -0
  124. package/tools/shell-api/transforms-bus.test.ts +233 -0
  125. package/tools/shell-api/verifier-width-regressions.test.ts +147 -0
  126. package/tools/shell-api-rpc.test.js +189 -0
  127. package/tools/user-prompt-card.test.js +80 -10
@@ -0,0 +1,591 @@
1
+ /**
2
+ * The row build shared by both backends (S3 capture, S4 hook), so `registerRows` behaves
3
+ * identically whichever interception is active.
4
+ *
5
+ * The builder is pure with respect to the bus: it takes an ordered provider snapshot, calls each
6
+ * provider's `rows(ctx)` once, and isolates failures. It caches nothing — the bridge never holds
7
+ * row values (docs/state.md).
8
+ */
9
+
10
+ import {
11
+ resolveRowPlacements,
12
+ rowPlacementLandingText,
13
+ snapshotProviders,
14
+ type RowPlacementLandingRecord,
15
+ type RowPlacementResolution,
16
+ } from "./bus.ts";
17
+ import { getConfigHome } from "./config.ts";
18
+ import { recordNotice } from "./notices.ts";
19
+ import { clearRowNameRejections, rejectReservedCategory, rejectRowName } from "./row-names.ts";
20
+ import type { CustomizeRow, InlineHelpers, RowContext, RowProvider } from "./types.ts";
21
+
22
+ /** A provider that threw while its rows were built; all of that provider's rows were dropped. */
23
+ export interface RowBuildFailure {
24
+ providerId: string;
25
+ message: string;
26
+ rowsDropped: true;
27
+ }
28
+
29
+ export interface RowBuildResult {
30
+ rows: CustomizeRow[];
31
+ failures: RowBuildFailure[];
32
+ /** The providers this build fanned out to, in the same snapshot order. */
33
+ providers: RowProvider[];
34
+ /**
35
+ * One record per provider that did not throw, in snapshot order. Each `rows` array is that
36
+ * provider's staged block; capture and hook place these instead of re-deriving the fan-out.
37
+ */
38
+ blocks: RowBuildRecord[];
39
+ }
40
+
41
+ /** One provider's contribution to the most recent fan-out, kept for duplicate diagnostics. */
42
+ export interface RowBuildRecord {
43
+ providerId: string;
44
+ category: string;
45
+ rows: CustomizeRow[];
46
+ }
47
+
48
+ const ROWS_STATE = Symbol.for("gentle-shell-bridge.rows.state.v1");
49
+
50
+ /** The host's category for a row that names none (`lib/visual-customize-view.ts:387`). */
51
+ const HOST_DEFAULT_CATEGORY = "Settings";
52
+
53
+ interface RowsState {
54
+ /** Rows produced by the last menu build, per provider; `undefined` before any build. */
55
+ lastBuild?: RowBuildRecord[];
56
+ }
57
+
58
+ function rowsHost(): Record<symbol, unknown> {
59
+ // SAFETY: `globalThis` accepts symbol keys and only `rowsState()` writes this slot; a foreign
60
+ // value is rejected there before use.
61
+ return globalThis as unknown as Record<symbol, unknown>;
62
+ }
63
+
64
+ function rowsState(): RowsState {
65
+ const host = rowsHost();
66
+ const existing = host[ROWS_STATE];
67
+ if (isRowsState(existing)) return existing;
68
+ const created: RowsState = {};
69
+ host[ROWS_STATE] = created;
70
+ return created;
71
+ }
72
+
73
+ function isRowsState(value: unknown): value is RowsState {
74
+ return isRecord(value) && (value.lastBuild === undefined || Array.isArray(value.lastBuild));
75
+ }
76
+
77
+ /** The rows the last menu build actually received, or `undefined` when there has been no build. */
78
+ export function getLastRowBuild(): RowBuildRecord[] | undefined {
79
+ const last = rowsState().lastBuild;
80
+ return last === undefined ? undefined : last.map((record) => ({ ...record, rows: [...record.rows] }));
81
+ }
82
+
83
+ /** Test-only seam; deliberately not re-exported from `src/index.ts`. */
84
+ export function resetRowBuildStateForTests(): void {
85
+ delete rowsState().lastBuild;
86
+ }
87
+
88
+ /**
89
+ * Context for the capture backend, where the theme arrives as the host factory's second argument
90
+ * and the config home is resolved from the process (`./config.ts`).
91
+ */
92
+ export function createRowContext(theme: unknown): RowContext {
93
+ return { theme, configHome: getConfigHome() };
94
+ }
95
+
96
+ /**
97
+ * Context for the hook backend, where an unproven host registry may pass its own context. A
98
+ * usable `theme` and a string `configHome` are reused as given; anything missing is derived
99
+ * locally, so a provider always receives both fields.
100
+ */
101
+ export function contextFromHost(value: unknown): RowContext {
102
+ if (!isRecord(value)) return createRowContext(undefined);
103
+ return {
104
+ theme: "theme" in value ? value.theme : undefined,
105
+ configHome: typeof value.configHome === "string" ? value.configHome : getConfigHome(),
106
+ };
107
+ }
108
+
109
+ /**
110
+ * The row's visible text, when it can be read without running a plugin's throw into the build.
111
+ * A label function is evaluated exactly as the host would evaluate it when it renders, so a name
112
+ * cannot pass the build and break the menu; a throw leaves the row unvalidated (the host's own
113
+ * failure behaviour, unchanged).
114
+ */
115
+ function rowLabelText(row: CustomizeRow): string | undefined {
116
+ const label = row.label;
117
+ if (label === undefined) return undefined;
118
+ if (typeof label === "string") return label;
119
+ try {
120
+ const shown: unknown = label();
121
+ return typeof shown === "string" ? shown : undefined;
122
+ } catch {
123
+ return undefined;
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Apply the row-name shape to one provider row (N7, N8): its line name (`choice.setting`) and its
129
+ * visible label. Returns `false` when the row must not reach the host — the caller drops it, so the
130
+ * rejected name exists nowhere instead of being sanitized into something the author never wrote.
131
+ */
132
+ function acceptsRowName(providerId: string, row: CustomizeRow): boolean {
133
+ const setting = row.choice?.setting;
134
+ if (setting !== undefined && rejectRowName("rows", providerId, "line name", setting)) {
135
+ return false;
136
+ }
137
+ const label = rowLabelText(row);
138
+ if (label !== undefined && rejectRowName("rows", providerId, "row label", label)) {
139
+ return false;
140
+ }
141
+ return true;
142
+ }
143
+
144
+ /**
145
+ * Contain a BUTTON row's `action` (S16): a row with `action` and no `choice` is the host's own
146
+ * `Reset`/`Profiles` shape, and the host runs it on Enter/Space. This host catches a throw and
147
+ * reports it (`lib/visual-customize-view.ts:224-234`), but a host that does not — or an action that
148
+ * only returns a rejected promise nobody awaits — would put a plugin's failure in Pi's render loop.
149
+ * So the bridge catches it, reports it ONCE through the notice channel the diagnostics record lists
150
+ * (`./notices.ts` records an identical message+level once, so pressing the row again does not
151
+ * repeat it) and returns normally: the menu and every other row stay usable.
152
+ *
153
+ * The row is a shallow COPY — the provider's object is never mutated — and every other field is the
154
+ * same reference. A toggle row (one with a `choice`) is returned untouched: its action's failure
155
+ * behaviour is the host's and is not part of this rule.
156
+ */
157
+ function containButtonAction(providerId: string, row: CustomizeRow): CustomizeRow {
158
+ const action = row.action;
159
+ if (row.choice !== undefined || typeof action !== "function") return row;
160
+ const name = rowLabelText(row);
161
+ const where = name === undefined ? "a button row" : `the button row ${JSON.stringify(name)}`;
162
+ return {
163
+ ...row,
164
+ action: async (inline: InlineHelpers): Promise<void> => {
165
+ try {
166
+ await action(inline);
167
+ } catch (error) {
168
+ recordNotice(
169
+ `gentle-shell-bridge: ${where} from ${JSON.stringify(providerId)} failed: ` +
170
+ `${errorMessage(error)}. The menu stays open; fix the row's action.`,
171
+ "error",
172
+ );
173
+ }
174
+ },
175
+ };
176
+ }
177
+
178
+ /**
179
+ * Apply the bridge's ONE behaviour to a row that carries a choice (A1–A3): ←/→ moves the cursor,
180
+ * Enter applies. The host decides per row (`lib/visual-customize-view.ts:565` applies on the move only
181
+ * while `choice.applyOnMove !== false`), so a provider row that omits the field — every row before
182
+ * this rule — would change its value the moment the user steps onto it, with no `›` cursor and no
183
+ * "Enter applies". The bridge owns the menu integration, so it normalises rather than trusting the
184
+ * author: one behaviour for every row it contributes, including a provider's explicit `true`.
185
+ *
186
+ * The provider's row and `choice` are never mutated: the change is a shallow copy, every other field
187
+ * is the same reference, and a row that already conforms keeps its identity (the provider's object is
188
+ * what the host receives).
189
+ */
190
+ function confirmOnEnter(row: CustomizeRow): CustomizeRow {
191
+ const choice = row.choice;
192
+ if (choice === undefined || choice.applyOnMove === false) return row;
193
+ return { ...row, choice: { ...choice, applyOnMove: false } };
194
+ }
195
+
196
+ /**
197
+ * Fan out to the providers in subscription order, isolating failures: a provider that throws
198
+ * while building its rows loses exactly those rows, and every other provider still applies.
199
+ *
200
+ * Rows from one provider are staged first, so a mid-build throw drops all of them rather than
201
+ * half. A row without a category is shallow-cloned with its provider's category; a row the
202
+ * provider returned is never mutated.
203
+ *
204
+ * A row whose line name or label breaks the row-name shape is dropped as it is staged (N8): it is
205
+ * absent from the array the host receives AND from the build record the diagnostics record reads, so it is
206
+ * not part of the effective set. The rejection is recorded verbatim for the report; the bridge never
207
+ * rewrites a name it was given.
208
+ *
209
+ * A row that asks for a RESERVED category is dropped the same way (S15): `Keymaps` is the host's own
210
+ * interaction, so the row is refused and reported while its siblings still reach the menu. A
211
+ * provider whose OWN category is reserved loses every row — including one registered by a copy of
212
+ * this package older than the registration check (`./bus.ts`), so one rule holds however the bus was
213
+ * filled.
214
+ *
215
+ * Every row that carries a `choice` is staged with `applyOnMove: false` (A2), on a copy of the row
216
+ * and of its `choice` — see `confirmOnEnter`. A BUTTON row (S16) keeps no choice and gains none; its
217
+ * `action` is contained by `containButtonAction`.
218
+ */
219
+ export function buildRows(ctx: RowContext): RowBuildResult {
220
+ const providers = snapshotProviders();
221
+ const rows: CustomizeRow[] = [];
222
+ const failures: RowBuildFailure[] = [];
223
+ const buildRecords: RowBuildRecord[] = [];
224
+
225
+ for (const provider of providers) {
226
+ const staged: CustomizeRow[] = [];
227
+ // This build is the new evidence for this provider, so a rejection a previous build recorded
228
+ // does not outlive the name it described.
229
+ clearRowNameRejections("rows", provider.id);
230
+ try {
231
+ // A provider standing in the reserved page loses all of its rows: the refusal is about the
232
+ // page, not about one row of it.
233
+ if (!rejectReservedCategory(provider.id, provider.category)) {
234
+ for (const row of provider.rows(ctx)) {
235
+ if (!acceptsRowName(provider.id, row)) continue;
236
+ const withCategory =
237
+ row.category === undefined ? { ...row, category: provider.category } : row;
238
+ if (rejectReservedCategory(provider.id, withCategory.category)) continue;
239
+ staged.push(containButtonAction(provider.id, confirmOnEnter(withCategory)));
240
+ }
241
+ }
242
+ } catch (error) {
243
+ failures.push({
244
+ providerId: provider.id,
245
+ message: errorMessage(error),
246
+ rowsDropped: true,
247
+ });
248
+ continue;
249
+ }
250
+ buildRecords.push({ providerId: provider.id, category: provider.category, rows: staged });
251
+ rows.push(...staged);
252
+ }
253
+
254
+ rowsState().lastBuild = buildRecords;
255
+ return { rows, failures, providers, blocks: buildRecords };
256
+ }
257
+
258
+ /** Where one build's provider blocks go, and the array that results from placing them. */
259
+ export interface RowPlacementPlan {
260
+ /** Every provider row the plan inserts, in the order it holds in `planned`. */
261
+ rows: CustomizeRow[];
262
+ /** The complete array: the host rows by identity, with each provider's block at its slot. */
263
+ planned: CustomizeRow[];
264
+ /** The host's own categories in first-appearance order, for the diagnostics record. */
265
+ hostCategories: string[];
266
+ /** What the resolver says each opted-in provider asked for and where it should land. */
267
+ landings: RowPlacementLandingRecord[];
268
+ /** False when no provider named `placement` or `order`: the pre-feature tail append applies. */
269
+ optsIn: boolean;
270
+ }
271
+
272
+ /** The provider id inside a resolver anchor phrase (`"loon.news"`), or undefined for start/end. */
273
+ function anchoredProviderId(anchor: string): string | undefined {
274
+ if (!anchor.startsWith('"')) return undefined;
275
+ try {
276
+ const parsed: unknown = JSON.parse(anchor);
277
+ return typeof parsed === "string" ? parsed : undefined;
278
+ } catch {
279
+ return undefined;
280
+ }
281
+ }
282
+
283
+ /**
284
+ * Place a build's provider blocks into the host array (S4, S5, S6).
285
+ *
286
+ * `resolveRowPlacements` is the ONLY source of the draw order: this function turns its per-category
287
+ * blocks into insertion points, never re-sorting them. The host array is read, never mutated here:
288
+ * the caller applies `planned` in one in-place write, so no index can drift between splices.
289
+ *
290
+ * - a block's category is the ROW's actual category (`row.category ?? provider.category`), never the
291
+ * provider's declared one; a provider whose rows override it contributes one block per actual
292
+ * category, so an insertion point is a boundary of the category the renderer filters;
293
+ * - `start` inserts before the category's first host row; `after X` follows X's block, including
294
+ * when X is itself at `start`; `end` follows the category's own rows;
295
+ * - a category the host did not build has no boundary, so its blocks are appended after every host
296
+ * row, and the page appears after the host's pages (`new Set(...)` sees it);
297
+ * - the two fields ARE the opt-in: a provider that names neither keeps the pre-feature tail append
298
+ * exactly, in subscription order, while only opted-in providers are placed (S6). With no opted-in
299
+ * provider the plan is byte-for-byte the old `[...host, ...built rows]`;
300
+ * - an `after X` follower of an unopted X follows that provider's block IN THE TAIL, because the
301
+ * anchor's rows really are there (S9); chains keep the resolver's order;
302
+ * - host rows are never split: an insertion point is a block boundary, so a consecutive
303
+ * `choice.setting` pair stays consecutive.
304
+ */
305
+ export function planRowPlacement(
306
+ host: readonly CustomizeRow[],
307
+ providers: readonly RowProvider[],
308
+ blocks: readonly RowBuildRecord[],
309
+ ): RowPlacementPlan {
310
+ const spans = new Map<string, { first: number; last: number }>();
311
+ const hostCategories: string[] = [];
312
+ for (let index = 0; index < host.length; index++) {
313
+ const row = host[index];
314
+ const category = row.category ?? HOST_DEFAULT_CATEGORY;
315
+ const span = spans.get(category);
316
+ if (span === undefined) {
317
+ spans.set(category, { first: index, last: index });
318
+ hostCategories.push(category);
319
+ } else {
320
+ span.last = index;
321
+ }
322
+ }
323
+
324
+ const categoriesByProvider = new Map<string, string[]>();
325
+ const rowsByProviderCategory = new Map<string, Map<string, CustomizeRow[]>>();
326
+ for (const block of blocks) {
327
+ const categories = categoriesByProvider.get(block.providerId) ?? [];
328
+ const perCategory = rowsByProviderCategory.get(block.providerId) ?? new Map();
329
+ rowsByProviderCategory.set(block.providerId, perCategory);
330
+ for (const row of block.rows) {
331
+ const category = row.category ?? block.category;
332
+ if (!categories.includes(category)) categories.push(category);
333
+ const list = perCategory.get(category) ?? [];
334
+ list.push(row);
335
+ perCategory.set(category, list);
336
+ }
337
+ categoriesByProvider.set(block.providerId, categories);
338
+ }
339
+ for (const provider of providers) {
340
+ if (!categoriesByProvider.has(provider.id)) {
341
+ categoriesByProvider.set(provider.id, [provider.category]);
342
+ }
343
+ }
344
+
345
+ const optedIn = new Set(
346
+ providers
347
+ .filter((provider) => provider.placement !== undefined || provider.order !== undefined)
348
+ .map((provider) => provider.id),
349
+ );
350
+ const tailSegments = blocks
351
+ .filter((block) => !optedIn.has(block.providerId))
352
+ .map((block) => ({ providerId: block.providerId, rows: block.rows }));
353
+ const unoptedRows: CustomizeRow[] = [];
354
+ for (const segment of tailSegments) unoptedRows.push(...segment.rows);
355
+
356
+ if (optedIn.size === 0) {
357
+ // S6: no placement and no order anywhere is the pre-feature path, verbatim.
358
+ return {
359
+ rows: unoptedRows,
360
+ planned: [...host, ...unoptedRows],
361
+ hostCategories,
362
+ landings: [],
363
+ optsIn: false,
364
+ };
365
+ }
366
+
367
+ const resolutions = resolveRowPlacements(providers, hostCategories, categoriesByProvider);
368
+ const rowsOf = (resolution: RowPlacementResolution): CustomizeRow[] =>
369
+ rowsByProviderCategory.get(resolution.provider.id)?.get(resolution.category) ?? [];
370
+ const landings: RowPlacementLandingRecord[] = [];
371
+ for (const resolution of resolutions) {
372
+ if (!optedIn.has(resolution.provider.id)) continue;
373
+ if (rowsOf(resolution).length === 0) continue;
374
+ landings.push({
375
+ providerId: resolution.provider.id,
376
+ category: resolution.category,
377
+ requested: resolution.requested,
378
+ landed: rowPlacementLandingText(resolution),
379
+ ...(resolution.reason === undefined ? {} : { reason: resolution.reason }),
380
+ });
381
+ }
382
+
383
+ const byCategory = new Map<string, RowPlacementResolution[]>();
384
+ const resolutionByKey = new Map<string, RowPlacementResolution>();
385
+ const resolutionKey = (providerId: string, category: string): string =>
386
+ JSON.stringify([providerId, category]);
387
+ for (const resolution of resolutions) {
388
+ const list = byCategory.get(resolution.category);
389
+ if (list === undefined) byCategory.set(resolution.category, [resolution]);
390
+ else list.push(resolution);
391
+ resolutionByKey.set(resolutionKey(resolution.provider.id, resolution.category), resolution);
392
+ }
393
+
394
+ // An unopted provider's rows live in the tail, so a follower that asks for `after X` has to land
395
+ // in that tail too. Walk the resolver's own anchors: the follower must stay there only while every
396
+ // hop is an honoured provider anchor; a fallback reason ends the walk, because the resolver already
397
+ // placed that block at its category end.
398
+ const unoptedIds = new Set(
399
+ providers.filter((provider) => !optedIn.has(provider.id)).map((provider) => provider.id),
400
+ );
401
+ const tailRootOf = (resolution: RowPlacementResolution): string | undefined => {
402
+ const seen = new Set<string>();
403
+ let current = resolution.provider.id;
404
+ while (!seen.has(current)) {
405
+ if (unoptedIds.has(current)) return current;
406
+ seen.add(current);
407
+ const hop = resolutionByKey.get(resolutionKey(current, resolution.category));
408
+ if (hop === undefined || hop.reason !== undefined) return undefined;
409
+ const next = anchoredProviderId(hop.anchor);
410
+ if (next === undefined) return undefined;
411
+ current = next;
412
+ }
413
+ return undefined;
414
+ };
415
+ const tailFollowers = new Map<string, RowPlacementResolution[]>();
416
+ const tailFollowerKeys = new Set<string>();
417
+ for (const resolution of resolutions) {
418
+ if (!optedIn.has(resolution.provider.id)) continue;
419
+ if (rowsOf(resolution).length === 0) continue;
420
+ const root = tailRootOf(resolution);
421
+ if (root === undefined) continue;
422
+ tailFollowerKeys.add(resolutionKey(resolution.provider.id, resolution.category));
423
+ const list = tailFollowers.get(root);
424
+ if (list === undefined) tailFollowers.set(root, [resolution]);
425
+ else list.push(resolution);
426
+ }
427
+
428
+ // Split one category's resolver output into the start side and the end side. The resolver emits
429
+ // every block that hangs off `start` before every block that hangs off `end`, so the first direct
430
+ // `end` anchor is the boundary; a follower keeps the side of its anchor.
431
+ const startByCategory = new Map<string, CustomizeRow[]>();
432
+ const endByCategory = new Map<string, CustomizeRow[]>();
433
+ for (const [category, list] of byCategory) {
434
+ let side: "start" | "end" = "start";
435
+ const startRows: CustomizeRow[] = [];
436
+ const endRows: CustomizeRow[] = [];
437
+ for (const resolution of list) {
438
+ if (resolution.anchor === "end") side = "end";
439
+ if (!optedIn.has(resolution.provider.id)) continue;
440
+ if (tailFollowerKeys.has(resolutionKey(resolution.provider.id, resolution.category))) {
441
+ continue;
442
+ }
443
+ const rows = rowsOf(resolution);
444
+ if (rows.length === 0) continue;
445
+ if (side === "start") startRows.push(...rows);
446
+ else endRows.push(...rows);
447
+ }
448
+ if (startRows.length > 0) startByCategory.set(category, startRows);
449
+ if (endRows.length > 0) endByCategory.set(category, endRows);
450
+ }
451
+
452
+ const before = new Map<number, CustomizeRow[]>();
453
+ const after = new Map<number, CustomizeRow[]>();
454
+ const append: CustomizeRow[] = [];
455
+ for (const [category, rows] of startByCategory) {
456
+ const span = spans.get(category);
457
+ if (span === undefined) {
458
+ append.push(...rows);
459
+ continue;
460
+ }
461
+ const existing = before.get(span.first) ?? [];
462
+ before.set(span.first, [...existing, ...rows]);
463
+ }
464
+ for (const [category, rows] of endByCategory) {
465
+ const span = spans.get(category);
466
+ if (span === undefined) {
467
+ append.push(...rows);
468
+ continue;
469
+ }
470
+ const existing = after.get(span.last) ?? [];
471
+ after.set(span.last, [...existing, ...rows]);
472
+ }
473
+
474
+ const planned: CustomizeRow[] = [];
475
+ const inserted: CustomizeRow[] = [];
476
+ for (let index = 0; index < host.length; index++) {
477
+ const beforeRows = before.get(index);
478
+ if (beforeRows !== undefined) {
479
+ planned.push(...beforeRows);
480
+ inserted.push(...beforeRows);
481
+ }
482
+ planned.push(host[index]);
483
+ const afterRows = after.get(index);
484
+ if (afterRows !== undefined) {
485
+ planned.push(...afterRows);
486
+ inserted.push(...afterRows);
487
+ }
488
+ }
489
+ if (append.length > 0) {
490
+ planned.push(...append);
491
+ inserted.push(...append);
492
+ }
493
+ const tailRows: CustomizeRow[] = [];
494
+ for (const segment of tailSegments) {
495
+ tailRows.push(...segment.rows);
496
+ for (const follower of tailFollowers.get(segment.providerId) ?? []) {
497
+ tailRows.push(...rowsOf(follower));
498
+ }
499
+ }
500
+ // An anchor with no surviving block has no tail segment to follow; keep its rows rather than drop
501
+ // them, at the tail's end, and leave the resolver's landing text unchanged for the report.
502
+ for (const [root, followers] of tailFollowers) {
503
+ if (tailSegments.some((segment) => segment.providerId === root)) continue;
504
+ for (const follower of followers) tailRows.push(...rowsOf(follower));
505
+ }
506
+ if (tailRows.length > 0) {
507
+ planned.push(...tailRows);
508
+ inserted.push(...tailRows);
509
+ }
510
+ return { rows: inserted, planned, hostCategories, landings, optsIn: true };
511
+ }
512
+
513
+ /**
514
+ * The landings to report when the planned write could not be made: every block that would have
515
+ * moved stays at the end, with why. A block the resolver ALREADY fell back to `end` keeps its exact
516
+ * reason (malformed, unknown id, cycle, unbuilt page), which the diagnostics record pins.
517
+ */
518
+ export function rowPlacementLandingsAfterSkippedMove(
519
+ plan: RowPlacementPlan,
520
+ problem: string,
521
+ ): RowPlacementLandingRecord[] {
522
+ return plan.landings.map((landing) =>
523
+ landing.landed === "end"
524
+ ? landing
525
+ : {
526
+ ...landing,
527
+ landed: "end",
528
+ reason: `the block stayed at the end because ${problem}`,
529
+ },
530
+ );
531
+ }
532
+
533
+ /**
534
+ * Why writing `planned` into `array` would be refused, checked BEFORE any mutation. An array index
535
+ * that is not writable used to make `splice` overwrite an earlier row and then throw, leaving a
536
+ * half-applied menu (S6); the caller now skips the move and reports the landing instead.
537
+ */
538
+ export function plannedArrayWriteProblem(
539
+ array: readonly CustomizeRow[],
540
+ planned: readonly CustomizeRow[],
541
+ ): string | undefined {
542
+ try {
543
+ const length = Object.getOwnPropertyDescriptor(array, "length");
544
+ if (length !== undefined && length.writable === false) {
545
+ return "the host array's length is read-only";
546
+ }
547
+ const extensible = Object.isExtensible(array);
548
+ for (let index = 0; index < planned.length; index++) {
549
+ const descriptor = Object.getOwnPropertyDescriptor(array, String(index));
550
+ if (descriptor !== undefined) {
551
+ if (descriptor.writable === false) {
552
+ return `the host array's index ${index} is read-only`;
553
+ }
554
+ } else if (!extensible) {
555
+ return "the host array is not extensible";
556
+ }
557
+ }
558
+ for (let index = planned.length; index < array.length; index++) {
559
+ const descriptor = Object.getOwnPropertyDescriptor(array, String(index));
560
+ if (descriptor !== undefined && descriptor.configurable === false) {
561
+ return `the host array's index ${index} cannot be removed`;
562
+ }
563
+ }
564
+ return undefined;
565
+ } catch {
566
+ return "the host array could not be inspected";
567
+ }
568
+ }
569
+
570
+ /** Apply a plan in one in-place write, or change nothing and return why it could not be done. */
571
+ export function applyRowPlacementPlan(
572
+ array: CustomizeRow[],
573
+ planned: readonly CustomizeRow[],
574
+ ): string | undefined {
575
+ const problem = plannedArrayWriteProblem(array, planned);
576
+ if (problem !== undefined) return problem;
577
+ try {
578
+ array.splice(0, array.length, ...planned);
579
+ return undefined;
580
+ } catch {
581
+ return "the host array refused the planned write";
582
+ }
583
+ }
584
+
585
+ export function isRecord(value: unknown): value is Record<string, unknown> {
586
+ return typeof value === "object" && value !== null && !Array.isArray(value);
587
+ }
588
+
589
+ function errorMessage(error: unknown): string {
590
+ return error instanceof Error ? error.message : String(error);
591
+ }