@aestheticfunction/dspack-emit 0.5.0 → 0.7.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 (39) hide show
  1. package/README.md +5 -3
  2. package/dist/targets/a2ui/surface.js +580 -36
  3. package/dist/transform/mapping.js +21 -7
  4. package/dist/transform/model.d.ts +94 -1
  5. package/dist/transform/model.js +25 -4
  6. package/dist/transform/parse-v2.d.ts +55 -24
  7. package/dist/transform/parse-v2.js +176 -2
  8. package/dist/transform/profile-schema-v2.js +224 -46
  9. package/dist/transform/shadcn-v2-respelling.d.ts +65 -0
  10. package/dist/transform/shadcn-v2-respelling.js +407 -0
  11. package/dist/transform/validate-v2.js +39 -3
  12. package/dist/types.d.ts +5 -1
  13. package/dist/validate/ajv.d.ts +19 -0
  14. package/dist/validate/ajv.js +78 -13
  15. package/package.json +6 -2
  16. package/src/a0.test.ts +235 -0
  17. package/src/engine-boundary.test.ts +10 -0
  18. package/src/eval-fixture.test.ts +27 -14
  19. package/src/instance-diagnostics.test.ts +194 -0
  20. package/src/layered-dissolution.test.ts +139 -0
  21. package/src/profile-v2.test.ts +9 -3
  22. package/src/review-findings.test.ts +4 -1
  23. package/src/surface-emit.test.ts +43 -11
  24. package/src/surface-fidelity.test.ts +12 -0
  25. package/src/t1.test.ts +370 -0
  26. package/src/t2.test.ts +222 -0
  27. package/src/t3.test.ts +304 -0
  28. package/src/t4.test.ts +278 -0
  29. package/src/targets/a2ui/surface.ts +747 -72
  30. package/src/transform/mapping.ts +22 -6
  31. package/src/transform/model.ts +107 -5
  32. package/src/transform/parse-v2.ts +228 -17
  33. package/src/transform/profile-schema-v2.ts +224 -46
  34. package/src/transform/profile.v2.schema.json +224 -46
  35. package/src/transform/shadcn-v2-respelling.ts +414 -0
  36. package/src/transform/validate-v2.ts +39 -3
  37. package/src/types.ts +13 -1
  38. package/src/validate/ajv.ts +96 -12
  39. package/src/validate-v2.test.ts +1 -1
@@ -45,7 +45,7 @@ import { collectChildren } from "../csr.js";
45
45
  import { Band, Diagnostics, Phase } from "./diagnostics.js";
46
46
  import { surfaceModelOf } from "../../transform/desugar.js";
47
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";
48
+ import { describeSelector, emptySurfaceModel, isCollect, WriteOrder, type Collect, type Donation, type Route, type Selector, type SurfaceModel } from "../../transform/model.js";
49
49
 
