@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
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Layered dissolution contexts (emit#37, ratified 2026-08-07).
3
+ *
4
+ * A dissolving boundary shadows the enclosing compound contexts where they
5
+ * overlap, but does not erase them: dispositions remain available through
6
+ * the ancestor chain. This closes the seam the post-T4 Build matrix measured
7
+ * (eval/t4-build-matrix.json, preference-settings) — an outer compound's sub
8
+ * inside a transparent inner boundary.
9
+ *
10
+ * Fail-first (recorded on main d3aab9f, before the change): the shape below
11
+ * refused at emit with
12
+ *
13
+ * unknown component 'card-footer': not a mapped component of the '…' profile
14
+ *
15
+ * because T1 dissolution governed the inner boundary's subtree by ITS OWN
16
+ * model alone, so `card-footer` (a sub of the OUTER `card`) found no
17
+ * disposition in the inner `field` model and fell through to emitNode. The
18
+ * surface was S1/S2/S3-clean — spec v0.4 §5.1 accepts it (a `card` ancestor
19
+ * exists at any depth) — so this was purely an emitter seam.
20
+ */
21
+ import { readFileSync } from "node:fs";
22
+ import { fileURLToPath } from "node:url";
23
+ import { describe, expect, it } from "vitest";
24
+ import { transformFromJson } from "./transform/index.js";
25
+ import { emitSurface } from "./targets/a2ui/surface.js";
26
+ import { loadProfile } from "./transform/profile-load.js";
27
+ import type { DspackDoc, DspackSurface } from "./types.js";
28
+
29
+ const repo = (p: string) => fileURLToPath(new URL(`../${p}`, import.meta.url));
30
+ const contract = JSON.parse(readFileSync(repo("eval/shadcn-v3.dspack.json"), "utf8")) as DspackDoc & {
31
+ examples: Array<{ id: string; surface: DspackSurface }>;
32
+ };
33
+ const fixture = JSON.parse(readFileSync(repo("eval/shadcn-v3.eval.profile.json"), "utf8"));
34
+
35
+ const profileOf = (keep: string[]) => {
36
+ const doc = structuredClone(fixture) as Record<string, unknown> & { components: Array<{ dspackId: string }> };
37
+ const keepSet = new Set(keep);
38
+ (doc as Record<string, unknown>).intentionallyOmitted = doc.components.filter((c) => !keepSet.has(c.dspackId)).map((c) => c.dspackId).sort();
39
+ doc.components = doc.components.filter((c) => keepSet.has(c.dspackId));
40
+ delete (doc as Record<string, unknown>)["x-scaffold"];
41
+ return loadProfile(doc);
42
+ };
43
+
44
+ const surfaceOf = (root: unknown, intent = "preference-settings"): DspackSurface =>
45
+ ({ dspackSurface: "0.1", system: contract.name as string, intent, root }) as DspackSurface;
46
+
47
+ const instancesOf = (messages: unknown[]) =>
48
+ (messages[1] as { updateComponents: { components: Array<Record<string, unknown>> } }).updateComponents.components;
49
+
50
+ describe("layered dissolution: an outer compound's sub survives inside a dissolved inner boundary", () => {
51
+ const profile = profileOf(["card", "field", "field-set", "field-group", "switch", "button", "badge"]);
52
+
53
+ it("card-footer inside a transparent field resolves against card's model and its button rises", () => {
54
+ const { messages } = emitSurface(
55
+ surfaceOf({
56
+ component: "card",
57
+ children: [
58
+ { component: "card-header", children: [{ component: "card-title", text: "Preferences" }] },
59
+ {
60
+ component: "card-content",
61
+ children: [
62
+ {
63
+ component: "field",
64
+ children: [
65
+ { component: "field-label", text: "Weekly digest" },
66
+ { component: "switch", props: { name: "digest" } },
67
+ { component: "card-footer", children: [{ component: "button", text: "Save" }] },
68
+ ],
69
+ },
70
+ ],
71
+ },
72
+ ],
73
+ }),
74
+ contract,
75
+ { profile },
76
+ );
77
+ const comps = instancesOf(messages);
78
+ // No wrapper instance survives for any dissolved boundary.
79
+ for (const gone of ["Card_footer", "Field", "CardFooter", "CardHeader"]) {
80
+ expect(comps.some((c) => c.component === gone)).toBe(false);
81
+ }
82
+ // The field donated its label onto the switch (T1 still works through the layering).
83
+ const sw = comps.find((c) => c.component === "Switch")!;
84
+ expect(sw.label).toBe("Weekly digest");
85
+ // card-footer dissolved (card's disposition, reached through the ancestor
86
+ // chain) and its button rose as a real instance.
87
+ const button = comps.find((c) => c.component === "Button")!;
88
+ expect(button.child).toBeDefined();
89
+ // The whole thing is emittable and A3-valid.
90
+ const check = transformFromJson(contract, { profile, surface: { messages } });
91
+ expect(check.validation.gates.find((g) => g.name === "instance")?.pass).toBe(true);
92
+ });
93
+
94
+ it("the inner boundary's own dispositions resolve first (innermost-first walk)", () => {
95
+ // Genuine same-id overlap between two frames is structurally impossible —
96
+ // sub-component ids are unique document-wide (enforced by S2), so the
97
+ // ratified "inner shadows outer" is defined but unreachable for real
98
+ // contracts. What IS observable is that the inner frame is consulted
99
+ // first: field-title inside a dissolved field takes FIELD's asText (h4),
100
+ // never a fallthrough to some outer default.
101
+ const { messages } = emitSurface(
102
+ surfaceOf({
103
+ component: "card",
104
+ children: [
105
+ {
106
+ component: "card-content",
107
+ children: [
108
+ {
109
+ component: "field",
110
+ children: [
111
+ { component: "field-title", text: "Section" },
112
+ { component: "switch", props: { name: "x" } },
113
+ ],
114
+ },
115
+ ],
116
+ },
117
+ ],
118
+ }),
119
+ contract,
120
+ { profile },
121
+ );
122
+ const comps = instancesOf(messages);
123
+ const text = comps.find((c) => c.component === "Text" && c.text === "Section")!;
124
+ expect(text).toBeDefined();
125
+ expect(text.variant).toBe("h4"); // field's asText, not card's h3
126
+ });
127
+
128
+ it("determinism holds across the layered walk", () => {
129
+ const root = {
130
+ component: "card",
131
+ children: [
132
+ { component: "card-content", children: [{ component: "field", children: [{ component: "field-label", text: "L" }, { component: "switch" }, { component: "card-footer", children: [{ component: "button", text: "Go" }] }] }] },
133
+ ],
134
+ };
135
+ const a = emitSurface(surfaceOf(root), contract, { profile });
136
+ const b = emitSurface(surfaceOf(root), contract, { profile });
137
+ expect(JSON.stringify([a.messages, a.warnings, a.fidelity])).toBe(JSON.stringify([b.messages, b.warnings, b.fidelity]));
138
+ });
139
+ });
@@ -354,10 +354,16 @@ describe("load-time refusal matrix (v2 grammar)", () => {
354
354
  expect(out).toContain("one sub, one disposition");
355
355
  });
356
356
 
357
- it("unimplemented capability spellings are refused by the schema, not reinterpreted", () => {
358
- // T1 plan-level transparency, T1 donation, T3 joins — none parseable.
359
- expect(refusal({ transparent: true })).not.toBe("LOADED");
357
+ it("unimplemented capability spellings are refused; T1's are now implemented with their own rules", () => {
358
+ // T1 landed: `transparent` is a real spelling — on THIS plan it refuses
359
+ // for its true reason (a transparent plan declares no catalog surface,
360
+ // and Widget declares structural slots), not because the grammar is
361
+ // closed to it.
362
+ expect(refusal({ transparent: true })).toContain("declares no catalog surface");
363
+ // `onto` remains INTERNAL vocabulary: donation is authored via
364
+ // transparent.donate blocks; a raw onto key on a route stays refused.
360
365
  expect(refusal({ routes: [{ from: ["self.text"], to: "prop:label", onto: "control" }] })).not.toBe("LOADED");
366
+ // T3 joins have not landed and stay refused, never reinterpreted.
361
367
  expect(refusal({ collects: [{ of: ["s"], into: "prop:items", shape: "records", field: "f", row: ["r"], cells: ["c"], joinOn: "id" }] })).not.toBe("LOADED");
362
368
  });
363
369
  });
@@ -223,10 +223,13 @@ describe("dead and contradictory spellings refuse at load (findings 4, 5, 13)",
223
223
  describe("the ledger never reports a discarded value as landed (findings 7, 11, 12)", () => {
224
224
  it("a first-wins-skipped harvest ledgers as dropped/lossy, not moved", () => {
225
225
  // The shipped v1 Table: authored caption prop beats the harvested one.
226
+ // columns/rows ride the same structuralPassthrough so the instance stays
227
+ // catalog-valid (both are required; emitSurface now refuses otherwise) —
228
+ // the first-wins dynamics under test concern only the caption.
226
229
  const { fidelity } = emitSurface(
227
230
  surface({
228
231
  component: "table",
229
- props: { caption: "Authored" },
232
+ props: { caption: "Authored", columns: ["A"], rows: [{ cells: ["1"] }] },
230
233
  children: [{ component: "table-caption", text: "Harvested" }],
231
234
  }),
232
235
  doc,
@@ -8,8 +8,9 @@
8
8
  * - Compound flattening lands the documented projection (title/description/
9
9
  * cancelLabel/confirmLabel/triggerLabel + synthesized action).
10
10
  * - Unknown components fail with a typed error (never silently dropped).
11
- * - A CSR violating the emitted component's required props FAILS gate A3 —
12
- * the gate is proven non-vacuous.
11
+ * - A CSR that would emit an instance missing a required prop REFUSES at
12
+ * emitSurface (with the cause); gate A3 stays non-vacuous for
13
+ * hand-authored surfaces — defense in depth, proven separately.
13
14
  * - Emission is deterministic.
14
15
  */
15
16
  import { readFileSync } from "node:fs";
@@ -111,16 +112,19 @@ describe("emitSurface: worked example (ex.delete-account-confirmation)", () => {
111
112
  }
112
113
  });
113
114
 
114
- it("lift is relocation, never synthesis: a trigger with no text anywhere still fails A3", () => {
115
+ it("lift is relocation, never synthesis: a trigger with no text anywhere refuses at emission", () => {
116
+ // Nothing exists to lift, so nothing is synthesized — and instead of
117
+ // emitting an AlertDialog missing its required `triggerLabel` for gate A3
118
+ // to refuse downstream, emitSurface now refuses the emission itself,
119
+ // naming the unfilled requirement and where the value should have come
120
+ // from. (Gate A3 keeps full-schema rigor for hand-authored surfaces — see
121
+ // the non-vacuity test below.)
115
122
  const bare: DspackSurface = structuredClone(workedExample.surface);
116
123
  const trigger = bare.root.children![0].children![0];
117
124
  trigger.children = [{ component: "button", props: { variant: "destructive" }, children: [{ component: "badge" }] }];
118
- const { messages: bareMessages, warnings: bareWarnings } = emitSurface(bare, doc);
119
- const dialog = componentsOf(bareMessages).find((c) => c.component === "AlertDialog")!;
120
- expect(dialog.triggerLabel).toBeUndefined();
121
- expect(bareWarnings.map((w) => w.code)).not.toContain("surface-label-lifted");
122
- const { validation } = transform(doc, "0.9.1", { messages: bareMessages });
123
- expect(validation.gates.find((g) => g.name === "instance")!.pass).toBe(false); // A3 refuses, as before
125
+ expect(() => emitSurface(bare, doc)).toThrowError(EmitSurfaceError);
126
+ expect(() => emitSurface(bare, doc)).toThrowError(/required prop 'triggerLabel' has no value after emission/);
127
+ expect(() => emitSurface(bare, doc)).toThrowError(/alert-dialog-trigger/);
124
128
  });
125
129
  });
126
130
 
@@ -184,7 +188,7 @@ describe("emitSurface: failure modes", () => {
184
188
  expect(() => emitSurface(bad, doc)).toThrowError(/does not match contract name/);
185
189
  });
186
190
 
187
- it("gate A3 is non-vacuous: an AlertDialog missing its title fails instance validation", () => {
191
+ it("emitSurface refuses an AlertDialog missing its title, with the sub-component cause", () => {
188
192
  const missingTitle: DspackSurface = {
189
193
  dspackSurface: "0.1",
190
194
  system: "shadcn/ui",
@@ -205,10 +209,38 @@ describe("emitSurface: failure modes", () => {
205
209
  ],
206
210
  },
207
211
  };
208
- const { messages } = emitSurface(missingTitle, doc);
212
+ expect(() => emitSurface(missingTitle, doc)).toThrowError(EmitSurfaceError);
213
+ expect(() => emitSurface(missingTitle, doc)).toThrowError(/required prop 'title' has no value after emission/);
214
+ expect(() => emitSurface(missingTitle, doc)).toThrowError(/alert-dialog-title/);
215
+ });
216
+
217
+ it("gate A3 is non-vacuous: a hand-authored AlertDialog missing its title fails instance validation", () => {
218
+ // Defense in depth: the emitter's guard refuses upstream, but gate A3
219
+ // must still catch invalid instances that arrive without going through
220
+ // emitSurface at all — and its (now branch-scoped) errors must name the
221
+ // genuine problem.
222
+ const messages = [
223
+ {
224
+ version: "v0.9",
225
+ updateComponents: {
226
+ surfaceId: "s",
227
+ components: [
228
+ {
229
+ id: "root",
230
+ component: "AlertDialog",
231
+ triggerLabel: "Delete",
232
+ cancelLabel: "Cancel",
233
+ action: { event: { name: "delete", context: {} } },
234
+ },
235
+ ],
236
+ },
237
+ },
238
+ ];
209
239
  const { validation } = transform(doc, "0.9.1", { messages });
210
240
  const instance = validation.gates.find((g) => g.name === "instance")!;
211
241
  expect(instance.pass).toBe(false);
212
242
  expect((instance.errors ?? []).join("\n")).toMatch(/title/);
243
+ // And branch-scoped: no other component's branch leaks into the report.
244
+ for (const e of instance.errors ?? []) expect(e).toContain("AlertDialog#root");
213
245
  });
214
246
  });
@@ -78,10 +78,22 @@ describe("every transformation reports itself", () => {
78
78
  });
79
79
 
80
80
  it("collection records the gathered rows, per-cell flattening losses, and drops", () => {
81
+ // The header row keeps the Table instance catalog-valid (`columns` is
82
+ // required; emitSurface now refuses invalid instances) — the ledger
83
+ // behaviour under test lives in the body/footer handling.
81
84
  const entries = fidelityOf({
82
85
  component: "table",
83
86
  children: [
84
87
  { component: "table-caption", text: "Orders" },
88
+ {
89
+ component: "table-header",
90
+ children: [
91
+ {
92
+ component: "table-row",
93
+ children: [{ component: "table-head", text: "Status" }, { component: "table-head", text: "Order" }],
94
+ },
95
+ ],
96
+ },
85
97
  {
86
98
  component: "table-body",
87
99
  children: [
package/src/t1.test.ts ADDED
@@ -0,0 +1,370 @@
1
+ /**
2
+ * T1: transparent identity + constrained control donation.
3
+ *
4
+ * The named production failure this exists to fix, measured across three
5
+ * milestones: a fully governed `card > form > form-field > form-item >
6
+ * form-label + input` surface refused solely because `form` was a casualty.
7
+ * Fail-first evidence (captured before any T1 code, /tmp/t1-failfirst.txt):
8
+ *
9
+ * 1. the eval fixture refuses the v3 contract — form family: 6 unresolved;
10
+ * 2. the T1 spellings were refused by the v2 grammar (7 pathed issues);
11
+ * 3. the shipped profile refuses the example: unknown component 'form'.
12
+ *
13
+ * T1's rules, each pinned here:
14
+ * - a transparent plan emits NO instance; children rise; the root may not
15
+ * be transparent;
16
+ * - donation is scoped to its dissolving BOUNDARY (form-item), which is
17
+ * what lets a three-field form donate three labels to three inputs
18
+ * instead of refusing;
19
+ * - exactly one eligible control per boundary — zero and several refuse;
20
+ * - eligibility is declared, never guessed (the plan must declare every
21
+ * donated destination);
22
+ * - the control's own content beats donated context (first-wins below the
23
+ * control's writes);
24
+ * - nothing to donate is not an error: the destination stays absent and
25
+ * gate A3 arbitrates — relocation, never synthesis;
26
+ * - provenance identifies donor and receiver in the ledger.
27
+ */
28
+ import { readFileSync } from "node:fs";
29
+ import { fileURLToPath } from "node:url";
30
+ import { describe, expect, it } from "vitest";
31
+ import { transformFromJson } from "./transform/index.js";
32
+ import { emitSurface, EmitSurfaceError } from "./targets/a2ui/surface.js";
33
+ import { loadProfile, ProfileLoadError } from "./transform/profile-load.js";
34
+ import { ProfileContractError } from "./transform/validate-v2.js";
35
+ import type { DspackDoc, DspackSurface } from "./types.js";
36
+
37
+ const repo = (p: string) => fileURLToPath(new URL(`../${p}`, import.meta.url));
38
+ const contract = JSON.parse(readFileSync(repo("eval/shadcn-v3.dspack.json"), "utf8")) as DspackDoc & {
39
+ examples: Array<{ id: string; surface: DspackSurface }>;
40
+ };
41
+ const fixture = JSON.parse(readFileSync(repo("eval/shadcn-v3.eval.profile.json"), "utf8"));
42
+
43
+ import { SHADCN_V3_T1_SURFACES } from "./transform/shadcn-v2-respelling.js";
44
+
45
+ /** The T1 resolution of the form family — shared with the eval fixture builder. */
46
+ const FORM_T1_SURFACE = SHADCN_V3_T1_SURFACES.form;
47
+
48
+ /**
49
+ * A hermetic T1 profile: ONLY the plans the target failure needs, taken from
50
+ * the eval fixture (card and input are the transplanted shipped plans; input
51
+ * declares `label`, which is what makes it donation-eligible), plus the
52
+ * transparent form. The full fixture deliberately keeps 80 other unresolved
53
+ * decisions and correctly refuses — the eval-overlay measurement covers that
54
+ * side; these tests isolate T1 itself.
55
+ */
56
+ const t1Profile = (mutate?: (doc: Record<string, unknown>) => void) => {
57
+ const base = structuredClone(fixture) as Record<string, unknown> & { components: Array<Record<string, unknown>> };
58
+ const pick = (id: string) => structuredClone(base.components.find((c) => c.dspackId === id)!);
59
+ const form = pick("form");
60
+ form.surface = structuredClone(FORM_T1_SURFACE);
61
+ // The form's contract props are React-side function/state machinery with no
62
+ // declarative projection; a transparent plan declares no catalog surface —
63
+ // the required componentPlan fields stay present and EMPTY.
64
+ delete form.propMap;
65
+ form.structural = {};
66
+ form.required = [];
67
+ const doc: Record<string, unknown> & { components: Array<Record<string, unknown>> } = {
68
+ ...base,
69
+ components: [pick("card"), form, pick("input")],
70
+ "x-scaffold": undefined,
71
+ };
72
+ delete (doc as Record<string, unknown>)["x-scaffold"];
73
+ mutate?.(doc);
74
+ return loadProfile(doc);
75
+ };
76
+
77
+ const expense = contract.examples.find((e) => e.id.includes("expense"))!;
78
+
79
+ describe("T1 grammar and gates", () => {
80
+ it("the T1 spellings load (the fail-first refusal, inverted)", () => {
81
+ const profile = t1Profile();
82
+ expect(profile.language).toBe("v2");
83
+ });
84
+
85
+ it("a transparent plan with structural, propMap, required, routes, or collects refuses", () => {
86
+ const out: string[] = [];
87
+ try {
88
+ t1Profile((doc) => {
89
+ const form = (doc.components as Array<Record<string, unknown>>).find((c) => c.dspackId === "form")!;
90
+ form.structural = { x: { schema: {}, description: "d", synthNote: "s" } };
91
+ });
92
+ } catch (e) {
93
+ out.push(...(e as ProfileLoadError).issues.map((i) => i.message));
94
+ }
95
+ expect(out.join("\n")).toContain("transparent plan declares no catalog surface");
96
+ });
97
+
98
+ it("a donation writing a destination no receiver plan declares refuses at the contract gate", () => {
99
+ expect(() =>
100
+ transformFromJson(contract, {
101
+ profile: t1Profile((doc) => {
102
+ const form = (doc.components as Array<Record<string, unknown>>).find((c) => c.dspackId === "form")!;
103
+ (form.surface as typeof FORM_T1_SURFACE).subs["form-item"] = {
104
+ transparent: { donate: [{ from: "sub(form-label).text", to: "prop:nonexistentDest" }] },
105
+ } as never;
106
+ }),
107
+ }),
108
+ ).toThrowError(ProfileContractError);
109
+ });
110
+
111
+ it("a donation source that is not a declared sub refuses at the contract gate", () => {
112
+ expect(() =>
113
+ transformFromJson(contract, {
114
+ profile: t1Profile((doc) => {
115
+ const form = (doc.components as Array<Record<string, unknown>>).find((c) => c.dspackId === "form")!;
116
+ (form.surface as typeof FORM_T1_SURFACE).subs["form-item"] = {
117
+ transparent: { donate: [{ from: "sub(imaginary-label).text", to: "prop:label" }] },
118
+ } as never;
119
+ }),
120
+ }),
121
+ ).toThrowError(ProfileContractError);
122
+ });
123
+ });
124
+
125
+ /**
126
+ * A measured discovery worth its own frame: ex.expense-report-form is NOT a
127
+ * pure T1 shape. Its first three fields are the named chain (label + input);
128
+ * fields 4-6 are radio-group (T2's territory) and textarea (T5's). T1 alone
129
+ * therefore cannot emit the full example — what it does, and what these tests
130
+ * pin, is (a) emit the NAMED CHAIN completely, and (b) move the full
131
+ * example's first blocker from "unknown component 'form'" to the unresolved
132
+ * T2/T5 controls, exactly the failure-shift the architecture predicted.
133
+ */
134
+ const namedChain = (): DspackSurface => {
135
+ const root = structuredClone(expense.surface.root) as { children: unknown[] };
136
+ root.children = root.children.slice(0, 3); // the three input-controlled fields
137
+ return { ...structuredClone(expense.surface), root } as DspackSurface;
138
+ };
139
+
140
+ describe("T1 emits the named production failure", () => {
141
+ it("the named chain (form > form-field > form-item > form-label + input) emits: wrappers dissolve, labels donate per field", () => {
142
+ const { messages, warnings, fidelity } = emitSurface(namedChain(), contract, { profile: t1Profile() });
143
+ const components = (messages[1] as { updateComponents: { components: Array<Record<string, unknown>> } })
144
+ .updateComponents.components;
145
+
146
+ // No wrapper survives: no instance for form / form-field / form-item /
147
+ // form-control, and no invented FormAsAnything component.
148
+ const names = components.map((c) => c.component);
149
+ expect(names.every((n) => !String(n).startsWith("Form"))).toBe(true);
150
+
151
+ // Every input carries the label its field's form-label donated.
152
+ const fields = components.filter((c) => c.component === "TextField");
153
+ expect(fields.length).toBeGreaterThanOrEqual(3);
154
+ const labels = fields.map((f) => f.label);
155
+ expect(labels).toEqual(expect.arrayContaining(["Merchant", "Amount in USD"]));
156
+ expect(labels.every((l) => typeof l === "string" && l.length > 0)).toBe(true);
157
+
158
+ // Descriptions rise as caption Text; the description text survives.
159
+ expect(JSON.stringify(components)).toContain("Use the name printed on the receipt");
160
+
161
+ // Provenance: the ledger names donor and receiver for each donation.
162
+ const donated = fidelity.filter((f) => f.kind === "donated");
163
+ expect(donated.length).toBe(fields.length);
164
+ expect(donated[0].source).toContain("form-label");
165
+ expect(donated[0].destination).toContain("label @");
166
+ expect(donated[0].note).toContain("single eligible control");
167
+
168
+ // form-message drops with its authored reason.
169
+ expect(warnings.some((w) => w.code === "surface-sub-dropped" && w.message.includes("validation state"))).toBe(true);
170
+
171
+ // The transparent root dissolved into the synthesized layout root.
172
+ expect(components[0]).toMatchObject({ id: "root", component: "Column" });
173
+ expect(warnings.some((w) => w.code === "surface-synthesized-wrap" && w.message.includes("transparent root"))).toBe(true);
174
+
175
+ // And the emitted instances validate against the catalog (gate A3).
176
+ const check = transformFromJson(contract, { profile: t1Profile(), surface: { messages } });
177
+ expect(check.validation.gates.find((g) => g.name === "instance")?.pass).toBe(true);
178
+ });
179
+
180
+ it("the FULL example's first blocker shifts from 'unknown form' to the T2/T5 controls", () => {
181
+ // Before T1 (fail-first record): unknown component 'form'. After T1: the
182
+ // wrappers dissolve fine and the refusal names the radio-group field's
183
+ // boundary — the frontier moved to exactly where T2 begins.
184
+ try {
185
+ emitSurface(expense.surface, contract, { profile: t1Profile() });
186
+ expect.unreachable("fields 4-6 need T2/T5; the full example must still refuse");
187
+ } catch (e) {
188
+ expect(e).toBeInstanceOf(EmitSurfaceError);
189
+ expect((e as Error).message).toContain("exactly one eligible control");
190
+ expect((e as Error).message).not.toContain("unknown component 'form'");
191
+ }
192
+ });
193
+
194
+ it("emission is deterministic: two runs produce identical bytes", () => {
195
+ const a = emitSurface(namedChain(), contract, { profile: t1Profile() });
196
+ const b = emitSurface(namedChain(), contract, { profile: t1Profile() });
197
+ expect(JSON.stringify(a.messages)).toBe(JSON.stringify(b.messages));
198
+ expect(JSON.stringify(a.warnings)).toBe(JSON.stringify(b.warnings));
199
+ expect(JSON.stringify(a.fidelity)).toBe(JSON.stringify(b.fidelity));
200
+ });
201
+ });
202
+
203
+ describe("T1 fail-closed boundaries", () => {
204
+ const surfaceOf = (root: unknown): DspackSurface =>
205
+ ({ dspackSurface: "0.1", system: contract.name as string, intent: "data-submission", root }) as DspackSurface;
206
+
207
+ it("zero eligible controls refuses, naming the boundary", () => {
208
+ const s = surfaceOf({
209
+ component: "card",
210
+ children: [
211
+ {
212
+ component: "form",
213
+ children: [
214
+ {
215
+ component: "form-item",
216
+ children: [{ component: "form-label", text: "Orphan label" }],
217
+ },
218
+ ],
219
+ },
220
+ ],
221
+ });
222
+ try {
223
+ emitSurface(s, contract, { profile: t1Profile() });
224
+ expect.unreachable("a donation with no control must refuse");
225
+ } catch (e) {
226
+ expect(e).toBeInstanceOf(EmitSurfaceError);
227
+ expect((e as Error).message).toContain("exactly one eligible control");
228
+ expect((e as Error).message).toContain("found 0");
229
+ }
230
+ });
231
+
232
+ it("several eligible controls refuse — donation never broadcasts", () => {
233
+ const s = surfaceOf({
234
+ component: "card",
235
+ children: [
236
+ {
237
+ component: "form",
238
+ children: [
239
+ {
240
+ component: "form-item",
241
+ children: [
242
+ { component: "form-label", text: "Which one?" },
243
+ { component: "input", props: { type: "text" } },
244
+ { component: "input", props: { type: "email" } },
245
+ ],
246
+ },
247
+ ],
248
+ },
249
+ ],
250
+ });
251
+ try {
252
+ emitSurface(s, contract, { profile: t1Profile() });
253
+ expect.unreachable("two candidate controls must refuse");
254
+ } catch (e) {
255
+ expect((e as Error).message).toContain("found 2");
256
+ expect((e as Error).message).toContain("never broadcasts");
257
+ }
258
+ });
259
+
260
+ it("root-transparency, single survivor: the descendant IS the root (no transport wrap)", () => {
261
+ const s = surfaceOf({
262
+ component: "form",
263
+ children: [
264
+ {
265
+ component: "form-item",
266
+ children: [
267
+ { component: "form-label", text: "Lone" },
268
+ { component: "input", props: { type: "text" } },
269
+ ],
270
+ },
271
+ ],
272
+ });
273
+ const { messages, fidelity } = emitSurface(s, contract, { profile: t1Profile() });
274
+ const components = (messages[1] as { updateComponents: { components: Array<Record<string, unknown>> } })
275
+ .updateComponents.components;
276
+ expect(components[0]).toMatchObject({ id: "root", component: "TextField", label: "Lone" });
277
+ expect(components.some((c) => c.component === "Column")).toBe(false);
278
+ expect(fidelity.some((f) => f.note?.includes("single surviving descendant is preserved as the root"))).toBe(true);
279
+ });
280
+
281
+ it("root-transparency, several survivors: the synthesized wrap is structural transport", () => {
282
+ const s = surfaceOf({
283
+ component: "form",
284
+ children: [
285
+ { component: "form-item", children: [{ component: "form-label", text: "A" }, { component: "input", props: { type: "text" } }] },
286
+ { component: "form-item", children: [{ component: "form-label", text: "B" }, { component: "input", props: { type: "email" } }] },
287
+ ],
288
+ });
289
+ const { messages, warnings, fidelity } = emitSurface(s, contract, { profile: t1Profile() });
290
+ const components = (messages[1] as { updateComponents: { components: Array<Record<string, unknown>> } })
291
+ .updateComponents.components;
292
+ expect(components[0]).toMatchObject({ id: "root", component: "Column" });
293
+ expect(warnings.some((w) => w.code === "surface-synthesized-wrap" && w.message.includes("transparent root"))).toBe(true);
294
+ expect(fidelity.some((f) => f.kind === "wrapped" && f.note?.includes("structural transport"))).toBe(true);
295
+ });
296
+
297
+ it("root-transparency, nothing survives: refuse — never fabricate", () => {
298
+ const s = surfaceOf({ component: "form", children: [{ component: "form-message" }] });
299
+ try {
300
+ emitSurface(s, contract, { profile: t1Profile() });
301
+ expect.unreachable("an empty transparent root must refuse");
302
+ } catch (e) {
303
+ expect(e).toBeInstanceOf(EmitSurfaceError);
304
+ expect((e as Error).message).toContain("dissolved to nothing");
305
+ }
306
+ });
307
+
308
+ it("the control's own content beats donated context, and the loss is ledgered", () => {
309
+ const s = surfaceOf({
310
+ component: "card",
311
+ children: [
312
+ {
313
+ component: "form",
314
+ children: [
315
+ {
316
+ component: "form-item",
317
+ children: [
318
+ { component: "form-label", text: "Donated label" },
319
+ { component: "input", text: "Own label", props: { type: "text" } },
320
+ ],
321
+ },
322
+ ],
323
+ },
324
+ ],
325
+ });
326
+ const { messages, fidelity } = emitSurface(s, contract, { profile: t1Profile() });
327
+ const field = (messages[1] as { updateComponents: { components: Array<Record<string, unknown>> } })
328
+ .updateComponents.components.find((c) => c.component === "TextField")!;
329
+ expect(field.label).toBe("Own label");
330
+ const lost = fidelity.find((f) => f.kind === "dropped" && f.note?.includes("donated value did not land"));
331
+ expect(lost).toBeDefined();
332
+ });
333
+
334
+ it("nothing to donate leaves the destination unfilled and emission refuses — relocation, never synthesis", () => {
335
+ // No form-label exists, so no label is donated and NOTHING is synthesized
336
+ // in its place. The shipped TextField requires `label`, so instead of
337
+ // emitting an instance gate A3 would refuse downstream, emitSurface now
338
+ // refuses the emission itself, naming the unfilled requirement.
339
+ const s = surfaceOf({
340
+ component: "card",
341
+ children: [
342
+ {
343
+ component: "form",
344
+ children: [
345
+ {
346
+ component: "form-item",
347
+ children: [{ component: "input", props: { type: "text" } }],
348
+ },
349
+ ],
350
+ },
351
+ ],
352
+ });
353
+ expect(() => emitSurface(s, contract, { profile: t1Profile() })).toThrowError(EmitSurfaceError);
354
+ expect(() => emitSurface(s, contract, { profile: t1Profile() })).toThrowError(
355
+ /required prop 'label' has no value after emission/,
356
+ );
357
+ });
358
+
359
+ it("a transparent plan emits no catalog entry, and coverage says so", () => {
360
+ const out = transformFromJson(contract, { profile: t1Profile() });
361
+ expect((out.catalog.components as Record<string, unknown>)["Form"]).toBeUndefined();
362
+ const row = out.mapping.coverage.find((c) => c.id === "form");
363
+ expect(row?.detail).toContain("transparent");
364
+ // The form family's derived sub-coverage is fully resolved.
365
+ const unresolved = out.mapping.coverage.filter(
366
+ (c) => c.disposition === "unclassified" && c.id.startsWith("form."),
367
+ );
368
+ expect(unresolved).toEqual([]);
369
+ });
370
+ });