@aestheticfunction/dspack-emit 0.4.0 → 0.5.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 (74) 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 +566 -224
  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 +50 -0
  15. package/dist/transform/model.d.ts +275 -0
  16. package/dist/transform/model.js +148 -0
  17. package/dist/transform/parse-v2.d.ts +78 -0
  18. package/dist/transform/parse-v2.js +305 -0
  19. package/dist/transform/profile-load.d.ts +8 -7
  20. package/dist/transform/profile-load.js +101 -24
  21. package/dist/transform/profile-schema-v2.d.ts +9 -0
  22. package/dist/transform/profile-schema-v2.js +430 -0
  23. package/dist/transform/profile-schema.d.ts +8 -0
  24. package/dist/transform/profile-schema.js +382 -0
  25. package/dist/transform/profiles.d.ts +31 -1
  26. package/dist/transform/scaffold.d.ts +29 -12
  27. package/dist/transform/scaffold.js +91 -31
  28. package/dist/transform/shadcn-v2-respelling.d.ts +12 -0
  29. package/dist/transform/shadcn-v2-respelling.js +49 -0
  30. package/dist/transform/validate-v2.d.ts +36 -0
  31. package/dist/transform/validate-v2.js +100 -0
  32. package/dist/types.d.ts +19 -0
  33. package/dist/validate/ajv.js +98 -29
  34. package/dist/validate/meta/catalog-meta.d.ts +10 -0
  35. package/dist/validate/meta/catalog-meta.js +157 -0
  36. package/package.json +3 -3
  37. package/src/__snapshots__/byte-neutral.test.ts.snap +66 -0
  38. package/src/browser-boundary.test.ts +47 -0
  39. package/src/byte-neutral.test.ts +246 -0
  40. package/src/cli.ts +60 -0
  41. package/src/dangling-ref.test.ts +118 -0
  42. package/src/desugar.test.ts +162 -0
  43. package/src/engine-boundary.test.ts +248 -0
  44. package/src/eval-fixture.test.ts +89 -0
  45. package/src/functions.test.ts +182 -0
  46. package/src/index.ts +4 -1
  47. package/src/profile-load.test.ts +99 -1
  48. package/src/profile-v2.test.ts +363 -0
  49. package/src/review-findings.test.ts +292 -0
  50. package/src/schema-mirrors.test.ts +35 -0
  51. package/src/surface-fidelity.test.ts +213 -0
  52. package/src/targets/a2ui/diagnostics.ts +136 -0
  53. package/src/targets/a2ui/surface.ts +920 -242
  54. package/src/transform/desugar.ts +194 -0
  55. package/src/transform/emit.ts +65 -0
  56. package/src/transform/index.ts +5 -0
  57. package/src/transform/mapping.ts +42 -0
  58. package/src/transform/model.ts +325 -0
  59. package/src/transform/parse-v2.ts +397 -0
  60. package/src/transform/profile-load.ts +107 -28
  61. package/src/transform/profile-schema-v2.ts +430 -0
  62. package/src/transform/profile-schema.ts +382 -0
  63. package/src/transform/profile.v2.schema.json +422 -0
  64. package/src/transform/profiles.ts +32 -1
  65. package/src/transform/scaffold.ts +124 -47
  66. package/src/transform/shadcn-v2-respelling.ts +61 -0
  67. package/src/transform/validate-v2.ts +138 -0
  68. package/src/types.ts +20 -0
  69. package/src/validate/ajv.ts +91 -32
  70. package/src/validate/meta/catalog-meta.ts +167 -0
  71. package/src/validate-v2.test.ts +173 -0
  72. package/dist/transform/profile.v1.schema.json +0 -153
  73. package/dist/validate/meta/a2ui-catalog.meta.0_9_1.json +0 -39
  74. package/dist/validate/meta/a2ui-catalog.meta.1_0.json +0 -34
@@ -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, isCollect, WriteOrder, type Collect, 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,6 +96,11 @@ 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);
@@ -100,7 +128,7 @@ export function emitSurface(
100
128
  },
101
129
  ];
102
130
  void rootId; // root is components[0] by construction (pre-order emission)
103
- return { messages, warnings: emitter.warnings };
131
+ return { messages, warnings: emitter.diagnostics.ordered(), fidelity: emitter.diagnostics.orderedFidelity() };
104
132
  }
105
133
 
