@aestheticfunction/dspack-emit 0.4.1 → 0.6.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 (72) hide show
  1. package/README.md +16 -6
  2. package/dist/cli.js +56 -0
  3. package/dist/index.d.ts +4 -1
  4. package/dist/index.js +3 -1
  5. package/dist/targets/a2ui/diagnostics.d.ts +110 -0
  6. package/dist/targets/a2ui/diagnostics.js +94 -0
  7. package/dist/targets/a2ui/surface.d.ts +28 -9
  8. package/dist/targets/a2ui/surface.js +1004 -222
  9. package/dist/transform/desugar.d.ts +32 -0
  10. package/dist/transform/desugar.js +156 -0
  11. package/dist/transform/emit.js +59 -0
  12. package/dist/transform/index.js +4 -0
  13. package/dist/transform/mapping.d.ts +0 -6
  14. package/dist/transform/mapping.js +66 -2
  15. package/dist/transform/model.d.ts +368 -0
  16. package/dist/transform/model.js +169 -0
  17. package/dist/transform/parse-v2.d.ts +109 -0
  18. package/dist/transform/parse-v2.js +479 -0
  19. package/dist/transform/profile-load.d.ts +7 -6
  20. package/dist/transform/profile-load.js +99 -20
  21. package/dist/transform/profile-schema-v2.d.ts +9 -0
  22. package/dist/transform/profile-schema-v2.js +608 -0
  23. package/dist/transform/profiles.d.ts +31 -1
  24. package/dist/transform/scaffold.d.ts +29 -12
  25. package/dist/transform/scaffold.js +91 -31
  26. package/dist/transform/shadcn-v2-respelling.d.ts +77 -0
  27. package/dist/transform/shadcn-v2-respelling.js +456 -0
  28. package/dist/transform/validate-v2.d.ts +36 -0
  29. package/dist/transform/validate-v2.js +136 -0
  30. package/dist/types.d.ts +23 -0
  31. package/dist/validate/ajv.js +96 -25
  32. package/dist/validate/meta/a2ui-catalog.meta.0_9_1.json +39 -0
  33. package/dist/validate/meta/a2ui-catalog.meta.1_0.json +34 -0
  34. package/package.json +2 -2
  35. package/src/__snapshots__/byte-neutral.test.ts.snap +66 -0
  36. package/src/a0.test.ts +235 -0
  37. package/src/byte-neutral.test.ts +246 -0
  38. package/src/cli.ts +60 -0
  39. package/src/dangling-ref.test.ts +118 -0
  40. package/src/desugar.test.ts +162 -0
  41. package/src/engine-boundary.test.ts +248 -0
  42. package/src/eval-fixture.test.ts +102 -0
  43. package/src/functions.test.ts +182 -0
  44. package/src/index.ts +4 -1
  45. package/src/layered-dissolution.test.ts +139 -0
  46. package/src/profile-load.test.ts +99 -1
  47. package/src/profile-v2.test.ts +369 -0
  48. package/src/review-findings.test.ts +292 -0
  49. package/src/schema-mirrors.test.ts +5 -0
  50. package/src/surface-fidelity.test.ts +213 -0
  51. package/src/t1.test.ts +369 -0
  52. package/src/t2.test.ts +222 -0
  53. package/src/t3.test.ts +304 -0
  54. package/src/t4.test.ts +278 -0
  55. package/src/targets/a2ui/diagnostics.ts +136 -0
  56. package/src/targets/a2ui/surface.ts +1468 -235
  57. package/src/transform/desugar.ts +194 -0
  58. package/src/transform/emit.ts +65 -0
  59. package/src/transform/index.ts +5 -0
  60. package/src/transform/mapping.ts +60 -2
  61. package/src/transform/model.ts +427 -0
  62. package/src/transform/parse-v2.ts +608 -0
  63. package/src/transform/profile-load.ts +104 -22
  64. package/src/transform/profile-schema-v2.ts +608 -0
  65. package/src/transform/profile.v2.schema.json +600 -0
  66. package/src/transform/profiles.ts +32 -1
  67. package/src/transform/scaffold.ts +124 -47
  68. package/src/transform/shadcn-v2-respelling.ts +475 -0
  69. package/src/transform/validate-v2.ts +174 -0
  70. package/src/types.ts +32 -0
  71. package/src/validate/ajv.ts +89 -26
  72. package/src/validate-v2.test.ts +173 -0
@@ -8,16 +8,28 @@
8
8
  * id-referenced component list.
9
9
  *
10
10
  * Deterministic by construction: same surface + contract + profile => same
11
- * messages. All projection knowledge is data in the profile's `surfacePlan`
12
- * directives; this engine contains no component-name-specific code.
11
+ * messages. All projection knowledge is data, and this engine contains no
12
+ * component-name-specific code.
13
+ *
14
+ * It also contains no DIRECTIVE-specific code. The engine reads only the
15
+ * internal Identity / Route / Collect model (transform/model.ts); the authored
16
+ * v1 directives are surface syntax that transform/desugar.ts translates, and
17
+ * that module is the only compatibility boundary. src/engine-boundary.test.ts
18
+ * fails if a legacy directive name reappears here.
19
+ *
20
+ * Two orderings are declared rather than emergent, because both are observable
21
+ * in hashed artifacts and neither should be decided by the shape of a method:
22
+ * `WriteOrder` fixes when each route and collect writes (object key order), and
23
+ * the diagnostics' phase/band keys fix the emitted warning sequence.
13
24
  *
14
25
  * Honest scope (mirrors MAPPING.md):
