@aestheticfunction/dspack-emit 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,18 @@ 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");
110
120
 
111
121
  const surfaceId = options.surfaceId ?? slug(surface.intent);
112
122
  const theme: Json = { agentDisplayName: `${doc.name} via dspack` };
@@ -144,6 +154,25 @@ export function slug(value: string): string {
144
154
  .replace(/^_+|_+$/g, "");
145
155
  return s || "surface";
146
156
  }
157
+ /**
158
+ * T1: one donation, resolved at its dissolving boundary and carried
159
+ * EXPLICITLY in the rewritten child list until the receiving control's own
160
+ * emission applies it as a first-wins pre-write. The committed instance of
161
+ * another node is never mutated; ordering cannot affect output because the
162
+ * write happens inside the control's own construction, in donation order.
163
+ */
164
+ interface PendingDonation {
165
+ prop: string;
166
+ value: string;
167
+ origin: string;
168
+ donorPath: string;
169
+ donorComponent: string;
170
+ }
171
+
172
+ type RewrittenChild =
173
+ | { node: SurfaceNode; suffix: string; donations?: PendingDonation[] }
174
+ | { text: string; textVariant: string };
175
+
147
176
  class SurfaceEmitter {
148
177
  readonly components: Json[] = [];
149
178
  readonly diagnostics = new Diagnostics();
@@ -161,7 +190,7 @@ class SurfaceEmitter {
161
190
  * desugar.ts; if any of them appears below, the compatibility boundary has
162
191
  * leaked (src/engine-boundary.test.ts fails on exactly that).
163
192
  */
164
- emitNode(node: SurfaceNode, path: string, treePath: readonly number[] = []): string {
193
+ emitNode(node: SurfaceNode, path: string, treePath: readonly number[] = [], donations: PendingDonation[] = []): string {
165
194
  const plan = this.byDspackId.get(node.component);
166
195
  if (!plan) {
167
196
  // A declared casualty refuses with its authored reason — the refusal is
@@ -212,6 +241,29 @@ class SurfaceEmitter {
212
241
  // the explicit phase model, never this loop's order.
213
242
  this.applyOperations(node, model, instance, id, path, treePath);
214
243
 
244
+ // T1 donations: contextual values a dissolved wrapper handed to this
245
+ // control, applied AFTER the control's own writes, first-wins — inherited
246
+ // context fills what the control left absent and never beats its own
247
+ // authored content. The ledger records exactly what happened either way.
248
+ for (const d of donations) {
249
+ const landed = this.write(instance, d.prop, d.value as Json[keyof Json]);
250
+ this.diagnostics.pushFidelity(
251
+ {
252
+ source: `${d.donorPath} (${d.donorComponent}.text)`,
253
+ destination: `${d.prop} @ ${path} (${node.component})`,
254
+ origin: d.origin,
255
+ kind: landed ? "donated" : "dropped",
256
+ class: landed ? "maps-cleanly" : "lossy",
257
+ note: landed
258
+ ? `donated by '${d.donorComponent}' to '${node.component}' — the dissolving boundary's single eligible control`
259
+ : `'${d.prop}' already written on '${node.component}'; the donated value did not land`,
260
+ },
261
+ treePath,
262
+ Band.BeforeChildren,
263
+ Phase.PropMap,
264
+ );
265
+ }
266
+
215
267
  if (!model.consumesSubtree) {
216
268
  this.emitChildren(node, model, instance, id, path, treePath);
217
269
  }
@@ -269,6 +321,10 @@ class SurfaceEmitter {
269
321
 
270
322
  for (const { route, rule } of model.routes.map((route, rule) => ({ route, rule }))) {
271
323
  if (route.order === WriteOrder.Consume || route.order === WriteOrder.Children) continue;
324
+ if (route.order === WriteOrder.Slot) {
325
+ steps.push({ order: route.order, run: () => this.applySlotRoute(node, model, route, rule, instance, path, treePath) });
326
+ continue;
327
+ }
272
328
  steps.push({ order: route.order, run: () => this.applyRoute(node, route, rule, instance, id, path, treePath) });
273
329
  }
274
330
  for (const [rule, collect] of model.collects.entries()) {
@@ -281,6 +337,9 @@ class SurfaceEmitter {
281
337
  if (model.collects.some((c) => c.as.kind !== "inline")) {
282
338
  steps.push({ order: WriteOrder.Collect + 1, run: () => this.closeCollects(node, model, path, treePath) });
283
339
  }
340
+ if (model.routes.some((r) => r.order === WriteOrder.Slot)) {
341
+ steps.push({ order: WriteOrder.Slot + 1, run: () => this.closeSlots(node, model, path, treePath) });
342
+ }
284
343
 
285
344
  steps.sort((a, b) => a.order - b.order);
286
345
  for (const step of steps) step.run();
@@ -701,6 +760,176 @@ class SurfaceEmitter {
701
760
  ): void {
702
761
  void model;
703
762
  if (collect.as.kind === "inline") return;
763
+
764
+ // T2 item-mode: each descendant matching `of` (document order) becomes
765
+ // one record whose fields resolve against THAT item's own node. Absent
766
+ // sources omit the field — gate A3 arbitrates required record shapes,
767
+ // never synthesis. Sibling content the collect does not claim follows
768
+ // the ordinary consumed-subtree accounting (closeCollects).
769
+ if (collect.fields) {
770
+ const itemLocal = (n: SurfaceNode, sel: Selector): Json[keyof Json] | undefined =>
771
+ sel.kind === "self-text" ? n.text : sel.kind === "self-id" ? n.id : sel.kind === "self-prop" ? (n.props?.[sel.prop] as Json[keyof Json] | undefined) : undefined;
772
+
773
+ // Gather left items and (when a join is declared) joined counterparts,
774
+ // both in document order.
775
+ const lefts: Array<{ n: SurfaceNode; nPath: string }> = [];
776
+ const rights: Array<{ n: SurfaceNode; nPath: string }> = [];
777
+ const gather = (n: SurfaceNode, nPath: string): void => {
778
+ if (collect.of.includes(n.component)) {
779
+ lefts.push({ n, nPath });
780
+ return; // an item's subtree is the item's; nested items do not re-match
781
+ }
782
+ if (collect.join?.with.includes(n.component)) {
783
+ rights.push({ n, nPath });
784
+ return;
785
+ }
786
+ collectChildren(n).forEach((c, i) => gather(c.node, `${nPath}${c.suffix}[${i}]`));
787
+ };
788
+ collectChildren(node).forEach((c, i) => gather(c.node, `${path}${c.suffix}[${i}]`));
789
+
790
+ // T3: the declared key join. Every edge refuses — the profile names
791
+ // the relation, the emitter never infers one.
792
+ const counterparts = new Map<string, { n: SurfaceNode; nPath: string }>();
793
+ if (collect.join) {
794
+ const j = collect.join;
795
+ const seenLeft = new Map<string, string>();
796
+ for (const item of lefts) {
797
+ const key = itemLocal(item.n, j.leftKey);
798
+ if (typeof key !== "string" || key === "") {
799
+ throw new EmitSurfaceError(
800
+ `join '${j.origin}': item '${item.n.component}' carries no key (${describeSelector(j.leftKey)}); a keyless item cannot participate in a declared join`,
801
+ item.nPath,
802
+ );
803
+ }
804
+ const prior = seenLeft.get(key);
805
+ if (prior !== undefined) {
806
+ throw new EmitSurfaceError(
807
+ `join '${j.origin}': duplicate left key '${key}' (also at ${prior}); join keys must be unique on each side`,
808
+ item.nPath,
809
+ );
810
+ }
811
+ seenLeft.set(key, item.nPath);
812
+ }
813
+ for (const cp of rights) {
814
+ const key = itemLocal(cp.n, j.rightKey);
815
+ if (typeof key !== "string" || key === "") {
816
+ throw new EmitSurfaceError(
817
+ `join '${j.origin}': counterpart '${cp.n.component}' carries no key (${describeSelector(j.rightKey)})`,
818
+ cp.nPath,
819
+ );
820
+ }
821
+ if (counterparts.has(key)) {
822
+ throw new EmitSurfaceError(
823
+ `join '${j.origin}': duplicate right key '${key}'; join keys must be unique on each side`,
824
+ cp.nPath,
825
+ );
826
+ }
827
+ if (!seenLeft.has(key)) {
828
+ throw new EmitSurfaceError(
829
+ `join '${j.origin}': counterpart '${cp.n.component}' key '${key}' matches no item; a dangling counterpart is a contradiction, not surplus`,
830
+ cp.nPath,
831
+ );
832
+ }
833
+ counterparts.set(key, cp);
834
+ }
835
+ }
836
+
837
+ const records: Json[] = [];
838
+ for (const item of lefts) {
839
+ const record: Json = {};
840
+ for (const [fieldName, sel] of Object.entries(collect.fields)) {
841
+ const value = itemLocal(item.n, sel);
842
+ if (value !== undefined) record[fieldName] = value;
843
+ }
844
+ this.diagnostics.pushFidelity(
845
+ {
846
+ source: `${item.nPath} (${item.n.component})`,
847
+ destination: collect.as.name,
848
+ origin: collect.origin,
849
+ kind: "moved",
850
+ class: "maps-cleanly",
851
+ note: `item record { ${Object.keys(record).join(", ")} } collected`,
852
+ },
853
+ treePath,
854
+ Band.BeforeChildren,
855
+ Phase.TableBody,
856
+ rule,
857
+ );
858
+
859
+ if (collect.join) {
860
+ const j = collect.join;
861
+ const key = itemLocal(item.n, j.leftKey) as string;
862
+ const cp = counterparts.get(key);
863
+ if (!cp && !j.optional) {
864
+ throw new EmitSurfaceError(
865
+ `join '${j.origin}': item '${item.n.component}' key '${key}' has no counterpart among [${j.with.join(", ")}]; exactly one is required (declare optional to relax to 0..1)`,
866
+ item.nPath,
867
+ );
868
+ }
869
+ if (cp) {
870
+ for (const [fieldName, jSel] of Object.entries(j.fields)) {
871
+ if ("kind" in jSel && jSel.kind === "joined-children") {
872
+ // The slot-valued field: the counterpart's children emit as
873
+ // instances; the record carries the reference. Repetition's
874
+ // ratified slot form — not T4 multi-slot routing. The child
875
+ // list goes through the SAME rewriting as any parent's
876
+ // (mirroring the transparent-root host pattern), so a
877
+ // transparent top-level child inside a joined panel
878
+ // dissolves instead of refusing as an unroutable instance.
879
+ const spliced = this.rewriteChildren(cp.n, emptySurfaceModel(), cp.nPath, treePath);
880
+ if (spliced.length === 0) continue;
881
+ const ids = spliced.map((k, ki) =>
882
+ "textVariant" in k
883
+ ? this.emitTextPrimitive(
884
+ k.text,
885
+ `${slug(key)}_${slug(k.textVariant)}`,
886
+ cp.nPath,
887
+ [...treePath, Band.Children, records.length, ki],
888
+ Phase.TextChild,
889
+ 0,
890
+ k.textVariant,
891
+ )
892
+ : this.emitNode(k.node, `${cp.nPath}${k.suffix}[${ki}]`, [...treePath, Band.Children, records.length], k.donations ?? []),
893
+ );
894
+ record[fieldName] =
895
+ ids.length === 1 ? ids[0] : this.wrapInColumn(ids, `${slug(key)}`, cp.nPath, treePath);
896
+ } else {
897
+ const value = itemLocal(cp.n, jSel as Selector);
898
+ if (value !== undefined) record[fieldName] = value;
899
+ }
900
+ }
901
+ this.diagnostics.pushFidelity(
902
+ {
903
+ source: `${cp.nPath} (${cp.n.component})`,
904
+ destination: `${collect.as.name} @ item '${key}'`,
905
+ origin: j.origin,
906
+ kind: "joined",
907
+ class: "maps-cleanly",
908
+ note: `counterpart joined on key '${key}' -> fields { ${Object.keys(j.fields).join(", ")} }`,
909
+ },
910
+ treePath,
911
+ Band.BeforeChildren,
912
+ Phase.TableBody,
913
+ rule,
914
+ );
915
+ }
916
+ }
917
+ records.push(record);
918
+ }
919
+ if (records.length > 0) {
920
+ const landed = this.write(instance, collect.as.name, records as Json[keyof Json]);
921
+ if (!landed) {
922
+ this.diagnostics.pushFidelity(
923
+ { source: `${path} (${collect.of.join("|")} items)`, destination: "(discarded)", origin: collect.origin, kind: "dropped", class: "lossy", note: `'${collect.as.name}' was already written by an earlier phase; the collected records did not land` },
924
+ treePath,
925
+ Band.BeforeChildren,
926
+ Phase.TableBody,
927
+ rule,
928
+ );
929
+ }
930
+ }
931
+ return;
932
+ }
704
933
  const out: Json[] = [];
705
934
  const flat: string[] = [];
706
935
  const scalarField = Object.values(collect.item ?? {}).find((f) => isCollect(f) && f.scalar) as Collect | undefined;
@@ -772,24 +1001,156 @@ class SurfaceEmitter {
772
1001
  * is either an explicit drop or an unrecognized sub — both warned, never
773
1002
  * silently ignored — followed by the composition casualty for the compound.
774
1003
  */
1004
+ /**
1005
+ * T4: one slot route — the ordered children of exactly one descendant
1006
+ * instance of the named sub become instances, and the slot carries the
1007
+ * reference (multi wraps in the profile's wrap component, exactly like
1008
+ * T3's joined-children). The region's child list goes through the SAME
1009
+ * rewriting as any parent's (this plan's dispositions apply to nested
1010
+ * subs), with subs claimed by sibling routes skipped — their consumption
1011
+ * is their own route's ledger entry. Zero regions leave the destination
1012
+ * absent (gate A3 arbitrates); several refuse: a slot names one region.
1013
+ */
1014
+ private applySlotRoute(
1015
+ node: SurfaceNode,
1016
+ model: SurfaceModel,
1017
+ route: Route,
1018
+ rule: number,
1019
+ instance: Json,
1020
+ path: string,
1021
+ treePath: readonly number[],
1022
+ ): void {
1023
+ const sel = route.from[0];
1024
+ if (sel.kind !== "sub-children") return;
1025
+ const region = sel.subs[0];
1026
+
1027
+ const found: Array<{ n: SurfaceNode; nPath: string }> = [];
1028
+ const locate = (n: SurfaceNode, nPath: string): void => {
1029
+ for (const c of collectChildren(n)) {
1030
+ if (c.node.component === region) found.push({ n: c.node, nPath: `${nPath}${c.suffix}` });
1031
+ locate(c.node, `${nPath}${c.suffix}`);
1032
+ }
1033
+ };
1034
+ locate(node, path);
1035
+
1036
+ if (found.length === 0) return; // absent region: the destination stays absent and A3 arbitrates
1037
+ if (found.length > 1) {
1038
+ throw new EmitSurfaceError(
1039
+ `slot route '${route.origin}': ${found.length} instances of '${region}' in this '${node.component}'; ` +
1040
+ `a slot names ONE region — exactly one may appear`,
1041
+ path,
1042
+ );
1043
+ }
1044
+
1045
+ const claimed = new Set<string>();
1046
+ for (const r of model.routes) {
1047
+ if (r === route) continue;
1048
+ for (const s of r.from) if ("subs" in s) for (const id of s.subs as string[]) claimed.add(id);
1049
+ }
1050
+ for (const c of model.collects) for (const id of [...c.of, ...(c.join?.with ?? [])]) claimed.add(id);
1051
+
1052
+ const src = found[0];
1053
+ const spliced = this.rewriteChildren(src.n, model, src.nPath, treePath, claimed);
1054
+ if (spliced.length === 0) return; // an empty region carries nothing; absent, A3 arbitrates
1055
+ const ids = spliced.map((k, ki) =>
1056
+ "textVariant" in k
1057
+ ? this.emitTextPrimitive(
1058
+ k.text,
1059
+ `${slug(region)}_${slug(k.textVariant)}`,
1060
+ src.nPath,
1061
+ [...treePath, Band.BeforeChildren, rule, ki],
1062
+ Phase.SubContentFlatten,
1063
+ rule,
1064
+ k.textVariant,
1065
+ )
1066
+ : this.emitNode(k.node, `${src.nPath}${k.suffix}[${ki}]`, [...treePath, Band.BeforeChildren, rule, ki], k.donations ?? []),
1067
+ );
1068
+ const ref = ids.length === 1 ? ids[0] : this.wrapInColumn(ids, slug(region), src.nPath, treePath);
1069
+ const landed = this.write(instance, route.to.name, ref);
1070
+ this.diagnostics.pushFidelity(
1071
+ {
1072
+ source: `${src.nPath} (${region} children)`,
1073
+ destination: `${route.to.name} @ ${path} (${node.component})`,
1074
+ origin: route.origin,
1075
+ kind: landed ? "moved" : "dropped",
1076
+ class: landed ? "maps-cleanly" : "lossy",
1077
+ note: landed
1078
+ ? `region '${region}' emitted as instances; the slot carries the reference`
1079
+ : `'${route.to.name}' already written; the region's reference did not land`,
1080
+ },
1081
+ treePath,
1082
+ Band.BeforeChildren,
1083
+ Phase.SubContentFlatten,
1084
+ rule,
1085
+ );
1086
+ }
1087
+
1088
+ /**
1089
+ * Fail-closed closure for a slot-routed compound: every DIRECT child must
1090
+ * be a claimed region, a route-consumed sub, a collected family, or carry
1091
+ * a disposition — an unclaimed child is structural content with no
1092
+ * destination, and approximating it silently is exactly what this engine
1093
+ * refuses to do.
1094
+ */
1095
+ private closeSlots(
1096
+ node: SurfaceNode,
1097
+ model: SurfaceModel,
1098
+ path: string,
1099
+ treePath: readonly number[],
1100
+ ): void {
1101
+ const claimed = new Set<string>();
1102
+ for (const r of model.routes) for (const s of r.from) if ("subs" in s) for (const id of s.subs as string[]) claimed.add(id);
1103
+ for (const c of model.collects) for (const id of [...c.of, ...(c.join?.with ?? [])]) claimed.add(id);
1104
+
1105
+ for (const child of collectChildren(node)) {
1106
+ const c = child.node.component;
1107
+ if (claimed.has(c) || c in model.subIdentity) continue;
1108
+ const reason = model.drops[c];
1109
+ if (reason !== undefined) {
1110
+ const childPath = `${path}${child.suffix}`;
1111
+ this.diagnostics.push(
1112
+ { code: "surface-sub-dropped", message: `${childPath}: '${c}' dropped: ${reason}.` },
1113
+ treePath,
1114
+ Band.BeforeChildren,
1115
+ Phase.SubContentFlatten,
1116
+ );
1117
+ this.diagnostics.pushFidelity(
1118
+ { source: `${childPath} (${c})`, destination: "(discarded)", origin: `drops.${c}`, kind: "dropped", class: "lossy", note: reason },
1119
+ treePath,
1120
+ Band.BeforeChildren,
1121
+ Phase.SubContentFlatten,
1122
+ );
1123
+ continue;
1124
+ }
1125
+ throw new EmitSurfaceError(
1126
+ `'${c}' is a direct child of slot-routed compound '${node.component}' with no destination — ` +
1127
+ `every region must be claimed by a route, collected, or carry a disposition`,
1128
+ `${path}${child.suffix}`,
1129
+ );
1130
+ }
1131
+ }
1132
+
775
1133
  private closeCollects(
776
1134
  node: SurfaceNode,
777
1135
  model: SurfaceModel,
778
1136
  path: string,
779
1137
  treePath: readonly number[],
780
1138
  ): void {
781
- const claimedByCollect = new Set(model.collects.flatMap((c) => c.of));
1139
+ const claimedByCollect = new Set(model.collects.flatMap((c) => [...c.of, ...(c.join?.with ?? [])]));
782
1140
  for (const child of collectChildren(node)) {
783
1141
  const c = child.node.component;
784
1142
  if (claimedByCollect.has(c) || this.claimedByRoute(model, c)) continue;
785
1143
  const childPath = `${path}${child.suffix}`;
786
1144
  const reason = model.drops[c];
1145
+ const itemMode = model.collects.some((col) => col.fields);
787
1146
  this.diagnostics.push(
788
1147
  {
789
1148
  code: "surface-sub-dropped",
790
1149
  message: reason
791
1150
  ? `${childPath}: '${c}' dropped: ${reason}.`
792
- : `${childPath}: '${c}' has no slot in the synthesized table shape; dropped.`,
1151
+ : itemMode
1152
+ ? `${childPath}: '${c}' is not a collected item and has no disposition; dropped (sibling pairing is T3's declared join).`
1153
+ : `${childPath}: '${c}' has no slot in the synthesized table shape; dropped.`,
793
1154
  },
794
1155
  treePath,
795
1156
  Band.BeforeChildren,
@@ -810,10 +1171,13 @@ class SurfaceEmitter {
810
1171
  );
811
1172
  }
812
1173
 
1174
+ const itemsOnly = model.collects.every((col) => col.fields);
813
1175
  this.diagnostics.push(
814
1176
  {
815
1177
  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).`,
1178
+ message: itemsOnly
1179
+ ? `${path}: compound '${node.component}' subtree consumed into collected item records (uncollected content is not carried).`
1180
+ : `${path}: compound '${node.component}' subtree consumed into the synthesized table shape (documented casualty; cell content beyond text is not carried).`,
817
1181
  },
818
1182
  treePath,
819
1183
  Band.BeforeChildren,
@@ -919,10 +1283,15 @@ class SurfaceEmitter {
919
1283
  treePath: readonly number[],
920
1284
  ): void {
921
1285
  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
1286
+ const raw = collectChildren(node);
1287
+ const anyTransparentChild = raw.some((c) => {
1288
+ const plan = this.byDspackId.get(c.node.component);
1289
+ return plan !== undefined && surfaceModelOf(plan).transparent;
1290
+ });
1291
+ const childNodes: RewrittenChild[] =
1292
+ Object.keys(model.subIdentity).length > 0 || Object.keys(model.drops).length > 0 || anyTransparentChild
924
1293
  ? this.rewriteChildren(node, model, path, treePath)
925
- : collectChildren(node).map((c) => ({ node: c.node, suffix: c.suffix }));
1294
+ : raw.map((c) => ({ node: c.node, suffix: c.suffix }));
926
1295
  if (childNodes.length === 0) return;
927
1296
 
928
1297
  const childIds = childNodes.map((child, i) =>
@@ -936,7 +1305,7 @@ class SurfaceEmitter {
936
1305
  0,
937
1306
  child.textVariant,
938
1307
  )
939
- : this.emitNode(child.node, `${path}${child.suffix}[${i}]`, [...treePath, Band.Children, i]),
1308
+ : this.emitNode(child.node, `${path}${child.suffix}[${i}]`, [...treePath, Band.Children, i], child.donations ?? []),
940
1309
  );
941
1310
 
942
1311
  if (!childRoute) {
@@ -954,56 +1323,170 @@ class SurfaceEmitter {
954
1323
  }
955
1324
 
956
1325
  /**
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.
1326
+ * T1, the general root-transparency rule (ratified): a transparent node is
1327
+ * a semantic statement that the dspack node has no emitted identity — valid
1328
+ * at the root too. The root dissolves through the ORDINARY machinery
1329
+ * (presented as a child of a synthetic host, so boundary donations, sub
1330
+ * dispositions, and every refusal apply), then:
1331
+ *
1332
+ * - exactly one surviving descendant -> it IS the root (id "root",
1333
+ * components[0]) — the existing root invariant, preserved
1334
+ * deterministically;
1335
+ * - several survivors -> they wrap in the synthesized
1336
+ * wrap component, which is structural TRANSPORT, not a replacement
1337
+ * identity for the transparent component;
1338
+ * - nothing survives -> refuse. Fabricating content for
1339
+ * an empty root would be synthesis of meaning, not structure.
1340
+ *
1341
+ * No component is special-cased by name.
1342
+ */
1343
+ emitTransparentRoot(root: SurfaceNode, path: string): string {
1344
+ const { wrapComponent, wrapChildrenProp } = this.profile.surfaceSynthesis;
1345
+
1346
+ // Present the root AS A CHILD of a synthetic host, so the ordinary
1347
+ // rewriting machinery performs the whole dissolution — the plan-transparent
1348
+ // ledger entry, the boundary's own donations (transparentDonate), sub
1349
+ // dispositions, and every refusal — with no root-only special case.
1350
+ const host = { component: "__root_host__", children: [root] } as unknown as SurfaceNode;
1351
+ const spliced = this.rewriteChildren(host, emptySurfaceModel(), path, []);
1352
+
1353
+ if (spliced.length === 0) {
1354
+ throw new EmitSurfaceError(
1355
+ `transparent root '${root.component}' dissolved to nothing — no descendant survives to become the root, and fabricating one is refused`,
1356
+ path,
1357
+ );
1358
+ }
1359
+
1360
+ if (spliced.length === 1) {
1361
+ const only = spliced[0];
1362
+ this.diagnostics.pushFidelity(
1363
+ {
1364
+ source: `${path} (${root.component})`,
1365
+ destination: "root",
1366
+ origin: `plan.${root.component}`,
1367
+ kind: "moved",
1368
+ class: "maps-cleanly",
1369
+ note: "transparent root: its single surviving descendant is preserved as the root instance",
1370
+ },
1371
+ [],
1372
+ Band.BeforeChildren,
1373
+ Phase.ChildRewrite,
1374
+ );
1375
+ return "textVariant" in only
1376
+ ? this.emitTextPrimitive(only.text, "root", path, [Band.Children, 0], Phase.TextChild, 0, only.textVariant)
1377
+ : this.emitNode(only.node, path, [Band.Children, 0], only.donations ?? []);
1378
+ }
1379
+
1380
+ const id = this.allocateId("root", path, { treePath: [], band: Band.BeforeChildren, phase: Phase.IdAllocation, rule: 0 });
1381
+ const index = this.components.length;
1382
+ this.components.push({});
1383
+ const childIds = spliced.map((child, i) =>
1384
+ "textVariant" in child
1385
+ ? this.emitTextPrimitive(child.text, `root_${slug(child.textVariant)}`, path, [Band.Children, i], Phase.TextChild, 0, child.textVariant)
1386
+ : this.emitNode(child.node, `${path}.children[${i}]`, [Band.Children, i], child.donations ?? []),
1387
+ );
1388
+
1389
+ this.components[index] = { id, component: wrapComponent, [wrapChildrenProp]: childIds };
1390
+ this.diagnostics.push(
1391
+ {
1392
+ code: "surface-synthesized-wrap",
1393
+ message: `${path}: transparent root '${root.component}' dissolved; ${childIds.length} risen child(ren) wrapped in a synthesized ${wrapComponent} ('root').`,
1394
+ },
1395
+ [],
1396
+ Band.AfterChildren,
1397
+ Phase.Wrap,
1398
+ );
1399
+ this.diagnostics.pushFidelity(
1400
+ { source: `${path} (${childIds.length} risen children)`, destination: `synthesized ${wrapComponent} 'root'`, origin: "surfaceSynthesis.wrapComponent", kind: "wrapped", class: "synthesis-defaults", note: "structural transport for several risen children — not a replacement identity for the transparent root" },
1401
+ [],
1402
+ Band.AfterChildren,
1403
+ Phase.Wrap,
1404
+ );
1405
+ return id;
1406
+ }
1407
+
1408
+ /**
1409
+ * Identity applied to the child list: sub dispositions from the surrounding
1410
+ * model, T1 plan-level transparency for child COMPONENTS (dissolved under
1411
+ * their own model — the `ctx` switch), and donation boundaries. A
1412
+ * dissolving boundary that carries donations harvests them from its own
1413
+ * subtree, consumes the donor subs, and attaches the pending writes to its
1414
+ * single eligible control — refusing on zero or several candidates. The
1415
+ * pending writes ride the returned child list explicitly and apply inside
1416
+ * the control's own construction: no committed instance is ever mutated.
960
1417
  */
961
1418
  private rewriteChildren(
962
1419
  node: SurfaceNode,
963
1420
  model: SurfaceModel,
964
1421
  path: string,
965
1422
  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];
1423
+ /**
1424
+ * T4: subs claimed by SIBLING routes of the enclosing compound (text
1425
+ * harvests, other slot sources). A claimed sub is skipped silently at any
1426
+ * dissolution depth — its consumption is ledgered by its own route, and
1427
+ * recording it twice would say it was dropped when it was moved.
1428
+ */
1429
+ claimedSubs: ReadonlySet<string> = new Set(),
1430
+ ): RewrittenChild[] {
1431
+ const push = (w: Warning) => this.diagnostics.push(w, treePath, Band.BeforeChildren, Phase.ChildRewrite);
1432
+ const ledger = (f: SurfaceFidelityEntry) =>
1433
+ this.diagnostics.pushFidelity(f, treePath, Band.BeforeChildren, Phase.ChildRewrite);
1434
+
1435
+ // Layered dissolution contexts (emit#37, ratified 2026-08-07). A
1436
+ // dissolving boundary shadows the enclosing compound contexts where they
1437
+ // overlap, but does not erase them: a component's disposition is resolved
1438
+ // against the stack of enclosing models, innermost first, so an outer
1439
+ // compound's sub (e.g. `card-footer`) keeps its disposition when it
1440
+ // appears inside a dissolved inner boundary (e.g. a transparent `field`).
1441
+ // A single-frame stack resolves identically to the pre-amendment single
1442
+ // `ctx` — the byte pins prove it.
1443
+ const resolve = <T>(stack: readonly SurfaceModel[], pick: (m: SurfaceModel) => T | undefined): T | undefined => {
1444
+ for (const m of stack) {
1445
+ const v = pick(m);
1446
+ if (v !== undefined) return v;
1447
+ }
1448
+ return undefined;
1449
+ };
1450
+
1451
+ const visit = (n: SurfaceNode, suffix: string, stack: readonly SurfaceModel[], out: RewrittenChild[]): void => {
1452
+ if (claimedSubs.has(n.component)) return;
1453
+ // An authored drop is warn-and-discard, exactly like the collect path —
1454
+ // resolved through the ancestor chain (inner shadows outer).
1455
+ const dropReason = resolve(stack, (m) => m.drops[n.component]);
973
1456
  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
- );
1457
+ push({ code: "surface-sub-dropped", message: `${path}: '${n.component}' dropped: ${dropReason}.` });
1458
+ ledger({ source: `${path} (${n.component})`, destination: "(discarded)", origin: `drops.${n.component}`, kind: "dropped", class: "lossy", note: dropReason });
986
1459
  return;
987
1460
  }
988
- const identity = model.subIdentity[n.component];
1461
+
1462
+ // T1: a child COMPONENT whose plan is transparent dissolves here — its
1463
+ // subtree governed by ITS OWN model PUSHED ONTO the enclosing stack, so
1464
+ // the boundary shadows but does not erase the outer contexts.
1465
+ const childPlan = this.byDspackId.get(n.component);
1466
+ const childModel = childPlan ? surfaceModelOf(childPlan) : undefined;
1467
+ if (childModel?.transparent) {
1468
+ ledger({
1469
+ source: `${path} (${n.component})`,
1470
+ destination: "(children rise in place)",
1471
+ origin: `plan.${n.component}`,
1472
+ kind: "flattened",
1473
+ class: "lossy",
1474
+ note: "transparent identity: the component dissolves; its own structure is not carried",
1475
+ });
1476
+ dissolve(n, suffix, [childModel, ...stack], childModel.transparentDonate, `plan.${n.component}`, out);
1477
+ return;
1478
+ }
1479
+
1480
+ const identity = resolve(stack, (m) => m.subIdentity[n.component]);
989
1481
  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);
1482
+ push({
1483
+ code: "surface-sub-flattened",
1484
+ message: `${path}: grouping sub-component '${n.component}' spliced inline (subFlatten strategy); its own structure is not carried.`,
1485
+ });
1486
+ ledger({ source: `${path} (${n.component})`, destination: "(children rise in place)", origin: `subs.${n.component}`, kind: "flattened", class: "lossy", note: "transparent grouping dissolved; its own structure is not carried" });
1487
+ // A grouping sub has no model of its own; its children continue under
1488
+ // the same enclosing stack that resolved it.
1489
+ dissolve(n, suffix, stack, identity.donate ?? [], `subs.${n.component}`, out);
1007
1490
  return;
1008
1491
  }
1009
1492
  if (identity?.kind === "as-text") {
@@ -1013,35 +1496,107 @@ class SurfaceEmitter {
1013
1496
  // Structure destroyed, text preserved — the same loss the cell
1014
1497
  // flatten records, and it must class the same way.
1015
1498
  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
- );
1499
+ ledger({ source: `${path} (${n.component} containing ${names})`, destination: "(subtree text)", origin: `subs.${n.component}`, kind: "flattened", class: "lossy", note: "re-identified as text; nested component structure and props are not carried" });
1022
1500
  }
1023
1501
  if (text !== "") {
1024
1502
  out.push({ text, textVariant: identity.variant });
1025
1503
  } 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
- );
1504
+ push({ code: "surface-sub-dropped", message: `${path}: '${n.component}' carried no text to synthesize; dropped.` });
1505
+ ledger({ source: `${path} (${n.component})`, destination: "(discarded)", origin: `subs.${n.component}`, kind: "dropped", class: "lossy", note: "re-identified as text but carried none" });
1038
1506
  }
1039
1507
  return;
1040
1508
  }
1041
1509
  out.push({ node: n, suffix });
1042
1510
  };
1043
- for (const child of collectChildren(node)) visit(child.node, child.suffix);
1044
- return out;
1511
+
1512
+ /**
1513
+ * Dissolves one boundary node under `innerCtx`. When the boundary carries
1514
+ * donations: harvest first-wins per donation, consume every donor sub,
1515
+ * splice the rest, then bind the pending writes to the single eligible
1516
+ * control among the spliced replacements — zero or several refuse.
1517
+ * Eligibility is declared, never guessed: a control's plan must declare
1518
+ * every donated destination.
1519
+ */
1520
+ const dissolve = (
1521
+ n: SurfaceNode,
1522
+ suffix: string,
1523
+ innerStack: readonly SurfaceModel[],
1524
+ donations: readonly Donation[],
1525
+ originLabel: string,
1526
+ out: RewrittenChild[],
1527
+ ): void => {
1528
+ const consumedDonorSubs = new Set<string>();
1529
+ const pending: PendingDonation[] = [];
1530
+ for (const d of donations) {
1531
+ let value: string | undefined;
1532
+ let donorComponent = n.component;
1533
+ if (d.from.kind === "self-text") {
1534
+ value = n.text;
1535
+ } else if (d.from.kind === "sub-text") {
1536
+ for (const sub of d.from.subs) consumedDonorSubs.add(sub);
1537
+ const walk = (m: SurfaceNode): void => {
1538
+ if (value === undefined && d.from.kind === "sub-text" && d.from.subs.includes(m.component) && m.text !== undefined) {
1539
+ value = m.text;
1540
+ donorComponent = m.component;
1541
+ }
1542
+ for (const c of collectChildren(m)) walk(c.node);
1543
+ };
1544
+ walk(n);
1545
+ }
1546
+ if (value !== undefined) {
1547
+ pending.push({ prop: d.to.name, value, origin: d.origin, donorPath: `${path}${suffix}`, donorComponent });
1548
+ }
1549
+ // Nothing to donate is not an error: the destination stays absent and
1550
+ // gate A3 arbitrates — relocation, never synthesis (the lift rule).
1551
+ }
1552
+
1553
+ // The boundary's own text rises as body text unless a self.text
1554
+ // donation claimed it (the plain transparent-sub behaviour otherwise).
1555
+ const selfDonated = donations.some((d) => d.from.kind === "self-text");
1556
+ const spliced: RewrittenChild[] = [];
1557
+ if (!selfDonated && n.text !== undefined && n.text !== "") spliced.push({ text: n.text, textVariant: "body" });
1558
+
1559
+ for (const child of collectChildren(n)) {
1560
+ if (consumedDonorSubs.has(child.node.component)) {
1561
+ const supplied = pending.some((q) => q.donorComponent === child.node.component && q.value === child.node.text);
1562
+ if (!supplied) {
1563
+ push({ code: "surface-sub-dropped", message: `${path}: '${child.node.component}' dropped: its text was not the donated value (first donor wins).` });
1564
+ ledger({ source: `${path}${child.suffix} (${child.node.component})`, destination: "(discarded)", origin: originLabel, kind: "dropped", class: "lossy", note: "surplus donor: the donation was already supplied (first donor wins)" });
1565
+ }
1566
+ continue;
1567
+ }
1568
+ visit(child.node, child.suffix, innerStack, spliced);
1569
+ }
1570
+
1571
+ if (pending.length > 0) {
1572
+ const controls = spliced.filter((entry): entry is { node: SurfaceNode; suffix: string; donations?: PendingDonation[] } => {
1573
+ if (!("node" in entry)) return false;
1574
+ const plan = this.byDspackId.get(entry.node.component);
1575
+ if (!plan || surfaceModelOf(plan).transparent) return false;
1576
+ const declared = new Set([
1577
+ ...Object.keys(plan.structural ?? {}),
1578
+ ...Object.values(plan.propMap ?? {}).map((pp) => pp.a2ui),
1579
+ ]);
1580
+ return pending.every((q) => declared.has(q.prop));
1581
+ });
1582
+ if (controls.length !== 1) {
1583
+ const names = controls.map((c) => `'${c.node.component}'`).join(", ");
1584
+ throw new EmitSurfaceError(
1585
+ `donation boundary '${n.component}' (${originLabel}) requires exactly one eligible control declaring ` +
1586
+ `[${pending.map((q) => q.prop).join(", ")}]; found ${controls.length}${controls.length ? ` (${names})` : ""} — ` +
1587
+ `a donation relocates onto one control, never broadcasts`,
1588
+ `${path}${suffix}`,
1589
+ );
1590
+ }
1591
+ controls[0].donations = [...(controls[0].donations ?? []), ...pending];
1592
+ }
1593
+
1594
+ out.push(...spliced);
1595
+ };
1596
+
1597
+ const rootOut: RewrittenChild[] = [];
1598
+ for (const child of collectChildren(node)) visit(child.node, child.suffix, [model], rootOut);
1599
+ return rootOut;
1045
1600
  }
1046
1601
 
1047
1602
  private emitTextPrimitive(