106
134
  function primaryColor(doc: DspackDoc, profile: Profile): string | null {
@@ -116,10 +144,9 @@ export function slug(value: string): string {
116
144
  .replace(/^_+|_+$/g, "");
117
145
  return s || "surface";
118
146
  }
119
-
120
147
  class SurfaceEmitter {
121
148
  readonly components: Json[] = [];
122
- readonly warnings: Warning[] = [];
149
+ readonly diagnostics = new Diagnostics();
123
150
  private readonly usedIds = new Set<string>();
124
151
 
125
152
  constructor(
@@ -127,8 +154,14 @@ class SurfaceEmitter {
127
154
  private readonly byDspackId: Map<string, ComponentPlan>,
128
155
  ) {}
129
156
 
130
- /** Emits the component for `node` (and its subtree) and returns its instance id. */
131
- emitNode(node: SurfaceNode, path: string): string {
157
+ /**
158
+ * Emits the component for `node` (and its subtree) and returns its instance id.
159
+ *
160
+ * Reads ONLY the internal model. The v1 directive names live exclusively in
161
+ * desugar.ts; if any of them appears below, the compatibility boundary has
162
+ * leaked (src/engine-boundary.test.ts fails on exactly that).
163
+ */
164
+ emitNode(node: SurfaceNode, path: string, treePath: readonly number[] = []): string {
132
165
  const plan = this.byDspackId.get(node.component);
133
166
  if (!plan) {
134
167
  // A declared casualty refuses with its authored reason — the refusal is
@@ -148,197 +181,860 @@ class SurfaceEmitter {
148
181
  );
149
182
  }
150
183
 
184
+ const model = surfaceModelOf(plan);
185
+ const at = (band: Band, phase: Phase, rule = 0) =>
186
+ ({ treePath, band, phase, rule }) as const;
187
+
151
188
  // A2UI renderers begin at the component with id "root" (see the
152
189
  // 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);
190
+ const id =
191
+ path === "$.root"
192
+ ? this.allocateId("root", path, at(Band.BeforeChildren, Phase.IdAllocation))
193
+ : this.allocateId(node.id ?? plan.a2ui.toLowerCase(), path, at(Band.BeforeChildren, Phase.IdAllocation));
154
194
  // Reserve the slot so parent components precede children in the flat list.
155
195
  const index = this.components.length;
156
196
  this.components.push({});
157
197
  const instance: Json = { id, component: plan.a2ui };
158
198
 
159
- this.applyPropMap(node, plan, instance, path);
160
- const sp = plan.surfacePlan ?? {};
161
- const consumesSubtree = Boolean(sp.subText || sp.subButtonText || sp.subTable);
199
+ this.applyPropMap(node, plan, model, instance, path, treePath);
162
200
 
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];
167
- }
201
+ // A declared casualty is an authored refusal: it must never be laundered
202
+ // into a parent's text fold. The plan-lookup gate above only fires when a
203
+ // casualty is emitted as its OWN node; a consuming route or a re-identified
204
+ // sub walks the subtree directly and would otherwise fold the casualty's
205
+ // text in with a mere warning.
206
+ if (model.consumesSubtree || Object.keys(model.subIdentity).length > 0) {
207
+ this.refuseConsumedCasualty(node, path);
168
208
  }
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);
209
+
210
+ // Routes and collects, in declared order. Ordering of OUTPUT is first-wins
211
+ // (except where a route declares `overwrite`); ordering of DIAGNOSTICS is
212
+ // the explicit phase model, never this loop's order.
213
+ this.applyOperations(node, model, instance, id, path, treePath);
214
+
215
+ if (!model.consumesSubtree) {
216
+ this.emitChildren(node, model, instance, id, path, treePath);
174
217
  }
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
- });
218
+
219
+ // The one loss channel nothing else ledgers: node text on a plan with no
220
+ // self.text route. v1 has always silently discarded it — warnings are
221
+ // byte-frozen, so the WARNING stays absent — but the ledger exists
222
+ // precisely so no discard is unaccounted. (Consuming plans are exempt:
223
+ // their document-order walk may legitimately read the node's own text.)
224
+ const readsSelfText = model.routes.some((r) => r.from.some((s) => s.kind === "self-text"));
225
+ if (node.text !== undefined && !readsSelfText && !model.consumesSubtree) {
226
+ this.diagnostics.pushFidelity(
227
+ {
228
+ source: `${path} (text)`,
229
+ destination: "(discarded)",
230
+ origin: "(no rule)",
231
+ kind: "dropped",
232
+ class: "lossy",
233
+ note: `'${node.component}' has no self.text route; its text was discarded`,
234
+ },
235
+ treePath,
236
+ Band.BeforeChildren,
237
+ Phase.PropMap,
238
+ );
182
239
  }
