@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
@@ -1,6 +1,10 @@
1
1
  import { shadcnProfile } from "../../transform/profiles.js";
2
2
  import { toHex6 } from "../../transform/color.js";
3
3
  import { collectChildren } from "../csr.js";
4
+ import { Band, Diagnostics, Phase } from "./diagnostics.js";
5
+ import { surfaceModelOf } from "../../transform/desugar.js";
6
+ import { validateProfileAgainstContract } from "../../transform/validate-v2.js";
7
+ import { describeSelector, emptySurfaceModel, isCollect, WriteOrder } from "../../transform/model.js";
4
8
  export class EmitSurfaceError extends Error {
5
9
  path;
6
10
  constructor(message, path) {
@@ -17,13 +21,26 @@ export function emitSurface(surface, doc, options = {}) {
17
21
  if (surface.system !== doc.name) {
18
22
  throw new EmitSurfaceError(`surface.system '${surface.system}' does not match contract name '${doc.name}'`, "$.system");
19
23
  }
24
+ // A v2 profile that does not fit this contract refuses before any node
25
+ // emits — the same gate transform() runs, so surface-only callers get the
26
+ // same fail-closed story.
27
+ validateProfileAgainstContract(profile, doc);
20
28
  const byDspackId = new Map();
21
29
  for (const plan of profile.components) {
22
30
  if (plan.dspackId)
23
31
  byDspackId.set(plan.dspackId, plan);
24
32
  }
33
+ // T1: a transparent ROOT still needs an instance renderers can start from
34
+ // (components[0], id "root"). The established arity discipline answers it:
35
+ // the root dissolves and its risen children wrap in the profile's
36
+ // synthesized wrap component, which becomes the root — synthesis, recorded,
37
+ // never silent. (ex.expense-report-form roots at `form` directly; refusing
38
+ // transparent roots would refuse the exact failure T1 exists to fix.)
25
39
  const emitter = new SurfaceEmitter(profile, byDspackId);
26
- const rootId = emitter.emitNode(surface.root, "$.root");
40
+ const rootPlan = byDspackId.get(surface.root.component);
41
+ const rootId = rootPlan && surfaceModelOf(rootPlan).transparent
42
+ ? emitter.emitTransparentRoot(surface.root, "$.root")
43
+ : emitter.emitNode(surface.root, "$.root");
27
44
  const surfaceId = options.surfaceId ?? slug(surface.intent);
28
45
  const theme = { agentDisplayName: `${doc.name} via dspack` };
29
46
  const primaryHex = primaryColor(doc, profile);
@@ -44,7 +61,7 @@ export function emitSurface(surface, doc, options = {}) {
44
61
  },
45
62
  ];
46
63
  void rootId; // root is components[0] by construction (pre-order emission)
47
- return { messages, warnings: emitter.warnings };
64
+ return { messages, warnings: emitter.diagnostics.ordered(), fidelity: emitter.diagnostics.orderedFidelity() };
48
65
  }
49
66
  function primaryColor(doc, profile) {
50
67
  const { category, name } = profile.primaryColorToken;
@@ -62,14 +79,20 @@ class SurfaceEmitter {
62
79
  profile;
63
80
  byDspackId;
64
81
  components = [];
65
- warnings = [];
82
+ diagnostics = new Diagnostics();
66
83
  usedIds = new Set();
67
84
  constructor(profile, byDspackId) {
68
85
  this.profile = profile;
69
86
  this.byDspackId = byDspackId;
70
87
  }
71
- /** Emits the component for `node` (and its subtree) and returns its instance id. */
72
- emitNode(node, path) {
88
+ /**
89
+ * Emits the component for `node` (and its subtree) and returns its instance id.
90
+ *
91
+ * Reads ONLY the internal model. The v1 directive names live exclusively in
92
+ * desugar.ts; if any of them appears below, the compatibility boundary has
93
+ * leaked (src/engine-boundary.test.ts fails on exactly that).
94
+ */
95
+ emitNode(node, path, treePath = [], donations = []) {
73
96
  const plan = this.byDspackId.get(node.component);
74
97
  if (!plan) {
75
98
  // A declared casualty refuses with its authored reason — the refusal is
@@ -82,283 +105,1035 @@ class SurfaceEmitter {
82
105
  throw new EmitSurfaceError(`unknown component '${node.component}': not a mapped component of the '${this.profile.catalogTitle}' profile ` +
83
106
  `(sub-components are consumed by their compound parent and cannot be emitted standalone)`, path);
84
107
  }
108
+ const model = surfaceModelOf(plan);
109
+ const at = (band, phase, rule = 0) => ({ treePath, band, phase, rule });
85
110
  // A2UI renderers begin at the component with id "root" (see the
86
111
  // hand-authored surfaces); the surface root always emits under that id.
87
- const id = path === "$.root" ? this.allocateId("root", path) : this.allocateId(node.id ?? plan.a2ui.toLowerCase(), path);
112
+ const id = path === "$.root"
113
+ ? this.allocateId("root", path, at(Band.BeforeChildren, Phase.IdAllocation))
114
+ : this.allocateId(node.id ?? plan.a2ui.toLowerCase(), path, at(Band.BeforeChildren, Phase.IdAllocation));
88
115
  // Reserve the slot so parent components precede children in the flat list.
89
116
  const index = this.components.length;
90
117
  this.components.push({});
91
118
  const instance = { id, component: plan.a2ui };
92
- this.applyPropMap(node, plan, instance, path);
93
- const sp = plan.surfacePlan ?? {};
94
- const consumesSubtree = Boolean(sp.subText || sp.subButtonText || sp.subTable);
95
- if (sp.structuralPassthrough) {
96
- for (const key of sp.structuralPassthrough) {
97
- const value = node.props?.[key];
98
- if (value !== undefined)
99
- instance[key] = value;
119
+ this.applyPropMap(node, plan, model, instance, path, treePath);
120
+ // A declared casualty is an authored refusal: it must never be laundered
121
+ // into a parent's text fold. The plan-lookup gate above only fires when a
122
+ // casualty is emitted as its OWN node; a consuming route or a re-identified
123
+ // sub walks the subtree directly and would otherwise fold the casualty's
124
+ // text in with a mere warning.
125
+ if (model.consumesSubtree || Object.keys(model.subIdentity).length > 0) {
126
+ this.refuseConsumedCasualty(node, path);
127
+ }
128
+ // Routes and collects, in declared order. Ordering of OUTPUT is first-wins
129
+ // (except where a route declares `overwrite`); ordering of DIAGNOSTICS is
130
+ // the explicit phase model, never this loop's order.
131
+ this.applyOperations(node, model, instance, id, path, treePath);
132
+ // T1 donations: contextual values a dissolved wrapper handed to this
133
+ // control, applied AFTER the control's own writes, first-wins — inherited
134
+ // context fills what the control left absent and never beats its own
135
+ // authored content. The ledger records exactly what happened either way.
136
+ for (const d of donations) {
137
+ const landed = this.write(instance, d.prop, d.value);
138
+ this.diagnostics.pushFidelity({
139
+ source: `${d.donorPath} (${d.donorComponent}.text)`,
140
+ destination: `${d.prop} @ ${path} (${node.component})`,
141
+ origin: d.origin,
142
+ kind: landed ? "donated" : "dropped",
143
+ class: landed ? "maps-cleanly" : "lossy",
144
+ note: landed
145
+ ? `donated by '${d.donorComponent}' to '${node.component}' — the dissolving boundary's single eligible control`
146
+ : `'${d.prop}' already written on '${node.component}'; the donated value did not land`,
147
+ }, treePath, Band.BeforeChildren, Phase.PropMap);
148
+ }
149
+ if (!model.consumesSubtree) {
150
+ this.emitChildren(node, model, instance, id, path, treePath);
151
+ }
152
+ // The one loss channel nothing else ledgers: node text on a plan with no
153
+ // self.text route. v1 has always silently discarded it — warnings are
154
+ // byte-frozen, so the WARNING stays absent — but the ledger exists
155
+ // precisely so no discard is unaccounted. (Consuming plans are exempt:
156
+ // their document-order walk may legitimately read the node's own text.)
157
+ const readsSelfText = model.routes.some((r) => r.from.some((s) => s.kind === "self-text"));
158
+ if (node.text !== undefined && !readsSelfText && !model.consumesSubtree) {
159
+ this.diagnostics.pushFidelity({
160
+ source: `${path} (text)`,
161
+ destination: "(discarded)",
162
+ origin: "(no rule)",
163
+ kind: "dropped",
164
+ class: "lossy",
165
+ note: `'${node.component}' has no self.text route; its text was discarded`,
166
+ }, treePath, Band.BeforeChildren, Phase.PropMap);
167
+ }
168
+ this.components[index] = instance;
169
+ return id;
170
+ }
171
+ /**
172
+ * Applies every route and collect in declared WriteOrder — never in
173
+ * declaration order and never in traversal happenstance. Object key order is
174
+ * observable, so this sequence is part of the compatibility contract.
175
+ *
176
+ * Consuming routes are the one group resolved together: a compound is walked
177
+ * ONCE in document order and each destination takes the first thing it sees.
178
+ * That is not an implementation detail leaking through — it is what consuming
179
+ * a compound means, and resolving those routes independently would let
180
+ * declaration order decide which of two siblings wins.
181
+ */
182
+ applyOperations(node, model, instance, id, path, treePath) {
183
+ const consuming = model.routes
184
+ .map((route, rule) => ({ route, rule }))
185
+ .filter(({ route }) => route.order === WriteOrder.Consume);
186
+ const steps = [];
187
+ for (const { route, rule } of model.routes.map((route, rule) => ({ route, rule }))) {
188
+ if (route.order === WriteOrder.Consume || route.order === WriteOrder.Children)
189
+ continue;
190
+ if (route.order === WriteOrder.Slot) {
191
+ steps.push({ order: route.order, run: () => this.applySlotRoute(node, model, route, rule, instance, path, treePath) });
192
+ continue;
100
193
  }
194
+ steps.push({ order: route.order, run: () => this.applyRoute(node, route, rule, instance, id, path, treePath) });
101
195
  }
102
- if (sp.subText || sp.subButtonText)
103
- this.applySubContent(node, sp.subText ?? {}, sp.subButtonText ?? {}, instance, path);
104
- if (sp.subTable)
105
- this.applySubTable(node, sp.subTable, instance, path);
106
- if (sp.textProp && node.text !== undefined)
107
- instance[sp.textProp] = node.text;
108
- if (sp.textChildProp && node.text !== undefined) {
109
- instance[sp.textChildProp] = this.emitTextPrimitive(node.text, `${id}_label`, path);
196
+ for (const [rule, collect] of model.collects.entries()) {
197
+ if (collect.as.kind === "inline")
198
+ continue;
199
+ steps.push({ order: collect.order, run: () => this.applyCollect(node, model, collect, rule, instance, path, treePath) });
200
+ }
201
+ if (consuming.length > 0) {
202
+ steps.push({ order: WriteOrder.Consume, run: () => this.applyConsuming(node, consuming, instance, path, treePath) });
110
203
  }
111
- if (sp.actionProp) {
112
- const eventName = slug(node.id ?? instance.confirmLabel ?? node.text ?? node.component);
113
- instance[sp.actionProp] = { event: { name: eventName, context: {} } };
114
- this.warnings.push({
115
- code: "surface-synthesized-action",
116
- message: `${path}: A2UI requires a declarative action on ${plan.a2ui}; synthesized event '${eventName}'.`,
117
- });
204
+ if (model.collects.some((c) => c.as.kind !== "inline")) {
205
+ steps.push({ order: WriteOrder.Collect + 1, run: () => this.closeCollects(node, model, path, treePath) });
118
206
  }
119
- if (!consumesSubtree) {
120
- const childNodes = sp.subFlatten ? this.flattenSubs(node, sp.subFlatten, path) : collectChildren(node);
121
- if (childNodes.length > 0) {
122
- const childIds = childNodes.map((child, i) => "textVariant" in child
123
- ? this.emitTextPrimitive(child.text, `${id}_${slug(child.textVariant)}`, path, child.textVariant)
124
- : this.emitNode(child.node, `${path}${child.suffix}[${i}]`));
125
- if (sp.childrenProp) {
126
- instance[sp.childrenProp] = childIds;
207
+ if (model.routes.some((r) => r.order === WriteOrder.Slot)) {
208
+ steps.push({ order: WriteOrder.Slot + 1, run: () => this.closeSlots(node, model, path, treePath) });
209
+ }
210
+ steps.sort((a, b) => a.order - b.order);
211
+ for (const step of steps)
212
+ step.run();
213
+ }
214
+ /**
215
+ * One document-order walk serving every consuming route, then the audited
216
+ * lift for any destination still empty, then the composition warning.
217
+ */
218
+ applyConsuming(node, consuming, instance, path, treePath) {
219
+ const record = (route, rule, nPath, component) => {
220
+ this.diagnostics.pushFidelity({
221
+ source: `${nPath} (${component}.text)`,
222
+ destination: route.to.name,
223
+ origin: route.origin,
224
+ kind: "moved",
225
+ class: "maps-cleanly",
226
+ }, treePath, Band.BeforeChildren, Phase.SubContentFlatten, rule);
227
+ };
228
+ const visit = (n, nPath, insideSubs) => {
229
+ for (const { route, rule } of consuming) {
230
+ if (instance[route.to.name] !== undefined)
231
+ continue;
232
+ const primary = route.from[0];
233
+ if (primary.kind === "sub-text") {
234
+ if (primary.subs.includes(n.component) && n.text !== undefined) {
235
+ instance[route.to.name] = n.text;
236
+ record(route, rule, nPath, n.component);
237
+ }
127
238
  }
128
- else if (sp.childProp) {
129
- instance[sp.childProp] = childIds.length === 1 ? childIds[0] : this.wrapInColumn(childIds, id, path);
239
+ else if (primary.kind === "sub-label") {
240
+ if (n !== node && n.text !== undefined && primary.subs.some((sub) => insideSubs.has(sub))) {
241
+ const plan = this.byDspackId.get(n.component);
242
+ const bearsLabel = plan !== undefined && surfaceModelOf(plan).routes.some((r) => r.to.kind === "text-child");
243
+ if (bearsLabel) {
244
+ instance[route.to.name] = n.text;
245
+ record(route, rule, nPath, n.component);
246
+ }
247
+ }
130
248
  }
131
- else {
132
- throw new EmitSurfaceError(`component '${node.component}' has children but its surface plan declares no child slot`, path);
249
+ }
250
+ const next = new Set(insideSubs);
251
+ for (const { route } of consuming) {
252
+ const primary = route.from[0];
253
+ if (primary.kind === "sub-label" && primary.subs.includes(n.component))
254
+ next.add(n.component);
255
+ }
256
+ collectChildren(n).forEach((child, i) => visit(child.node, `${nPath}${child.suffix}[${i}]`, next));
257
+ };
258
+ visit(node, path, new Set());
259
+ for (const { route, rule } of consuming) {
260
+ if (instance[route.to.name] !== undefined)
261
+ continue;
262
+ for (const selector of route.from.slice(1)) {
263
+ const found = this.resolve(node, selector, path, treePath, rule, route);
264
+ if (found !== undefined) {
265
+ instance[route.to.name] = found;
266
+ this.diagnostics.pushFidelity({
267
+ source: `${path} (fallback)`,
268
+ destination: route.to.name,
269
+ origin: route.origin,
270
+ kind: selector.kind === "sub-text-lift" ? "lifted" : "moved",
271
+ class: "maps-cleanly",
272
+ note: selector.kind === "sub-text-lift" ? "audited lift: relocation of existing text, never synthesis" : undefined,
273
+ }, treePath, Band.BeforeChildren, Phase.LabelLift, rule);
274
+ break;
133
275
  }
134
276
  }
135
277
  }
136
- this.components[index] = instance;
137
- return id;
278
+ this.diagnostics.push({
279
+ code: "surface-composition-flattened",
280
+ message: `${path}: compound '${node.component}' subtree flattened onto emitted props (documented casualty; nested props beyond text are not carried).`,
281
+ }, treePath, Band.BeforeChildren, Phase.SubContentFlatten);
282
+ this.diagnostics.pushFidelity({
283
+ source: `${path} (${node.component} subtree)`,
284
+ destination: "(props of this instance)",
285
+ origin: consuming.map(({ route }) => route.origin).join(", "),
286
+ kind: "flattened",
287
+ class: "lossy",
288
+ note: "compound composition consumed into props; structure and nested props beyond text are not carried",
289
+ }, treePath, Band.BeforeChildren, Phase.SubContentFlatten);
290
+ }
291
+ /**
292
+ * Writes `value` unless the destination is taken and the route is
293
+ * first-wins. Returns whether the write LANDED — the fidelity ledger must
294
+ * record a discarded harvest as discarded, never as a clean move.
295
+ */
296
+ write(instance, name, value, overwrite) {
297
+ if (overwrite || instance[name] === undefined) {
298
+ instance[name] = value;
299
+ return true;
300
+ }
301
+ return false;
302
+ }
303
+ applyRoute(node, route, rule, instance, id, path, treePath) {
304
+ // `children` is not a value route: it produces instances, and is handled
305
+ // with the child walk so ids exist in emission order.
306
+ if (route.from.some((s) => s.kind === "children"))
307
+ return;
308
+ for (const selector of route.from) {
309
+ if (selector.kind === "synthesized-action") {
310
+ const eventName = slug(node.id ?? instance.confirmLabel ?? node.text ?? node.component);
311
+ this.write(instance, route.to.name, { event: { name: eventName, context: {} } }, route.overwrite);
312
+ this.diagnostics.pushFidelity({
313
+ source: "(no source: A2UI requires a declarative action)",
314
+ destination: route.to.name,
315
+ origin: route.origin,
316
+ kind: "synthesized",
317
+ class: "synthesis-defaults",
318
+ note: `event name '${eventName}' derived from the node's id/label/component slug`,
319
+ }, treePath, Band.BeforeChildren, Phase.Action, rule);
320
+ this.diagnostics.push({
321
+ code: "surface-synthesized-action",
322
+ message: `${path}: A2UI requires a declarative action on ${instance.component}; synthesized event '${eventName}'.`,
323
+ }, treePath, Band.BeforeChildren, Phase.Action, rule);
324
+ return;
325
+ }
326
+ const found = this.resolve(node, selector, path, treePath, rule, route);
327
+ if (found === undefined)
328
+ continue;
329
+ if (route.to.kind === "text-child") {
330
+ this.write(instance, route.to.name, this.emitTextPrimitive(String(found), `${id}_label`, path, treePath, Phase.TextChild, rule), route.overwrite);
331
+ }
332
+ else {
333
+ const landed = this.write(instance, route.to.name, found, route.overwrite);
334
+ this.diagnostics.pushFidelity(landed
335
+ ? {
336
+ source: `${path} (${describeSelector(selector)})`,
337
+ destination: route.to.name,
338
+ origin: route.origin,
339
+ kind: selector.kind === "self-prop" ? "projected" : "moved",
340
+ class: "maps-cleanly",
341
+ }
342
+ : {
343
+ source: `${path} (${describeSelector(selector)})`,
344
+ destination: "(discarded)",
345
+ origin: route.origin,
346
+ kind: "dropped",
347
+ class: "lossy",
348
+ note: `'${route.to.name}' was already written by an earlier phase; the harvested value did not land`,
349
+ }, treePath, Band.BeforeChildren, selector.kind === "self-prop" ? Phase.PropMap : Phase.TextChild, rule);
350
+ }
351
+ return; // ordered fallback: the first selector that yields wins
352
+ }
353
+ }
354
+ /** Resolves one selector against the node's subtree; `undefined` when it yields nothing. */
355
+ resolve(node, selector, path, treePath, rule, route) {
356
+ switch (selector.kind) {
357
+ case "self-text":
358
+ return node.text;
359
+ case "self-prop":
360
+ return node.props?.[selector.prop];
361
+ case "sub-text": {
362
+ // v1 visited the node itself as well as its descendants.
363
+ let hit;
364
+ const visit = (n) => {
365
+ if (hit === undefined && selector.subs.includes(n.component) && n.text !== undefined)
366
+ hit = n.text;
367
+ for (const child of collectChildren(n))
368
+ visit(child.node);
369
+ };
370
+ visit(node);
371
+ return hit;
372
+ }
373
+ case "sub-label": {
374
+ // Only a label-bearing component qualifies — one whose own model routes
375
+ // its text to a text-child destination — never incidental descendant text.
376
+ let hit;
377
+ const visit = (n, insideSub) => {
378
+ if (hit === undefined && insideSub && n !== node && n.text !== undefined) {
379
+ const plan = this.byDspackId.get(n.component);
380
+ const bearsLabel = plan !== undefined && surfaceModelOf(plan).routes.some((r) => r.to.kind === "text-child");
381
+ if (bearsLabel)
382
+ hit = n.text;
383
+ }
384
+ for (const child of collectChildren(n))
385
+ visit(child.node, insideSub || selector.subs.includes(n.component));
386
+ };
387
+ visit(node, false);
388
+ return hit;
389
+ }
390
+ case "sub-text-lift": {
391
+ // Audited lift: relocation of text that exists, never synthesis. If
392
+ // nothing exists to lift the destination stays missing and gate A3
393
+ // refuses the instance, exactly as before.
394
+ const lift = (n, inside) => {
395
+ const here = inside || selector.subs.includes(n.component);
396
+ if (here && n.text !== undefined && n.text !== "")
397
+ return { text: n.text, component: n.component };
398
+ for (const child of collectChildren(n)) {
399
+ const found = lift(child.node, here);
400
+ if (found)
401
+ return found;
402
+ }
403
+ return undefined;
404
+ };
405
+ const found = lift(node, false);
406
+ if (!found)
407
+ return undefined;
408
+ this.diagnostics.push({
409
+ code: "surface-label-lifted",
410
+ 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).`,
411
+ }, treePath, Band.BeforeChildren, Phase.LabelLift, rule);
412
+ return found.text;
413
+ }
414
+ case "subtree-text": {
415
+ let hit;
416
+ const visit = (n) => {
417
+ if (hit === undefined && selector.subs.includes(n.component))
418
+ hit = n;
419
+ for (const child of collectChildren(n))
420
+ visit(child.node);
421
+ };
422
+ visit(node);
423
+ return hit ? this.subtreeText(hit) : undefined;
424
+ }
425
+ case "children":
426
+ case "synthesized-action":
427
+ return undefined;
428
+ }
138
429
  }
139
430
  /** CSR props -> A2UI props via the profile's existing PropPlan projections. */
140
- applyPropMap(node, plan, instance, path) {
431
+ applyPropMap(node, plan, model, instance, path, treePath) {
432
+ // A prop routed verbatim to a SAME-NAMED destination is projected by that
433
+ // route, not by the prop map — v1 spelled this `structuralPassthrough`.
434
+ // The name check matters: a v2 route may read a declared contract prop
435
+ // into a differently-named destination, and that read must not suppress
436
+ // the prop's own projection (both writes are real, to distinct names).
437
+ const routedVerbatim = new Set(model.routes
438
+ .filter((r) => r.from.some((s) => s.kind === "self-prop" && s.prop === r.to.name))
439
+ .map((r) => r.from.find((s) => s.kind === "self-prop").prop));
141
440
  for (const [prop, raw] of Object.entries(node.props ?? {})) {
142
- if (plan.surfacePlan?.structuralPassthrough?.includes(prop))
441
+ if (routedVerbatim.has(prop))
143
442
  continue;
144
443
  const pp = plan.propMap?.[prop];
145
444
  if (!pp) {
146
- this.warnings.push({
445
+ this.diagnostics.push({
147
446
  code: "surface-prop-dropped",
148
447
  message: `${path}: prop '${prop}' on '${node.component}' has no A2UI projection; dropped.`,
149
- });
448
+ }, treePath, Band.BeforeChildren, Phase.PropMap);
449
+ this.diagnostics.pushFidelity({ source: `${path} (props.${prop})`, destination: "(discarded)", origin: `propMap.${prop}`, kind: "dropped", class: "lossy", note: "no A2UI projection" }, treePath, Band.BeforeChildren, Phase.PropMap);
150
450
  continue;
151
451
  }
152
- const value = pp.valueMap ? (pp.valueMap[String(raw)] ?? pp.default) : raw;
452
+ const mapped = pp.valueMap ? pp.valueMap[String(raw)] : undefined;
453
+ const value = pp.valueMap ? (mapped ?? pp.default) : raw;
153
454
  if (value === undefined) {
154
- this.warnings.push({
455
+ this.diagnostics.push({
155
456
  code: "surface-prop-value-dropped",
156
457
  message: `${path}: value '${String(raw)}' of prop '${prop}' has no projection and no default; dropped.`,
157
- });
458
+ }, treePath, Band.BeforeChildren, Phase.PropMap);
459
+ this.diagnostics.pushFidelity({ source: `${path} (props.${prop}='${String(raw)}')`, destination: "(discarded)", origin: `propMap.${prop}`, kind: "dropped", class: "lossy", note: "value has no projection and no default" }, treePath, Band.BeforeChildren, Phase.PropMap);
158
460
  continue;
159
461
  }
160
462
  instance[pp.a2ui] = value;
463
+ this.diagnostics.pushFidelity({
464
+ source: `${path} (props.${prop})`,
465
+ destination: pp.a2ui,
466
+ origin: `propMap.${prop}`,
467
+ kind: "projected",
468
+ class: pp.valueMap && mapped === undefined ? "synthesis-defaults" : "maps-cleanly",
469
+ note: pp.valueMap && mapped === undefined ? `value '${String(raw)}' fell back to the declared default '${String(pp.default)}'` : undefined,
470
+ }, treePath, Band.BeforeChildren, Phase.PropMap);
161
471
  }
162
472
  }
163
473
  /**
164
- * Compound flattening: pull text out of named sub-components anywhere in the
165
- * subtree. The subtree is consumed — the documented composition casualty.
474
+ * Refuse when a consumed subtree contains a component the profile declared a
475
+ * casualty. Consumption is how compounds fold their parts into props; it is
476
+ * NOT an escape hatch around an author's "this cannot be represented".
477
+ * Fail-closed and loud, with the authored reason, exactly like the direct
478
+ * emission path — including the offending node's own path, so the refusal
479
+ * points at the casualty rather than the parent that would have eaten it.
166
480
  */
167
- applySubContent(node, subText, subButtonText, instance, path) {
168
- const visit = (n, insideSub) => {
169
- const textProp = subText[n.component];
170
- if (textProp !== undefined && n.text !== undefined && instance[textProp] === undefined) {
171
- instance[textProp] = n.text;
172
- }
173
- const buttonProp = insideSub ? subButtonText[insideSub] : undefined;
174
- if (buttonProp !== undefined && n.text !== undefined && instance[buttonProp] === undefined && n !== node) {
175
- // Only a label-bearing component qualifies (one whose surface plan
176
- // projects its text as a child label, e.g. the trigger's button) —
177
- // never incidental text on other descendants.
178
- const plan = this.byDspackId.get(n.component);
179
- if (plan?.surfacePlan?.textChildProp)
180
- instance[buttonProp] = n.text;
481
+ refuseConsumedCasualty(node, path) {
482
+ const walk = (n, nodePath) => {
483
+ if (n !== node) {
484
+ const casualty = this.profile.casualtyComponents.find((c) => c.dspackId === n.component);
485
+ if (casualty && !this.byDspackId.has(n.component)) {
486
+ throw new EmitSurfaceError(`component '${n.component}' is a declared casualty (${casualty.class}) of the ` +
487
+ `'${this.profile.catalogTitle}' profile and cannot be consumed into ` +
488
+ `'${node.component}': ${casualty.reason}`, nodePath);
489
+ }
181
490
  }
182
- const nextInside = subButtonText[n.component] !== undefined ? n.component : insideSub;
183
- for (const child of collectChildren(n))
184
- visit(child.node, nextInside);
491
+ collectChildren(n).forEach((child, i) => walk(child.node, `${nodePath}${child.suffix}[${i}]`));
185
492
  };
186
- visit(node, null);
187
- // Audited label lift (spec v0.4 amendment, 2026-07-04): when no
188
- // label-bearing component inside a subButtonText sub carried direct text,
189
- // lift the FIRST direct text found under that sub (the sub's own text
190
- // included, document order). This is a LIFT of existing text — relocation,
191
- // never synthesis: if nothing exists to lift, the prop stays missing and
192
- // gate A3 refuses the instance exactly as before. Every lift is recorded,
193
- // like the other documented casualties, so audit reports can count them.
194
- for (const [subId, buttonProp] of Object.entries(subButtonText)) {
195
- if (instance[buttonProp] !== undefined)
196
- continue;
197
- const lift = (n, inside) => {
198
- const here = inside || n.component === subId;
199
- if (here && n.text !== undefined && n.text !== "")
200
- return { text: n.text, component: n.component };
201
- for (const child of collectChildren(n)) {
202
- const found = lift(child.node, here);
203
- if (found)
204
- return found;
493
+ walk(node, path);
494
+ }
495
+ /**
496
+ * Repetition: collect repeated sub-structures into array-valued destinations.
497
+ * Nothing here is table-shaped — the depth is nesting and the record key is an
498
+ * item field name. Cells flatten to their subtree TEXT in document order;
499
+ * nested structure and props are a warned per-cell loss, never re-interpreted.
500
+ */
501
+ /**
502
+ * Repetition: collect one repeated sub-structure into an array-valued
503
+ * destination. Nothing here is table-shaped — the depth is nesting and the
504
+ * record key is an item field name. Cells flatten to their subtree TEXT in
505
+ * document order; nested structure and props are a warned per-cell loss,
506
+ * never re-interpreted into semantic fields.
507
+ */
508
+ applyCollect(node, model, collect, rule, instance, path, treePath) {
509
+ void model;
510
+ if (collect.as.kind === "inline")
511
+ return;
512
+ // T2 item-mode: each descendant matching `of` (document order) becomes
513
+ // one record whose fields resolve against THAT item's own node. Absent
514
+ // sources omit the field — gate A3 arbitrates required record shapes,
515
+ // never synthesis. Sibling content the collect does not claim follows
516
+ // the ordinary consumed-subtree accounting (closeCollects).
517
+ if (collect.fields) {
518
+ const itemLocal = (n, sel) => sel.kind === "self-text" ? n.text : sel.kind === "self-id" ? n.id : sel.kind === "self-prop" ? n.props?.[sel.prop] : undefined;
519
+ // Gather left items and (when a join is declared) joined counterparts,
520
+ // both in document order.
521
+ const lefts = [];
522
+ const rights = [];
523
+ const gather = (n, nPath) => {
524
+ if (collect.of.includes(n.component)) {
525
+ lefts.push({ n, nPath });
526
+ return; // an item's subtree is the item's; nested items do not re-match
205
527
  }
206
- return undefined;
528
+ if (collect.join?.with.includes(n.component)) {
529
+ rights.push({ n, nPath });
530
+ return;
531
+ }
532
+ collectChildren(n).forEach((c, i) => gather(c.node, `${nPath}${c.suffix}[${i}]`));
207
533
  };
208
- const found = lift(node, false);
209
- if (found) {
210
- instance[buttonProp] = found.text;
211
- this.warnings.push({
212
- code: "surface-label-lifted",
213
- message: `${path}: '${buttonProp}' lifted from direct text on '${found.component}' inside '${subId}' — no label-bearing component carried it (documented projection extension; lift, never synthesis).`,
214
- });
534
+ collectChildren(node).forEach((c, i) => gather(c.node, `${path}${c.suffix}[${i}]`));
535
+ // T3: the declared key join. Every edge refuses — the profile names
536
+ // the relation, the emitter never infers one.
537
+ const counterparts = new Map();
538
+ if (collect.join) {
539
+ const j = collect.join;
540
+ const seenLeft = new Map();
541
+ for (const item of lefts) {
542
+ const key = itemLocal(item.n, j.leftKey);
543
+ if (typeof key !== "string" || key === "") {
544
+ throw new EmitSurfaceError(`join '${j.origin}': item '${item.n.component}' carries no key (${describeSelector(j.leftKey)}); a keyless item cannot participate in a declared join`, item.nPath);
545
+ }
546
+ const prior = seenLeft.get(key);
547
+ if (prior !== undefined) {
548
+ throw new EmitSurfaceError(`join '${j.origin}': duplicate left key '${key}' (also at ${prior}); join keys must be unique on each side`, item.nPath);
549
+ }
550
+ seenLeft.set(key, item.nPath);
551
+ }
552
+ for (const cp of rights) {
553
+ const key = itemLocal(cp.n, j.rightKey);
554
+ if (typeof key !== "string" || key === "") {
555
+ throw new EmitSurfaceError(`join '${j.origin}': counterpart '${cp.n.component}' carries no key (${describeSelector(j.rightKey)})`, cp.nPath);
556
+ }
557
+ if (counterparts.has(key)) {
558
+ throw new EmitSurfaceError(`join '${j.origin}': duplicate right key '${key}'; join keys must be unique on each side`, cp.nPath);
559
+ }
560
+ if (!seenLeft.has(key)) {
561
+ throw new EmitSurfaceError(`join '${j.origin}': counterpart '${cp.n.component}' key '${key}' matches no item; a dangling counterpart is a contradiction, not surplus`, cp.nPath);
562
+ }
563
+ counterparts.set(key, cp);
564
+ }
215
565
  }
566
+ const records = [];
567
+ for (const item of lefts) {
568
+ const record = {};
569
+ for (const [fieldName, sel] of Object.entries(collect.fields)) {
570
+ const value = itemLocal(item.n, sel);
571
+ if (value !== undefined)
572
+ record[fieldName] = value;
573
+ }
574
+ this.diagnostics.pushFidelity({
575
+ source: `${item.nPath} (${item.n.component})`,
576
+ destination: collect.as.name,
577
+ origin: collect.origin,
578
+ kind: "moved",
579
+ class: "maps-cleanly",
580
+ note: `item record { ${Object.keys(record).join(", ")} } collected`,
581
+ }, treePath, Band.BeforeChildren, Phase.TableBody, rule);
582
+ if (collect.join) {
583
+ const j = collect.join;
584
+ const key = itemLocal(item.n, j.leftKey);
585
+ const cp = counterparts.get(key);
586
+ if (!cp && !j.optional) {
587
+ throw new EmitSurfaceError(`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)`, item.nPath);
588
+ }
589
+ if (cp) {
590
+ for (const [fieldName, jSel] of Object.entries(j.fields)) {
591
+ if ("kind" in jSel && jSel.kind === "joined-children") {
592
+ // The slot-valued field: the counterpart's children emit as
593
+ // instances; the record carries the reference. Repetition's
594
+ // ratified slot form — not T4 multi-slot routing. The child
595
+ // list goes through the SAME rewriting as any parent's
596
+ // (mirroring the transparent-root host pattern), so a
597
+ // transparent top-level child inside a joined panel
598
+ // dissolves instead of refusing as an unroutable instance.
599
+ const spliced = this.rewriteChildren(cp.n, emptySurfaceModel(), cp.nPath, treePath);
600
+ if (spliced.length === 0)
601
+ continue;
602
+ const ids = spliced.map((k, ki) => "textVariant" in k
603
+ ? this.emitTextPrimitive(k.text, `${slug(key)}_${slug(k.textVariant)}`, cp.nPath, [...treePath, Band.Children, records.length, ki], Phase.TextChild, 0, k.textVariant)
604
+ : this.emitNode(k.node, `${cp.nPath}${k.suffix}[${ki}]`, [...treePath, Band.Children, records.length], k.donations ?? []));
605
+ record[fieldName] =
606
+ ids.length === 1 ? ids[0] : this.wrapInColumn(ids, `${slug(key)}`, cp.nPath, treePath);
607
+ }
608
+ else {
609
+ const value = itemLocal(cp.n, jSel);
610
+ if (value !== undefined)
611
+ record[fieldName] = value;
612
+ }
613
+ }
614
+ this.diagnostics.pushFidelity({
615
+ source: `${cp.nPath} (${cp.n.component})`,
616
+ destination: `${collect.as.name} @ item '${key}'`,
617
+ origin: j.origin,
618
+ kind: "joined",
619
+ class: "maps-cleanly",
620
+ note: `counterpart joined on key '${key}' -> fields { ${Object.keys(j.fields).join(", ")} }`,
621
+ }, treePath, Band.BeforeChildren, Phase.TableBody, rule);
622
+ }
623
+ }
624
+ records.push(record);
625
+ }
626
+ if (records.length > 0) {
627
+ const landed = this.write(instance, collect.as.name, records);
628
+ if (!landed) {
629
+ this.diagnostics.pushFidelity({ 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` }, treePath, Band.BeforeChildren, Phase.TableBody, rule);
630
+ }
631
+ }
632
+ return;
633
+ }
634
+ const out = [];
635
+ const flat = [];
636
+ const scalarField = Object.values(collect.item ?? {}).find((f) => isCollect(f) && f.scalar);
637
+ const itemKey = Object.keys(collect.item ?? {})[0] ?? "items";
638
+ for (const child of collectChildren(node)) {
639
+ if (!collect.of.includes(child.node.component))
640
+ continue;
641
+ const childPath = `${path}${child.suffix}`;
642
+ for (const inner of collectChildren(child.node)) {
643
+ if (!scalarField || !scalarField.of.includes(inner.node.component)) {
644
+ this.diagnostics.push({
645
+ code: "surface-sub-dropped",
646
+ message: `${childPath}: '${inner.node.component}' inside '${child.node.component}' has no slot; dropped.`,
647
+ }, treePath, Band.BeforeChildren, Phase.TableBody, rule);
648
+ this.diagnostics.pushFidelity({ source: `${childPath} (${inner.node.component})`, destination: "(discarded)", origin: collect.origin, kind: "dropped", class: "lossy", note: "no slot inside the collected repetition" }, treePath, Band.BeforeChildren, Phase.TableBody, rule);
649
+ continue;
650
+ }
651
+ const cells = this.collectRow(inner.node, scalarField, `${childPath}${inner.suffix}`, treePath, rule);
652
+ if (this.isFlatTarget(collect))
653
+ flat.push(...cells);
654
+ else
655
+ out.push({ [itemKey]: cells });
656
+ }
657
+ }
658
+ const value = this.isFlatTarget(collect) ? flat : out;
659
+ if (value.length > 0) {
660
+ const landed = this.write(instance, collect.as.name, value);
661
+ this.diagnostics.pushFidelity(landed
662
+ ? {
663
+ source: `${path} (${collect.of.join("|")} repetitions)`,
664
+ destination: collect.as.name,
665
+ origin: collect.origin,
666
+ kind: "moved",
667
+ class: "maps-cleanly",
668
+ note: this.isFlatTarget(collect)
669
+ ? `${flat.length} cell(s) collected into one flat list`
670
+ : `${out.length} record(s) collected`,
671
+ }
672
+ : {
673
+ source: `${path} (${collect.of.join("|")} repetitions)`,
674
+ destination: "(discarded)",
675
+ origin: collect.origin,
676
+ kind: "dropped",
677
+ class: "lossy",
678
+ note: `'${collect.as.name}' was already written by an earlier phase; the collected ${this.isFlatTarget(collect) ? "cells" : "records"} did not land`,
679
+ }, treePath, Band.BeforeChildren, Phase.TableBody, rule);
680
+ }
681
+ }
682
+ /**
683
+ * After every collect has run: anything the collects and routes did not claim
684
+ * is either an explicit drop or an unrecognized sub — both warned, never
685
+ * silently ignored — followed by the composition casualty for the compound.
686
+ */
687
+ /**
688
+ * T4: one slot route — the ordered children of exactly one descendant
689
+ * instance of the named sub become instances, and the slot carries the
690
+ * reference (multi wraps in the profile's wrap component, exactly like
691
+ * T3's joined-children). The region's child list goes through the SAME
692
+ * rewriting as any parent's (this plan's dispositions apply to nested
693
+ * subs), with subs claimed by sibling routes skipped — their consumption
694
+ * is their own route's ledger entry. Zero regions leave the destination
695
+ * absent (gate A3 arbitrates); several refuse: a slot names one region.
696
+ */
697
+ applySlotRoute(node, model, route, rule, instance, path, treePath) {
698
+ const sel = route.from[0];
699
+ if (sel.kind !== "sub-children")
700
+ return;
701
+ const region = sel.subs[0];
702
+ const found = [];
703
+ const locate = (n, nPath) => {
704
+ for (const c of collectChildren(n)) {
705
+ if (c.node.component === region)
706
+ found.push({ n: c.node, nPath: `${nPath}${c.suffix}` });
707
+ locate(c.node, `${nPath}${c.suffix}`);
708
+ }
709
+ };
710
+ locate(node, path);
711
+ if (found.length === 0)
712
+ return; // absent region: the destination stays absent and A3 arbitrates
713
+ if (found.length > 1) {
714
+ throw new EmitSurfaceError(`slot route '${route.origin}': ${found.length} instances of '${region}' in this '${node.component}'; ` +
715
+ `a slot names ONE region — exactly one may appear`, path);
216
716
  }
217
- this.warnings.push({
717
+ const claimed = new Set();
718
+ for (const r of model.routes) {
719
+ if (r === route)
720
+ continue;
721
+ for (const s of r.from)
722
+ if ("subs" in s)
723
+ for (const id of s.subs)
724
+ claimed.add(id);
725
+ }
726
+ for (const c of model.collects)
727
+ for (const id of [...c.of, ...(c.join?.with ?? [])])
728
+ claimed.add(id);
729
+ const src = found[0];
730
+ const spliced = this.rewriteChildren(src.n, model, src.nPath, treePath, claimed);
731
+ if (spliced.length === 0)
732
+ return; // an empty region carries nothing; absent, A3 arbitrates
733
+ const ids = spliced.map((k, ki) => "textVariant" in k
734
+ ? this.emitTextPrimitive(k.text, `${slug(region)}_${slug(k.textVariant)}`, src.nPath, [...treePath, Band.BeforeChildren, rule, ki], Phase.SubContentFlatten, rule, k.textVariant)
735
+ : this.emitNode(k.node, `${src.nPath}${k.suffix}[${ki}]`, [...treePath, Band.BeforeChildren, rule, ki], k.donations ?? []));
736
+ const ref = ids.length === 1 ? ids[0] : this.wrapInColumn(ids, slug(region), src.nPath, treePath);
737
+ const landed = this.write(instance, route.to.name, ref);
738
+ this.diagnostics.pushFidelity({
739
+ source: `${src.nPath} (${region} children)`,
740
+ destination: `${route.to.name} @ ${path} (${node.component})`,
741
+ origin: route.origin,
742
+ kind: landed ? "moved" : "dropped",
743
+ class: landed ? "maps-cleanly" : "lossy",
744
+ note: landed
745
+ ? `region '${region}' emitted as instances; the slot carries the reference`
746
+ : `'${route.to.name}' already written; the region's reference did not land`,
747
+ }, treePath, Band.BeforeChildren, Phase.SubContentFlatten, rule);
748
+ }
749
+ /**
750
+ * Fail-closed closure for a slot-routed compound: every DIRECT child must
751
+ * be a claimed region, a route-consumed sub, a collected family, or carry
752
+ * a disposition — an unclaimed child is structural content with no
753
+ * destination, and approximating it silently is exactly what this engine
754
+ * refuses to do.
755
+ */
756
+ closeSlots(node, model, path, treePath) {
757
+ const claimed = new Set();
758
+ for (const r of model.routes)
759
+ for (const s of r.from)
760
+ if ("subs" in s)
761
+ for (const id of s.subs)
762
+ claimed.add(id);
763
+ for (const c of model.collects)
764
+ for (const id of [...c.of, ...(c.join?.with ?? [])])
765
+ claimed.add(id);
766
+ for (const child of collectChildren(node)) {
767
+ const c = child.node.component;
768
+ if (claimed.has(c) || c in model.subIdentity)
769
+ continue;
770
+ const reason = model.drops[c];
771
+ if (reason !== undefined) {
772
+ const childPath = `${path}${child.suffix}`;
773
+ this.diagnostics.push({ code: "surface-sub-dropped", message: `${childPath}: '${c}' dropped: ${reason}.` }, treePath, Band.BeforeChildren, Phase.SubContentFlatten);
774
+ this.diagnostics.pushFidelity({ source: `${childPath} (${c})`, destination: "(discarded)", origin: `drops.${c}`, kind: "dropped", class: "lossy", note: reason }, treePath, Band.BeforeChildren, Phase.SubContentFlatten);
775
+ continue;
776
+ }
777
+ throw new EmitSurfaceError(`'${c}' is a direct child of slot-routed compound '${node.component}' with no destination — ` +
778
+ `every region must be claimed by a route, collected, or carry a disposition`, `${path}${child.suffix}`);
779
+ }
780
+ }
781
+ closeCollects(node, model, path, treePath) {
782
+ const claimedByCollect = new Set(model.collects.flatMap((c) => [...c.of, ...(c.join?.with ?? [])]));
783
+ for (const child of collectChildren(node)) {
784
+ const c = child.node.component;
785
+ if (claimedByCollect.has(c) || this.claimedByRoute(model, c))
786
+ continue;
787
+ const childPath = `${path}${child.suffix}`;
788
+ const reason = model.drops[c];
789
+ const itemMode = model.collects.some((col) => col.fields);
790
+ this.diagnostics.push({
791
+ code: "surface-sub-dropped",
792
+ message: reason
793
+ ? `${childPath}: '${c}' dropped: ${reason}.`
794
+ : itemMode
795
+ ? `${childPath}: '${c}' is not a collected item and has no disposition; dropped (sibling pairing is T3's declared join).`
796
+ : `${childPath}: '${c}' has no slot in the synthesized table shape; dropped.`,
797
+ }, treePath, Band.BeforeChildren, Phase.TableBody);
798
+ this.diagnostics.pushFidelity({
799
+ source: `${childPath} (${c})`,
800
+ destination: "(discarded)",
801
+ origin: reason ? `drops.${c}` : "collect",
802
+ kind: "dropped",
803
+ class: "lossy",
804
+ note: reason ?? "no slot in the collected shape",
805
+ }, treePath, Band.BeforeChildren, Phase.TableBody);
806
+ }
807
+ const itemsOnly = model.collects.every((col) => col.fields);
808
+ this.diagnostics.push({
218
809
  code: "surface-composition-flattened",
219
- message: `${path}: compound '${node.component}' subtree flattened onto emitted props (documented casualty; nested props beyond text are not carried).`,
220
- });
810
+ message: itemsOnly
811
+ ? `${path}: compound '${node.component}' subtree consumed into collected item records (uncollected content is not carried).`
812
+ : `${path}: compound '${node.component}' subtree consumed into the synthesized table shape (documented casualty; cell content beyond text is not carried).`,
813
+ }, treePath, Band.BeforeChildren, Phase.TableFlatten);
814
+ this.diagnostics.pushFidelity({
815
+ source: `${path} (${node.component} subtree)`,
816
+ destination: "(collected props)",
817
+ origin: model.collects.map((c) => c.origin).join(", "),
818
+ kind: "flattened",
819
+ class: "lossy",
820
+ note: "compound consumed into the collected shape; cell content beyond text is not carried",
821
+ }, treePath, Band.BeforeChildren, Phase.TableFlatten);
221
822
  }
222
- emitTextPrimitive(text, preferredId, path, variant) {
223
- const { textComponent, textProp } = this.profile.surfaceSynthesis;
224
- const id = this.allocateId(preferredId, path);
225
- const instance = { id, component: textComponent, [textProp]: text };
226
- if (variant !== undefined)
227
- instance.variant = variant;
228
- this.components.push(instance);
229
- this.warnings.push({
230
- code: "surface-synthesized-text",
231
- message: `${path}: node text projected as a synthesized ${textComponent} child ('${id}') — the surface format has no text primitive.`,
823
+ /** True when a collect writes one flat list rather than one record per repetition. */
824
+ isFlatTarget(collect) {
825
+ return collect.flatten;
826
+ }
827
+ /** True when some route already consumes this component's text. */
828
+ claimedByRoute(model, component) {
829
+ return model.routes.some((r) => r.from.some((s) => "subs" in s && s.subs.includes(component)));
830
+ }
831
+ /** One repetition's scalar cells, each flattened to its subtree text. */
832
+ collectRow(row, field, rowPath, treePath, rule) {
833
+ const cells = [];
834
+ for (const child of collectChildren(row)) {
835
+ const c = child.node.component;
836
+ const subs = field.scalar.from[0].subs;
837
+ if (subs.includes(c)) {
838
+ cells.push(this.cellText(child.node, `${rowPath}${child.suffix}`, treePath, rule));
839
+ }
840
+ else {
841
+ this.diagnostics.push({
842
+ code: "surface-sub-dropped",
843
+ message: `${rowPath}: '${c}' has no slot in a synthesized table row; dropped (its text is not lifted).`,
844
+ }, treePath, Band.BeforeChildren, Phase.TableBody, rule);
845
+ this.diagnostics.pushFidelity({ source: `${rowPath} (${c})`, destination: "(discarded)", origin: field.origin, kind: "dropped", class: "lossy", note: "no slot in a collected row; its text is not lifted" }, treePath, Band.BeforeChildren, Phase.TableBody, rule);
846
+ }
847
+ }
848
+ return cells;
849
+ }
850
+ cellText(cell, cellPath, treePath, rule) {
851
+ const nested = collectChildren(cell);
852
+ const text = this.subtreeText(cell);
853
+ if (nested.length > 0) {
854
+ const names = nested.map((c) => `'${c.node.component}'`).join(", ");
855
+ this.diagnostics.push({
856
+ code: "surface-table-cell-flattened",
857
+ message: `${cellPath}: nested ${names} flattened to cell text; component structure and props are not carried by the synthesized table shape.`,
858
+ }, treePath, Band.BeforeChildren, Phase.TableBody, rule);
859
+ this.diagnostics.pushFidelity({ 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" }, treePath, Band.BeforeChildren, Phase.TableBody, rule);
860
+ }
861
+ return text;
862
+ }
863
+ /** Children as instance references, after any sub-identity rewriting. */
864
+ emitChildren(node, model, instance, id, path, treePath) {
865
+ const childRoute = model.routes.find((r) => r.from.some((s) => s.kind === "children"));
866
+ const raw = collectChildren(node);
867
+ const anyTransparentChild = raw.some((c) => {
868
+ const plan = this.byDspackId.get(c.node.component);
869
+ return plan !== undefined && surfaceModelOf(plan).transparent;
232
870
  });
871
+ const childNodes = Object.keys(model.subIdentity).length > 0 || Object.keys(model.drops).length > 0 || anyTransparentChild
872
+ ? this.rewriteChildren(node, model, path, treePath)
873
+ : raw.map((c) => ({ node: c.node, suffix: c.suffix }));
874
+ if (childNodes.length === 0)
875
+ return;
876
+ const childIds = childNodes.map((child, i) => "textVariant" in child
877
+ ? this.emitTextPrimitive(child.text, `${id}_${slug(child.textVariant)}`, path, [...treePath, Band.Children, i], Phase.TextChild, 0, child.textVariant)
878
+ : this.emitNode(child.node, `${path}${child.suffix}[${i}]`, [...treePath, Band.Children, i], child.donations ?? []));
879
+ if (!childRoute) {
880
+ throw new EmitSurfaceError(`component '${node.component}' has children but its surface plan declares no child slot`, path);
881
+ }
882
+ if (childRoute.to.kind === "slots") {
883
+ instance[childRoute.to.name] = childIds;
884
+ }
885
+ else {
886
+ instance[childRoute.to.name] =
887
+ childIds.length === 1 ? childIds[0] : this.wrapInColumn(childIds, id, path, treePath);
888
+ }
889
+ }
890
+ /**
891
+ * T1, the general root-transparency rule (ratified): a transparent node is
892
+ * a semantic statement that the dspack node has no emitted identity — valid
893
+ * at the root too. The root dissolves through the ORDINARY machinery
894
+ * (presented as a child of a synthetic host, so boundary donations, sub
895
+ * dispositions, and every refusal apply), then:
896
+ *
897
+ * - exactly one surviving descendant -> it IS the root (id "root",
898
+ * components[0]) — the existing root invariant, preserved
899
+ * deterministically;
900
+ * - several survivors -> they wrap in the synthesized
901
+ * wrap component, which is structural TRANSPORT, not a replacement
902
+ * identity for the transparent component;
903
+ * - nothing survives -> refuse. Fabricating content for
904
+ * an empty root would be synthesis of meaning, not structure.
905
+ *
906
+ * No component is special-cased by name.
907
+ */
908
+ emitTransparentRoot(root, path) {
909
+ const { wrapComponent, wrapChildrenProp } = this.profile.surfaceSynthesis;
910
+ // Present the root AS A CHILD of a synthetic host, so the ordinary
911
+ // rewriting machinery performs the whole dissolution — the plan-transparent
912
+ // ledger entry, the boundary's own donations (transparentDonate), sub
913
+ // dispositions, and every refusal — with no root-only special case.
914
+ const host = { component: "__root_host__", children: [root] };
915
+ const spliced = this.rewriteChildren(host, emptySurfaceModel(), path, []);
916
+ if (spliced.length === 0) {
917
+ throw new EmitSurfaceError(`transparent root '${root.component}' dissolved to nothing — no descendant survives to become the root, and fabricating one is refused`, path);
918
+ }
919
+ if (spliced.length === 1) {
920
+ const only = spliced[0];
921
+ this.diagnostics.pushFidelity({
922
+ source: `${path} (${root.component})`,
923
+ destination: "root",
924
+ origin: `plan.${root.component}`,
925
+ kind: "moved",
926
+ class: "maps-cleanly",
927
+ note: "transparent root: its single surviving descendant is preserved as the root instance",
928
+ }, [], Band.BeforeChildren, Phase.ChildRewrite);
929
+ return "textVariant" in only
930
+ ? this.emitTextPrimitive(only.text, "root", path, [Band.Children, 0], Phase.TextChild, 0, only.textVariant)
931
+ : this.emitNode(only.node, path, [Band.Children, 0], only.donations ?? []);
932
+ }
933
+ const id = this.allocateId("root", path, { treePath: [], band: Band.BeforeChildren, phase: Phase.IdAllocation, rule: 0 });
934
+ const index = this.components.length;
935
+ this.components.push({});
936
+ const childIds = spliced.map((child, i) => "textVariant" in child
937
+ ? this.emitTextPrimitive(child.text, `root_${slug(child.textVariant)}`, path, [Band.Children, i], Phase.TextChild, 0, child.textVariant)
938
+ : this.emitNode(child.node, `${path}.children[${i}]`, [Band.Children, i], child.donations ?? []));
939
+ this.components[index] = { id, component: wrapComponent, [wrapChildrenProp]: childIds };
940
+ this.diagnostics.push({
941
+ code: "surface-synthesized-wrap",
942
+ message: `${path}: transparent root '${root.component}' dissolved; ${childIds.length} risen child(ren) wrapped in a synthesized ${wrapComponent} ('root').`,
943
+ }, [], Band.AfterChildren, Phase.Wrap);
944
+ this.diagnostics.pushFidelity({ 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" }, [], Band.AfterChildren, Phase.Wrap);
233
945
  return id;
234
946
  }
235
947
  /**
236
- * Named parent strategy "subFlatten" (e.g. Card): grouping sub-components
237
- * splice their children inline in document order (their own structure is a
238
- * warned, documented loss); text-bearing sub-components synthesize the
239
- * profile's text primitive with the declared variant. Everything else
240
- * passes through to ordinary child emission.
948
+ * Identity applied to the child list: sub dispositions from the surrounding
949
+ * model, T1 plan-level transparency for child COMPONENTS (dissolved under
950
+ * their own model — the `ctx` switch), and donation boundaries. A
951
+ * dissolving boundary that carries donations harvests them from its own
952
+ * subtree, consumes the donor subs, and attaches the pending writes to its
953
+ * single eligible control — refusing on zero or several candidates. The
954
+ * pending writes ride the returned child list explicitly and apply inside
955
+ * the control's own construction: no committed instance is ever mutated.
241
956
  */
242
- flattenSubs(node, spec, path) {
243
- const out = [];
244
- const visit = (n, suffix) => {
245
- if (spec.transparent.includes(n.component)) {
246
- this.warnings.push({
957
+ rewriteChildren(node, model, path, treePath,
958
+ /**
959
+ * T4: subs claimed by SIBLING routes of the enclosing compound (text
960
+ * harvests, other slot sources). A claimed sub is skipped silently at any
961
+ * dissolution depth — its consumption is ledgered by its own route, and
962
+ * recording it twice would say it was dropped when it was moved.
963
+ */
964
+ claimedSubs = new Set()) {
965
+ const push = (w) => this.diagnostics.push(w, treePath, Band.BeforeChildren, Phase.ChildRewrite);
966
+ const ledger = (f) => this.diagnostics.pushFidelity(f, treePath, Band.BeforeChildren, Phase.ChildRewrite);
967
+ // Layered dissolution contexts (emit#37, ratified 2026-08-07). A
968
+ // dissolving boundary shadows the enclosing compound contexts where they
969
+ // overlap, but does not erase them: a component's disposition is resolved
970
+ // against the stack of enclosing models, innermost first, so an outer
971
+ // compound's sub (e.g. `card-footer`) keeps its disposition when it
972
+ // appears inside a dissolved inner boundary (e.g. a transparent `field`).
973
+ // A single-frame stack resolves identically to the pre-amendment single
974
+ // `ctx` — the byte pins prove it.
975
+ const resolve = (stack, pick) => {
976
+ for (const m of stack) {
977
+ const v = pick(m);
978
+ if (v !== undefined)
979
+ return v;
980
+ }
981
+ return undefined;
982
+ };
983
+ const visit = (n, suffix, stack, out) => {
984
+ if (claimedSubs.has(n.component))
985
+ return;
986
+ // An authored drop is warn-and-discard, exactly like the collect path —
987
+ // resolved through the ancestor chain (inner shadows outer).
988
+ const dropReason = resolve(stack, (m) => m.drops[n.component]);
989
+ if (dropReason !== undefined) {
990
+ push({ code: "surface-sub-dropped", message: `${path}: '${n.component}' dropped: ${dropReason}.` });
991
+ ledger({ source: `${path} (${n.component})`, destination: "(discarded)", origin: `drops.${n.component}`, kind: "dropped", class: "lossy", note: dropReason });
992
+ return;
993
+ }
994
+ // T1: a child COMPONENT whose plan is transparent dissolves here — its
995
+ // subtree governed by ITS OWN model PUSHED ONTO the enclosing stack, so
996
+ // the boundary shadows but does not erase the outer contexts.
997
+ const childPlan = this.byDspackId.get(n.component);
998
+ const childModel = childPlan ? surfaceModelOf(childPlan) : undefined;
999
+ if (childModel?.transparent) {
1000
+ ledger({
1001
+ source: `${path} (${n.component})`,
1002
+ destination: "(children rise in place)",
1003
+ origin: `plan.${n.component}`,
1004
+ kind: "flattened",
1005
+ class: "lossy",
1006
+ note: "transparent identity: the component dissolves; its own structure is not carried",
1007
+ });
1008
+ dissolve(n, suffix, [childModel, ...stack], childModel.transparentDonate, `plan.${n.component}`, out);
1009
+ return;
1010
+ }
1011
+ const identity = resolve(stack, (m) => m.subIdentity[n.component]);
1012
+ if (identity?.kind === "transparent") {
1013
+ push({
247
1014
  code: "surface-sub-flattened",
248
1015
  message: `${path}: grouping sub-component '${n.component}' spliced inline (subFlatten strategy); its own structure is not carried.`,
249
1016
  });
250
- if (n.text !== undefined && n.text !== "")
251
- out.push({ text: n.text, textVariant: "body" });
252
- for (const child of collectChildren(n))
253
- visit(child.node, child.suffix);
1017
+ 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" });
1018
+ // A grouping sub has no model of its own; its children continue under
1019
+ // the same enclosing stack that resolved it.
1020
+ dissolve(n, suffix, stack, identity.donate ?? [], `subs.${n.component}`, out);
254
1021
  return;
255
1022
  }
256
- const variant = spec.asText[n.component];
257
- if (variant !== undefined) {
1023
+ if (identity?.kind === "as-text") {
258
1024
  const text = this.subtreeText(n);
1025
+ const nested = collectChildren(n);
1026
+ if (nested.length > 0) {
1027
+ // Structure destroyed, text preserved — the same loss the cell
1028
+ // flatten records, and it must class the same way.
1029
+ const names = nested.map((c) => `'${c.node.component}'`).join(", ");
1030
+ 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" });
1031
+ }
259
1032
  if (text !== "") {
260
- out.push({ text, textVariant: variant });
1033
+ out.push({ text, textVariant: identity.variant });
261
1034
  }
262
1035
  else {
263
- this.warnings.push({
264
- code: "surface-sub-dropped",
265
- message: `${path}: '${n.component}' carried no text to synthesize; dropped.`,
266
- });
1036
+ push({ code: "surface-sub-dropped", message: `${path}: '${n.component}' carried no text to synthesize; dropped.` });
1037
+ ledger({ source: `${path} (${n.component})`, destination: "(discarded)", origin: `subs.${n.component}`, kind: "dropped", class: "lossy", note: "re-identified as text but carried none" });
267
1038
  }
268
1039
  return;
269
1040
  }
270
1041
  out.push({ node: n, suffix });
271
1042
  };
272
- for (const child of collectChildren(node))
273
- visit(child.node, child.suffix);
274
- return out;
275
- }
276
- /**
277
- * Named parent strategy "subTable": consume the tabular sub tree into the
278
- * synthesized caption/columns/rows shape. Domain-neutral: a cell is its
279
- * subtree's text in document order — nested component structure and props
280
- * are a per-cell warned loss, never re-interpreted into semantic fields.
281
- * structuralPassthrough values (the props path) win over consumed ones.
282
- */
283
- applySubTable(node, spec, instance, path) {
284
- const columns = [];
285
- const rows = [];
286
- let caption;
287
- const cellText = (cell, cellPath) => {
288
- const nested = collectChildren(cell);
289
- const text = this.subtreeText(cell);
290
- if (nested.length > 0) {
291
- const names = nested.map((c) => `'${c.node.component}'`).join(", ");
292
- this.warnings.push({
293
- code: "surface-table-cell-flattened",
294
- message: `${cellPath}: nested ${names} flattened to cell text; component structure and props are not carried by the synthesized table shape.`,
295
- });
296
- }
297
- return text;
298
- };
299
- const consumeRow = (row, rowPath, into) => {
300
- for (const child of collectChildren(row)) {
301
- const c = child.node.component;
302
- if (c === spec.cell || c === spec.headerCell) {
303
- into.push(cellText(child.node, `${rowPath}${child.suffix}`));
1043
+ /**
1044
+ * Dissolves one boundary node under `innerCtx`. When the boundary carries
1045
+ * donations: harvest first-wins per donation, consume every donor sub,
1046
+ * splice the rest, then bind the pending writes to the single eligible
1047
+ * control among the spliced replacements — zero or several refuse.
1048
+ * Eligibility is declared, never guessed: a control's plan must declare
1049
+ * every donated destination.
1050
+ */
1051
+ const dissolve = (n, suffix, innerStack, donations, originLabel, out) => {
1052
+ const consumedDonorSubs = new Set();
1053
+ const pending = [];
1054
+ for (const d of donations) {
1055
+ let value;
1056
+ let donorComponent = n.component;
1057
+ if (d.from.kind === "self-text") {
1058
+ value = n.text;
304
1059
  }
305
- else if (spec.drops[c] !== undefined) {
306
- this.warnings.push({ code: "surface-sub-dropped", message: `${rowPath}: '${c}' dropped: ${spec.drops[c]}.` });
1060
+ else if (d.from.kind === "sub-text") {
1061
+ for (const sub of d.from.subs)
1062
+ consumedDonorSubs.add(sub);
1063
+ const walk = (m) => {
1064
+ if (value === undefined && d.from.kind === "sub-text" && d.from.subs.includes(m.component) && m.text !== undefined) {
1065
+ value = m.text;
1066
+ donorComponent = m.component;
1067
+ }
1068
+ for (const c of collectChildren(m))
1069
+ walk(c.node);
1070
+ };
1071
+ walk(n);
307
1072
  }
308
- else {
309
- this.warnings.push({
310
- code: "surface-sub-dropped",
311
- message: `${rowPath}: '${c}' has no slot in a synthesized table row; dropped (its text is not lifted).`,
312
- });
313
- }
314
- }
315
- };
316
- for (const child of collectChildren(node)) {
317
- const c = child.node.component;
318
- const childPath = `${path}${child.suffix}`;
319
- if (c === spec.caption) {
320
- caption ??= cellText(child.node, childPath);
321
- }
322
- else if (c === spec.header) {
323
- for (const inner of collectChildren(child.node)) {
324
- if (inner.node.component === spec.row)
325
- consumeRow(inner.node, `${childPath}${inner.suffix}`, columns);
326
- else
327
- this.warnings.push({ code: "surface-sub-dropped", message: `${childPath}: '${inner.node.component}' inside '${spec.header}' has no slot; dropped.` });
1073
+ if (value !== undefined) {
1074
+ pending.push({ prop: d.to.name, value, origin: d.origin, donorPath: `${path}${suffix}`, donorComponent });
328
1075
  }
1076
+ // Nothing to donate is not an error: the destination stays absent and
1077
+ // gate A3 arbitrates — relocation, never synthesis (the lift rule).
329
1078
  }
330
- else if (c === spec.body) {
331
- for (const inner of collectChildren(child.node)) {
332
- if (inner.node.component === spec.row) {
333
- const cells = [];
334
- consumeRow(inner.node, `${childPath}${inner.suffix}`, cells);
335
- rows.push({ cells });
336
- }
337
- else {
338
- this.warnings.push({ code: "surface-sub-dropped", message: `${childPath}: '${inner.node.component}' inside '${spec.body}' has no slot; dropped.` });
1079
+ // The boundary's own text rises as body text unless a self.text
1080
+ // donation claimed it (the plain transparent-sub behaviour otherwise).
1081
+ const selfDonated = donations.some((d) => d.from.kind === "self-text");
1082
+ const spliced = [];
1083
+ if (!selfDonated && n.text !== undefined && n.text !== "")
1084
+ spliced.push({ text: n.text, textVariant: "body" });
1085
+ for (const child of collectChildren(n)) {
1086
+ if (consumedDonorSubs.has(child.node.component)) {
1087
+ const supplied = pending.some((q) => q.donorComponent === child.node.component && q.value === child.node.text);
1088
+ if (!supplied) {
1089
+ push({ code: "surface-sub-dropped", message: `${path}: '${child.node.component}' dropped: its text was not the donated value (first donor wins).` });
1090
+ 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)" });
339
1091
  }
1092
+ continue;
340
1093
  }
1094
+ visit(child.node, child.suffix, innerStack, spliced);
341
1095
  }
342
- else if (spec.drops[c] !== undefined) {
343
- this.warnings.push({ code: "surface-sub-dropped", message: `${childPath}: '${c}' dropped: ${spec.drops[c]}.` });
344
- }
345
- else {
346
- this.warnings.push({
347
- code: "surface-sub-dropped",
348
- message: `${childPath}: '${c}' has no slot in the synthesized table shape; dropped.`,
1096
+ if (pending.length > 0) {
1097
+ const controls = spliced.filter((entry) => {
1098
+ if (!("node" in entry))
1099
+ return false;
1100
+ const plan = this.byDspackId.get(entry.node.component);
1101
+ if (!plan || surfaceModelOf(plan).transparent)
1102
+ return false;
1103
+ const declared = new Set([
1104
+ ...Object.keys(plan.structural ?? {}),
1105
+ ...Object.values(plan.propMap ?? {}).map((pp) => pp.a2ui),
1106
+ ]);
1107
+ return pending.every((q) => declared.has(q.prop));
349
1108
  });
1109
+ if (controls.length !== 1) {
1110
+ const names = controls.map((c) => `'${c.node.component}'`).join(", ");
1111
+ throw new EmitSurfaceError(`donation boundary '${n.component}' (${originLabel}) requires exactly one eligible control declaring ` +
1112
+ `[${pending.map((q) => q.prop).join(", ")}]; found ${controls.length}${controls.length ? ` (${names})` : ""} — ` +
1113
+ `a donation relocates onto one control, never broadcasts`, `${path}${suffix}`);
1114
+ }
1115
+ controls[0].donations = [...(controls[0].donations ?? []), ...pending];
350
1116
  }
351
- }
352
- if (instance[spec.targetCaption] === undefined && caption !== undefined)
353
- instance[spec.targetCaption] = caption;
354
- if (instance[spec.targetColumns] === undefined && columns.length > 0)
355
- instance[spec.targetColumns] = columns;
356
- if (instance[spec.targetRows] === undefined && rows.length > 0)
357
- instance[spec.targetRows] = rows;
358
- this.warnings.push({
359
- code: "surface-composition-flattened",
360
- message: `${path}: compound '${node.component}' subtree consumed into the synthesized table shape (documented casualty; cell content beyond text is not carried).`,
361
- });
1117
+ out.push(...spliced);
1118
+ };
1119
+ const rootOut = [];
1120
+ for (const child of collectChildren(node))
1121
+ visit(child.node, child.suffix, [model], rootOut);
1122
+ return rootOut;
1123
+ }
1124
+ emitTextPrimitive(text, preferredId, path, treePath, phase, rule, variant) {
1125
+ const { textComponent, textProp } = this.profile.surfaceSynthesis;
1126
+ const id = this.allocateId(preferredId, path, { treePath, band: Band.BeforeChildren, phase, rule });
1127
+ const instance = { id, component: textComponent, [textProp]: text };
1128
+ if (variant !== undefined)
1129
+ instance.variant = variant;
1130
+ this.components.push(instance);
1131
+ this.diagnostics.push({
1132
+ code: "surface-synthesized-text",
1133
+ message: `${path}: node text projected as a synthesized ${textComponent} child ('${id}') — the surface format has no text primitive.`,
1134
+ }, treePath, Band.BeforeChildren, phase, rule);
1135
+ this.diagnostics.pushFidelity({ source: `${path} (text)`, destination: `synthesized ${textComponent} '${id}'`, origin: "surfaceSynthesis.textComponent", kind: "synthesized", class: "synthesis-defaults", note: "the surface format has no text primitive" }, treePath, Band.BeforeChildren, phase, rule);
1136
+ return id;
362
1137
  }
363
1138
  /** All text in a node's subtree, document order, space-joined. */
364
1139
  subtreeText(node) {
@@ -372,30 +1147,37 @@ class SurfaceEmitter {
372
1147
  visit(node);
373
1148
  return parts.join(" ");
374
1149
  }
375
- wrapInColumn(childIds, parentId, path) {
1150
+ wrapInColumn(childIds, parentId, path, treePath) {
376
1151
  const { wrapComponent, wrapChildrenProp } = this.profile.surfaceSynthesis;
377
- const id = this.allocateId(`${parentId}_col`, path);
378
- this.components.push({
379
- id,
380
- component: wrapComponent,
381
- [wrapChildrenProp]: childIds,
1152
+ const id = this.allocateId(`${parentId}_col`, path, {
1153
+ treePath,
1154
+ band: Band.AfterChildren,
1155
+ phase: Phase.Wrap,
1156
+ rule: 0,
382
1157
  });
383
- this.warnings.push({
1158
+ this.components.push({ id, component: wrapComponent, [wrapChildrenProp]: childIds });
1159
+ this.diagnostics.push({
384
1160
  code: "surface-synthesized-wrap",
385
1161
  message: `${path}: ${childIds.length} children wrapped in a synthesized ${wrapComponent} ('${id}') — the target slot takes a single child.`,
386
- });
1162
+ }, treePath, Band.AfterChildren, Phase.Wrap);
1163
+ this.diagnostics.pushFidelity({ 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" }, treePath, Band.AfterChildren, Phase.Wrap);
387
1164
  return id;
388
1165
  }
389
- allocateId(preferred, path) {
1166
+ /**
1167
+ * Deterministic and stateful: `slug`, then `_2`, `_3`, … in first-come order.
1168
+ * Allocation order is emission order, which the model does not change.
1169
+ */
1170
+ allocateId(preferred, path, where) {
390
1171
  let id = slug(preferred);
391
1172
  let n = 2;
392
1173
  while (this.usedIds.has(id))
393
1174
  id = `${slug(preferred)}_${n++}`;
394
1175
  if (id !== slug(preferred)) {
395
- this.warnings.push({
1176
+ this.diagnostics.push({
396
1177
  code: "surface-id-deduplicated",
397
1178
  message: `${path}: node id '${preferred}' already used; emitted as '${id}'.`,
398
- });
1179
+ }, where.treePath, where.band, where.phase, where.rule);
1180
+ this.diagnostics.pushFidelity({ 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, …" }, where.treePath, where.band, where.phase, where.rule);
399
1181
  }
400
1182
  this.usedIds.add(id);
401
1183
  return id;