50
50
  export class EmitSurfaceError extends Error {
51
51
  constructor(
@@ -105,8 +105,24 @@ export function emitSurface(
105
105
  for (const plan of profile.components) {
106
106
  if (plan.dspackId) byDspackId.set(plan.dspackId, plan);
107
107
  }
108
+ // T1: a transparent ROOT still needs an instance renderers can start from
109
+ // (components[0], id "root"). The established arity discipline answers it:
110
+ // the root dissolves and its risen children wrap in the profile's
111
+ // synthesized wrap component, which becomes the root — synthesis, recorded,
112
+ // never silent. (ex.expense-report-form roots at `form` directly; refusing
113
+ // transparent roots would refuse the exact failure T1 exists to fix.)
108
114
  const emitter = new SurfaceEmitter(profile, byDspackId);
109
- const rootId = emitter.emitNode(surface.root, "$.root");
115
+ const rootPlan = byDspackId.get(surface.root.component);
116
+ const rootId =
117
+ rootPlan && surfaceModelOf(rootPlan).transparent
118
+ ? emitter.emitTransparentRoot(surface.root, "$.root")
119
+ : emitter.emitNode(surface.root, "$.root");
120
+
121
+ // Every instance is assembled; refuse the whole emission if any of them
122
+ // could not validate against the catalog this surface names (required
123
+ // presence + enum membership — the observed defect class; gate A3 keeps
124
+ // full-schema rigor downstream).
125
+ emitter.refuseCatalogInvalid();
110
126
 
111
127
  const surfaceId = options.surfaceId ?? slug(surface.intent);
112
128
  const theme: Json = { agentDisplayName: `${doc.name} via dspack` };
@@ -144,10 +160,40 @@ export function slug(value: string): string {
144
160
  .replace(/^_+|_+$/g, "");
145
161
  return s || "surface";
146
162
  }
163
+ /**
164
+ * T1: one donation, resolved at its dissolving boundary and carried
165
+ * EXPLICITLY in the rewritten child list until the receiving control's own
166
+ * emission applies it as a first-wins pre-write. The committed instance of
167
+ * another node is never mutated; ordering cannot affect output because the
168
+ * write happens inside the control's own construction, in donation order.
169
+ */
170
+ interface PendingDonation {
171
+ prop: string;
172
+ value: string;
173
+ origin: string;
174
+ donorPath: string;
175
+ donorComponent: string;
176
+ }
177
+
178
+ type RewrittenChild =
179
+ | { node: SurfaceNode; suffix: string; donations?: PendingDonation[] }
180
+ | { text: string; textVariant: string };
181
+
147
182
  class SurfaceEmitter {
148
183
  readonly components: Json[] = [];
149
184
  readonly diagnostics = new Diagnostics();
150
185
  private readonly usedIds = new Set<string>();
186
+ /**
187
+ * Evidence channel for the final catalog-validity guard: authored props
188
+ * dropped per EMITTED instance — either the prop had no A2UI projection at
189
+ * all, or its value had no projection and no default. Keyed by instance
190
+ * object so a later missing-required refusal can cite its cause. This is
191
+ * bookkeeping alongside the (byte-frozen) warnings, never a new warning.
192
+ */
193
+ private readonly droppedProps = new Map<
194
+ Json,
195
+ Array<{ prop: string; dest?: string; raw: unknown; component: string; path: string; reason: "no-projection" | "no-value" }>
196
+ >();
151
197
 
152
198
  constructor(
153
199
  private readonly profile: Profile,
@@ -161,7 +207,7 @@ class SurfaceEmitter {
161
207
  * desugar.ts; if any of them appears below, the compatibility boundary has
162
208
  * leaked (src/engine-boundary.test.ts fails on exactly that).
163
209
  */
164
- emitNode(node: SurfaceNode, path: string, treePath: readonly number[] = []): string {
210
+ emitNode(node: SurfaceNode, path: string, treePath: readonly number[] = [], donations: PendingDonation[] = []): string {
165
211
  const plan = this.byDspackId.get(node.component);
166
212
  if (!plan) {
167
213
  // A declared casualty refuses with its authored reason — the refusal is
@@ -212,6 +258,29 @@ class SurfaceEmitter {
212
258
  // the explicit phase model, never this loop's order.
213
259
  this.applyOperations(node, model, instance, id, path, treePath);
214
260
 
261
+ // T1 donations: contextual values a dissolved wrapper handed to this
262
+ // control, applied AFTER the control's own writes, first-wins — inherited
263
+ // context fills what the control left absent and never beats its own
264
+ // authored content. The ledger records exactly what happened either way.
265
+ for (const d of donations) {
266
+ const landed = this.write(instance, d.prop, d.value as Json[keyof Json]);
267
+ this.diagnostics.pushFidelity(
268
+ {
269
+ source: `${d.donorPath} (${d.donorComponent}.text)`,
270
+ destination: `${d.prop} @ ${path} (${node.component})`,
271
+ origin: d.origin,
272
+ kind: landed ? "donated" : "dropped",
273
+ class: landed ? "maps-cleanly" : "lossy",
274
+ note: landed
275
+ ? `donated by '${d.donorComponent}' to '${node.component}' — the dissolving boundary's single eligible control`
276
+ : `'${d.prop}' already written on '${node.component}'; the donated value did not land`,
277
+ },
278
+ treePath,
279
+ Band.BeforeChildren,
280
+ Phase.PropMap,
281
+ );
282
+ }
283
+
215
284
  if (!model.consumesSubtree) {
216
285
  this.emitChildren(node, model, instance, id, path, treePath);
217
286
  }
@@ -269,6 +338,10 @@ class SurfaceEmitter {
269
338
 
270
339
  for (const { route, rule } of model.routes.map((route, rule) => ({ route, rule }))) {
271
340
  if (route.order === WriteOrder.Consume || route.order === WriteOrder.Children) continue;
341
+ if (route.order === WriteOrder.Slot) {
342
+ steps.push({ order: route.order, run: () => this.applySlotRoute(node, model, route, rule, instance, path, treePath) });
343
+ continue;
344
+ }
272
345
  steps.push({ order: route.order, run: () => this.applyRoute(node, route, rule, instance, id, path, treePath) });
273
346
  }
274
347
  for (const [rule, collect] of model.collects.entries()) {
@@ -281,6 +354,9 @@ class SurfaceEmitter {
281
354
  if (model.collects.some((c) => c.as.kind !== "inline")) {
282
355
  steps.push({ order: WriteOrder.Collect + 1, run: () => this.closeCollects(node, model, path, treePath) });
283
356
  }
357
+ if (model.routes.some((r) => r.order === WriteOrder.Slot)) {
358
+ steps.push({ order: WriteOrder.Slot + 1, run: () => this.closeSlots(node, model, path, treePath) });
359
+ }
284
360
 
285
361
  steps.sort((a, b) => a.order - b.order);
286
362
  for (const step of steps) step.run();
@@ -532,8 +608,9 @@ class SurfaceEmitter {
532
608
 
533
609
  case "sub-text-lift": {
534
610
  // 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.
611
+ // nothing exists to lift the destination stays missing — refused at
612
+ // emission by the final catalog-validity guard when it is required,
613
+ // arbitrated by gate A3 otherwise. Either way, no fabrication.
537
614
  const lift = (n: SurfaceNode, inside: boolean): { text: string; component: string } | undefined => {
538
615
  const here = inside || selector.subs.includes(n.component);
539
616
  if (here && n.text !== undefined && n.text !== "") return { text: n.text, component: n.component };
@@ -597,6 +674,7 @@ class SurfaceEmitter {
597
674
  if (routedVerbatim.has(prop)) continue;
598
675
  const pp = plan.propMap?.[prop];
599
676
  if (!pp) {
677
+ this.recordDrop(instance, { prop, raw, component: node.component, path, reason: "no-projection" });
600
678
  this.diagnostics.push(
601
679
  {
602
680
  code: "surface-prop-dropped",
@@ -617,6 +695,7 @@ class SurfaceEmitter {
617
695
  const mapped = pp.valueMap ? pp.valueMap[String(raw)] : undefined;
618
696
  const value = pp.valueMap ? (mapped ?? pp.default) : raw;
619
697
  if (value === undefined) {
698
+ this.recordDrop(instance, { prop, dest: pp.a2ui, raw, component: node.component, path, reason: "no-value" });
620
699
  this.diagnostics.push(
621
700
  {
622
701
  code: "surface-prop-value-dropped",
@@ -651,6 +730,104 @@ class SurfaceEmitter {
651
730
  }
652
731
  }
653
732
 
733
+ private recordDrop(
734
+ instance: Json,
735
+ entry: { prop: string; dest?: string; raw: unknown; component: string; path: string; reason: "no-projection" | "no-value" },
736
+ ): void {
737
+ const list = this.droppedProps.get(instance);
738
+ if (list) list.push(entry);
739
+ else this.droppedProps.set(instance, [entry]);
740
+ }
741
+
742
+ /**
743
+ * Final guard (ratified 2026-08-10): never return a surface whose instances
744
+ * the emitted catalog itself refuses. Two checks per instance, against its
745
+ * own ComponentPlan:
746
+ *
747
+ * - every catalog-required prop carries a value (`plan.required` — the
748
+ * same list mapping.ts emits as `required: ["component", ...]`);
749
+ * - every propMap-projected prop with a `targetEnum` carries a member of
750
+ * that enum (without a valueMap the authored value passes through
751
+ * verbatim, so an off-vocabulary value used to land silently).
752
+ *
753
+ * On any violation the whole emission refuses with ONE aggregated message
754
+ * citing each violation and — where the node's recorded drop diagnostics
755
+ * recover it — the cause. This covers the observed defect class
756
+ * (required-presence + enum-membership); full-schema rigor stays gate A3's
757
+ * job, downstream, as defense in depth. Warnings and fidelity recording are
758
+ * untouched: a surface that emits, emits byte-identically to before.
759
+ */
760
+ refuseCatalogInvalid(): void {
761
+ const byA2ui = new Map<string, ComponentPlan>();
762
+ for (const plan of [...this.profile.components, ...this.profile.synthesized]) {
763
+ // Transparent plans dissolve at emission — no instance ever carries them.
764
+ if (!surfaceModelOf(plan).transparent) byA2ui.set(plan.a2ui, plan);
765
+ }
766
+
767
+ const violations: string[] = [];
768
+ for (const inst of this.components) {
769
+ const plan = byA2ui.get(String(inst.component));
770
+ if (!plan) continue; // no plan to check against: gate A3 arbitrates downstream
771
+ const where = `${inst.component}#${inst.id}`;
772
+ const drops = this.droppedProps.get(inst) ?? [];
773
+
774
+ for (const req of plan.required) {
775
+ if (inst[req] !== undefined) continue;
776
+ violations.push(`${where}: required prop '${req}' has no value after emission${this.missingCause(plan, req, drops)}`);
777
+ }
778
+
779
+ for (const [src, pp] of Object.entries(plan.propMap ?? {})) {
780
+ if (!pp.targetEnum) continue;
781
+ const value = inst[pp.a2ui];
782
+ if (value === undefined) continue;
783
+ if (typeof value === "string" && pp.targetEnum.includes(value)) continue;
784
+ const cause = pp.valueMap ? "" : ` — authored 'props.${src}' passed through verbatim (this propMap declares no valueMap)`;
785
+ violations.push(
786
+ `${where}: prop '${pp.a2ui}' value ${JSON.stringify(value)} is outside the catalog's enum (allowed: ${pp.targetEnum.join(", ")})${cause}`,
787
+ );
788
+ }
789
+ }
790
+
791
+ if (violations.length > 0) {
792
+ throw new EmitSurfaceError(
793
+ `refusing to emit: ${violations.length} instance value(s) would not validate against the emitted catalog ` +
794
+ `(gate A3 would refuse this surface downstream):\n` +
795
+ violations.map((v) => ` - ${v}`).join("\n"),
796
+ "$",
797
+ );
798
+ }
799
+ }
800
+
801
+ /**
802
+ * The recoverable cause for a required prop with no value: the authored
803
+ * prop this node DID carry that was dropped (recorded at PropMap time),
804
+ * and/or where the plan's own routes expect the value to come from.
805
+ */
806
+ private missingCause(
807
+ plan: ComponentPlan,
808
+ req: string,
809
+ drops: Array<{ prop: string; dest?: string; raw: unknown; component: string; path: string; reason: "no-projection" | "no-value" }>,
810
+ ): string {
811
+ const model = surfaceModelOf(plan);
812
+ const feeders = model.routes.filter((r) => r.to.name === req);
813
+ const subs = [
814
+ ...new Set(feeders.flatMap((r) => r.from.flatMap((s) => ("subs" in s ? [...(s.subs as string[])] : [])))),
815
+ ];
816
+ const source =
817
+ subs.length > 0
818
+ ? ` (${req} comes from the ${subs.map((s) => `'${s}'`).join(" / ")} sub-component${subs.length > 1 ? "s" : ""})`
819
+ : feeders.length > 0
820
+ ? ` (${req} is fed by ${feeders.map((r) => r.from.map(describeSelector).join(" | ")).join(", ")})`
821
+ : "";
822
+ const drop = drops.find((d) => d.prop === req || d.dest === req);
823
+ if (!drop) return source;
824
+ const why =
825
+ drop.reason === "no-projection"
826
+ ? `authored 'props.${drop.prop}' on '${drop.component}' has no A2UI projection`
827
+ : `authored 'props.${drop.prop}'=${JSON.stringify(drop.raw)} on '${drop.component}' has no projection for that value and no default`;
828
+ return ` — ${why}${source}`;
829
+ }
830
+
654
831
  /**
655
832
  * Refuse when a consumed subtree contains a component the profile declared a
656
833
  * casualty. Consumption is how compounds fold their parts into props; it is
@@ -701,6 +878,176 @@ class SurfaceEmitter {
701
878
  ): void {
702
879
  void model;
703
880
  if (collect.as.kind === "inline") return;
881
+
882
+ // T2 item-mode: each descendant matching `of` (document order) becomes
883
+ // one record whose fields resolve against THAT item's own node. Absent
884
+ // sources omit the field — gate A3 arbitrates required record shapes,
885
+ // never synthesis. Sibling content the collect does not claim follows
886
+ // the ordinary consumed-subtree accounting (closeCollects).
887
+ if (collect.fields) {
888
+ const itemLocal = (n: SurfaceNode, sel: Selector): Json[keyof Json] | undefined =>
889
+ sel.kind === "self-text" ? n.text : sel.kind === "self-id" ? n.id : sel.kind === "self-prop" ? (n.props?.[sel.prop] as Json[keyof Json] | undefined) : undefined;
890
+
891
+ // Gather left items and (when a join is declared) joined counterparts,
892
+ // both in document order.
893
+ const lefts: Array<{ n: SurfaceNode; nPath: string }> = [];
894
+ const rights: Array<{ n: SurfaceNode; nPath: string }> = [];
895
+ const gather = (n: SurfaceNode, nPath: string): void => {
896
+ if (collect.of.includes(n.component)) {
897
+ lefts.push({ n, nPath });
898
+ return; // an item's subtree is the item's; nested items do not re-match
899
+ }
900
+ if (collect.join?.with.includes(n.component)) {
901
+ rights.push({ n, nPath });
902
+ return;
903
+ }
904
+ collectChildren(n).forEach((c, i) => gather(c.node, `${nPath}${c.suffix}[${i}]`));
905
+ };
906
+ collectChildren(node).forEach((c, i) => gather(c.node, `${path}${c.suffix}[${i}]`));
907
+
908
+ // T3: the declared key join. Every edge refuses — the profile names
909
+ // the relation, the emitter never infers one.
910
+ const counterparts = new Map<string, { n: SurfaceNode; nPath: string }>();
911
+ if (collect.join) {
912
+ const j = collect.join;
913
+ const seenLeft = new Map<string, string>();
914
+ for (const item of lefts) {
915
+ const key = itemLocal(item.n, j.leftKey);
916
+ if (typeof key !== "string" || key === "") {
917
+ throw new EmitSurfaceError(
918
+ `join '${j.origin}': item '${item.n.component}' carries no key (${describeSelector(j.leftKey)}); a keyless item cannot participate in a declared join`,
919
+ item.nPath,
920
+ );
921
+ }
922
+ const prior = seenLeft.get(key);
923
+ if (prior !== undefined) {
924
+ throw new EmitSurfaceError(
925
+ `join '${j.origin}': duplicate left key '${key}' (also at ${prior}); join keys must be unique on each side`,
926
+ item.nPath,
927
+ );
928
+ }
929
+ seenLeft.set(key, item.nPath);
930
+ }
931
+ for (const cp of rights) {
932
+ const key = itemLocal(cp.n, j.rightKey);
933
+ if (typeof key !== "string" || key === "") {
934
+ throw new EmitSurfaceError(
935
+ `join '${j.origin}': counterpart '${cp.n.component}' carries no key (${describeSelector(j.rightKey)})`,
936
+ cp.nPath,
937
+ );
938
+ }
939
+ if (counterparts.has(key)) {
940
+ throw new EmitSurfaceError(
941
+ `join '${j.origin}': duplicate right key '${key}'; join keys must be unique on each side`,
942
+ cp.nPath,
943
+ );
944
+ }
945
+ if (!seenLeft.has(key)) {
946
+ throw new EmitSurfaceError(
947
+ `join '${j.origin}': counterpart '${cp.n.component}' key '${key}' matches no item; a dangling counterpart is a contradiction, not surplus`,
948
+ cp.nPath,
949
+ );
950
+ }
951
+ counterparts.set(key, cp);
952
+ }
953
+ }
954
+
955
+ const records: Json[] = [];
956
+ for (const item of lefts) {
957
+ const record: Json = {};
958
+ for (const [fieldName, sel] of Object.entries(collect.fields)) {
959
+ const value = itemLocal(item.n, sel);
960
+ if (value !== undefined) record[fieldName] = value;
961
+ }
962
+ this.diagnostics.pushFidelity(
963
+ {
964
+ source: `${item.nPath} (${item.n.component})`,
965
+ destination: collect.as.name,
966
+ origin: collect.origin,
967
+ kind: "moved",
968
+ class: "maps-cleanly",
969
+ note: `item record { ${Object.keys(record).join(", ")} } collected`,
970
+ },
971
+ treePath,
972
+ Band.BeforeChildren,
973
+ Phase.TableBody,
974
+ rule,
975
+ );
976
+
977
+ if (collect.join) {
978
+ const j = collect.join;
979
+ const key = itemLocal(item.n, j.leftKey) as string;
980
+ const cp = counterparts.get(key);
981
+ if (!cp && !j.optional) {
982
+ throw new EmitSurfaceError(
983
+ `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)`,
984
+ item.nPath,
985
+ );
986
+ }
987
+ if (cp) {
988
+ for (const [fieldName, jSel] of Object.entries(j.fields)) {
989
+ if ("kind" in jSel && jSel.kind === "joined-children") {
990
+ // The slot-valued field: the counterpart's children emit as
991
+ // instances; the record carries the reference. Repetition's
992
+ // ratified slot form — not T4 multi-slot routing. The child
993
+ // list goes through the SAME rewriting as any parent's
994
+ // (mirroring the transparent-root host pattern), so a
995
+ // transparent top-level child inside a joined panel
996
+ // dissolves instead of refusing as an unroutable instance.
997
+ const spliced = this.rewriteChildren(cp.n, emptySurfaceModel(), cp.nPath, treePath);
998
+ if (spliced.length === 0) continue;
999
+ const ids = spliced.map((k, ki) =>
1000
+ "textVariant" in k
1001
+ ? this.emitTextPrimitive(
1002
+ k.text,
1003
+ `${slug(key)}_${slug(k.textVariant)}`,
1004
+ cp.nPath,
1005
+ [...treePath, Band.Children, records.length, ki],
1006
+ Phase.TextChild,
1007
+ 0,
1008
+ k.textVariant,
1009
+ )
1010
+ : this.emitNode(k.node, `${cp.nPath}${k.suffix}[${ki}]`, [...treePath, Band.Children, records.length], k.donations ?? []),
1011
+ );
1012
+ record[fieldName] =
1013
+ ids.length === 1 ? ids[0] : this.wrapInColumn(ids, `${slug(key)}`, cp.nPath, treePath);
1014
+ } else {
1015
+ const value = itemLocal(cp.n, jSel as Selector);
1016
+ if (value !== undefined) record[fieldName] = value;
1017
+ }
1018
+ }
1019
+ this.diagnostics.pushFidelity(
1020
+ {
1021
+ source: `${cp.nPath} (${cp.n.component})`,
1022
+ destination: `${collect.as.name} @ item '${key}'`,
1023
+ origin: j.origin,
1024
+ kind: "joined",
1025
+ class: "maps-cleanly",
1026
+ note: `counterpart joined on key '${key}' -> fields { ${Object.keys(j.fields).join(", ")} }`,
1027
+ },
1028
+ treePath,
1029
+ Band.BeforeChildren,
1030
+ Phase.TableBody,
1031
+ rule,
1032
+ );
1033
+ }
1034
+ }
1035
+ records.push(record);
1036
+ }
1037
+ if (records.length > 0) {
1038
+ const landed = this.write(instance, collect.as.name, records as Json[keyof Json]);
1039
+ if (!landed) {
1040
+ this.diagnostics.pushFidelity(
1041
+ { 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` },
1042
+ treePath,
1043
+ Band.BeforeChildren,
1044
+ Phase.TableBody,
1045
+ rule,
1046
+ );
1047
+ }
1048
+ }
1049
+ return;
1050
+ }
704
1051
  const out: Json[] = [];
705
1052
  const flat: string[] = [];
706
1053
  const scalarField = Object.values(collect.item ?? {}).find((f) => isCollect(f) && f.scalar) as Collect | undefined;
@@ -772,24 +1119,156 @@ class SurfaceEmitter {
772
1119
  * is either an explicit drop or an unrecognized sub — both warned, never
773
1120
  * silently ignored — followed by the composition casualty for the compound.
774
1121
  */
1122
+ /**
1123
+ * T4: one slot route — the ordered children of exactly one descendant
1124
+ * instance of the named sub become instances, and the slot carries the
1125
+ * reference (multi wraps in the profile's wrap component, exactly like
1126
+ * T3's joined-children). The region's child list goes through the SAME
1127
+ * rewriting as any parent's (this plan's dispositions apply to nested
1128
+ * subs), with subs claimed by sibling routes skipped — their consumption
1129
+ * is their own route's ledger entry. Zero regions leave the destination
1130
+ * absent (gate A3 arbitrates); several refuse: a slot names one region.
1131
+ */
1132
+ private applySlotRoute(
1133
+ node: SurfaceNode,
1134
+ model: SurfaceModel,
1135
+ route: Route,
1136
+ rule: number,
1137
+ instance: Json,
1138
+ path: string,
1139
+ treePath: readonly number[],
1140
+ ): void {
1141
+ const sel = route.from[0];
1142
+ if (sel.kind !== "sub-children") return;
1143
+ const region = sel.subs[0];
1144
+
1145
+ const found: Array<{ n: SurfaceNode; nPath: string }> = [];
1146
+ const locate = (n: SurfaceNode, nPath: string): void => {
1147
+ for (const c of collectChildren(n)) {
1148
+ if (c.node.component === region) found.push({ n: c.node, nPath: `${nPath}${c.suffix}` });
1149
+ locate(c.node, `${nPath}${c.suffix}`);
1150
+ }
1151
+ };
1152
+ locate(node, path);
1153
+
1154
+ if (found.length === 0) return; // absent region: the destination stays absent and A3 arbitrates
1155
+ if (found.length > 1) {
1156
+ throw new EmitSurfaceError(
1157
+ `slot route '${route.origin}': ${found.length} instances of '${region}' in this '${node.component}'; ` +
1158
+ `a slot names ONE region — exactly one may appear`,
1159
+ path,
1160
+ );
1161
+ }
1162
+
1163
+ const claimed = new Set<string>();
1164
+ for (const r of model.routes) {
1165
+ if (r === route) continue;
1166
+ for (const s of r.from) if ("subs" in s) for (const id of s.subs as string[]) claimed.add(id);
1167
+ }
1168
+ for (const c of model.collects) for (const id of [...c.of, ...(c.join?.with ?? [])]) claimed.add(id);
1169
+
1170
+ const src = found[0];
1171
+ const spliced = this.rewriteChildren(src.n, model, src.nPath, treePath, claimed);
1172
+ if (spliced.length === 0) return; // an empty region carries nothing; absent, A3 arbitrates
1173
+ const ids = spliced.map((k, ki) =>
1174
+ "textVariant" in k
1175
+ ? this.emitTextPrimitive(
1176
+ k.text,
1177
+ `${slug(region)}_${slug(k.textVariant)}`,
1178
+ src.nPath,
1179
+ [...treePath, Band.BeforeChildren, rule, ki],
1180
+ Phase.SubContentFlatten,
1181
+ rule,
1182
+ k.textVariant,
1183
+ )
1184
+ : this.emitNode(k.node, `${src.nPath}${k.suffix}[${ki}]`, [...treePath, Band.BeforeChildren, rule, ki], k.donations ?? []),
1185
+ );
1186
+ const ref = ids.length === 1 ? ids[0] : this.wrapInColumn(ids, slug(region), src.nPath, treePath);
1187
+ const landed = this.write(instance, route.to.name, ref);
1188
+ this.diagnostics.pushFidelity(
1189
+ {
1190
+ source: `${src.nPath} (${region} children)`,
1191
+ destination: `${route.to.name} @ ${path} (${node.component})`,
1192
+ origin: route.origin,
1193
+ kind: landed ? "moved" : "dropped",
1194
+ class: landed ? "maps-cleanly" : "lossy",
1195
+ note: landed
1196
+ ? `region '${region}' emitted as instances; the slot carries the reference`
1197
+ : `'${route.to.name}' already written; the region's reference did not land`,
1198
+ },
1199
+ treePath,
1200
+ Band.BeforeChildren,
1201
+ Phase.SubContentFlatten,
1202
+ rule,
1203
+ );
1204
+ }
1205
+
1206
+ /**
1207
+ * Fail-closed closure for a slot-routed compound: every DIRECT child must
1208
+ * be a claimed region, a route-consumed sub, a collected family, or carry
1209
+ * a disposition — an unclaimed child is structural content with no
1210
+ * destination, and approximating it silently is exactly what this engine
1211
+ * refuses to do.
1212
+ */
1213
+ private closeSlots(
1214
+ node: SurfaceNode,
1215
+ model: SurfaceModel,
1216
+ path: string,
1217
+ treePath: readonly number[],
1218
+ ): void {
1219
+ const claimed = new Set<string>();
1220
+ for (const r of model.routes) for (const s of r.from) if ("subs" in s) for (const id of s.subs as string[]) claimed.add(id);
1221
+ for (const c of model.collects) for (const id of [...c.of, ...(c.join?.with ?? [])]) claimed.add(id);
1222
+
1223
+ for (const child of collectChildren(node)) {
1224
+ const c = child.node.component;
1225
+ if (claimed.has(c) || c in model.subIdentity) continue;
1226
+ const reason = model.drops[c];
1227
+ if (reason !== undefined) {
1228
+ const childPath = `${path}${child.suffix}`;
1229
+ this.diagnostics.push(
1230
+ { code: "surface-sub-dropped", message: `${childPath}: '${c}' dropped: ${reason}.` },
1231
+ treePath,
1232
+ Band.BeforeChildren,
1233
+ Phase.SubContentFlatten,
1234
+ );
1235
+ this.diagnostics.pushFidelity(
1236
+ { source: `${childPath} (${c})`, destination: "(discarded)", origin: `drops.${c}`, kind: "dropped", class: "lossy", note: reason },
1237
+ treePath,
1238
+ Band.BeforeChildren,
1239
+ Phase.SubContentFlatten,
1240
+ );
1241
+ continue;
1242
+ }
1243
+ throw new EmitSurfaceError(
1244
+ `'${c}' is a direct child of slot-routed compound '${node.component}' with no destination — ` +
1245
+ `every region must be claimed by a route, collected, or carry a disposition`,
1246
+ `${path}${child.suffix}`,
1247
+ );
1248
+ }
1249
+ }
1250
+
775
1251
  private closeCollects(
776
1252
  node: SurfaceNode,
777
1253
  model: SurfaceModel,
778
1254
  path: string,
779
1255
  treePath: readonly number[],
780
1256
  ): void {
781
- const claimedByCollect = new Set(model.collects.flatMap((c) => c.of));
1257
+ const claimedByCollect = new Set(model.collects.flatMap((c) => [...c.of, ...(c.join?.with ?? [])]));
782
1258
  for (const child of collectChildren(node)) {
783
1259
  const c = child.node.component;
784
1260
  if (claimedByCollect.has(c) || this.claimedByRoute(model, c)) continue;
785
1261
  const childPath = `${path}${child.suffix}`;
786
1262
  const reason = model.drops[c];
1263
+ const itemMode = model.collects.some((col) => col.fields);
787
1264
  this.diagnostics.push(
788
1265
  {
789
1266
  code: "surface-sub-dropped",
790
1267
  message: reason
791
1268
  ? `${childPath}: '${c}' dropped: ${reason}.`
792
- : `${childPath}: '${c}' has no slot in the synthesized table shape; dropped.`,
1269
+ : itemMode
1270
+ ? `${childPath}: '${c}' is not a collected item and has no disposition; dropped (sibling pairing is T3's declared join).`
1271
+ : `${childPath}: '${c}' has no slot in the synthesized table shape; dropped.`,
793
1272
  },
794
1273
  treePath,
795
1274
  Band.BeforeChildren,
@@ -810,10 +1289,13 @@ class SurfaceEmitter {
810
1289
  );
811
1290
  }
812
1291
 
1292
+ const itemsOnly = model.collects.every((col) => col.fields);
813
1293
  this.diagnostics.push(
814
1294
  {
815
1295
  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).`,
1296
+ message: itemsOnly
1297
+ ? `${path}: compound '${node.component}' subtree consumed into collected item records (uncollected content is not carried).`
1298
+ : `${path}: compound '${node.component}' subtree consumed into the synthesized table shape (documented casualty; cell content beyond text is not carried).`,
817
1299
  },
818
1300
  treePath,
819
1301
  Band.BeforeChildren,
@@ -919,10 +1401,15 @@ class SurfaceEmitter {
919
1401
  treePath: readonly number[],
920
1402
  ): void {
921
1403
  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
1404
+ const raw = collectChildren(node);
1405
+ const anyTransparentChild = raw.some((c) => {
1406
+ const plan = this.byDspackId.get(c.node.component);
1407
+ return plan !== undefined && surfaceModelOf(plan).transparent;
1408
+ });
1409
+ const childNodes: RewrittenChild[] =
1410
+ Object.keys(model.subIdentity).length > 0 || Object.keys(model.drops).length > 0 || anyTransparentChild
924
1411
  ? this.rewriteChildren(node, model, path, treePath)
925
- : collectChildren(node).map((c) => ({ node: c.node, suffix: c.suffix }));
1412
+ : raw.map((c) => ({ node: c.node, suffix: c.suffix }));
926
1413
  if (childNodes.length === 0) return;
927
1414
 
928
1415
  const childIds = childNodes.map((child, i) =>
@@ -936,7 +1423,7 @@ class SurfaceEmitter {
936
1423
  0,
937
1424
  child.textVariant,
938
1425
  )
939
- : this.emitNode(child.node, `${path}${child.suffix}[${i}]`, [...treePath, Band.Children, i]),
1426
+ : this.emitNode(child.node, `${path}${child.suffix}[${i}]`, [...treePath, Band.Children, i], child.donations ?? []),
940
1427
  );
941
1428
 
942
1429
  if (!childRoute) {
@@ -954,56 +1441,170 @@ class SurfaceEmitter {
954
1441
  }
955
1442
 
956
1443
  /**
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.
1444
+ * T1, the general root-transparency rule (ratified): a transparent node is
1445
+ * a semantic statement that the dspack node has no emitted identity — valid
1446
+ * at the root too. The root dissolves through the ORDINARY machinery
1447
+ * (presented as a child of a synthetic host, so boundary donations, sub
1448
+ * dispositions, and every refusal apply), then:
1449
+ *
1450
+ * - exactly one surviving descendant -> it IS the root (id "root",
1451
+ * components[0]) — the existing root invariant, preserved
1452
+ * deterministically;
1453
+ * - several survivors -> they wrap in the synthesized
1454
+ * wrap component, which is structural TRANSPORT, not a replacement
1455
+ * identity for the transparent component;
1456
+ * - nothing survives -> refuse. Fabricating content for
1457
+ * an empty root would be synthesis of meaning, not structure.
1458
+ *
1459
+ * No component is special-cased by name.
1460
+ */
1461
+ emitTransparentRoot(root: SurfaceNode, path: string): string {
1462
+ const { wrapComponent, wrapChildrenProp } = this.profile.surfaceSynthesis;
1463
+
1464
+ // Present the root AS A CHILD of a synthetic host, so the ordinary
1465
+ // rewriting machinery performs the whole dissolution — the plan-transparent
1466
+ // ledger entry, the boundary's own donations (transparentDonate), sub
1467
+ // dispositions, and every refusal — with no root-only special case.
1468
+ const host = { component: "__root_host__", children: [root] } as unknown as SurfaceNode;
1469
+ const spliced = this.rewriteChildren(host, emptySurfaceModel(), path, []);
1470
+
1471
+ if (spliced.length === 0) {
1472
+ throw new EmitSurfaceError(
1473
+ `transparent root '${root.component}' dissolved to nothing — no descendant survives to become the root, and fabricating one is refused`,
1474
+ path,
1475
+ );
1476
+ }
1477
+
1478
+ if (spliced.length === 1) {
1479
+ const only = spliced[0];
1480
+ this.diagnostics.pushFidelity(
1481
+ {
1482
+ source: `${path} (${root.component})`,
1483
+ destination: "root",
1484
+ origin: `plan.${root.component}`,
1485
+ kind: "moved",
1486
+ class: "maps-cleanly",
1487
+ note: "transparent root: its single surviving descendant is preserved as the root instance",
1488
+ },
1489
+ [],
1490
+ Band.BeforeChildren,
1491
+ Phase.ChildRewrite,
1492
+ );
1493
+ return "textVariant" in only
1494
+ ? this.emitTextPrimitive(only.text, "root", path, [Band.Children, 0], Phase.TextChild, 0, only.textVariant)
1495
+ : this.emitNode(only.node, path, [Band.Children, 0], only.donations ?? []);
1496
+ }
1497
+
1498
+ const id = this.allocateId("root", path, { treePath: [], band: Band.BeforeChildren, phase: Phase.IdAllocation, rule: 0 });
1499
+ const index = this.components.length;
1500
+ this.components.push({});
1501
+ const childIds = spliced.map((child, i) =>
1502
+ "textVariant" in child
1503
+ ? this.emitTextPrimitive(child.text, `root_${slug(child.textVariant)}`, path, [Band.Children, i], Phase.TextChild, 0, child.textVariant)
1504
+ : this.emitNode(child.node, `${path}.children[${i}]`, [Band.Children, i], child.donations ?? []),
1505
+ );
1506
+
1507
+ this.components[index] = { id, component: wrapComponent, [wrapChildrenProp]: childIds };
1508
+ this.diagnostics.push(
1509
+ {
1510
+ code: "surface-synthesized-wrap",
1511
+ message: `${path}: transparent root '${root.component}' dissolved; ${childIds.length} risen child(ren) wrapped in a synthesized ${wrapComponent} ('root').`,
1512
+ },
1513
+ [],
1514
+ Band.AfterChildren,
1515
+ Phase.Wrap,
1516
+ );
1517
+ this.diagnostics.pushFidelity(
1518
+ { 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" },
1519
+ [],
1520
+ Band.AfterChildren,
1521
+ Phase.Wrap,
1522
+ );
1523
+ return id;
1524
+ }
1525
+
1526
+ /**
1527
+ * Identity applied to the child list: sub dispositions from the surrounding
1528
+ * model, T1 plan-level transparency for child COMPONENTS (dissolved under
1529
+ * their own model — the `ctx` switch), and donation boundaries. A
1530
+ * dissolving boundary that carries donations harvests them from its own
1531
+ * subtree, consumes the donor subs, and attaches the pending writes to its
1532
+ * single eligible control — refusing on zero or several candidates. The
1533
+ * pending writes ride the returned child list explicitly and apply inside
1534
+ * the control's own construction: no committed instance is ever mutated.
960
1535
  */
961
1536
  private rewriteChildren(
962
1537
  node: SurfaceNode,
963
1538
  model: SurfaceModel,
964
1539
  path: string,
965
1540
  treePath: readonly number[],
966
- ): Array<{ node: SurfaceNode; suffix: string } | { text: string; textVariant: string }> {
967
- const out: Array<{ node: SurfaceNode; suffix: string } | { text: string; textVariant: string }> = [];
968
- const visit = (n: SurfaceNode, suffix: string): void => {
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];
1541
+ /**
1542
+ * T4: subs claimed by SIBLING routes of the enclosing compound (text
1543
+ * harvests, other slot sources). A claimed sub is skipped silently at any
1544
+ * dissolution depth — its consumption is ledgered by its own route, and
1545
+ * recording it twice would say it was dropped when it was moved.
1546
+ */
1547
+ claimedSubs: ReadonlySet<string> = new Set(),
1548
+ ): RewrittenChild[] {
1549
+ const push = (w: Warning) => this.diagnostics.push(w, treePath, Band.BeforeChildren, Phase.ChildRewrite);
1550
+ const ledger = (f: SurfaceFidelityEntry) =>
1551
+ this.diagnostics.pushFidelity(f, treePath, Band.BeforeChildren, Phase.ChildRewrite);
1552
+
1553
+ // Layered dissolution contexts (emit#37, ratified 2026-08-07). A
1554
+ // dissolving boundary shadows the enclosing compound contexts where they
1555
+ // overlap, but does not erase them: a component's disposition is resolved
1556
+ // against the stack of enclosing models, innermost first, so an outer
1557
+ // compound's sub (e.g. `card-footer`) keeps its disposition when it
1558
+ // appears inside a dissolved inner boundary (e.g. a transparent `field`).
1559
+ // A single-frame stack resolves identically to the pre-amendment single
1560
+ // `ctx` — the byte pins prove it.
1561
+ const resolve = <T>(stack: readonly SurfaceModel[], pick: (m: SurfaceModel) => T | undefined): T | undefined => {
1562
+ for (const m of stack) {
1563
+ const v = pick(m);
1564
+ if (v !== undefined) return v;
1565
+ }
1566
+ return undefined;
1567
+ };
1568
+
1569
+ const visit = (n: SurfaceNode, suffix: string, stack: readonly SurfaceModel[], out: RewrittenChild[]): void => {
1570
+ if (claimedSubs.has(n.component)) return;
1571
+ // An authored drop is warn-and-discard, exactly like the collect path —
1572
+ // resolved through the ancestor chain (inner shadows outer).
1573
+ const dropReason = resolve(stack, (m) => m.drops[n.component]);
973
1574
  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
- );
1575
+ push({ code: "surface-sub-dropped", message: `${path}: '${n.component}' dropped: ${dropReason}.` });
1576
+ ledger({ source: `${path} (${n.component})`, destination: "(discarded)", origin: `drops.${n.component}`, kind: "dropped", class: "lossy", note: dropReason });
986
1577
  return;
987
1578
  }
988
- const identity = model.subIdentity[n.component];
1579
+
1580
+ // T1: a child COMPONENT whose plan is transparent dissolves here — its
1581
+ // subtree governed by ITS OWN model PUSHED ONTO the enclosing stack, so
1582
+ // the boundary shadows but does not erase the outer contexts.
1583
+ const childPlan = this.byDspackId.get(n.component);
1584
+ const childModel = childPlan ? surfaceModelOf(childPlan) : undefined;
1585
+ if (childModel?.transparent) {
1586
+ ledger({
1587
+ source: `${path} (${n.component})`,
1588
+ destination: "(children rise in place)",
1589
+ origin: `plan.${n.component}`,
1590
+ kind: "flattened",
1591
+ class: "lossy",
1592
+ note: "transparent identity: the component dissolves; its own structure is not carried",
1593
+ });
1594
+ dissolve(n, suffix, [childModel, ...stack], childModel.transparentDonate, `plan.${n.component}`, out);
1595
+ return;
1596
+ }
1597
+
1598
+ const identity = resolve(stack, (m) => m.subIdentity[n.component]);
989
1599
  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
- );
1005
- if (n.text !== undefined && n.text !== "") out.push({ text: n.text, textVariant: "body" });
1006
- for (const child of collectChildren(n)) visit(child.node, child.suffix);
1600
+ push({
1601
+ code: "surface-sub-flattened",
1602
+ message: `${path}: grouping sub-component '${n.component}' spliced inline (subFlatten strategy); its own structure is not carried.`,
1603
+ });
1604
+ 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" });
1605
+ // A grouping sub has no model of its own; its children continue under
1606
+ // the same enclosing stack that resolved it.
1607
+ dissolve(n, suffix, stack, identity.donate ?? [], `subs.${n.component}`, out);
1007
1608
  return;
1008
1609
  }
1009
1610
  if (identity?.kind === "as-text") {
@@ -1013,35 +1614,109 @@ class SurfaceEmitter {
1013
1614
  // Structure destroyed, text preserved — the same loss the cell
1014
1615
  // flatten records, and it must class the same way.
1015
1616
  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
- );
1617
+ 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" });
1022
1618
  }
1023
1619
  if (text !== "") {
1024
1620
  out.push({ text, textVariant: identity.variant });
1025
1621
  } else {
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
- );
1622
+ push({ code: "surface-sub-dropped", message: `${path}: '${n.component}' carried no text to synthesize; dropped.` });
1623
+ ledger({ source: `${path} (${n.component})`, destination: "(discarded)", origin: `subs.${n.component}`, kind: "dropped", class: "lossy", note: "re-identified as text but carried none" });
1038
1624
  }
1039
1625
  return;
1040
1626
  }
1041
1627
  out.push({ node: n, suffix });
1042
1628
  };
1043
- for (const child of collectChildren(node)) visit(child.node, child.suffix);
1044
- return out;
1629
+
1630
+ /**
1631
+ * Dissolves one boundary node under `innerCtx`. When the boundary carries
1632
+ * donations: harvest first-wins per donation, consume every donor sub,
1633
+ * splice the rest, then bind the pending writes to the single eligible
1634
+ * control among the spliced replacements — zero or several refuse.
1635
+ * Eligibility is declared, never guessed: a control's plan must declare
1636
+ * every donated destination.
1637
+ */
1638
+ const dissolve = (
1639
+ n: SurfaceNode,
1640
+ suffix: string,
1641
+ innerStack: readonly SurfaceModel[],
1642
+ donations: readonly Donation[],
1643
+ originLabel: string,
1644
+ out: RewrittenChild[],
1645
+ ): void => {
1646
+ const consumedDonorSubs = new Set<string>();
1647
+ const pending: PendingDonation[] = [];
1648
+ for (const d of donations) {
1649
+ let value: string | undefined;
1650
+ let donorComponent = n.component;
1651
+ if (d.from.kind === "self-text") {
1652
+ value = n.text;
1653
+ } else if (d.from.kind === "sub-text") {
1654
+ for (const sub of d.from.subs) consumedDonorSubs.add(sub);
1655
+ const walk = (m: SurfaceNode): void => {
1656
+ if (value === undefined && d.from.kind === "sub-text" && d.from.subs.includes(m.component) && m.text !== undefined) {
1657
+ value = m.text;
1658
+ donorComponent = m.component;
1659
+ }
1660
+ for (const c of collectChildren(m)) walk(c.node);
1661
+ };
1662
+ walk(n);
1663
+ }
1664
+ if (value !== undefined) {
1665
+ pending.push({ prop: d.to.name, value, origin: d.origin, donorPath: `${path}${suffix}`, donorComponent });
1666
+ }
1667
+ // Nothing to donate is not an error: the destination stays absent —
1668
+ // refused at emission by the final catalog-validity guard when it is
1669
+ // required, arbitrated by gate A3 otherwise. Relocation, never
1670
+ // synthesis (the lift rule).
1671
+ }
1672
+
1673
+ // The boundary's own text rises as body text unless a self.text
1674
+ // donation claimed it (the plain transparent-sub behaviour otherwise).
1675
+ const selfDonated = donations.some((d) => d.from.kind === "self-text");
1676
+ const spliced: RewrittenChild[] = [];
1677
+ if (!selfDonated && n.text !== undefined && n.text !== "") spliced.push({ text: n.text, textVariant: "body" });
1678
+
1679
+ for (const child of collectChildren(n)) {
1680
+ if (consumedDonorSubs.has(child.node.component)) {
1681
+ const supplied = pending.some((q) => q.donorComponent === child.node.component && q.value === child.node.text);
1682
+ if (!supplied) {
1683
+ push({ code: "surface-sub-dropped", message: `${path}: '${child.node.component}' dropped: its text was not the donated value (first donor wins).` });
1684
+ 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)" });
1685
+ }
1686
+ continue;
1687
+ }
1688
+ visit(child.node, child.suffix, innerStack, spliced);
1689
+ }
1690
+
1691
+ if (pending.length > 0) {
1692
+ const controls = spliced.filter((entry): entry is { node: SurfaceNode; suffix: string; donations?: PendingDonation[] } => {
1693
+ if (!("node" in entry)) return false;
1694
+ const plan = this.byDspackId.get(entry.node.component);
1695
+ if (!plan || surfaceModelOf(plan).transparent) return false;
1696
+ const declared = new Set([
1697
+ ...Object.keys(plan.structural ?? {}),
1698
+ ...Object.values(plan.propMap ?? {}).map((pp) => pp.a2ui),
1699
+ ]);
1700
+ return pending.every((q) => declared.has(q.prop));
1701
+ });
1702
+ if (controls.length !== 1) {
1703
+ const names = controls.map((c) => `'${c.node.component}'`).join(", ");
1704
+ throw new EmitSurfaceError(
1705
+ `donation boundary '${n.component}' (${originLabel}) requires exactly one eligible control declaring ` +
1706
+ `[${pending.map((q) => q.prop).join(", ")}]; found ${controls.length}${controls.length ? ` (${names})` : ""} — ` +
1707
+ `a donation relocates onto one control, never broadcasts`,
1708
+ `${path}${suffix}`,
1709
+ );
1710
+ }
1711
+ controls[0].donations = [...(controls[0].donations ?? []), ...pending];
1712
+ }
1713
+
1714
+ out.push(...spliced);
1715
+ };
1716
+
1717
+ const rootOut: RewrittenChild[] = [];
1718
+ for (const child of collectChildren(node)) visit(child.node, child.suffix, [model], rootOut);
1719
+ return rootOut;
1045
1720
  }
1046
1721
 
1047
1722
  private emitTextPrimitive(