183
240
 
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,
241
+ this.components[index] = instance;
242
+ return id;
243
+ }
244
+
245
+ /**
246
+ * Applies every route and collect in declared WriteOrder — never in
247
+ * declaration order and never in traversal happenstance. Object key order is
248
+ * observable, so this sequence is part of the compatibility contract.
249
+ *
250
+ * Consuming routes are the one group resolved together: a compound is walked
251
+ * ONCE in document order and each destination takes the first thing it sees.
252
+ * That is not an implementation detail leaking through — it is what consuming
253
+ * a compound means, and resolving those routes independently would let
254
+ * declaration order decide which of two siblings wins.
255
+ */
256
+ private applyOperations(
257
+ node: SurfaceNode,
258
+ model: SurfaceModel,
259
+ instance: Json,
260
+ id: string,
261
+ path: string,
262
+ treePath: readonly number[],
263
+ ): void {
264
+ const consuming = model.routes
265
+ .map((route, rule) => ({ route, rule }))
266
+ .filter(({ route }) => route.order === WriteOrder.Consume);
267
+
268
+ const steps: Array<{ order: number; run: () => void }> = [];
269
+
270
+ for (const { route, rule } of model.routes.map((route, rule) => ({ route, rule }))) {
271
+ if (route.order === WriteOrder.Consume || route.order === WriteOrder.Children) continue;
272
+ steps.push({ order: route.order, run: () => this.applyRoute(node, route, rule, instance, id, path, treePath) });
273
+ }
274
+ for (const [rule, collect] of model.collects.entries()) {
275
+ if (collect.as.kind === "inline") continue;
276
+ steps.push({ order: collect.order, run: () => this.applyCollect(node, model, collect, rule, instance, path, treePath) });
277
+ }
278
+ if (consuming.length > 0) {
279
+ steps.push({ order: WriteOrder.Consume, run: () => this.applyConsuming(node, consuming, instance, path, treePath) });
280
+ }
281
+ if (model.collects.some((c) => c.as.kind !== "inline")) {
282
+ steps.push({ order: WriteOrder.Collect + 1, run: () => this.closeCollects(node, model, path, treePath) });
283
+ }
284
+
285
+ steps.sort((a, b) => a.order - b.order);
286
+ for (const step of steps) step.run();
287
+ }
288
+
289
+ /**
290
+ * One document-order walk serving every consuming route, then the audited
291
+ * lift for any destination still empty, then the composition warning.
292
+ */
293
+ private applyConsuming(
294
+ node: SurfaceNode,
295
+ consuming: Array<{ route: Route; rule: number }>,
296
+ instance: Json,
297
+ path: string,
298
+ treePath: readonly number[],
299
+ ): void {
300
+ const record = (route: Route, rule: number, nPath: string, component: string): void => {
301
+ this.diagnostics.pushFidelity(
302
+ {
303
+ source: `${nPath} (${component}.text)`,
304
+ destination: route.to.name,
305
+ origin: route.origin,
306
+ kind: "moved",
307
+ class: "maps-cleanly",
308
+ },
309
+ treePath,
310
+ Band.BeforeChildren,
311
+ Phase.SubContentFlatten,
312
+ rule,
313
+ );
314
+ };
315
+ const visit = (n: SurfaceNode, nPath: string, insideSubs: ReadonlySet<string>): void => {
316
+ for (const { route, rule } of consuming) {
317
+ if (instance[route.to.name] !== undefined) continue;
318
+ const primary = route.from[0];
319
+ if (primary.kind === "sub-text") {
320
+ if (primary.subs.includes(n.component) && n.text !== undefined) {
321
+ instance[route.to.name] = n.text;
322
+ record(route, rule, nPath, n.component);
323
+ }
324
+ } else if (primary.kind === "sub-label") {
325
+ if (n !== node && n.text !== undefined && primary.subs.some((sub) => insideSubs.has(sub))) {
326
+ const plan = this.byDspackId.get(n.component);
327
+ const bearsLabel = plan !== undefined && surfaceModelOf(plan).routes.some((r) => r.to.kind === "text-child");
328
+ if (bearsLabel) {
329
+ instance[route.to.name] = n.text;
330
+ record(route, rule, nPath, n.component);
331
+ }
332
+ }
333
+ }
334
+ }
335
+ const next = new Set(insideSubs);
336
+ for (const { route } of consuming) {
337
+ const primary = route.from[0];
338
+ if (primary.kind === "sub-label" && primary.subs.includes(n.component)) next.add(n.component);
339
+ }
340
+ collectChildren(n).forEach((child, i) => visit(child.node, `${nPath}${child.suffix}[${i}]`, next));
341
+ };
342
+ visit(node, path, new Set());
343
+
344
+ for (const { route, rule } of consuming) {
345
+ if (instance[route.to.name] !== undefined) continue;
346
+ for (const selector of route.from.slice(1)) {
347
+ const found = this.resolve(node, selector, path, treePath, rule, route);
348
+ if (found !== undefined) {
349
+ instance[route.to.name] = found as Json[keyof Json];
350
+ this.diagnostics.pushFidelity(
351
+ {
352
+ source: `${path} (fallback)`,
353
+ destination: route.to.name,
354
+ origin: route.origin,
355
+ kind: selector.kind === "sub-text-lift" ? "lifted" : "moved",
356
+ class: "maps-cleanly",
357
+ note: selector.kind === "sub-text-lift" ? "audited lift: relocation of existing text, never synthesis" : undefined,
358
+ },
359
+ treePath,
360
+ Band.BeforeChildren,
361
+ Phase.LabelLift,
362
+ rule,
200
363
  );
364
+ break;
201
365
  }
202
366
  }
203
367
  }
204
368
 
205
- this.components[index] = instance;
206
- return id;
369
+ this.diagnostics.push(
370
+ {
371
+ code: "surface-composition-flattened",
372
+ message: `${path}: compound '${node.component}' subtree flattened onto emitted props (documented casualty; nested props beyond text are not carried).`,
373
+ },
374
+ treePath,
375
+ Band.BeforeChildren,
376
+ Phase.SubContentFlatten,
377
+ );
378
+ this.diagnostics.pushFidelity(
379
+ {
380
+ source: `${path} (${node.component} subtree)`,
381
+ destination: "(props of this instance)",
382
+ origin: consuming.map(({ route }) => route.origin).join(", "),
383
+ kind: "flattened",
384
+ class: "lossy",
385
+ note: "compound composition consumed into props; structure and nested props beyond text are not carried",
386
+ },
387
+ treePath,
388
+ Band.BeforeChildren,
389
+ Phase.SubContentFlatten,
390
+ );
391
+ }
392
+
393
+ /**
394
+ * Writes `value` unless the destination is taken and the route is
395
+ * first-wins. Returns whether the write LANDED — the fidelity ledger must
396
+ * record a discarded harvest as discarded, never as a clean move.
397
+ */
398
+ private write(instance: Json, name: string, value: Json[keyof Json], overwrite?: boolean): boolean {
399
+ if (overwrite || instance[name] === undefined) {
400
+ instance[name] = value;
401
+ return true;
402
+ }
403
+ return false;
404
+ }
405
+
406
+ private applyRoute(
407
+ node: SurfaceNode,
408
+ route: Route,
409
+ rule: number,
410
+ instance: Json,
411
+ id: string,
412
+ path: string,
413
+ treePath: readonly number[],
414
+ ): void {
415
+ // `children` is not a value route: it produces instances, and is handled
416
+ // with the child walk so ids exist in emission order.
417
+ if (route.from.some((s) => s.kind === "children")) return;
418
+
419
+ for (const selector of route.from) {
420
+ if (selector.kind === "synthesized-action") {
421
+ const eventName = slug(node.id ?? (instance.confirmLabel as string) ?? node.text ?? node.component);
422
+ this.write(instance, route.to.name, { event: { name: eventName, context: {} } } as Json[keyof Json], route.overwrite);
423
+ this.diagnostics.pushFidelity(
424
+ {
425
+ source: "(no source: A2UI requires a declarative action)",
426
+ destination: route.to.name,
427
+ origin: route.origin,
428
+ kind: "synthesized",
429
+ class: "synthesis-defaults",
430
+ note: `event name '${eventName}' derived from the node's id/label/component slug`,
431
+ },
432
+ treePath,
433
+ Band.BeforeChildren,
434
+ Phase.Action,
435
+ rule,
436
+ );
437
+ this.diagnostics.push(
438
+ {
439
+ code: "surface-synthesized-action",
440
+ message: `${path}: A2UI requires a declarative action on ${instance.component as string}; synthesized event '${eventName}'.`,
441
+ },
442
+ treePath,
443
+ Band.BeforeChildren,
444
+ Phase.Action,
445
+ rule,
446
+ );
447
+ return;
448
+ }
449
+
450
+ const found = this.resolve(node, selector, path, treePath, rule, route);
451
+ if (found === undefined) continue;
452
+
453
+ if (route.to.kind === "text-child") {
454
+ this.write(
455
+ instance,
456
+ route.to.name,
457
+ this.emitTextPrimitive(String(found), `${id}_label`, path, treePath, Phase.TextChild, rule),
458
+ route.overwrite,
459
+ );
460
+ } else {
461
+ const landed = this.write(instance, route.to.name, found as Json[keyof Json], route.overwrite);
462
+ this.diagnostics.pushFidelity(
463
+ landed
464
+ ? {
465
+ source: `${path} (${describeSelector(selector)})`,
466
+ destination: route.to.name,
467
+ origin: route.origin,
468
+ kind: selector.kind === "self-prop" ? "projected" : "moved",
469
+ class: "maps-cleanly",
470
+ }
471
+ : {
472
+ source: `${path} (${describeSelector(selector)})`,
473
+ destination: "(discarded)",
474
+ origin: route.origin,
475
+ kind: "dropped",
476
+ class: "lossy",
477
+ note: `'${route.to.name}' was already written by an earlier phase; the harvested value did not land`,
478
+ },
479
+ treePath,
480
+ Band.BeforeChildren,
481
+ selector.kind === "self-prop" ? Phase.PropMap : Phase.TextChild,
482
+ rule,
483
+ );
484
+ }
485
+ return; // ordered fallback: the first selector that yields wins
486
+ }
487
+ }
488
+
489
+ /** Resolves one selector against the node's subtree; `undefined` when it yields nothing. */
490
+ private resolve(
491
+ node: SurfaceNode,
492
+ selector: Selector,
493
+ path: string,
494
+ treePath: readonly number[],
495
+ rule: number,
496
+ route: Route,
497
+ ): string | Json[keyof Json] | undefined {
498
+ switch (selector.kind) {
499
+ case "self-text":
500
+ return node.text;
501
+
502
+ case "self-prop":
503
+ return node.props?.[selector.prop] as Json[keyof Json] | undefined;
504
+
505
+ case "sub-text": {
506
+ // v1 visited the node itself as well as its descendants.
507
+ let hit: string | undefined;
508
+ const visit = (n: SurfaceNode): void => {
509
+ if (hit === undefined && selector.subs.includes(n.component) && n.text !== undefined) hit = n.text;
510
+ for (const child of collectChildren(n)) visit(child.node);
511
+ };
512
+ visit(node);
513
+ return hit;
514
+ }
515
+
516
+ case "sub-label": {
517
+ // Only a label-bearing component qualifies — one whose own model routes
518
+ // its text to a text-child destination — never incidental descendant text.
519
+ let hit: string | undefined;
520
+ const visit = (n: SurfaceNode, insideSub: boolean): void => {
521
+ if (hit === undefined && insideSub && n !== node && n.text !== undefined) {
522
+ const plan = this.byDspackId.get(n.component);
523
+ const bearsLabel =
524
+ plan !== undefined && surfaceModelOf(plan).routes.some((r) => r.to.kind === "text-child");
525
+ if (bearsLabel) hit = n.text;
526
+ }
527
+ for (const child of collectChildren(n)) visit(child.node, insideSub || selector.subs.includes(n.component));
528
+ };
529
+ visit(node, false);
530
+ return hit;
531
+ }
532
+
533
+ case "sub-text-lift": {
534
+ // Audited lift: relocation of text that exists, never synthesis. If
535
+ // nothing exists to lift the destination stays missing and gate A3
536
+ // refuses the instance, exactly as before.
537
+ const lift = (n: SurfaceNode, inside: boolean): { text: string; component: string } | undefined => {
538
+ const here = inside || selector.subs.includes(n.component);
539
+ if (here && n.text !== undefined && n.text !== "") return { text: n.text, component: n.component };
540
+ for (const child of collectChildren(n)) {
541
+ const found = lift(child.node, here);
542
+ if (found) return found;
543
+ }
544
+ return undefined;
545
+ };
546
+ const found = lift(node, false);
547
+ if (!found) return undefined;
548
+ this.diagnostics.push(
549
+ {
550
+ code: "surface-label-lifted",
551
+ 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).`,
552
+ },
553
+ treePath,
554
+ Band.BeforeChildren,
555
+ Phase.LabelLift,
556
+ rule,
557
+ );
558
+ return found.text;
559
+ }
560
+
561
+ case "subtree-text": {
562
+ let hit: SurfaceNode | undefined;
563
+ const visit = (n: SurfaceNode): void => {
564
+ if (hit === undefined && selector.subs.includes(n.component)) hit = n;
565
+ for (const child of collectChildren(n)) visit(child.node);
566
+ };
567
+ visit(node);
568
+ return hit ? this.subtreeText(hit) : undefined;
569
+ }
570
+
571
+ case "children":
572
+ case "synthesized-action":
573
+ return undefined;
574
+ }
207
575
  }
208
576
 
209
577
  /** CSR props -> A2UI props via the profile's existing PropPlan projections. */
210
- private applyPropMap(node: SurfaceNode, plan: ComponentPlan, instance: Json, path: string): void {
578
+ private applyPropMap(
579
+ node: SurfaceNode,
580
+ plan: ComponentPlan,
581
+ model: SurfaceModel,
582
+ instance: Json,
583
+ path: string,
584
+ treePath: readonly number[],
585
+ ): void {
586
+ // A prop routed verbatim to a SAME-NAMED destination is projected by that
587
+ // route, not by the prop map — v1 spelled this `structuralPassthrough`.
588
+ // The name check matters: a v2 route may read a declared contract prop
589
+ // into a differently-named destination, and that read must not suppress
590
+ // the prop's own projection (both writes are real, to distinct names).
591
+ const routedVerbatim = new Set(
592
+ model.routes
593
+ .filter((r) => r.from.some((s) => s.kind === "self-prop" && s.prop === r.to.name))
594
+ .map((r) => (r.from.find((s) => s.kind === "self-prop") as { prop: string }).prop),
595
+ );
211
596
  for (const [prop, raw] of Object.entries(node.props ?? {})) {
212
- if (plan.surfacePlan?.structuralPassthrough?.includes(prop)) continue;
597
+ if (routedVerbatim.has(prop)) continue;
213
598
  const pp = plan.propMap?.[prop];
214
599
  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
- });
600
+ this.diagnostics.push(
601
+ {
602
+ code: "surface-prop-dropped",
603
+ message: `${path}: prop '${prop}' on '${node.component}' has no A2UI projection; dropped.`,
604
+ },
605
+ treePath,
606
+ Band.BeforeChildren,
607
+ Phase.PropMap,
608
+ );
609
+ this.diagnostics.pushFidelity(
610
+ { source: `${path} (props.${prop})`, destination: "(discarded)", origin: `propMap.${prop}`, kind: "dropped", class: "lossy", note: "no A2UI projection" },
611
+ treePath,
612
+ Band.BeforeChildren,
613
+ Phase.PropMap,
614
+ );
219
615
  continue;
220
616
  }
221
- const value = pp.valueMap ? (pp.valueMap[String(raw)] ?? pp.default) : raw;
617
+ const mapped = pp.valueMap ? pp.valueMap[String(raw)] : undefined;
618
+ const value = pp.valueMap ? (mapped ?? pp.default) : raw;
222
619
  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
- });
620
+ this.diagnostics.push(
621
+ {
622
+ code: "surface-prop-value-dropped",
623
+ message: `${path}: value '${String(raw)}' of prop '${prop}' has no projection and no default; dropped.`,
624
+ },
625
+ treePath,
626
+ Band.BeforeChildren,
627
+ Phase.PropMap,
628
+ );
629
+ this.diagnostics.pushFidelity(
630
+ { source: `${path} (props.${prop}='${String(raw)}')`, destination: "(discarded)", origin: `propMap.${prop}`, kind: "dropped", class: "lossy", note: "value has no projection and no default" },
631
+ treePath,
632
+ Band.BeforeChildren,
633
+ Phase.PropMap,
634
+ );
227
635
  continue;
228
636
  }
229
637
  instance[pp.a2ui] = value as Json[keyof Json];
638
+ this.diagnostics.pushFidelity(
639
+ {
640
+ source: `${path} (props.${prop})`,
641
+ destination: pp.a2ui,
642
+ origin: `propMap.${prop}`,
643
+ kind: "projected",
644
+ class: pp.valueMap && mapped === undefined ? "synthesis-defaults" : "maps-cleanly",
645
+ note: pp.valueMap && mapped === undefined ? `value '${String(raw)}' fell back to the declared default '${String(pp.default)}'` : undefined,
646
+ },
647
+ treePath,
648
+ Band.BeforeChildren,
649
+ Phase.PropMap,
650
+ );
230
651
  }
231
652
  }
232
653
 
233
654
  /**
234
- * Compound flattening: pull text out of named sub-components anywhere in the
235
- * subtree. The subtree is consumed — the documented composition casualty.
655
+ * Refuse when a consumed subtree contains a component the profile declared a
656
+ * casualty. Consumption is how compounds fold their parts into props; it is
657
+ * NOT an escape hatch around an author's "this cannot be represented".
658
+ * Fail-closed and loud, with the authored reason, exactly like the direct
659
+ * emission path — including the offending node's own path, so the refusal
660
+ * points at the casualty rather than the parent that would have eaten it.
236
661
  */
237
- private applySubContent(
662
+ private refuseConsumedCasualty(node: SurfaceNode, path: string): void {
663
+ const walk = (n: SurfaceNode, nodePath: string): void => {
664
+ if (n !== node) {
665
+ const casualty = this.profile.casualtyComponents.find((c) => c.dspackId === n.component);
666
+ if (casualty && !this.byDspackId.has(n.component)) {
667
+ throw new EmitSurfaceError(
668
+ `component '${n.component}' is a declared casualty (${casualty.class}) of the ` +
669
+ `'${this.profile.catalogTitle}' profile and cannot be consumed into ` +
670
+ `'${node.component}': ${casualty.reason}`,
671
+ nodePath,
672
+ );
673
+ }
674
+ }
675
+ collectChildren(n).forEach((child, i) => walk(child.node, `${nodePath}${child.suffix}[${i}]`));
676
+ };
677
+ walk(node, path);
678
+ }
679
+
680
+ /**
681
+ * Repetition: collect repeated sub-structures into array-valued destinations.
682
+ * Nothing here is table-shaped — the depth is nesting and the record key is an
683
+ * item field name. Cells flatten to their subtree TEXT in document order;
684
+ * nested structure and props are a warned per-cell loss, never re-interpreted.
685
+ */
686
+ /**
687
+ * Repetition: collect one repeated sub-structure into an array-valued
688
+ * destination. Nothing here is table-shaped — the depth is nesting and the
689
+ * record key is an item field name. Cells flatten to their subtree TEXT in
690
+ * document order; nested structure and props are a warned per-cell loss,
691
+ * never re-interpreted into semantic fields.
692
+ */
693
+ private applyCollect(
238
694
  node: SurfaceNode,
239
- subText: Record<string, string>,
240
- subButtonText: Record<string, string>,
695
+ model: SurfaceModel,
696
+ collect: Collect,
697
+ rule: number,
241
698
  instance: Json,
242
699
  path: string,
700
+ treePath: readonly number[],
243
701
  ): 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;
248
- }
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;
256
- }
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;
702
+ void model;
703
+ if (collect.as.kind === "inline") return;
704
+ const out: Json[] = [];
705
+ const flat: string[] = [];
706
+ const scalarField = Object.values(collect.item ?? {}).find((f) => isCollect(f) && f.scalar) as Collect | undefined;
707
+ const itemKey = Object.keys(collect.item ?? {})[0] ?? "items";
708
+
709
+ for (const child of collectChildren(node)) {
710
+ if (!collect.of.includes(child.node.component)) continue;
711
+ const childPath = `${path}${child.suffix}`;
712
+ for (const inner of collectChildren(child.node)) {
713
+ if (!scalarField || !scalarField.of.includes(inner.node.component)) {
714
+ this.diagnostics.push(
715
+ {
716
+ code: "surface-sub-dropped",
717
+ message: `${childPath}: '${inner.node.component}' inside '${child.node.component}' has no slot; dropped.`,
718
+ },
719
+ treePath,
720
+ Band.BeforeChildren,
721
+ Phase.TableBody,
722
+ rule,
723
+ );
724
+ this.diagnostics.pushFidelity(
725
+ { source: `${childPath} (${inner.node.component})`, destination: "(discarded)", origin: collect.origin, kind: "dropped", class: "lossy", note: "no slot inside the collected repetition" },
726
+ treePath,
727
+ Band.BeforeChildren,
728
+ Phase.TableBody,
729
+ rule,
730
+ );
731
+ continue;
277
732
  }
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
- });
733
+ const cells = this.collectRow(inner.node, scalarField, `${childPath}${inner.suffix}`, treePath, rule);
734
+ if (this.isFlatTarget(collect)) flat.push(...cells);
735
+ else out.push({ [itemKey]: cells } as Json);
287
736
  }
288
737
  }
289
738
 
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
- });
739
+ const value = this.isFlatTarget(collect) ? flat : out;
740
+ if (value.length > 0) {
741
+ const landed = this.write(instance, collect.as.name, value as Json[keyof Json]);
742
+ this.diagnostics.pushFidelity(
743
+ landed
744
+ ? {
745
+ source: `${path} (${collect.of.join("|")} repetitions)`,
746
+ destination: collect.as.name,
747
+ origin: collect.origin,
748
+ kind: "moved",
749
+ class: "maps-cleanly",
750
+ note: this.isFlatTarget(collect)
751
+ ? `${flat.length} cell(s) collected into one flat list`
752
+ : `${out.length} record(s) collected`,
753
+ }
754
+ : {
755
+ source: `${path} (${collect.of.join("|")} repetitions)`,
756
+ destination: "(discarded)",
757
+ origin: collect.origin,
758
+ kind: "dropped",
759
+ class: "lossy",
760
+ note: `'${collect.as.name}' was already written by an earlier phase; the collected ${this.isFlatTarget(collect) ? "cells" : "records"} did not land`,
761
+ },
762
+ treePath,
763
+ Band.BeforeChildren,
764
+ Phase.TableBody,
765
+ rule,
766
+ );
767
+ }
294
768
  }
295
769
 
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;
770
+ /**
771
+ * After every collect has run: anything the collects and routes did not claim
772
+ * is either an explicit drop or an unrecognized sub — both warned, never
773
+ * silently ignored — followed by the composition casualty for the compound.
774
+ */
775
+ private closeCollects(
776
+ node: SurfaceNode,
777
+ model: SurfaceModel,
778
+ path: string,
779
+ treePath: readonly number[],
780
+ ): void {
781
+ const claimedByCollect = new Set(model.collects.flatMap((c) => c.of));
782
+ for (const child of collectChildren(node)) {
783
+ const c = child.node.component;
784
+ if (claimedByCollect.has(c) || this.claimedByRoute(model, c)) continue;
785
+ const childPath = `${path}${child.suffix}`;
786
+ const reason = model.drops[c];
787
+ this.diagnostics.push(
788
+ {
789
+ code: "surface-sub-dropped",
790
+ message: reason
791
+ ? `${childPath}: '${c}' dropped: ${reason}.`
792
+ : `${childPath}: '${c}' has no slot in the synthesized table shape; dropped.`,
793
+ },
794
+ treePath,
795
+ Band.BeforeChildren,
796
+ Phase.TableBody,
797
+ );
798
+ this.diagnostics.pushFidelity(
799
+ {
800
+ source: `${childPath} (${c})`,
801
+ destination: "(discarded)",
802
+ origin: reason ? `drops.${c}` : "collect",
803
+ kind: "dropped",
804
+ class: "lossy",
805
+ note: reason ?? "no slot in the collected shape",
806
+ },
807
+ treePath,
808
+ Band.BeforeChildren,
809
+ Phase.TableBody,
810
+ );
811
+ }
812
+
813
+ this.diagnostics.push(
814
+ {
815
+ code: "surface-composition-flattened",
816
+ message: `${path}: compound '${node.component}' subtree consumed into the synthesized table shape (documented casualty; cell content beyond text is not carried).`,
817
+ },
818
+ treePath,
819
+ Band.BeforeChildren,
820
+ Phase.TableFlatten,
821
+ );
822
+ this.diagnostics.pushFidelity(
823
+ {
824
+ source: `${path} (${node.component} subtree)`,
825
+ destination: "(collected props)",
826
+ origin: model.collects.map((c) => c.origin).join(", "),
827
+ kind: "flattened",
828
+ class: "lossy",
829
+ note: "compound consumed into the collected shape; cell content beyond text is not carried",
830
+ },
831
+ treePath,
832
+ Band.BeforeChildren,
833
+ Phase.TableFlatten,
834
+ );
835
+ }
836
+
837
+ /** True when a collect writes one flat list rather than one record per repetition. */
838
+ private isFlatTarget(collect: Collect): boolean {
839
+ return collect.flatten;
840
+ }
841
+
842
+ /** True when some route already consumes this component's text. */
843
+ private claimedByRoute(model: SurfaceModel, component: string): boolean {
844
+ return model.routes.some((r) =>
845
+ r.from.some((s) => "subs" in s && (s.subs as string[]).includes(component)),
846
+ );
847
+ }
848
+
849
+ /** One repetition's scalar cells, each flattened to its subtree text. */
850
+ private collectRow(
851
+ row: SurfaceNode,
852
+ field: Collect,
853
+ rowPath: string,
854
+ treePath: readonly number[],
855
+ rule: number,
856
+ ): string[] {
857
+ const cells: string[] = [];
858
+ for (const child of collectChildren(row)) {
859
+ const c = child.node.component;
860
+ const subs = (field.scalar!.from[0] as { subs: string[] }).subs;
861
+ if (subs.includes(c)) {
862
+ cells.push(this.cellText(child.node, `${rowPath}${child.suffix}`, treePath, rule));
863
+ } else {
864
+ this.diagnostics.push(
865
+ {
866
+ code: "surface-sub-dropped",
867
+ message: `${rowPath}: '${c}' has no slot in a synthesized table row; dropped (its text is not lifted).`,
868
+ },
869
+ treePath,
870
+ Band.BeforeChildren,
871
+ Phase.TableBody,
872
+ rule,
873
+ );
874
+ this.diagnostics.pushFidelity(
875
+ { source: `${rowPath} (${c})`, destination: "(discarded)", origin: field.origin, kind: "dropped", class: "lossy", note: "no slot in a collected row; its text is not lifted" },
876
+ treePath,
877
+ Band.BeforeChildren,
878
+ Phase.TableBody,
879
+ rule,
880
+ );
881
+ }
882
+ }
883
+ return cells;
884
+ }
885
+
886
+ private cellText(cell: SurfaceNode, cellPath: string, treePath: readonly number[], rule: number): string {
887
+ const nested = collectChildren(cell);
888
+ const text = this.subtreeText(cell);
889
+ if (nested.length > 0) {
890
+ const names = nested.map((c) => `'${c.node.component}'`).join(", ");
891
+ this.diagnostics.push(
892
+ {
893
+ code: "surface-table-cell-flattened",
894
+ message: `${cellPath}: nested ${names} flattened to cell text; component structure and props are not carried by the synthesized table shape.`,
895
+ },
896
+ treePath,
897
+ Band.BeforeChildren,
898
+ Phase.TableBody,
899
+ rule,
900
+ );
901
+ this.diagnostics.pushFidelity(
902
+ { 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" },
903
+ treePath,
904
+ Band.BeforeChildren,
905
+ Phase.TableBody,
906
+ rule,
907
+ );
908
+ }
909
+ return text;
910
+ }
911
+
912
+ /** Children as instance references, after any sub-identity rewriting. */
913
+ private emitChildren(
914
+ node: SurfaceNode,
915
+ model: SurfaceModel,
916
+ instance: Json,
917
+ id: string,
918
+ path: string,
919
+ treePath: readonly number[],
920
+ ): void {
921
+ const childRoute = model.routes.find((r) => r.from.some((s) => s.kind === "children"));
922
+ const childNodes =
923
+ Object.keys(model.subIdentity).length > 0 || Object.keys(model.drops).length > 0
924
+ ? this.rewriteChildren(node, model, path, treePath)
925
+ : collectChildren(node).map((c) => ({ node: c.node, suffix: c.suffix }));
926
+ if (childNodes.length === 0) return;
927
+
928
+ const childIds = childNodes.map((child, i) =>
929
+ "textVariant" in child
930
+ ? this.emitTextPrimitive(
931
+ child.text,
932
+ `${id}_${slug(child.textVariant)}`,
933
+ path,
934
+ [...treePath, Band.Children, i],
935
+ Phase.TextChild,
936
+ 0,
937
+ child.textVariant,
938
+ )
939
+ : this.emitNode(child.node, `${path}${child.suffix}[${i}]`, [...treePath, Band.Children, i]),
940
+ );
941
+
942
+ if (!childRoute) {
943
+ throw new EmitSurfaceError(
944
+ `component '${node.component}' has children but its surface plan declares no child slot`,
945
+ path,
946
+ );
947
+ }
948
+ if (childRoute.to.kind === "slots") {
949
+ instance[childRoute.to.name] = childIds;
950
+ } else {
951
+ instance[childRoute.to.name] =
952
+ childIds.length === 1 ? childIds[0] : this.wrapInColumn(childIds, id, path, treePath);
953
+ }
307
954
  }
308
955
 
309
956
  /**
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.
957
+ * Identity applied to named sub-components met in this node's child list:
958
+ * `transparent` dissolves (its children rise in document order, recursively),
959
+ * `as-text` becomes the profile's text primitive carrying its subtree text.
315
960
  */
316
- private flattenSubs(
961
+ private rewriteChildren(
317
962
  node: SurfaceNode,
318
- spec: NonNullable<NonNullable<ComponentPlan["surfacePlan"]>["subFlatten"]>,
963
+ model: SurfaceModel,
319
964
  path: string,
965
+ treePath: readonly number[],
320
966
  ): Array<{ node: SurfaceNode; suffix: string } | { text: string; textVariant: string }> {
321
967
  const out: Array<{ node: SurfaceNode; suffix: string } | { text: string; textVariant: string }> = [];
322
968
  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
- });
969
+ // An authored drop is warn-and-discard, exactly like the collect path:
970
+ // the sub is skipped with its reason on record, never emitted and never
971
+ // crashed into the unknown-component refusal.
972
+ const dropReason = model.drops[n.component];
973
+ if (dropReason !== undefined) {
974
+ this.diagnostics.push(
975
+ { code: "surface-sub-dropped", message: `${path}: '${n.component}' dropped: ${dropReason}.` },
976
+ treePath,
977
+ Band.BeforeChildren,
978
+ Phase.ChildRewrite,
979
+ );
980
+ this.diagnostics.pushFidelity(
981
+ { source: `${path} (${n.component})`, destination: "(discarded)", origin: `drops.${n.component}`, kind: "dropped", class: "lossy", note: dropReason },
982
+ treePath,
983
+ Band.BeforeChildren,
984
+ Phase.ChildRewrite,
985
+ );
986
+ return;
987
+ }
988
+ const identity = model.subIdentity[n.component];
989
+ if (identity?.kind === "transparent") {
990
+ this.diagnostics.push(
991
+ {
992
+ code: "surface-sub-flattened",
993
+ message: `${path}: grouping sub-component '${n.component}' spliced inline (subFlatten strategy); its own structure is not carried.`,
994
+ },
995
+ treePath,
996
+ Band.BeforeChildren,
997
+ Phase.ChildRewrite,
998
+ );
999
+ this.diagnostics.pushFidelity(
1000
+ { 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" },
1001
+ treePath,
1002
+ Band.BeforeChildren,
1003
+ Phase.ChildRewrite,
1004
+ );
328
1005
  if (n.text !== undefined && n.text !== "") out.push({ text: n.text, textVariant: "body" });
329
1006
  for (const child of collectChildren(n)) visit(child.node, child.suffix);
330
1007
  return;
331
1008
  }
332
- const variant = spec.asText[n.component];
333
- if (variant !== undefined) {
1009
+ if (identity?.kind === "as-text") {
334
1010
  const text = this.subtreeText(n);
1011
+ const nested = collectChildren(n);
1012
+ if (nested.length > 0) {
1013
+ // Structure destroyed, text preserved — the same loss the cell
1014
+ // flatten records, and it must class the same way.
1015
+ const names = nested.map((c) => `'${c.node.component}'`).join(", ");
1016
+ this.diagnostics.pushFidelity(
1017
+ { 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" },
1018
+ treePath,
1019
+ Band.BeforeChildren,
1020
+ Phase.ChildRewrite,
1021
+ );
1022
+ }
335
1023
  if (text !== "") {
336
- out.push({ text, textVariant: variant });
1024
+ out.push({ text, textVariant: identity.variant });
337
1025
  } else {
338
- this.warnings.push({
339
- code: "surface-sub-dropped",
340
- message: `${path}: '${n.component}' carried no text to synthesize; dropped.`,
341
- });
1026
+ this.diagnostics.push(
1027
+ { code: "surface-sub-dropped", message: `${path}: '${n.component}' carried no text to synthesize; dropped.` },
1028
+ treePath,
1029
+ Band.BeforeChildren,
1030
+ Phase.ChildRewrite,
1031
+ );
1032
+ this.diagnostics.pushFidelity(
1033
+ { source: `${path} (${n.component})`, destination: "(discarded)", origin: `subs.${n.component}`, kind: "dropped", class: "lossy", note: "re-identified as text but carried none" },
1034
+ treePath,
1035
+ Band.BeforeChildren,
1036
+ Phase.ChildRewrite,
1037
+ );
342
1038
  }
343
1039
  return;
344
1040
  }
@@ -348,89 +1044,38 @@ class SurfaceEmitter {
348
1044
  return out;
349
1045
  }
350
1046
 
351
- /**
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.
357
- */
358
- private applySubTable(
359
- node: SurfaceNode,
360
- spec: NonNullable<NonNullable<ComponentPlan["surfacePlan"]>["subTable"]>,
361
- instance: Json,
1047
+ private emitTextPrimitive(
1048
+ text: string,
1049
+ preferredId: string,
362
1050
  path: string,
363
- ): 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({
374
- code: "surface-table-cell-flattened",
375
- message: `${cellPath}: nested ${names} flattened to cell text; component structure and props are not carried by the synthesized table shape.`,
376
- });
377
- }
378
- return text;
379
- };
380
-
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]}.` });
388
- } 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
- });
393
- }
394
- }
395
- };
396
-
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.` });
406
- }
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.` });
415
- }
416
- }
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.`,
423
- });
424
- }
425
- }
426
-
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
- });
1051
+ treePath: readonly number[],
1052
+ phase: Phase,
1053
+ rule: number,
1054
+ variant?: string,
1055
+ ): string {
1056
+ const { textComponent, textProp } = this.profile.surfaceSynthesis;
1057
+ const id = this.allocateId(preferredId, path, { treePath, band: Band.BeforeChildren, phase, rule });
1058
+ const instance: Json = { id, component: textComponent, [textProp]: text };
1059
+ if (variant !== undefined) instance.variant = variant;
1060
+ this.components.push(instance);
1061
+ this.diagnostics.push(
1062
+ {
1063
+ code: "surface-synthesized-text",
1064
+ message: `${path}: node text projected as a synthesized ${textComponent} child ('${id}') — the surface format has no text primitive.`,
1065
+ },
1066
+ treePath,
1067
+ Band.BeforeChildren,
1068
+ phase,
1069
+ rule,
1070
+ );
1071
+ this.diagnostics.pushFidelity(
1072
+ { source: `${path} (text)`, destination: `synthesized ${textComponent} '${id}'`, origin: "surfaceSynthesis.textComponent", kind: "synthesized", class: "synthesis-defaults", note: "the surface format has no text primitive" },
1073
+ treePath,
1074
+ Band.BeforeChildren,
1075
+ phase,
1076
+ rule,
1077
+ );
1078
+ return id;
434
1079
  }
435
1080
 
436
1081
  /** All text in a node's subtree, document order, space-joined. */
@@ -444,30 +1089,63 @@ class SurfaceEmitter {
444
1089
  return parts.join(" ");
445
1090
  }
446
1091
 
447
- private wrapInColumn(childIds: string[], parentId: string, path: string): string {
1092
+ private wrapInColumn(childIds: string[], parentId: string, path: string, treePath: readonly number[]): string {
448
1093
  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.`,