15
- * - Compound composition flattens per the documented casualty mapping
16
- * (`subText` / `subButtonText` consume the node's whole subtree). When no
17
- * label-bearing component carries a `subButtonText` label, the first
18
- * direct text under that sub is LIFTED (audited, `surface-label-lifted`;
19
- * spec v0.4 amendment 2026-07-04) — relocation of existing text, never
20
- * synthesis.
26
+ * - Compound composition flattens per the documented casualty mapping:
27
+ * consuming routes absorb the node's whole subtree, resolved by ONE
28
+ * document-order walk so that position, not declaration order, decides
29
+ * which sibling claims a destination. When no label-bearing component
30
+ * carries a label, the first direct text under that sub is LIFTED (audited,
31
+ * `surface-label-lifted`; spec v0.4 amendment 2026-07-04) — relocation of
32
+ * existing text, never synthesis.
21
33
  * - A2UI requires declarative actions the surface format does not express;
22
34
  * they are synthesized (deterministic event-name slug) and recorded as
23
35
  * warnings, not silently invented.
@@ -26,10 +38,14 @@
26
38
  * are version-independent and instance-validate (gate A3) against both
27
39
  * generated catalogs.
28
40
  */
29
- import type { DspackDoc, DspackSurface, Json, SurfaceNode, Warning } from "../../types.js";
41
+ import type { DspackDoc, DspackSurface, Json, SurfaceFidelityEntry, SurfaceNode, Warning } from "../../types.js";
30
42
  import { shadcnProfile, type ComponentPlan, type Profile } from "../../transform/profiles.js";
31
43
  import { toHex6 } from "../../transform/color.js";
32
44
  import { collectChildren } from "../csr.js";
45
+ import { Band, Diagnostics, Phase } from "./diagnostics.js";
46
+ import { surfaceModelOf } from "../../transform/desugar.js";
47
+ import { validateProfileAgainstContract } from "../../transform/validate-v2.js";
48
+ import { describeSelector, emptySurfaceModel, isCollect, WriteOrder, type Collect, type Donation, type Route, type Selector, type SurfaceModel } from "../../transform/model.js";
33
49
 
34
50
  export class EmitSurfaceError extends Error {
35
51
  constructor(
@@ -46,6 +62,13 @@ export interface EmitSurfaceResult {
46
62
  messages: Json[];
47
63
  /** Every synthesis/drop performed — nothing is silent. */
48
64
  warnings: Warning[];
65
+ /**
66
+ * The transformation ledger: what every route, collect, projection, and
67
+ * synthesis DID to this surface — source, destination, originating profile
68
+ * rule, kind, and fidelity class. Additive alongside the byte-frozen
69
+ * messages and warnings; `--strict-surface` fails on configured classes.
70
+ */
71
+ fidelity: SurfaceFidelityEntry[];
49
72
  }
50
73
 
51
74
  export interface EmitSurfaceOptions {
@@ -73,12 +96,27 @@ export function emitSurface(
73
96
  );
74
97
  }
75
98
 
99
+ // A v2 profile that does not fit this contract refuses before any node
100
+ // emits — the same gate transform() runs, so surface-only callers get the
101
+ // same fail-closed story.
102
+ validateProfileAgainstContract(profile, doc);
103
+
76
104
  const byDspackId = new Map<string, ComponentPlan>();
77
105
  for (const plan of profile.components) {
78
106
  if (plan.dspackId) byDspackId.set(plan.dspackId, plan);
79
107
  }
108
+ // T1: a transparent ROOT still needs an instance renderers can start from
109
+ // (components[0], id "root"). The established arity discipline answers it:
110
+ // the root dissolves and its risen children wrap in the profile's
111
+ // synthesized wrap component, which becomes the root — synthesis, recorded,
112
+ // never silent. (ex.expense-report-form roots at `form` directly; refusing
113
+ // transparent roots would refuse the exact failure T1 exists to fix.)
80
114
  const emitter = new SurfaceEmitter(profile, byDspackId);
81
- const rootId = emitter.emitNode(surface.root, "$.root");
115
+ const rootPlan = byDspackId.get(surface.root.component);
116
+ const rootId =
117
+ rootPlan && surfaceModelOf(rootPlan).transparent
118
+ ? emitter.emitTransparentRoot(surface.root, "$.root")
119
+ : emitter.emitNode(surface.root, "$.root");
82
120
 
83
121
  const surfaceId = options.surfaceId ?? slug(surface.intent);
84
122
  const theme: Json = { agentDisplayName: `${doc.name} via dspack` };
@@ -100,7 +138,7 @@ export function emitSurface(
100
138
  },
101
139
  ];
102
140
  void rootId; // root is components[0] by construction (pre-order emission)
103
- return { messages, warnings: emitter.warnings };
141
+ return { messages, warnings: emitter.diagnostics.ordered(), fidelity: emitter.diagnostics.orderedFidelity() };
104
142
  }
105
143
 
106
144
  function primaryColor(doc: DspackDoc, profile: Profile): string | null {
@@ -116,10 +154,28 @@ export function slug(value: string): string {
116
154
  .replace(/^_+|_+$/g, "");
117
155
  return s || "surface";
118
156
  }
157
+ /**
158
+ * T1: one donation, resolved at its dissolving boundary and carried
159
+ * EXPLICITLY in the rewritten child list until the receiving control's own
160
+ * emission applies it as a first-wins pre-write. The committed instance of
161
+ * another node is never mutated; ordering cannot affect output because the
162
+ * write happens inside the control's own construction, in donation order.
163
+ */
164
+ interface PendingDonation {
165
+ prop: string;
166
+ value: string;
167
+ origin: string;
168
+ donorPath: string;
169
+ donorComponent: string;
170
+ }
171
+
172
+ type RewrittenChild =
173
+ | { node: SurfaceNode; suffix: string; donations?: PendingDonation[] }
174
+ | { text: string; textVariant: string };
119
175
 
120
176
  class SurfaceEmitter {
121
177
  readonly components: Json[] = [];
122
- readonly warnings: Warning[] = [];
178
+ readonly diagnostics = new Diagnostics();
123
179
  private readonly usedIds = new Set<string>();
124
180
 
125
181
  constructor(
@@ -127,8 +183,14 @@ class SurfaceEmitter {
127
183
  private readonly byDspackId: Map<string, ComponentPlan>,
128
184
  ) {}
129
185
 
130
- /** Emits the component for `node` (and its subtree) and returns its instance id. */
131
- emitNode(node: SurfaceNode, path: string): string {
186
+ /**
187
+ * Emits the component for `node` (and its subtree) and returns its instance id.
188
+ *
189
+ * Reads ONLY the internal model. The v1 directive names live exclusively in
190
+ * desugar.ts; if any of them appears below, the compatibility boundary has
191
+ * leaked (src/engine-boundary.test.ts fails on exactly that).
192
+ */
193
+ emitNode(node: SurfaceNode, path: string, treePath: readonly number[] = [], donations: PendingDonation[] = []): string {
132
194
  const plan = this.byDspackId.get(node.component);
133
195
  if (!plan) {
134
196
  // A declared casualty refuses with its authored reason — the refusal is
@@ -148,289 +210,1427 @@ class SurfaceEmitter {
148
210
  );
149
211
  }
150
212
 
213
+ const model = surfaceModelOf(plan);
214
+ const at = (band: Band, phase: Phase, rule = 0) =>
215
+ ({ treePath, band, phase, rule }) as const;
216
+
151
217
  // A2UI renderers begin at the component with id "root" (see the
152
218
  // hand-authored surfaces); the surface root always emits under that id.
153
- const id = path === "$.root" ? this.allocateId("root", path) : this.allocateId(node.id ?? plan.a2ui.toLowerCase(), path);
219
+ const id =
220
+ path === "$.root"
221
+ ? this.allocateId("root", path, at(Band.BeforeChildren, Phase.IdAllocation))
222
+ : this.allocateId(node.id ?? plan.a2ui.toLowerCase(), path, at(Band.BeforeChildren, Phase.IdAllocation));
154
223
  // Reserve the slot so parent components precede children in the flat list.
155
224
  const index = this.components.length;
156
225
  this.components.push({});
157
226
  const instance: Json = { id, component: plan.a2ui };
158
227
 
159
- this.applyPropMap(node, plan, instance, path);
160
- const sp = plan.surfacePlan ?? {};
161
- const consumesSubtree = Boolean(sp.subText || sp.subButtonText || sp.subTable);
228
+ this.applyPropMap(node, plan, model, instance, path, treePath);
229
+
230
+ // A declared casualty is an authored refusal: it must never be laundered
231
+ // into a parent's text fold. The plan-lookup gate above only fires when a
232
+ // casualty is emitted as its OWN node; a consuming route or a re-identified
233
+ // sub walks the subtree directly and would otherwise fold the casualty's
234
+ // text in with a mere warning.
235
+ if (model.consumesSubtree || Object.keys(model.subIdentity).length > 0) {
236
+ this.refuseConsumedCasualty(node, path);
237
+ }
238
+
239
+ // Routes and collects, in declared order. Ordering of OUTPUT is first-wins
240
+ // (except where a route declares `overwrite`); ordering of DIAGNOSTICS is
241
+ // the explicit phase model, never this loop's order.
242
+ this.applyOperations(node, model, instance, id, path, treePath);
243
+
244
+ // T1 donations: contextual values a dissolved wrapper handed to this
245
+ // control, applied AFTER the control's own writes, first-wins — inherited
246
+ // context fills what the control left absent and never beats its own
247
+ // authored content. The ledger records exactly what happened either way.
248
+ for (const d of donations) {
249
+ const landed = this.write(instance, d.prop, d.value as Json[keyof Json]);
250
+ this.diagnostics.pushFidelity(
251
+ {
252
+ source: `${d.donorPath} (${d.donorComponent}.text)`,
253
+ destination: `${d.prop} @ ${path} (${node.component})`,
254
+ origin: d.origin,
255
+ kind: landed ? "donated" : "dropped",
256
+ class: landed ? "maps-cleanly" : "lossy",
257
+ note: landed
258
+ ? `donated by '${d.donorComponent}' to '${node.component}' — the dissolving boundary's single eligible control`
259
+ : `'${d.prop}' already written on '${node.component}'; the donated value did not land`,
260
+ },
261
+ treePath,
262
+ Band.BeforeChildren,
263
+ Phase.PropMap,
264
+ );
265
+ }
266
+
267
+ if (!model.consumesSubtree) {
268
+ this.emitChildren(node, model, instance, id, path, treePath);
269
+ }
270
+
271
+ // The one loss channel nothing else ledgers: node text on a plan with no
272
+ // self.text route. v1 has always silently discarded it — warnings are
273
+ // byte-frozen, so the WARNING stays absent — but the ledger exists
274
+ // precisely so no discard is unaccounted. (Consuming plans are exempt:
275
+ // their document-order walk may legitimately read the node's own text.)
276
+ const readsSelfText = model.routes.some((r) => r.from.some((s) => s.kind === "self-text"));
277
+ if (node.text !== undefined && !readsSelfText && !model.consumesSubtree) {
278
+ this.diagnostics.pushFidelity(
279
+ {
280
+ source: `${path} (text)`,
281
+ destination: "(discarded)",
282
+ origin: "(no rule)",
283
+ kind: "dropped",
284
+ class: "lossy",
285
+ note: `'${node.component}' has no self.text route; its text was discarded`,
286
+ },
287
+ treePath,
288
+ Band.BeforeChildren,
289
+ Phase.PropMap,
290
+ );
291
+ }
292
+
293
+ this.components[index] = instance;
294
+ return id;
295
+ }
296
+
297
+ /**
298
+ * Applies every route and collect in declared WriteOrder — never in
299
+ * declaration order and never in traversal happenstance. Object key order is
300
+ * observable, so this sequence is part of the compatibility contract.
301
+ *
302
+ * Consuming routes are the one group resolved together: a compound is walked
303
+ * ONCE in document order and each destination takes the first thing it sees.
304
+ * That is not an implementation detail leaking through — it is what consuming
305
+ * a compound means, and resolving those routes independently would let
306
+ * declaration order decide which of two siblings wins.
307
+ */
308
+ private applyOperations(
309
+ node: SurfaceNode,
310
+ model: SurfaceModel,
311
+ instance: Json,
312
+ id: string,
313
+ path: string,
314
+ treePath: readonly number[],
315
+ ): void {
316
+ const consuming = model.routes
317
+ .map((route, rule) => ({ route, rule }))
318
+ .filter(({ route }) => route.order === WriteOrder.Consume);
319
+
320
+ const steps: Array<{ order: number; run: () => void }> = [];
162
321
 
163
- if (sp.structuralPassthrough) {
164
- for (const key of sp.structuralPassthrough) {
165
- const value = node.props?.[key];
166
- if (value !== undefined) instance[key] = value as Json[keyof Json];
322
+ for (const { route, rule } of model.routes.map((route, rule) => ({ route, rule }))) {
323
+ if (route.order === WriteOrder.Consume || route.order === WriteOrder.Children) continue;
324
+ if (route.order === WriteOrder.Slot) {
325
+ steps.push({ order: route.order, run: () => this.applySlotRoute(node, model, route, rule, instance, path, treePath) });
326
+ continue;
167
327
  }
328
+ steps.push({ order: route.order, run: () => this.applyRoute(node, route, rule, instance, id, path, treePath) });
168
329
  }
169
- if (sp.subText || sp.subButtonText) this.applySubContent(node, sp.subText ?? {}, sp.subButtonText ?? {}, instance, path);
170
- if (sp.subTable) this.applySubTable(node, sp.subTable, instance, path);
171
- if (sp.textProp && node.text !== undefined) instance[sp.textProp] = node.text;
172
- if (sp.textChildProp && node.text !== undefined) {
173
- instance[sp.textChildProp] = this.emitTextPrimitive(node.text, `${id}_label`, path);
330
+ for (const [rule, collect] of model.collects.entries()) {
331
+ if (collect.as.kind === "inline") continue;
332
+ steps.push({ order: collect.order, run: () => this.applyCollect(node, model, collect, rule, instance, path, treePath) });
174
333
  }
175
- if (sp.actionProp) {
176
- const eventName = slug(node.id ?? (instance.confirmLabel as string) ?? node.text ?? node.component);
177
- instance[sp.actionProp] = { event: { name: eventName, context: {} } };
178
- this.warnings.push({
179
- code: "surface-synthesized-action",
180
- message: `${path}: A2UI requires a declarative action on ${plan.a2ui}; synthesized event '${eventName}'.`,
181
- });
334
+ if (consuming.length > 0) {
335
+ steps.push({ order: WriteOrder.Consume, run: () => this.applyConsuming(node, consuming, instance, path, treePath) });
336
+ }
337
+ if (model.collects.some((c) => c.as.kind !== "inline")) {
338
+ steps.push({ order: WriteOrder.Collect + 1, run: () => this.closeCollects(node, model, path, treePath) });
339
+ }
340
+ if (model.routes.some((r) => r.order === WriteOrder.Slot)) {
341
+ steps.push({ order: WriteOrder.Slot + 1, run: () => this.closeSlots(node, model, path, treePath) });
182
342
  }
183
343
 
184
- if (!consumesSubtree) {
185
- const childNodes = sp.subFlatten ? this.flattenSubs(node, sp.subFlatten, path) : collectChildren(node);
186
- if (childNodes.length > 0) {
187
- const childIds = childNodes.map((child, i) =>
188
- "textVariant" in child
189
- ? this.emitTextPrimitive(child.text, `${id}_${slug(child.textVariant)}`, path, child.textVariant)
190
- : this.emitNode(child.node, `${path}${child.suffix}[${i}]`),
191
- );
192
- if (sp.childrenProp) {
193
- instance[sp.childrenProp] = childIds;
194
- } else if (sp.childProp) {
195
- instance[sp.childProp] = childIds.length === 1 ? childIds[0] : this.wrapInColumn(childIds, id, path);
196
- } else {
197
- throw new EmitSurfaceError(
198
- `component '${node.component}' has children but its surface plan declares no child slot`,
199
- path,
344
+ steps.sort((a, b) => a.order - b.order);
345
+ for (const step of steps) step.run();
346
+ }
347
+
348
+ /**
349
+ * One document-order walk serving every consuming route, then the audited
350
+ * lift for any destination still empty, then the composition warning.
351
+ */
352
+ private applyConsuming(
353
+ node: SurfaceNode,
354
+ consuming: Array<{ route: Route; rule: number }>,
355
+ instance: Json,
356
+ path: string,
357
+ treePath: readonly number[],
358
+ ): void {
359
+ const record = (route: Route, rule: number, nPath: string, component: string): void => {
360
+ this.diagnostics.pushFidelity(
361
+ {
362
+ source: `${nPath} (${component}.text)`,
363
+ destination: route.to.name,
364
+ origin: route.origin,
365
+ kind: "moved",
366
+ class: "maps-cleanly",
367
+ },
368
+ treePath,
369
+ Band.BeforeChildren,
370
+ Phase.SubContentFlatten,
371
+ rule,
372
+ );
373
+ };
374
+ const visit = (n: SurfaceNode, nPath: string, insideSubs: ReadonlySet<string>): void => {
375
+ for (const { route, rule } of consuming) {
376
+ if (instance[route.to.name] !== undefined) continue;
377
+ const primary = route.from[0];
378
+ if (primary.kind === "sub-text") {
379
+ if (primary.subs.includes(n.component) && n.text !== undefined) {
380
+ instance[route.to.name] = n.text;
381
+ record(route, rule, nPath, n.component);
382
+ }
383
+ } else if (primary.kind === "sub-label") {
384
+ if (n !== node && n.text !== undefined && primary.subs.some((sub) => insideSubs.has(sub))) {
385
+ const plan = this.byDspackId.get(n.component);
386
+ const bearsLabel = plan !== undefined && surfaceModelOf(plan).routes.some((r) => r.to.kind === "text-child");
387
+ if (bearsLabel) {
388
+ instance[route.to.name] = n.text;
389
+ record(route, rule, nPath, n.component);
390
+ }
391
+ }
392
+ }
393
+ }
394
+ const next = new Set(insideSubs);
395
+ for (const { route } of consuming) {
396
+ const primary = route.from[0];
397
+ if (primary.kind === "sub-label" && primary.subs.includes(n.component)) next.add(n.component);
398
+ }
399
+ collectChildren(n).forEach((child, i) => visit(child.node, `${nPath}${child.suffix}[${i}]`, next));
400
+ };
401
+ visit(node, path, new Set());
402
+
403
+ for (const { route, rule } of consuming) {
404
+ if (instance[route.to.name] !== undefined) continue;
405
+ for (const selector of route.from.slice(1)) {
406
+ const found = this.resolve(node, selector, path, treePath, rule, route);
407
+ if (found !== undefined) {
408
+ instance[route.to.name] = found as Json[keyof Json];
409
+ this.diagnostics.pushFidelity(
410
+ {
411
+ source: `${path} (fallback)`,
412
+ destination: route.to.name,
413
+ origin: route.origin,
414
+ kind: selector.kind === "sub-text-lift" ? "lifted" : "moved",
415
+ class: "maps-cleanly",
416
+ note: selector.kind === "sub-text-lift" ? "audited lift: relocation of existing text, never synthesis" : undefined,
417
+ },
418
+ treePath,
419
+ Band.BeforeChildren,
420
+ Phase.LabelLift,
421
+ rule,
200
422
  );
423
+ break;
201
424
  }
202
425
  }
203
426
  }
204
427
 
205
- this.components[index] = instance;
206
- return id;
428
+ this.diagnostics.push(
429
+ {
430
+ code: "surface-composition-flattened",
431
+ message: `${path}: compound '${node.component}' subtree flattened onto emitted props (documented casualty; nested props beyond text are not carried).`,
432
+ },
433
+ treePath,
434
+ Band.BeforeChildren,
435
+ Phase.SubContentFlatten,
436
+ );
437
+ this.diagnostics.pushFidelity(
438
+ {
439
+ source: `${path} (${node.component} subtree)`,
440
+ destination: "(props of this instance)",
441
+ origin: consuming.map(({ route }) => route.origin).join(", "),
442
+ kind: "flattened",
443
+ class: "lossy",
444
+ note: "compound composition consumed into props; structure and nested props beyond text are not carried",
445
+ },
446
+ treePath,
447
+ Band.BeforeChildren,
448
+ Phase.SubContentFlatten,
449
+ );
450
+ }
451
+
452
+ /**
453
+ * Writes `value` unless the destination is taken and the route is
454
+ * first-wins. Returns whether the write LANDED — the fidelity ledger must
455
+ * record a discarded harvest as discarded, never as a clean move.
456
+ */
457
+ private write(instance: Json, name: string, value: Json[keyof Json], overwrite?: boolean): boolean {
458
+ if (overwrite || instance[name] === undefined) {
459
+ instance[name] = value;
460
+ return true;
461
+ }
462
+ return false;
463
+ }
464
+
465
+ private applyRoute(
466
+ node: SurfaceNode,
467
+ route: Route,
468
+ rule: number,
469
+ instance: Json,
470
+ id: string,
471
+ path: string,
472
+ treePath: readonly number[],
473
+ ): void {
474
+ // `children` is not a value route: it produces instances, and is handled
475
+ // with the child walk so ids exist in emission order.
476
+ if (route.from.some((s) => s.kind === "children")) return;
477
+
478
+ for (const selector of route.from) {
479
+ if (selector.kind === "synthesized-action") {
480
+ const eventName = slug(node.id ?? (instance.confirmLabel as string) ?? node.text ?? node.component);
481
+ this.write(instance, route.to.name, { event: { name: eventName, context: {} } } as Json[keyof Json], route.overwrite);
482
+ this.diagnostics.pushFidelity(
483
+ {
484
+ source: "(no source: A2UI requires a declarative action)",
485
+ destination: route.to.name,
486
+ origin: route.origin,
487
+ kind: "synthesized",
488
+ class: "synthesis-defaults",
489
+ note: `event name '${eventName}' derived from the node's id/label/component slug`,
490
+ },
491
+ treePath,
492
+ Band.BeforeChildren,
493
+ Phase.Action,
494
+ rule,
495
+ );
496
+ this.diagnostics.push(
497
+ {
498
+ code: "surface-synthesized-action",
499
+ message: `${path}: A2UI requires a declarative action on ${instance.component as string}; synthesized event '${eventName}'.`,
500
+ },
501
+ treePath,
502
+ Band.BeforeChildren,
503
+ Phase.Action,
504
+ rule,
505
+ );
506
+ return;
507
+ }
508
+
509
+ const found = this.resolve(node, selector, path, treePath, rule, route);
510
+ if (found === undefined) continue;
511
+
512
+ if (route.to.kind === "text-child") {
513
+ this.write(
514
+ instance,
515
+ route.to.name,
516
+ this.emitTextPrimitive(String(found), `${id}_label`, path, treePath, Phase.TextChild, rule),
517
+ route.overwrite,
518
+ );
519
+ } else {
520
+ const landed = this.write(instance, route.to.name, found as Json[keyof Json], route.overwrite);
521
+ this.diagnostics.pushFidelity(
522
+ landed
523
+ ? {
524
+ source: `${path} (${describeSelector(selector)})`,
525
+ destination: route.to.name,
526
+ origin: route.origin,
527
+ kind: selector.kind === "self-prop" ? "projected" : "moved",
528
+ class: "maps-cleanly",
529
+ }
530
+ : {
531
+ source: `${path} (${describeSelector(selector)})`,
532
+ destination: "(discarded)",
533
+ origin: route.origin,
534
+ kind: "dropped",
535
+ class: "lossy",
536
+ note: `'${route.to.name}' was already written by an earlier phase; the harvested value did not land`,
537
+ },
538
+ treePath,
539
+ Band.BeforeChildren,
540
+ selector.kind === "self-prop" ? Phase.PropMap : Phase.TextChild,
541
+ rule,
542
+ );
543
+ }
544
+ return; // ordered fallback: the first selector that yields wins
545
+ }
546
+ }
547
+
548
+ /** Resolves one selector against the node's subtree; `undefined` when it yields nothing. */
549
+ private resolve(
550
+ node: SurfaceNode,
551
+ selector: Selector,
552
+ path: string,
553
+ treePath: readonly number[],
554
+ rule: number,
555
+ route: Route,
556
+ ): string | Json[keyof Json] | undefined {
557
+ switch (selector.kind) {
558
+ case "self-text":
559
+ return node.text;
560
+
561
+ case "self-prop":
562
+ return node.props?.[selector.prop] as Json[keyof Json] | undefined;
563
+
564
+ case "sub-text": {
565
+ // v1 visited the node itself as well as its descendants.
566
+ let hit: string | undefined;
567
+ const visit = (n: SurfaceNode): void => {
568
+ if (hit === undefined && selector.subs.includes(n.component) && n.text !== undefined) hit = n.text;
569
+ for (const child of collectChildren(n)) visit(child.node);
570
+ };
571
+ visit(node);
572
+ return hit;
573
+ }
574
+
575
+ case "sub-label": {
576
+ // Only a label-bearing component qualifies — one whose own model routes
577
+ // its text to a text-child destination — never incidental descendant text.
578
+ let hit: string | undefined;
579
+ const visit = (n: SurfaceNode, insideSub: boolean): void => {
580
+ if (hit === undefined && insideSub && n !== node && n.text !== undefined) {
581
+ const plan = this.byDspackId.get(n.component);
582
+ const bearsLabel =
583
+ plan !== undefined && surfaceModelOf(plan).routes.some((r) => r.to.kind === "text-child");
584
+ if (bearsLabel) hit = n.text;
585
+ }
586
+ for (const child of collectChildren(n)) visit(child.node, insideSub || selector.subs.includes(n.component));
587
+ };
588
+ visit(node, false);
589
+ return hit;
590
+ }
591
+
592
+ case "sub-text-lift": {
593
+ // Audited lift: relocation of text that exists, never synthesis. If
594
+ // nothing exists to lift the destination stays missing and gate A3
595
+ // refuses the instance, exactly as before.
596
+ const lift = (n: SurfaceNode, inside: boolean): { text: string; component: string } | undefined => {
597
+ const here = inside || selector.subs.includes(n.component);
598
+ if (here && n.text !== undefined && n.text !== "") return { text: n.text, component: n.component };
599
+ for (const child of collectChildren(n)) {
600
+ const found = lift(child.node, here);
601
+ if (found) return found;
602
+ }
603
+ return undefined;
604
+ };
605
+ const found = lift(node, false);
606
+ if (!found) return undefined;
607
+ this.diagnostics.push(
608
+ {
609
+ code: "surface-label-lifted",
610
+ message: `${path}: '${route.to.name}' lifted from direct text on '${found.component}' inside '${selector.subs.join("|")}' — no label-bearing component carried it (documented projection extension; lift, never synthesis).`,
611
+ },
612
+ treePath,
613
+ Band.BeforeChildren,
614
+ Phase.LabelLift,
615
+ rule,
616
+ );
617
+ return found.text;
618
+ }
619
+
620
+ case "subtree-text": {
621
+ let hit: SurfaceNode | undefined;
622
+ const visit = (n: SurfaceNode): void => {
623
+ if (hit === undefined && selector.subs.includes(n.component)) hit = n;
624
+ for (const child of collectChildren(n)) visit(child.node);
625
+ };
626
+ visit(node);
627
+ return hit ? this.subtreeText(hit) : undefined;
628
+ }
629
+
630
+ case "children":
631
+ case "synthesized-action":
632
+ return undefined;
633
+ }
207
634
  }
208
635
 
209
636
  /** CSR props -> A2UI props via the profile's existing PropPlan projections. */
210
- private applyPropMap(node: SurfaceNode, plan: ComponentPlan, instance: Json, path: string): void {
637
+ private applyPropMap(
638
+ node: SurfaceNode,
639
+ plan: ComponentPlan,
640
+ model: SurfaceModel,
641
+ instance: Json,
642
+ path: string,
643
+ treePath: readonly number[],
644
+ ): void {
645
+ // A prop routed verbatim to a SAME-NAMED destination is projected by that
646
+ // route, not by the prop map — v1 spelled this `structuralPassthrough`.
647
+ // The name check matters: a v2 route may read a declared contract prop
648
+ // into a differently-named destination, and that read must not suppress
649
+ // the prop's own projection (both writes are real, to distinct names).
650
+ const routedVerbatim = new Set(
651
+ model.routes
652
+ .filter((r) => r.from.some((s) => s.kind === "self-prop" && s.prop === r.to.name))
653
+ .map((r) => (r.from.find((s) => s.kind === "self-prop") as { prop: string }).prop),
654
+ );
211
655
  for (const [prop, raw] of Object.entries(node.props ?? {})) {
212
- if (plan.surfacePlan?.structuralPassthrough?.includes(prop)) continue;
656
+ if (routedVerbatim.has(prop)) continue;
213
657
  const pp = plan.propMap?.[prop];
214
658
  if (!pp) {
215
- this.warnings.push({
216
- code: "surface-prop-dropped",
217
- message: `${path}: prop '${prop}' on '${node.component}' has no A2UI projection; dropped.`,
218
- });
659
+ this.diagnostics.push(
660
+ {
661
+ code: "surface-prop-dropped",
662
+ message: `${path}: prop '${prop}' on '${node.component}' has no A2UI projection; dropped.`,
663
+ },
664
+ treePath,
665
+ Band.BeforeChildren,
666
+ Phase.PropMap,
667
+ );
668
+ this.diagnostics.pushFidelity(
669
+ { source: `${path} (props.${prop})`, destination: "(discarded)", origin: `propMap.${prop}`, kind: "dropped", class: "lossy", note: "no A2UI projection" },
670
+ treePath,
671
+ Band.BeforeChildren,
672
+ Phase.PropMap,
673
+ );
219
674
  continue;
220
675
  }
221
- const value = pp.valueMap ? (pp.valueMap[String(raw)] ?? pp.default) : raw;
676
+ const mapped = pp.valueMap ? pp.valueMap[String(raw)] : undefined;
677
+ const value = pp.valueMap ? (mapped ?? pp.default) : raw;
222
678
  if (value === undefined) {
223
- this.warnings.push({
224
- code: "surface-prop-value-dropped",
225
- message: `${path}: value '${String(raw)}' of prop '${prop}' has no projection and no default; dropped.`,
226
- });
679
+ this.diagnostics.push(
680
+ {
681
+ code: "surface-prop-value-dropped",
682
+ message: `${path}: value '${String(raw)}' of prop '${prop}' has no projection and no default; dropped.`,
683
+ },
684
+ treePath,
685
+ Band.BeforeChildren,
686
+ Phase.PropMap,
687
+ );
688
+ this.diagnostics.pushFidelity(
689
+ { source: `${path} (props.${prop}='${String(raw)}')`, destination: "(discarded)", origin: `propMap.${prop}`, kind: "dropped", class: "lossy", note: "value has no projection and no default" },
690
+ treePath,
691
+ Band.BeforeChildren,
692
+ Phase.PropMap,
693
+ );
227
694
  continue;
228
695
  }
229
696
  instance[pp.a2ui] = value as Json[keyof Json];
697
+ this.diagnostics.pushFidelity(
698
+ {
699
+ source: `${path} (props.${prop})`,
700
+ destination: pp.a2ui,
701
+ origin: `propMap.${prop}`,
702
+ kind: "projected",
703
+ class: pp.valueMap && mapped === undefined ? "synthesis-defaults" : "maps-cleanly",
704
+ note: pp.valueMap && mapped === undefined ? `value '${String(raw)}' fell back to the declared default '${String(pp.default)}'` : undefined,
705
+ },
706
+ treePath,
707
+ Band.BeforeChildren,
708
+ Phase.PropMap,
709
+ );
230
710
  }
231
711
  }
232
712
 
233
713
  /**
234
- * Compound flattening: pull text out of named sub-components anywhere in the
235
- * subtree. The subtree is consumed — the documented composition casualty.
714
+ * Refuse when a consumed subtree contains a component the profile declared a
715
+ * casualty. Consumption is how compounds fold their parts into props; it is
716
+ * NOT an escape hatch around an author's "this cannot be represented".
717
+ * Fail-closed and loud, with the authored reason, exactly like the direct
718
+ * emission path — including the offending node's own path, so the refusal
719
+ * points at the casualty rather than the parent that would have eaten it.
720
+ */
721
+ private refuseConsumedCasualty(node: SurfaceNode, path: string): void {
722
+ const walk = (n: SurfaceNode, nodePath: string): void => {
723
+ if (n !== node) {
724
+ const casualty = this.profile.casualtyComponents.find((c) => c.dspackId === n.component);
725
+ if (casualty && !this.byDspackId.has(n.component)) {
726
+ throw new EmitSurfaceError(
727
+ `component '${n.component}' is a declared casualty (${casualty.class}) of the ` +
728
+ `'${this.profile.catalogTitle}' profile and cannot be consumed into ` +
729
+ `'${node.component}': ${casualty.reason}`,
730
+ nodePath,
731
+ );
732
+ }
733
+ }
734
+ collectChildren(n).forEach((child, i) => walk(child.node, `${nodePath}${child.suffix}[${i}]`));
735
+ };
736
+ walk(node, path);
737
+ }
738
+
739
+ /**
740
+ * Repetition: collect repeated sub-structures into array-valued destinations.
741
+ * Nothing here is table-shaped — the depth is nesting and the record key is an
742
+ * item field name. Cells flatten to their subtree TEXT in document order;
743
+ * nested structure and props are a warned per-cell loss, never re-interpreted.
744
+ */
745
+ /**
746
+ * Repetition: collect one repeated sub-structure into an array-valued
747
+ * destination. Nothing here is table-shaped — the depth is nesting and the
748
+ * record key is an item field name. Cells flatten to their subtree TEXT in
749
+ * document order; nested structure and props are a warned per-cell loss,
750
+ * never re-interpreted into semantic fields.
236
751
  */
237
- private applySubContent(
752
+ private applyCollect(
238
753
  node: SurfaceNode,
239
- subText: Record<string, string>,
240
- subButtonText: Record<string, string>,
754
+ model: SurfaceModel,
755
+ collect: Collect,
756
+ rule: number,
241
757
  instance: Json,
242
758
  path: string,
759
+ treePath: readonly number[],
243
760
  ): void {
244
- const visit = (n: SurfaceNode, insideSub: string | null): void => {
245
- const textProp = subText[n.component];
246
- if (textProp !== undefined && n.text !== undefined && instance[textProp] === undefined) {
247
- instance[textProp] = n.text;
761
+ void model;
762
+ if (collect.as.kind === "inline") return;
763
+
764
+ // T2 item-mode: each descendant matching `of` (document order) becomes
765
+ // one record whose fields resolve against THAT item's own node. Absent
766
+ // sources omit the field — gate A3 arbitrates required record shapes,
767
+ // never synthesis. Sibling content the collect does not claim follows
768
+ // the ordinary consumed-subtree accounting (closeCollects).
769
+ if (collect.fields) {
770
+ const itemLocal = (n: SurfaceNode, sel: Selector): Json[keyof Json] | undefined =>
771
+ sel.kind === "self-text" ? n.text : sel.kind === "self-id" ? n.id : sel.kind === "self-prop" ? (n.props?.[sel.prop] as Json[keyof Json] | undefined) : undefined;
772
+
773
+ // Gather left items and (when a join is declared) joined counterparts,
774
+ // both in document order.
775
+ const lefts: Array<{ n: SurfaceNode; nPath: string }> = [];
776
+ const rights: Array<{ n: SurfaceNode; nPath: string }> = [];
777
+ const gather = (n: SurfaceNode, nPath: string): void => {
778
+ if (collect.of.includes(n.component)) {
779
+ lefts.push({ n, nPath });
780
+ return; // an item's subtree is the item's; nested items do not re-match
781
+ }
782
+ if (collect.join?.with.includes(n.component)) {
783
+ rights.push({ n, nPath });
784
+ return;
785
+ }
786
+ collectChildren(n).forEach((c, i) => gather(c.node, `${nPath}${c.suffix}[${i}]`));
787
+ };
788
+ collectChildren(node).forEach((c, i) => gather(c.node, `${path}${c.suffix}[${i}]`));
789
+
790
+ // T3: the declared key join. Every edge refuses — the profile names
791
+ // the relation, the emitter never infers one.
792
+ const counterparts = new Map<string, { n: SurfaceNode; nPath: string }>();
793
+ if (collect.join) {
794
+ const j = collect.join;
795
+ const seenLeft = new Map<string, string>();
796
+ for (const item of lefts) {
797
+ const key = itemLocal(item.n, j.leftKey);
798
+ if (typeof key !== "string" || key === "") {
799
+ throw new EmitSurfaceError(
800
+ `join '${j.origin}': item '${item.n.component}' carries no key (${describeSelector(j.leftKey)}); a keyless item cannot participate in a declared join`,
801
+ item.nPath,
802
+ );
803
+ }
804
+ const prior = seenLeft.get(key);
805
+ if (prior !== undefined) {
806
+ throw new EmitSurfaceError(
807
+ `join '${j.origin}': duplicate left key '${key}' (also at ${prior}); join keys must be unique on each side`,
808
+ item.nPath,
809
+ );
810
+ }
811
+ seenLeft.set(key, item.nPath);
812
+ }
813
+ for (const cp of rights) {
814
+ const key = itemLocal(cp.n, j.rightKey);
815
+ if (typeof key !== "string" || key === "") {
816
+ throw new EmitSurfaceError(
817
+ `join '${j.origin}': counterpart '${cp.n.component}' carries no key (${describeSelector(j.rightKey)})`,
818
+ cp.nPath,
819
+ );
820
+ }
821
+ if (counterparts.has(key)) {
822
+ throw new EmitSurfaceError(
823
+ `join '${j.origin}': duplicate right key '${key}'; join keys must be unique on each side`,
824
+ cp.nPath,
825
+ );
826
+ }
827
+ if (!seenLeft.has(key)) {
828
+ throw new EmitSurfaceError(
829
+ `join '${j.origin}': counterpart '${cp.n.component}' key '${key}' matches no item; a dangling counterpart is a contradiction, not surplus`,
830
+ cp.nPath,
831
+ );
832
+ }
833
+ counterparts.set(key, cp);
834
+ }
248
835
  }
249
- const buttonProp = insideSub ? subButtonText[insideSub] : undefined;
250
- if (buttonProp !== undefined && n.text !== undefined && instance[buttonProp] === undefined && n !== node) {
251
- // Only a label-bearing component qualifies (one whose surface plan
252
- // projects its text as a child label, e.g. the trigger's button) —
253
- // never incidental text on other descendants.
254
- const plan = this.byDspackId.get(n.component);
255
- if (plan?.surfacePlan?.textChildProp) instance[buttonProp] = n.text;
836
+
837
+ const records: Json[] = [];
838
+ for (const item of lefts) {
839
+ const record: Json = {};
840
+ for (const [fieldName, sel] of Object.entries(collect.fields)) {
841
+ const value = itemLocal(item.n, sel);
842
+ if (value !== undefined) record[fieldName] = value;
843
+ }
844
+ this.diagnostics.pushFidelity(
845
+ {
846
+ source: `${item.nPath} (${item.n.component})`,
847
+ destination: collect.as.name,
848
+ origin: collect.origin,
849
+ kind: "moved",
850
+ class: "maps-cleanly",
851
+ note: `item record { ${Object.keys(record).join(", ")} } collected`,
852
+ },
853
+ treePath,
854
+ Band.BeforeChildren,
855
+ Phase.TableBody,
856
+ rule,
857
+ );
858
+
859
+ if (collect.join) {
860
+ const j = collect.join;
861
+ const key = itemLocal(item.n, j.leftKey) as string;
862
+ const cp = counterparts.get(key);
863
+ if (!cp && !j.optional) {
864
+ throw new EmitSurfaceError(
865
+ `join '${j.origin}': item '${item.n.component}' key '${key}' has no counterpart among [${j.with.join(", ")}]; exactly one is required (declare optional to relax to 0..1)`,
866
+ item.nPath,
867
+ );
868
+ }
869
+ if (cp) {
870
+ for (const [fieldName, jSel] of Object.entries(j.fields)) {
871
+ if ("kind" in jSel && jSel.kind === "joined-children") {
872
+ // The slot-valued field: the counterpart's children emit as
873
+ // instances; the record carries the reference. Repetition's
874
+ // ratified slot form — not T4 multi-slot routing. The child
875
+ // list goes through the SAME rewriting as any parent's
876
+ // (mirroring the transparent-root host pattern), so a
877
+ // transparent top-level child inside a joined panel
878
+ // dissolves instead of refusing as an unroutable instance.
879
+ const spliced = this.rewriteChildren(cp.n, emptySurfaceModel(), cp.nPath, treePath);
880
+ if (spliced.length === 0) continue;
881
+ const ids = spliced.map((k, ki) =>
882
+ "textVariant" in k
883
+ ? this.emitTextPrimitive(
884
+ k.text,
885
+ `${slug(key)}_${slug(k.textVariant)}`,
886
+ cp.nPath,
887
+ [...treePath, Band.Children, records.length, ki],
888
+ Phase.TextChild,
889
+ 0,
890
+ k.textVariant,
891
+ )
892
+ : this.emitNode(k.node, `${cp.nPath}${k.suffix}[${ki}]`, [...treePath, Band.Children, records.length], k.donations ?? []),
893
+ );
894
+ record[fieldName] =
895
+ ids.length === 1 ? ids[0] : this.wrapInColumn(ids, `${slug(key)}`, cp.nPath, treePath);
896
+ } else {
897
+ const value = itemLocal(cp.n, jSel as Selector);
898
+ if (value !== undefined) record[fieldName] = value;
899
+ }
900
+ }
901
+ this.diagnostics.pushFidelity(
902
+ {
903
+ source: `${cp.nPath} (${cp.n.component})`,
904
+ destination: `${collect.as.name} @ item '${key}'`,
905
+ origin: j.origin,
906
+ kind: "joined",
907
+ class: "maps-cleanly",
908
+ note: `counterpart joined on key '${key}' -> fields { ${Object.keys(j.fields).join(", ")} }`,
909
+ },
910
+ treePath,
911
+ Band.BeforeChildren,
912
+ Phase.TableBody,
913
+ rule,
914
+ );
915
+ }
916
+ }
917
+ records.push(record);
256
918
  }
257
- const nextInside = subButtonText[n.component] !== undefined ? n.component : insideSub;
258
- for (const child of collectChildren(n)) visit(child.node, nextInside);
259
- };
260
- visit(node, null);
261
-
262
- // Audited label lift (spec v0.4 amendment, 2026-07-04): when no
263
- // label-bearing component inside a subButtonText sub carried direct text,
264
- // lift the FIRST direct text found under that sub (the sub's own text
265
- // included, document order). This is a LIFT of existing text — relocation,
266
- // never synthesis: if nothing exists to lift, the prop stays missing and
267
- // gate A3 refuses the instance exactly as before. Every lift is recorded,
268
- // like the other documented casualties, so audit reports can count them.
269
- for (const [subId, buttonProp] of Object.entries(subButtonText)) {
270
- if (instance[buttonProp] !== undefined) continue;
271
- const lift = (n: SurfaceNode, inside: boolean): { text: string; component: string } | undefined => {
272
- const here = inside || n.component === subId;
273
- if (here && n.text !== undefined && n.text !== "") return { text: n.text, component: n.component };
274
- for (const child of collectChildren(n)) {
275
- const found = lift(child.node, here);
276
- if (found) return found;
919
+ if (records.length > 0) {
920
+ const landed = this.write(instance, collect.as.name, records as Json[keyof Json]);
921
+ if (!landed) {
922
+ this.diagnostics.pushFidelity(
923
+ { source: `${path} (${collect.of.join("|")} items)`, destination: "(discarded)", origin: collect.origin, kind: "dropped", class: "lossy", note: `'${collect.as.name}' was already written by an earlier phase; the collected records did not land` },
924
+ treePath,
925
+ Band.BeforeChildren,
926
+ Phase.TableBody,
927
+ rule,
928
+ );
277
929
  }
278
- return undefined;
279
- };
280
- const found = lift(node, false);
281
- if (found) {
282
- instance[buttonProp] = found.text;
283
- this.warnings.push({
284
- code: "surface-label-lifted",
285
- message: `${path}: '${buttonProp}' lifted from direct text on '${found.component}' inside '${subId}' — no label-bearing component carried it (documented projection extension; lift, never synthesis).`,
286
- });
287
930
  }
931
+ return;
288
932
  }
933
+ const out: Json[] = [];
934
+ const flat: string[] = [];
935
+ const scalarField = Object.values(collect.item ?? {}).find((f) => isCollect(f) && f.scalar) as Collect | undefined;
936
+ const itemKey = Object.keys(collect.item ?? {})[0] ?? "items";
289
937
 
290
- this.warnings.push({
291
- code: "surface-composition-flattened",
292
- message: `${path}: compound '${node.component}' subtree flattened onto emitted props (documented casualty; nested props beyond text are not carried).`,
293
- });
294
- }
938
+ for (const child of collectChildren(node)) {
939
+ if (!collect.of.includes(child.node.component)) continue;
940
+ const childPath = `${path}${child.suffix}`;
941
+ for (const inner of collectChildren(child.node)) {
942
+ if (!scalarField || !scalarField.of.includes(inner.node.component)) {
943
+ this.diagnostics.push(
944
+ {
945
+ code: "surface-sub-dropped",
946
+ message: `${childPath}: '${inner.node.component}' inside '${child.node.component}' has no slot; dropped.`,
947
+ },
948
+ treePath,
949
+ Band.BeforeChildren,
950
+ Phase.TableBody,
951
+ rule,
952
+ );
953
+ this.diagnostics.pushFidelity(
954
+ { source: `${childPath} (${inner.node.component})`, destination: "(discarded)", origin: collect.origin, kind: "dropped", class: "lossy", note: "no slot inside the collected repetition" },
955
+ treePath,
956
+ Band.BeforeChildren,
957
+ Phase.TableBody,
958
+ rule,
959
+ );
960
+ continue;
961
+ }
962
+ const cells = this.collectRow(inner.node, scalarField, `${childPath}${inner.suffix}`, treePath, rule);
963
+ if (this.isFlatTarget(collect)) flat.push(...cells);
964
+ else out.push({ [itemKey]: cells } as Json);
965
+ }
966
+ }
295
967
 
296
- private emitTextPrimitive(text: string, preferredId: string, path: string, variant?: string): string {
297
- const { textComponent, textProp } = this.profile.surfaceSynthesis;
298
- const id = this.allocateId(preferredId, path);
299
- const instance: Json = { id, component: textComponent, [textProp]: text };
300
- if (variant !== undefined) instance.variant = variant;
301
- this.components.push(instance);
302
- this.warnings.push({
303
- code: "surface-synthesized-text",
304
- message: `${path}: node text projected as a synthesized ${textComponent} child ('${id}') — the surface format has no text primitive.`,
305
- });
306
- return id;
968
+ const value = this.isFlatTarget(collect) ? flat : out;
969
+ if (value.length > 0) {
970
+ const landed = this.write(instance, collect.as.name, value as Json[keyof Json]);
971
+ this.diagnostics.pushFidelity(
972
+ landed
973
+ ? {
974
+ source: `${path} (${collect.of.join("|")} repetitions)`,
975
+ destination: collect.as.name,
976
+ origin: collect.origin,
977
+ kind: "moved",
978
+ class: "maps-cleanly",
979
+ note: this.isFlatTarget(collect)
980
+ ? `${flat.length} cell(s) collected into one flat list`
981
+ : `${out.length} record(s) collected`,
982
+ }
983
+ : {
984
+ source: `${path} (${collect.of.join("|")} repetitions)`,
985
+ destination: "(discarded)",
986
+ origin: collect.origin,
987
+ kind: "dropped",
988
+ class: "lossy",
989
+ note: `'${collect.as.name}' was already written by an earlier phase; the collected ${this.isFlatTarget(collect) ? "cells" : "records"} did not land`,
990
+ },
991
+ treePath,
992
+ Band.BeforeChildren,
993
+ Phase.TableBody,
994
+ rule,
995
+ );
996
+ }
307
997
  }
308
998
 
309
999
  /**
310
- * Named parent strategy "subFlatten" (e.g. Card): grouping sub-components
311
- * splice their children inline in document order (their own structure is a
312
- * warned, documented loss); text-bearing sub-components synthesize the
313
- * profile's text primitive with the declared variant. Everything else
314
- * passes through to ordinary child emission.
1000
+ * After every collect has run: anything the collects and routes did not claim
1001
+ * is either an explicit drop or an unrecognized sub — both warned, never
1002
+ * silently ignored — followed by the composition casualty for the compound.
1003
+ */
1004
+ /**
1005
+ * T4: one slot route — the ordered children of exactly one descendant
1006
+ * instance of the named sub become instances, and the slot carries the
1007
+ * reference (multi wraps in the profile's wrap component, exactly like
1008
+ * T3's joined-children). The region's child list goes through the SAME
1009
+ * rewriting as any parent's (this plan's dispositions apply to nested
1010
+ * subs), with subs claimed by sibling routes skipped — their consumption
1011
+ * is their own route's ledger entry. Zero regions leave the destination
1012
+ * absent (gate A3 arbitrates); several refuse: a slot names one region.
315
1013
  */
316
- private flattenSubs(
1014
+ private applySlotRoute(
317
1015
  node: SurfaceNode,
318
- spec: NonNullable<NonNullable<ComponentPlan["surfacePlan"]>["subFlatten"]>,
1016
+ model: SurfaceModel,
1017
+ route: Route,
1018
+ rule: number,
1019
+ instance: Json,
319
1020
  path: string,
320
- ): Array<{ node: SurfaceNode; suffix: string } | { text: string; textVariant: string }> {
321
- const out: Array<{ node: SurfaceNode; suffix: string } | { text: string; textVariant: string }> = [];
322
- const visit = (n: SurfaceNode, suffix: string): void => {
323
- if (spec.transparent.includes(n.component)) {
324
- this.warnings.push({
325
- code: "surface-sub-flattened",
326
- message: `${path}: grouping sub-component '${n.component}' spliced inline (subFlatten strategy); its own structure is not carried.`,
327
- });
328
- if (n.text !== undefined && n.text !== "") out.push({ text: n.text, textVariant: "body" });
329
- for (const child of collectChildren(n)) visit(child.node, child.suffix);
330
- return;
331
- }
332
- const variant = spec.asText[n.component];
333
- if (variant !== undefined) {
334
- const text = this.subtreeText(n);
335
- if (text !== "") {
336
- out.push({ text, textVariant: variant });
337
- } else {
338
- this.warnings.push({
339
- code: "surface-sub-dropped",
340
- message: `${path}: '${n.component}' carried no text to synthesize; dropped.`,
341
- });
342
- }
343
- return;
1021
+ treePath: readonly number[],
1022
+ ): void {
1023
+ const sel = route.from[0];
1024
+ if (sel.kind !== "sub-children") return;
1025
+ const region = sel.subs[0];
1026
+
1027
+ const found: Array<{ n: SurfaceNode; nPath: string }> = [];
1028
+ const locate = (n: SurfaceNode, nPath: string): void => {
1029
+ for (const c of collectChildren(n)) {
1030
+ if (c.node.component === region) found.push({ n: c.node, nPath: `${nPath}${c.suffix}` });
1031
+ locate(c.node, `${nPath}${c.suffix}`);
344
1032
  }
345
- out.push({ node: n, suffix });
346
1033
  };
347
- for (const child of collectChildren(node)) visit(child.node, child.suffix);
348
- return out;
1034
+ locate(node, path);
1035
+
1036
+ if (found.length === 0) return; // absent region: the destination stays absent and A3 arbitrates
1037
+ if (found.length > 1) {
1038
+ throw new EmitSurfaceError(
1039
+ `slot route '${route.origin}': ${found.length} instances of '${region}' in this '${node.component}'; ` +
1040
+ `a slot names ONE region — exactly one may appear`,
1041
+ path,
1042
+ );
1043
+ }
1044
+
1045
+ const claimed = new Set<string>();
1046
+ for (const r of model.routes) {
1047
+ if (r === route) continue;
1048
+ for (const s of r.from) if ("subs" in s) for (const id of s.subs as string[]) claimed.add(id);
1049
+ }
1050
+ for (const c of model.collects) for (const id of [...c.of, ...(c.join?.with ?? [])]) claimed.add(id);
1051
+
1052
+ const src = found[0];
1053
+ const spliced = this.rewriteChildren(src.n, model, src.nPath, treePath, claimed);
1054
+ if (spliced.length === 0) return; // an empty region carries nothing; absent, A3 arbitrates
1055
+ const ids = spliced.map((k, ki) =>
1056
+ "textVariant" in k
1057
+ ? this.emitTextPrimitive(
1058
+ k.text,
1059
+ `${slug(region)}_${slug(k.textVariant)}`,
1060
+ src.nPath,
1061
+ [...treePath, Band.BeforeChildren, rule, ki],
1062
+ Phase.SubContentFlatten,
1063
+ rule,
1064
+ k.textVariant,
1065
+ )
1066
+ : this.emitNode(k.node, `${src.nPath}${k.suffix}[${ki}]`, [...treePath, Band.BeforeChildren, rule, ki], k.donations ?? []),
1067
+ );
1068
+ const ref = ids.length === 1 ? ids[0] : this.wrapInColumn(ids, slug(region), src.nPath, treePath);
1069
+ const landed = this.write(instance, route.to.name, ref);
1070
+ this.diagnostics.pushFidelity(
1071
+ {
1072
+ source: `${src.nPath} (${region} children)`,
1073
+ destination: `${route.to.name} @ ${path} (${node.component})`,
1074
+ origin: route.origin,
1075
+ kind: landed ? "moved" : "dropped",
1076
+ class: landed ? "maps-cleanly" : "lossy",
1077
+ note: landed
1078
+ ? `region '${region}' emitted as instances; the slot carries the reference`
1079
+ : `'${route.to.name}' already written; the region's reference did not land`,
1080
+ },
1081
+ treePath,
1082
+ Band.BeforeChildren,
1083
+ Phase.SubContentFlatten,
1084
+ rule,
1085
+ );
349
1086
  }
350
1087
 
351
1088
  /**
352
- * Named parent strategy "subTable": consume the tabular sub tree into the
353
- * synthesized caption/columns/rows shape. Domain-neutral: a cell is its
354
- * subtree's text in document order — nested component structure and props
355
- * are a per-cell warned loss, never re-interpreted into semantic fields.
356
- * structuralPassthrough values (the props path) win over consumed ones.
1089
+ * Fail-closed closure for a slot-routed compound: every DIRECT child must
1090
+ * be a claimed region, a route-consumed sub, a collected family, or carry
1091
+ * a disposition — an unclaimed child is structural content with no
1092
+ * destination, and approximating it silently is exactly what this engine
1093
+ * refuses to do.
357
1094
  */
358
- private applySubTable(
1095
+ private closeSlots(
359
1096
  node: SurfaceNode,
360
- spec: NonNullable<NonNullable<ComponentPlan["surfacePlan"]>["subTable"]>,
361
- instance: Json,
1097
+ model: SurfaceModel,
1098
+ path: string,
1099
+ treePath: readonly number[],
1100
+ ): void {
1101
+ const claimed = new Set<string>();
1102
+ for (const r of model.routes) for (const s of r.from) if ("subs" in s) for (const id of s.subs as string[]) claimed.add(id);
1103
+ for (const c of model.collects) for (const id of [...c.of, ...(c.join?.with ?? [])]) claimed.add(id);
1104
+
1105
+ for (const child of collectChildren(node)) {
1106
+ const c = child.node.component;
1107
+ if (claimed.has(c) || c in model.subIdentity) continue;
1108
+ const reason = model.drops[c];
1109
+ if (reason !== undefined) {
1110
+ const childPath = `${path}${child.suffix}`;
1111
+ this.diagnostics.push(
1112
+ { code: "surface-sub-dropped", message: `${childPath}: '${c}' dropped: ${reason}.` },
1113
+ treePath,
1114
+ Band.BeforeChildren,
1115
+ Phase.SubContentFlatten,
1116
+ );
1117
+ this.diagnostics.pushFidelity(
1118
+ { source: `${childPath} (${c})`, destination: "(discarded)", origin: `drops.${c}`, kind: "dropped", class: "lossy", note: reason },
1119
+ treePath,
1120
+ Band.BeforeChildren,
1121
+ Phase.SubContentFlatten,
1122
+ );
1123
+ continue;
1124
+ }
1125
+ throw new EmitSurfaceError(
1126
+ `'${c}' is a direct child of slot-routed compound '${node.component}' with no destination — ` +
1127
+ `every region must be claimed by a route, collected, or carry a disposition`,
1128
+ `${path}${child.suffix}`,
1129
+ );
1130
+ }
1131
+ }
1132
+
1133
+ private closeCollects(
1134
+ node: SurfaceNode,
1135
+ model: SurfaceModel,
362
1136
  path: string,
1137
+ treePath: readonly number[],
363
1138
  ): void {
364
- const columns: string[] = [];
365
- const rows: Json[] = [];
366
- let caption: string | undefined;
367
-
368
- const cellText = (cell: SurfaceNode, cellPath: string): string => {
369
- const nested = collectChildren(cell);
370
- const text = this.subtreeText(cell);
371
- if (nested.length > 0) {
372
- const names = nested.map((c) => `'${c.node.component}'`).join(", ");
373
- this.warnings.push({
1139
+ const claimedByCollect = new Set(model.collects.flatMap((c) => [...c.of, ...(c.join?.with ?? [])]));
1140
+ for (const child of collectChildren(node)) {
1141
+ const c = child.node.component;
1142
+ if (claimedByCollect.has(c) || this.claimedByRoute(model, c)) continue;
1143
+ const childPath = `${path}${child.suffix}`;
1144
+ const reason = model.drops[c];
1145
+ const itemMode = model.collects.some((col) => col.fields);
1146
+ this.diagnostics.push(
1147
+ {
1148
+ code: "surface-sub-dropped",
1149
+ message: reason
1150
+ ? `${childPath}: '${c}' dropped: ${reason}.`
1151
+ : itemMode
1152
+ ? `${childPath}: '${c}' is not a collected item and has no disposition; dropped (sibling pairing is T3's declared join).`
1153
+ : `${childPath}: '${c}' has no slot in the synthesized table shape; dropped.`,
1154
+ },
1155
+ treePath,
1156
+ Band.BeforeChildren,
1157
+ Phase.TableBody,
1158
+ );
1159
+ this.diagnostics.pushFidelity(
1160
+ {
1161
+ source: `${childPath} (${c})`,
1162
+ destination: "(discarded)",
1163
+ origin: reason ? `drops.${c}` : "collect",
1164
+ kind: "dropped",
1165
+ class: "lossy",
1166
+ note: reason ?? "no slot in the collected shape",
1167
+ },
1168
+ treePath,
1169
+ Band.BeforeChildren,
1170
+ Phase.TableBody,
1171
+ );
1172
+ }
1173
+
1174
+ const itemsOnly = model.collects.every((col) => col.fields);
1175
+ this.diagnostics.push(
1176
+ {
1177
+ code: "surface-composition-flattened",
1178
+ message: itemsOnly
1179
+ ? `${path}: compound '${node.component}' subtree consumed into collected item records (uncollected content is not carried).`
1180
+ : `${path}: compound '${node.component}' subtree consumed into the synthesized table shape (documented casualty; cell content beyond text is not carried).`,
1181
+ },
1182
+ treePath,
1183
+ Band.BeforeChildren,
1184
+ Phase.TableFlatten,
1185
+ );
1186
+ this.diagnostics.pushFidelity(
1187
+ {
1188
+ source: `${path} (${node.component} subtree)`,
1189
+ destination: "(collected props)",
1190
+ origin: model.collects.map((c) => c.origin).join(", "),
1191
+ kind: "flattened",
1192
+ class: "lossy",
1193
+ note: "compound consumed into the collected shape; cell content beyond text is not carried",
1194
+ },
1195
+ treePath,
1196
+ Band.BeforeChildren,
1197
+ Phase.TableFlatten,
1198
+ );
1199
+ }
1200
+
1201
+ /** True when a collect writes one flat list rather than one record per repetition. */
1202
+ private isFlatTarget(collect: Collect): boolean {
1203
+ return collect.flatten;
1204
+ }
1205
+
1206
+ /** True when some route already consumes this component's text. */
1207
+ private claimedByRoute(model: SurfaceModel, component: string): boolean {
1208
+ return model.routes.some((r) =>
1209
+ r.from.some((s) => "subs" in s && (s.subs as string[]).includes(component)),
1210
+ );
1211
+ }
1212
+
1213
+ /** One repetition's scalar cells, each flattened to its subtree text. */
1214
+ private collectRow(
1215
+ row: SurfaceNode,
1216
+ field: Collect,
1217
+ rowPath: string,
1218
+ treePath: readonly number[],
1219
+ rule: number,
1220
+ ): string[] {
1221
+ const cells: string[] = [];
1222
+ for (const child of collectChildren(row)) {
1223
+ const c = child.node.component;
1224
+ const subs = (field.scalar!.from[0] as { subs: string[] }).subs;
1225
+ if (subs.includes(c)) {
1226
+ cells.push(this.cellText(child.node, `${rowPath}${child.suffix}`, treePath, rule));
1227
+ } else {
1228
+ this.diagnostics.push(
1229
+ {
1230
+ code: "surface-sub-dropped",
1231
+ message: `${rowPath}: '${c}' has no slot in a synthesized table row; dropped (its text is not lifted).`,
1232
+ },
1233
+ treePath,
1234
+ Band.BeforeChildren,
1235
+ Phase.TableBody,
1236
+ rule,
1237
+ );
1238
+ this.diagnostics.pushFidelity(
1239
+ { source: `${rowPath} (${c})`, destination: "(discarded)", origin: field.origin, kind: "dropped", class: "lossy", note: "no slot in a collected row; its text is not lifted" },
1240
+ treePath,
1241
+ Band.BeforeChildren,
1242
+ Phase.TableBody,
1243
+ rule,
1244
+ );
1245
+ }
1246
+ }
1247
+ return cells;
1248
+ }
1249
+
1250
+ private cellText(cell: SurfaceNode, cellPath: string, treePath: readonly number[], rule: number): string {
1251
+ const nested = collectChildren(cell);
1252
+ const text = this.subtreeText(cell);
1253
+ if (nested.length > 0) {
1254
+ const names = nested.map((c) => `'${c.node.component}'`).join(", ");
1255
+ this.diagnostics.push(
1256
+ {
374
1257
  code: "surface-table-cell-flattened",
375
1258
  message: `${cellPath}: nested ${names} flattened to cell text; component structure and props are not carried by the synthesized table shape.`,
376
- });
1259
+ },
1260
+ treePath,
1261
+ Band.BeforeChildren,
1262
+ Phase.TableBody,
1263
+ rule,
1264
+ );
1265
+ this.diagnostics.pushFidelity(
1266
+ { source: `${cellPath} (nested ${names})`, destination: "(cell text)", origin: "collect cell", kind: "flattened", class: "lossy", note: "component structure and props inside the cell are not carried" },
1267
+ treePath,
1268
+ Band.BeforeChildren,
1269
+ Phase.TableBody,
1270
+ rule,
1271
+ );
1272
+ }
1273
+ return text;
1274
+ }
1275
+
1276
+ /** Children as instance references, after any sub-identity rewriting. */
1277
+ private emitChildren(
1278
+ node: SurfaceNode,
1279
+ model: SurfaceModel,
1280
+ instance: Json,
1281
+ id: string,
1282
+ path: string,
1283
+ treePath: readonly number[],
1284
+ ): void {
1285
+ const childRoute = model.routes.find((r) => r.from.some((s) => s.kind === "children"));
1286
+ const raw = collectChildren(node);
1287
+ const anyTransparentChild = raw.some((c) => {
1288
+ const plan = this.byDspackId.get(c.node.component);
1289
+ return plan !== undefined && surfaceModelOf(plan).transparent;
1290
+ });
1291
+ const childNodes: RewrittenChild[] =
1292
+ Object.keys(model.subIdentity).length > 0 || Object.keys(model.drops).length > 0 || anyTransparentChild
1293
+ ? this.rewriteChildren(node, model, path, treePath)
1294
+ : raw.map((c) => ({ node: c.node, suffix: c.suffix }));
1295
+ if (childNodes.length === 0) return;
1296
+
1297
+ const childIds = childNodes.map((child, i) =>
1298
+ "textVariant" in child
1299
+ ? this.emitTextPrimitive(
1300
+ child.text,
1301
+ `${id}_${slug(child.textVariant)}`,
1302
+ path,
1303
+ [...treePath, Band.Children, i],
1304
+ Phase.TextChild,
1305
+ 0,
1306
+ child.textVariant,
1307
+ )
1308
+ : this.emitNode(child.node, `${path}${child.suffix}[${i}]`, [...treePath, Band.Children, i], child.donations ?? []),
1309
+ );
1310
+
1311
+ if (!childRoute) {
1312
+ throw new EmitSurfaceError(
1313
+ `component '${node.component}' has children but its surface plan declares no child slot`,
1314
+ path,
1315
+ );
1316
+ }
1317
+ if (childRoute.to.kind === "slots") {
1318
+ instance[childRoute.to.name] = childIds;
1319
+ } else {
1320
+ instance[childRoute.to.name] =
1321
+ childIds.length === 1 ? childIds[0] : this.wrapInColumn(childIds, id, path, treePath);
1322
+ }
1323
+ }
1324
+
1325
+ /**
1326
+ * T1, the general root-transparency rule (ratified): a transparent node is
1327
+ * a semantic statement that the dspack node has no emitted identity — valid
1328
+ * at the root too. The root dissolves through the ORDINARY machinery
1329
+ * (presented as a child of a synthetic host, so boundary donations, sub
1330
+ * dispositions, and every refusal apply), then:
1331
+ *
1332
+ * - exactly one surviving descendant -> it IS the root (id "root",
1333
+ * components[0]) — the existing root invariant, preserved
1334
+ * deterministically;
1335
+ * - several survivors -> they wrap in the synthesized
1336
+ * wrap component, which is structural TRANSPORT, not a replacement
1337
+ * identity for the transparent component;
1338
+ * - nothing survives -> refuse. Fabricating content for
1339
+ * an empty root would be synthesis of meaning, not structure.
1340
+ *
1341
+ * No component is special-cased by name.
1342
+ */
1343
+ emitTransparentRoot(root: SurfaceNode, path: string): string {
1344
+ const { wrapComponent, wrapChildrenProp } = this.profile.surfaceSynthesis;
1345
+
1346
+ // Present the root AS A CHILD of a synthetic host, so the ordinary
1347
+ // rewriting machinery performs the whole dissolution — the plan-transparent
1348
+ // ledger entry, the boundary's own donations (transparentDonate), sub
1349
+ // dispositions, and every refusal — with no root-only special case.
1350
+ const host = { component: "__root_host__", children: [root] } as unknown as SurfaceNode;
1351
+ const spliced = this.rewriteChildren(host, emptySurfaceModel(), path, []);
1352
+
1353
+ if (spliced.length === 0) {
1354
+ throw new EmitSurfaceError(
1355
+ `transparent root '${root.component}' dissolved to nothing — no descendant survives to become the root, and fabricating one is refused`,
1356
+ path,
1357
+ );
1358
+ }
1359
+
1360
+ if (spliced.length === 1) {
1361
+ const only = spliced[0];
1362
+ this.diagnostics.pushFidelity(
1363
+ {
1364
+ source: `${path} (${root.component})`,
1365
+ destination: "root",
1366
+ origin: `plan.${root.component}`,
1367
+ kind: "moved",
1368
+ class: "maps-cleanly",
1369
+ note: "transparent root: its single surviving descendant is preserved as the root instance",
1370
+ },
1371
+ [],
1372
+ Band.BeforeChildren,
1373
+ Phase.ChildRewrite,
1374
+ );
1375
+ return "textVariant" in only
1376
+ ? this.emitTextPrimitive(only.text, "root", path, [Band.Children, 0], Phase.TextChild, 0, only.textVariant)
1377
+ : this.emitNode(only.node, path, [Band.Children, 0], only.donations ?? []);
1378
+ }
1379
+
1380
+ const id = this.allocateId("root", path, { treePath: [], band: Band.BeforeChildren, phase: Phase.IdAllocation, rule: 0 });
1381
+ const index = this.components.length;
1382
+ this.components.push({});
1383
+ const childIds = spliced.map((child, i) =>
1384
+ "textVariant" in child
1385
+ ? this.emitTextPrimitive(child.text, `root_${slug(child.textVariant)}`, path, [Band.Children, i], Phase.TextChild, 0, child.textVariant)
1386
+ : this.emitNode(child.node, `${path}.children[${i}]`, [Band.Children, i], child.donations ?? []),
1387
+ );
1388
+
1389
+ this.components[index] = { id, component: wrapComponent, [wrapChildrenProp]: childIds };
1390
+ this.diagnostics.push(
1391
+ {
1392
+ code: "surface-synthesized-wrap",
1393
+ message: `${path}: transparent root '${root.component}' dissolved; ${childIds.length} risen child(ren) wrapped in a synthesized ${wrapComponent} ('root').`,
1394
+ },
1395
+ [],
1396
+ Band.AfterChildren,
1397
+ Phase.Wrap,
1398
+ );
1399
+ this.diagnostics.pushFidelity(
1400
+ { source: `${path} (${childIds.length} risen children)`, destination: `synthesized ${wrapComponent} 'root'`, origin: "surfaceSynthesis.wrapComponent", kind: "wrapped", class: "synthesis-defaults", note: "structural transport for several risen children — not a replacement identity for the transparent root" },
1401
+ [],
1402
+ Band.AfterChildren,
1403
+ Phase.Wrap,
1404
+ );
1405
+ return id;
1406
+ }
1407
+
1408
+ /**
1409
+ * Identity applied to the child list: sub dispositions from the surrounding
1410
+ * model, T1 plan-level transparency for child COMPONENTS (dissolved under
1411
+ * their own model — the `ctx` switch), and donation boundaries. A
1412
+ * dissolving boundary that carries donations harvests them from its own
1413
+ * subtree, consumes the donor subs, and attaches the pending writes to its
1414
+ * single eligible control — refusing on zero or several candidates. The
1415
+ * pending writes ride the returned child list explicitly and apply inside
1416
+ * the control's own construction: no committed instance is ever mutated.
1417
+ */
1418
+ private rewriteChildren(
1419
+ node: SurfaceNode,
1420
+ model: SurfaceModel,
1421
+ path: string,
1422
+ treePath: readonly number[],
1423
+ /**
1424
+ * T4: subs claimed by SIBLING routes of the enclosing compound (text
1425
+ * harvests, other slot sources). A claimed sub is skipped silently at any
1426
+ * dissolution depth — its consumption is ledgered by its own route, and
1427
+ * recording it twice would say it was dropped when it was moved.
1428
+ */
1429
+ claimedSubs: ReadonlySet<string> = new Set(),
1430
+ ): RewrittenChild[] {
1431
+ const push = (w: Warning) => this.diagnostics.push(w, treePath, Band.BeforeChildren, Phase.ChildRewrite);
1432
+ const ledger = (f: SurfaceFidelityEntry) =>
1433
+ this.diagnostics.pushFidelity(f, treePath, Band.BeforeChildren, Phase.ChildRewrite);
1434
+
1435
+ // Layered dissolution contexts (emit#37, ratified 2026-08-07). A
1436
+ // dissolving boundary shadows the enclosing compound contexts where they
1437
+ // overlap, but does not erase them: a component's disposition is resolved
1438
+ // against the stack of enclosing models, innermost first, so an outer
1439
+ // compound's sub (e.g. `card-footer`) keeps its disposition when it
1440
+ // appears inside a dissolved inner boundary (e.g. a transparent `field`).
1441
+ // A single-frame stack resolves identically to the pre-amendment single
1442
+ // `ctx` — the byte pins prove it.
1443
+ const resolve = <T>(stack: readonly SurfaceModel[], pick: (m: SurfaceModel) => T | undefined): T | undefined => {
1444
+ for (const m of stack) {
1445
+ const v = pick(m);
1446
+ if (v !== undefined) return v;
377
1447
  }
378
- return text;
1448
+ return undefined;
379
1449
  };
380
1450
 
381
- const consumeRow = (row: SurfaceNode, rowPath: string, into: string[]): void => {
382
- for (const child of collectChildren(row)) {
383
- const c = child.node.component;
384
- if (c === spec.cell || c === spec.headerCell) {
385
- into.push(cellText(child.node, `${rowPath}${child.suffix}`));
386
- } else if (spec.drops[c] !== undefined) {
387
- this.warnings.push({ code: "surface-sub-dropped", message: `${rowPath}: '${c}' dropped: ${spec.drops[c]}.` });
1451
+ const visit = (n: SurfaceNode, suffix: string, stack: readonly SurfaceModel[], out: RewrittenChild[]): void => {
1452
+ if (claimedSubs.has(n.component)) return;
1453
+ // An authored drop is warn-and-discard, exactly like the collect path —
1454
+ // resolved through the ancestor chain (inner shadows outer).
1455
+ const dropReason = resolve(stack, (m) => m.drops[n.component]);
1456
+ if (dropReason !== undefined) {
1457
+ push({ code: "surface-sub-dropped", message: `${path}: '${n.component}' dropped: ${dropReason}.` });
1458
+ ledger({ source: `${path} (${n.component})`, destination: "(discarded)", origin: `drops.${n.component}`, kind: "dropped", class: "lossy", note: dropReason });
1459
+ return;
1460
+ }
1461
+
1462
+ // T1: a child COMPONENT whose plan is transparent dissolves here — its
1463
+ // subtree governed by ITS OWN model PUSHED ONTO the enclosing stack, so
1464
+ // the boundary shadows but does not erase the outer contexts.
1465
+ const childPlan = this.byDspackId.get(n.component);
1466
+ const childModel = childPlan ? surfaceModelOf(childPlan) : undefined;
1467
+ if (childModel?.transparent) {
1468
+ ledger({
1469
+ source: `${path} (${n.component})`,
1470
+ destination: "(children rise in place)",
1471
+ origin: `plan.${n.component}`,
1472
+ kind: "flattened",
1473
+ class: "lossy",
1474
+ note: "transparent identity: the component dissolves; its own structure is not carried",
1475
+ });
1476
+ dissolve(n, suffix, [childModel, ...stack], childModel.transparentDonate, `plan.${n.component}`, out);
1477
+ return;
1478
+ }
1479
+
1480
+ const identity = resolve(stack, (m) => m.subIdentity[n.component]);
1481
+ if (identity?.kind === "transparent") {
1482
+ push({
1483
+ code: "surface-sub-flattened",
1484
+ message: `${path}: grouping sub-component '${n.component}' spliced inline (subFlatten strategy); its own structure is not carried.`,
1485
+ });
1486
+ ledger({ source: `${path} (${n.component})`, destination: "(children rise in place)", origin: `subs.${n.component}`, kind: "flattened", class: "lossy", note: "transparent grouping dissolved; its own structure is not carried" });
1487
+ // A grouping sub has no model of its own; its children continue under
1488
+ // the same enclosing stack that resolved it.
1489
+ dissolve(n, suffix, stack, identity.donate ?? [], `subs.${n.component}`, out);
1490
+ return;
1491
+ }
1492
+ if (identity?.kind === "as-text") {
1493
+ const text = this.subtreeText(n);
1494
+ const nested = collectChildren(n);
1495
+ if (nested.length > 0) {
1496
+ // Structure destroyed, text preserved — the same loss the cell
1497
+ // flatten records, and it must class the same way.
1498
+ const names = nested.map((c) => `'${c.node.component}'`).join(", ");
1499
+ ledger({ source: `${path} (${n.component} containing ${names})`, destination: "(subtree text)", origin: `subs.${n.component}`, kind: "flattened", class: "lossy", note: "re-identified as text; nested component structure and props are not carried" });
1500
+ }
1501
+ if (text !== "") {
1502
+ out.push({ text, textVariant: identity.variant });
388
1503
  } else {
389
- this.warnings.push({
390
- code: "surface-sub-dropped",
391
- message: `${rowPath}: '${c}' has no slot in a synthesized table row; dropped (its text is not lifted).`,
392
- });
1504
+ push({ code: "surface-sub-dropped", message: `${path}: '${n.component}' carried no text to synthesize; dropped.` });
1505
+ ledger({ source: `${path} (${n.component})`, destination: "(discarded)", origin: `subs.${n.component}`, kind: "dropped", class: "lossy", note: "re-identified as text but carried none" });
393
1506
  }
1507
+ return;
394
1508
  }
1509
+ out.push({ node: n, suffix });
395
1510
  };
396
1511
 
397
- for (const child of collectChildren(node)) {
398
- const c = child.node.component;
399
- const childPath = `${path}${child.suffix}`;
400
- if (c === spec.caption) {
401
- caption ??= cellText(child.node, childPath);
402
- } else if (c === spec.header) {
403
- for (const inner of collectChildren(child.node)) {
404
- if (inner.node.component === spec.row) consumeRow(inner.node, `${childPath}${inner.suffix}`, columns);
405
- else this.warnings.push({ code: "surface-sub-dropped", message: `${childPath}: '${inner.node.component}' inside '${spec.header}' has no slot; dropped.` });
1512
+ /**
1513
+ * Dissolves one boundary node under `innerCtx`. When the boundary carries
1514
+ * donations: harvest first-wins per donation, consume every donor sub,
1515
+ * splice the rest, then bind the pending writes to the single eligible
1516
+ * control among the spliced replacements — zero or several refuse.
1517
+ * Eligibility is declared, never guessed: a control's plan must declare
1518
+ * every donated destination.
1519
+ */
1520
+ const dissolve = (
1521
+ n: SurfaceNode,
1522
+ suffix: string,
1523
+ innerStack: readonly SurfaceModel[],
1524
+ donations: readonly Donation[],
1525
+ originLabel: string,
1526
+ out: RewrittenChild[],
1527
+ ): void => {
1528
+ const consumedDonorSubs = new Set<string>();
1529
+ const pending: PendingDonation[] = [];
1530
+ for (const d of donations) {
1531
+ let value: string | undefined;
1532
+ let donorComponent = n.component;
1533
+ if (d.from.kind === "self-text") {
1534
+ value = n.text;
1535
+ } else if (d.from.kind === "sub-text") {
1536
+ for (const sub of d.from.subs) consumedDonorSubs.add(sub);
1537
+ const walk = (m: SurfaceNode): void => {
1538
+ if (value === undefined && d.from.kind === "sub-text" && d.from.subs.includes(m.component) && m.text !== undefined) {
1539
+ value = m.text;
1540
+ donorComponent = m.component;
1541
+ }
1542
+ for (const c of collectChildren(m)) walk(c.node);
1543
+ };
1544
+ walk(n);
406
1545
  }
407
- } else if (c === spec.body) {
408
- for (const inner of collectChildren(child.node)) {
409
- if (inner.node.component === spec.row) {
410
- const cells: string[] = [];
411
- consumeRow(inner.node, `${childPath}${inner.suffix}`, cells);
412
- rows.push({ cells });
413
- } else {
414
- this.warnings.push({ code: "surface-sub-dropped", message: `${childPath}: '${inner.node.component}' inside '${spec.body}' has no slot; dropped.` });
1546
+ if (value !== undefined) {
1547
+ pending.push({ prop: d.to.name, value, origin: d.origin, donorPath: `${path}${suffix}`, donorComponent });
1548
+ }
1549
+ // Nothing to donate is not an error: the destination stays absent and
1550
+ // gate A3 arbitrates — relocation, never synthesis (the lift rule).
1551
+ }
1552
+
1553
+ // The boundary's own text rises as body text unless a self.text
1554
+ // donation claimed it (the plain transparent-sub behaviour otherwise).
1555
+ const selfDonated = donations.some((d) => d.from.kind === "self-text");
1556
+ const spliced: RewrittenChild[] = [];
1557
+ if (!selfDonated && n.text !== undefined && n.text !== "") spliced.push({ text: n.text, textVariant: "body" });
1558
+
1559
+ for (const child of collectChildren(n)) {
1560
+ if (consumedDonorSubs.has(child.node.component)) {
1561
+ const supplied = pending.some((q) => q.donorComponent === child.node.component && q.value === child.node.text);
1562
+ if (!supplied) {
1563
+ push({ code: "surface-sub-dropped", message: `${path}: '${child.node.component}' dropped: its text was not the donated value (first donor wins).` });
1564
+ ledger({ source: `${path}${child.suffix} (${child.node.component})`, destination: "(discarded)", origin: originLabel, kind: "dropped", class: "lossy", note: "surplus donor: the donation was already supplied (first donor wins)" });
415
1565
  }
1566
+ continue;
416
1567
  }
417
- } else if (spec.drops[c] !== undefined) {
418
- this.warnings.push({ code: "surface-sub-dropped", message: `${childPath}: '${c}' dropped: ${spec.drops[c]}.` });
419
- } else {
420
- this.warnings.push({
421
- code: "surface-sub-dropped",
422
- message: `${childPath}: '${c}' has no slot in the synthesized table shape; dropped.`,
1568
+ visit(child.node, child.suffix, innerStack, spliced);
1569
+ }
1570
+
1571
+ if (pending.length > 0) {
1572
+ const controls = spliced.filter((entry): entry is { node: SurfaceNode; suffix: string; donations?: PendingDonation[] } => {
1573
+ if (!("node" in entry)) return false;
1574
+ const plan = this.byDspackId.get(entry.node.component);
1575
+ if (!plan || surfaceModelOf(plan).transparent) return false;
1576
+ const declared = new Set([
1577
+ ...Object.keys(plan.structural ?? {}),
1578
+ ...Object.values(plan.propMap ?? {}).map((pp) => pp.a2ui),
1579
+ ]);
1580
+ return pending.every((q) => declared.has(q.prop));
423
1581
  });
1582
+ if (controls.length !== 1) {
1583
+ const names = controls.map((c) => `'${c.node.component}'`).join(", ");
1584
+ throw new EmitSurfaceError(
1585
+ `donation boundary '${n.component}' (${originLabel}) requires exactly one eligible control declaring ` +
1586
+ `[${pending.map((q) => q.prop).join(", ")}]; found ${controls.length}${controls.length ? ` (${names})` : ""} — ` +
1587
+ `a donation relocates onto one control, never broadcasts`,
1588
+ `${path}${suffix}`,
1589
+ );
1590
+ }
1591
+ controls[0].donations = [...(controls[0].donations ?? []), ...pending];
424
1592
  }
425
- }
426
1593
 
427
- if (instance[spec.targetCaption] === undefined && caption !== undefined) instance[spec.targetCaption] = caption;
428
- if (instance[spec.targetColumns] === undefined && columns.length > 0) instance[spec.targetColumns] = columns;
429
- if (instance[spec.targetRows] === undefined && rows.length > 0) instance[spec.targetRows] = rows;
430
- this.warnings.push({
431
- code: "surface-composition-flattened",
432
- message: `${path}: compound '${node.component}' subtree consumed into the synthesized table shape (documented casualty; cell content beyond text is not carried).`,
433
- });
1594
+ out.push(...spliced);
1595
+ };
1596
+
1597
+ const rootOut: RewrittenChild[] = [];
1598
+ for (const child of collectChildren(node)) visit(child.node, child.suffix, [model], rootOut);
1599
+ return rootOut;
1600
+ }
1601
+
1602
+ private emitTextPrimitive(
1603
+ text: string,
1604
+ preferredId: string,
1605
+ path: string,
1606
+ treePath: readonly number[],
1607
+ phase: Phase,
1608
+ rule: number,
1609
+ variant?: string,
1610
+ ): string {
1611
+ const { textComponent, textProp } = this.profile.surfaceSynthesis;
1612
+ const id = this.allocateId(preferredId, path, { treePath, band: Band.BeforeChildren, phase, rule });
1613
+ const instance: Json = { id, component: textComponent, [textProp]: text };
1614
+ if (variant !== undefined) instance.variant = variant;
1615
+ this.components.push(instance);
1616
+ this.diagnostics.push(
1617
+ {
1618
+ code: "surface-synthesized-text",
1619
+ message: `${path}: node text projected as a synthesized ${textComponent} child ('${id}') — the surface format has no text primitive.`,
1620
+ },
1621
+ treePath,
1622
+ Band.BeforeChildren,
1623
+ phase,
1624
+ rule,
1625
+ );
1626
+ this.diagnostics.pushFidelity(
1627
+ { source: `${path} (text)`, destination: `synthesized ${textComponent} '${id}'`, origin: "surfaceSynthesis.textComponent", kind: "synthesized", class: "synthesis-defaults", note: "the surface format has no text primitive" },
1628
+ treePath,
1629
+ Band.BeforeChildren,
1630
+ phase,
1631
+ rule,
1632
+ );
1633
+ return id;
434
1634
  }
435
1635
 
436
1636
  /** All text in a node's subtree, document order, space-joined. */
@@ -444,30 +1644,63 @@ class SurfaceEmitter {
444
1644
  return parts.join(" ");
445
1645
  }
446
1646
 
447
- private wrapInColumn(childIds: string[], parentId: string, path: string): string {
1647
+ private wrapInColumn(childIds: string[], parentId: string, path: string, treePath: readonly number[]): string {
448
1648
  const { wrapComponent, wrapChildrenProp } = this.profile.surfaceSynthesis;
449
- const id = this.allocateId(`${parentId}_col`, path);
450
- this.components.push({
451
- id,
452
- component: wrapComponent,
453
- [wrapChildrenProp]: childIds,
454
- });
455
- this.warnings.push({
456
- code: "surface-synthesized-wrap",
457
- message: `${path}: ${childIds.length} children wrapped in a synthesized ${wrapComponent} ('${id}') — the target slot takes a single child.`,
1649
+ const id = this.allocateId(`${parentId}_col`, path, {
1650
+ treePath,
1651
+ band: Band.AfterChildren,
1652
+ phase: Phase.Wrap,
1653
+ rule: 0,
458
1654
  });
1655
+ this.components.push({ id, component: wrapComponent, [wrapChildrenProp]: childIds });
1656
+ this.diagnostics.push(
1657
+ {
1658
+ code: "surface-synthesized-wrap",
1659
+ message: `${path}: ${childIds.length} children wrapped in a synthesized ${wrapComponent} ('${id}') — the target slot takes a single child.`,
1660
+ },
1661
+ treePath,
1662
+ Band.AfterChildren,
1663
+ Phase.Wrap,
1664
+ );
1665
+ this.diagnostics.pushFidelity(
1666
+ { source: `${path} (${childIds.length} children)`, destination: `synthesized ${wrapComponent} '${id}'`, origin: "surfaceSynthesis.wrapComponent", kind: "wrapped", class: "synthesis-defaults", note: "the target slot takes a single child" },
1667
+ treePath,
1668
+ Band.AfterChildren,
1669
+ Phase.Wrap,
1670
+ );
459
1671
  return id;
460
1672
  }
461
1673
 
462
- private allocateId(preferred: string, path: string): string {
1674
+ /**
1675
+ * Deterministic and stateful: `slug`, then `_2`, `_3`, … in first-come order.
1676
+ * Allocation order is emission order, which the model does not change.
1677
+ */
1678
+ private allocateId(
1679
+ preferred: string,
1680
+ path: string,
1681
+ where: { treePath: readonly number[]; band: Band; phase: Phase; rule: number },
1682
+ ): string {
463
1683
  let id = slug(preferred);
464
1684
  let n = 2;
465
1685
  while (this.usedIds.has(id)) id = `${slug(preferred)}_${n++}`;
466
1686
  if (id !== slug(preferred)) {
467
- this.warnings.push({
468
- code: "surface-id-deduplicated",
469
- message: `${path}: node id '${preferred}' already used; emitted as '${id}'.`,
470
- });
1687
+ this.diagnostics.push(
1688
+ {
1689
+ code: "surface-id-deduplicated",
1690
+ message: `${path}: node id '${preferred}' already used; emitted as '${id}'.`,
1691
+ },
1692
+ where.treePath,
1693
+ where.band,
1694
+ where.phase,
1695
+ where.rule,
1696
+ );
1697
+ this.diagnostics.pushFidelity(
1698
+ { source: `${path} (id '${preferred}')`, destination: `id '${id}'`, origin: "allocateId", kind: "deduplicated", class: "maps-cleanly", note: "surface ids are deterministic first-come; collisions suffix _2, _3, …" },
1699
+ where.treePath,
1700
+ where.band,
1701
+ where.phase,
1702
+ where.rule,
1703
+ );
471
1704
  }
472
1705
  this.usedIds.add(id);
473
1706
  return id;