1094
+ const id = this.allocateId(`${parentId}_col`, path, {
1095
+ treePath,
1096
+ band: Band.AfterChildren,
1097
+ phase: Phase.Wrap,
1098
+ rule: 0,
458
1099
  });
1100
+ this.components.push({ id, component: wrapComponent, [wrapChildrenProp]: childIds });
1101
+ this.diagnostics.push(
1102
+ {
1103
+ code: "surface-synthesized-wrap",
1104
+ message: `${path}: ${childIds.length} children wrapped in a synthesized ${wrapComponent} ('${id}') — the target slot takes a single child.`,
1105
+ },
1106
+ treePath,
1107
+ Band.AfterChildren,
1108
+ Phase.Wrap,
1109
+ );
1110
+ this.diagnostics.pushFidelity(
1111
+ { 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" },
1112
+ treePath,
1113
+ Band.AfterChildren,
1114
+ Phase.Wrap,
1115
+ );
459
1116
  return id;
460
1117
  }
461
1118
 
462
- private allocateId(preferred: string, path: string): string {
1119
+ /**
1120
+ * Deterministic and stateful: `slug`, then `_2`, `_3`, … in first-come order.
1121
+ * Allocation order is emission order, which the model does not change.
1122
+ */
1123
+ private allocateId(
1124
+ preferred: string,
1125
+ path: string,
1126
+ where: { treePath: readonly number[]; band: Band; phase: Phase; rule: number },
1127
+ ): string {
463
1128
  let id = slug(preferred);
464
1129
  let n = 2;
465
1130
  while (this.usedIds.has(id)) id = `${slug(preferred)}_${n++}`;
466
1131
  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
- });
1132
+ this.diagnostics.push(
1133
+ {
1134
+ code: "surface-id-deduplicated",
1135
+ message: `${path}: node id '${preferred}' already used; emitted as '${id}'.`,
1136
+ },
1137
+ where.treePath,
1138
+ where.band,
1139
+ where.phase,
1140
+ where.rule,
1141
+ );
1142
+ this.diagnostics.pushFidelity(
1143
+ { 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, …" },
1144
+ where.treePath,
1145
+ where.band,
1146
+ where.phase,
1147
+ where.rule,
1148
+ );
471
1149
  }
472
1150
  this.usedIds.add(id);
473
1151
  return id;