behavior-contracts 0.9.3 → 0.10.1

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 (65) hide show
  1. package/README.md +535 -116
  2. package/cli-contract.yaml +116 -24
  3. package/dist/authoring.d.ts +18 -1
  4. package/dist/authoring.d.ts.map +1 -1
  5. package/dist/authoring.js +11 -0
  6. package/dist/authoring.js.map +1 -1
  7. package/dist/behavior.d.ts +23 -0
  8. package/dist/behavior.d.ts.map +1 -1
  9. package/dist/behavior.js.map +1 -1
  10. package/dist/bind.d.ts +25 -1
  11. package/dist/bind.d.ts.map +1 -1
  12. package/dist/bind.js +33 -9
  13. package/dist/bind.js.map +1 -1
  14. package/dist/builder.d.ts.map +1 -1
  15. package/dist/builder.js +21 -6
  16. package/dist/builder.js.map +1 -1
  17. package/dist/cli.js +65 -40
  18. package/dist/cli.js.map +1 -1
  19. package/dist/commands/codegen.d.ts +18 -12
  20. package/dist/commands/codegen.d.ts.map +1 -1
  21. package/dist/commands/codegen.js +111 -27
  22. package/dist/commands/codegen.js.map +1 -1
  23. package/dist/commands/ts-extract.d.ts +26 -0
  24. package/dist/commands/ts-extract.d.ts.map +1 -0
  25. package/dist/commands/ts-extract.js +265 -0
  26. package/dist/commands/ts-extract.js.map +1 -0
  27. package/dist/generated/commands.d.ts.map +1 -1
  28. package/dist/generated/commands.js +8 -0
  29. package/dist/generated/commands.js.map +1 -1
  30. package/dist/generated/contract.d.ts.map +1 -1
  31. package/dist/generated/contract.js +2 -2
  32. package/dist/generated/contract.js.map +1 -1
  33. package/dist/generated/program.d.ts +4 -0
  34. package/dist/generated/program.d.ts.map +1 -1
  35. package/dist/generated/program.js +7 -3
  36. package/dist/generated/program.js.map +1 -1
  37. package/dist/generated/types.d.ts +6 -2
  38. package/dist/generated/types.d.ts.map +1 -1
  39. package/dist/generator/emit-typed-native-go.d.ts +5 -7
  40. package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
  41. package/dist/generator/emit-typed-native-go.js +244 -404
  42. package/dist/generator/emit-typed-native-go.js.map +1 -1
  43. package/dist/generator/emit-typed-native-rust.d.ts +6 -8
  44. package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
  45. package/dist/generator/emit-typed-native-rust.js +241 -374
  46. package/dist/generator/emit-typed-native-rust.js.map +1 -1
  47. package/dist/guard.d.ts +23 -0
  48. package/dist/guard.d.ts.map +1 -1
  49. package/dist/guard.js +52 -0
  50. package/dist/guard.js.map +1 -1
  51. package/dist/index.d.ts +5 -32
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +24 -5
  54. package/dist/index.js.map +1 -1
  55. package/dist/ir-handle.d.ts +30 -0
  56. package/dist/ir-handle.d.ts.map +1 -0
  57. package/dist/ir-handle.js +2 -0
  58. package/dist/ir-handle.js.map +1 -0
  59. package/dist/lower.d.ts +35 -0
  60. package/dist/lower.d.ts.map +1 -0
  61. package/dist/lower.js +118 -0
  62. package/dist/lower.js.map +1 -0
  63. package/dist/provenance.d.ts +1 -1
  64. package/dist/provenance.d.ts.map +1 -1
  65. package/package.json +9 -1
@@ -174,16 +174,9 @@ fn de_overflow(model: &str, field: &str, expected: &str, actual_wire: String, ra
174
174
  function emitBehaviorErrorType() {
175
175
  return `${emitErrorTypeDefs()}\n\n${emitErrorHelpers()}`;
176
176
  }
177
- function portFieldName(wire) {
178
- const safe = wire.replace(/[^A-Za-z0-9_]/g, "_").toLowerCase();
179
- return `f_${safe}`;
180
- }
181
177
  function pascal(s) {
182
178
  return s.replace(/[^A-Za-z0-9]+/g, " ").split(" ").filter(Boolean).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("") || "X";
183
179
  }
184
- function portsStructName(compName, nodeId) {
185
- return `PortsNR${pascal(compName)}${pascal(nodeId)}`;
186
- }
187
180
  /**
188
181
  * resolveLeafSymbol — the op-agnostic transport symbol a covered leaf (= catalog component) is called
189
182
  * through at its execution point. A consumer-supplied override (`leafTransport.symbols[component]`) wins;
@@ -191,32 +184,32 @@ function portsStructName(compName, nodeId) {
191
184
  * resolution lives (SSoT) — the runner call sites, the import block, and the test observe transport fns
192
185
  * all read it. There is no per-node handler indirection: the leaf is one transport, not one method per node.
193
186
  */
194
- function resolveLeafSymbol(component, leaf) {
195
- return leaf?.symbols[component] ?? `leaf_${sanitize(component)}`;
187
+ function resolveLeafSymbol(component, leaf, specSymbol) {
188
+ // #176 resolution order: the SPEC-fixed `node.leafSymbol` (defineLeaf meta.transport) FIRST, then the CLI
189
+ // `--leaf-transport` override, then the default `leaf_<comp>`.
190
+ return specSymbol ?? leaf?.symbols[component] ?? `leaf_${sanitize(component)}`;
196
191
  }
197
192
  /**
198
- * portFieldSpread — the covered node's port fields, in declared `Object.keys(ports)` order, each carrying
199
- * its native ports-struct field name, its Copy-ness (borrow vs move), and its rendered field type. The ONE
200
- * place the transport-call port spread is derived (SSoT): a runner call site spreads `<var>.<f>` (Copy) /
201
- * `&<var>.<f>` (non-Copy); the test observe transport fn declares params of the matching type. Types come
202
- * from the SAME `compilePortNode` lowering `emitPortsStruct` uses, so the spread can never disagree with
203
- * the field types the ports struct declares.
193
+ * rustPayloadRow — assemble the op-agnostic transport payload `WireRow` from the node's boxed port entries
194
+ * (#183). The ONE place a rust transport payload is wrapped: every call site (point / map-element /
195
+ * fanout-element / batched item) builds its entries via {@link emitPortWireField} and wraps them here.
196
+ * `WireRow.entries` is a public field (the shared crate exports it), so cross-crate construction is direct.
204
197
  */
205
- function portFieldSpread(ports, portSchemas, comp, plan, typedNodes, asBinding, narrowed) {
206
- // #170: the transport-call spread reads the SAME lowering (incl. gate/guard narrowing) as the ports
207
- // struct fields — a narrowed opt-in-required port is a non-opt arg, matching the non-opt struct field.
208
- // #173: `expected` (declared port type from portSchemas) drives the SAME materialization the struct
209
- // field type uses, so the spread arg type can never disagree with the field type.
210
- const opts = asBinding !== undefined ? { asBinding, asBase: asBinding.name, narrowed } : narrowed !== undefined ? { narrowed } : undefined;
211
- return Object.keys(ports).map((pn) => {
212
- const expected = inputPortTypeRef(portSchemas?.[pn], plan);
213
- const c = compilePortNode(ports[pn], comp, plan, typedNodes, (h) => typedNodes.has(h), `port '${pn}' of node '${comp.name}'`, expected, opts);
214
- return { field: portFieldName(pn), isCopy: typeRefIsCopy(c.ref), renderedType: renderTypeRef(c.ref) };
215
- });
198
+ function rustPayloadRow(entries) {
199
+ return `WireRow { entries: vec![${entries.join(", ")}] }`;
200
+ }
201
+ /**
202
+ * rustPayloadBatch — the BATCHED/fanout payload: ONE WireRow `{items:[<per-element ports rows>…]}` over an
203
+ * already-built `Vec<WireValue>` of per-element WireRows (#183). Byte-equal to run_behavior's batched
204
+ * handler contract; the aligned result is a `WireValue::List` the runner reads via its `.items`.
205
+ */
206
+ function rustPayloadBatch(itemsExpr) {
207
+ return `WireRow { entries: vec![("items".to_string(), WireValue::List(WireList { items: ${itemsExpr} }))] }`;
216
208
  }
217
- /** leafCallArgs — the spread transport-call arguments for a ports-struct var (Copy→move, non-Copy→borrow). */
218
- function leafCallArgs(varExpr, spread) {
219
- return spread.map((p) => (p.isCopy ? `${varExpr}.${p.field}` : `&${varExpr}.${p.field}`)).join(", ");
209
+ /** rustListItems — extract the aligned per-element wires (a `Vec<WireValue>`) from a batched/fanout transport
210
+ * result (a `WireValue::List`); a non-list result yields an empty Vec → caught by the alignment length check. */
211
+ function rustListItems(wvExpr) {
212
+ return `match ${wvExpr} { WireValue::List(l) => l.items, _ => Vec::new() }`;
220
213
  }
221
214
  /** InNR<Comp> — the concrete per-component input struct name (fields = inputPorts). */
222
215
  function inStructName(compName) {
@@ -559,37 +552,59 @@ ${I}}`;
559
552
  * - `record` box each declared field recursively, assemble `WireValue::Row(WireRow{ entries })` — the typed
560
553
  * `obj<…>` → wire map ("M") crossing (the real op-agnostic `arr<value>` batch-write param fed a
561
554
  * typed `arr<obj>`);
562
- * - `list` box each element recursively into `WireValue::List(WireList{ items })` ("L").
563
- * A `map` value or an OPT-wrapped element (optDepth > 0) boxes AMBIGUOUSLY (map key order / opt present-vs-null
564
- * on the wire are not statically pinned to run_behavior's Value pass-through), so it stays FAIL-CLOSED LOUD —
565
- * strict-typing, no silent box. `depth` names the per-element closure binding uniquely across nesting.
555
+ * - `list` box each element recursively into `WireValue::List(WireList{ items })` ("L");
556
+ * - `map` (bc#181) box each entry's VALUE into a dynamic-keyed WireRow (BTreeMap order — no WireMap type);
557
+ * - `opt` (bc#185) TOTAL: None ⇒ `WireValue::Null`; present ⇒ unwrap all `Some` layers to the owned base
558
+ * and box it through the SAME per-kind walk (`boxBase`) — byte-equal to run_behavior's `Value`
559
+ * pass-through (null stays null), the write-side mirror of the read de-box's opt (`wrapSome`).
560
+ * `depth` names the per-element closure binding uniquely across nesting.
566
561
  */
562
+ /** rustScalarWireCtor — the WireValue constructor for a portable scalar (the ONE mapping; used both as
563
+ * `Ctor(x)` and, point-free, as a `.map(Ctor)` argument in the clippy-clean list box). */
564
+ function rustScalarWireCtor(scalar) {
565
+ switch (scalar) {
566
+ case "string":
567
+ return "WireValue::Str";
568
+ case "int":
569
+ return "WireValue::int";
570
+ case "float":
571
+ return "WireValue::float";
572
+ case "bool":
573
+ return "WireValue::Bool";
574
+ default:
575
+ throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust wire box: a bare 'null' scalar has no wire constructor`);
576
+ }
577
+ }
567
578
  function renderRustWireBox(plan, srcExpr, depth = 0) {
568
- if (plan.optDepth === 0) {
579
+ // boxBase — box a BASE-typed (non-opt) owned expr per the plan's kind. Both the required (optDepth 0) path
580
+ // and the opt arm (after its None/Some unwrap) fold through this ONE walk, so the opt element reuses the SAME
581
+ // per-kind box (no parallel path). The union is exhausted below; the trailing throw is a bare exhaustiveness
582
+ // guard, never a silent hole.
583
+ const boxBase = (baseSrc) => {
569
584
  if (plan.k === "value")
570
- return srcExpr; // identity — already the opaque BC wire.
571
- if (plan.k === "scalar") {
572
- switch (plan.scalar) {
573
- case "string":
574
- return `WireValue::Str(${srcExpr})`;
575
- case "int":
576
- return `WireValue::int(${srcExpr})`;
577
- case "float":
578
- return `WireValue::float(${srcExpr})`;
579
- case "bool":
580
- return `WireValue::Bool(${srcExpr})`;
581
- }
582
- }
585
+ return baseSrc; // identity — already the opaque BC wire.
586
+ // strip the source's OWN outer parens before wrapping in the ctor — `WireValue::Str(("a"+x))` is
587
+ // `clippy::double_parens`; `WireValue::Str("a"+x)` is clean (the ctor call already parenthesizes).
588
+ if (plan.k === "scalar")
589
+ return `${rustScalarWireCtor(plan.scalar)}(${rustStripOuterParens(baseSrc)})`;
583
590
  if (plan.k === "record") {
584
591
  // typed struct → wire map: box each declared field off its native struct field (moving it out of the owned
585
592
  // srcExpr — no probe), assemble a WireRow of (name, WireValue) in declared-field order.
586
- const entries = plan.fields.map((f) => `(${rustStrLit(f.name)}.to_string(), ${renderRustWireBox(f.plan, `${srcExpr}.${rustFieldName(f.name)}`, depth + 1)})`);
593
+ const entries = plan.fields.map((f) => `(${rustStrLit(f.name)}.to_string(), ${renderRustWireBox(f.plan, `${baseSrc}.${rustFieldName(f.name)}`, depth + 1)})`);
587
594
  return `WireValue::Row(WireRow { entries: vec![${entries.join(", ")}] })`;
588
595
  }
589
596
  if (plan.k === "list") {
590
597
  // typed Vec → wire list: consume the owned Vec, box each element recursively (box-once, no round-trip).
591
598
  const e = `e${depth}`;
592
- return `WireValue::List(WireList { items: ${srcExpr}.into_iter().map(|${e}| ${renderRustWireBox(plan.elem, e, depth + 1)}).collect() })`;
599
+ const elemBox = renderRustWireBox(plan.elem, e, depth + 1);
600
+ // clippy-clean: an IDENTITY element box (a `value` list — already a Vec<WireValue>) skips the map
601
+ // (`.map(|e| e)` is `clippy::map_identity`); a bare scalar CONSTRUCTOR box goes point-free
602
+ // (`.map(WireValue::Str)` not `.map(|e| WireValue::Str(e))` — `clippy::redundant_closure`).
603
+ if (elemBox === e)
604
+ return `WireValue::List(WireList { items: ${baseSrc} })`;
605
+ const scalarCtor = plan.elem.optDepth === 0 && plan.elem.k === "scalar" ? rustScalarWireCtor(plan.elem.scalar) : undefined;
606
+ const mapper = scalarCtor !== undefined ? scalarCtor : `|${e}| ${elemBox}`;
607
+ return `WireValue::List(WireList { items: ${baseSrc}.into_iter().map(${mapper}).collect() })`;
593
608
  }
594
609
  if (plan.k === "map") {
595
610
  // bc#181: typed map<V> → wire map, represented as a dynamic-keyed WireRow (there is NO WireMap type; a
@@ -599,10 +614,22 @@ function renderRustWireBox(plan, srcExpr, depth = 0) {
599
614
  // deterministic (matching the rust typed map's canonical key order).
600
615
  const k = `k${depth}`;
601
616
  const v = `v${depth}`;
602
- return `WireValue::Row(WireRow { entries: ${srcExpr}.into_iter().map(|(${k}, ${v})| (${k}, ${renderRustWireBox(plan.value, v, depth + 1)})).collect() })`;
617
+ return `WireValue::Row(WireRow { entries: ${baseSrc}.into_iter().map(|(${k}, ${v})| (${k}, ${renderRustWireBox(plan.value, v, depth + 1)})).collect() })`;
603
618
  }
604
- }
605
- throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust wire box: a value[] element of type '${plan.expectedType}' is not native-covered by the typed→wire box (an OPT-wrapped element boxes ambiguously — opt present-vs-null on the wire is not statically pinned to run_behavior's Value pass-through — so it stays fail-closed rather than risk a divergence)`);
619
+ throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust wire box: unexpected plan kind '${plan.k}'`);
620
+ };
621
+ if (plan.optDepth > 0) {
622
+ // bc#185: typed opt<T> → wire, TOTAL. `srcExpr` is an `Option<…Option<Base>>` (optDepth `Some` wraps — the
623
+ // mirror of the read-side de-box `wrapSome`). Presence is SINGLE-BIT on the wire and run_behavior passes the
624
+ // `Value` THROUGH (null stays null), so: None ⇒ WireValue::Null (byte-equal to value_to_wire(Value::Null));
625
+ // present ⇒ unwrap ALL optDepth `Some` layers to the owned base value and box it through the SAME per-kind
626
+ // walk (box-once, no decode→re-box). A present nested opt is a fully-`Some` chain (the read side never builds
627
+ // a partially-None present), so the `_ => Null` arm only ever fires for a genuine absent.
628
+ const ov = `ov${depth}`;
629
+ const pat = "Some(".repeat(plan.optDepth) + ov + ")".repeat(plan.optDepth);
630
+ return `match ${srcExpr} { ${pat} => ${boxBase(ov)}, _ => WireValue::Null }`;
631
+ }
632
+ return boxBase(srcExpr);
606
633
  }
607
634
  /** returnErrFail — the default de-box mismatch control flow: propagate the structured Error Value out of
608
635
  * the enclosing runner (fail/retry componentRef results + map/fanout element de-box, which fails closed
@@ -709,81 +736,6 @@ function portFieldRustType(node, comp, plan, typedNodes, expected, where = "port
709
736
  const c = compilePortNode(node, comp, plan, typedNodes, (h) => typedNodes.has(h), where, expected, opts);
710
737
  return renderTypeRef(c.ref);
711
738
  }
712
- /**
713
- * emitPortsStruct — the CONCRETE native ports struct for a componentRef node. Typed fields per the
714
- * static port type, constructed directly. NO `impl PortReaderT` / by-name `port()` — the covered runner
715
- * passes `&PortsNR…` to the concrete `node_*` method by direct generic instantiation, and the handler
716
- * reads `ports.f_<field>` DIRECTLY. The struct derives Clone (a bc#87 parallel stage clones it into the
717
- * per-worker dispatch). Every field is a NATIVE Rust type (bc#90 / runtime-free) — NO boxed `Value`.
718
- */
719
- function emitPortsStruct(comp, node, asBinding, plan, typedNodes, narrowed) {
720
- const name = portsStructName(comp.name, node.id);
721
- const portNames = Object.keys(node.ports);
722
- if (portNames.length === 0) {
723
- return `// ${name} — native ports for node '${node.id}' (${node.component}); no ports.\n#[derive(Clone)]\npub struct ${name};`;
724
- }
725
- // a node WITH ports always resolves through the one port lowering, which needs the type plan + the
726
- // prior-node map (both are supplied by every caller — narrow the optional params for the fields below).
727
- if (plan === undefined || typedNodes === undefined) {
728
- throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust typed-native: ports struct for node '${node.id}' needs a type plan + prior-node map`);
729
- }
730
- // #170: the field TYPE reads the SAME lowering (incl. gate/guard narrowing) the init does, so a narrowed
731
- // opt-in-required port is a non-opt field AND a non-opt initializer — they can never disagree.
732
- // #173: the field TYPE is the DECLARED port type (portSchemas → inputPortTypeRef), materialized by the
733
- // SAME compilePortTo the init uses — field and init read one lowering, so they cannot diverge.
734
- const portOpts = asBinding !== undefined ? { asBinding, asBase: asBinding.name, narrowed } : narrowed !== undefined ? { narrowed } : undefined;
735
- const types = portNames.map((p) => portFieldRustType(node.ports[p], comp, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[p], plan), `port '${p}' of node '${node.id}'`, portOpts));
736
- const fields = portNames
737
- .map((p, i) => ` pub ${portFieldName(p)}: ${types[i]}, // ${JSON.stringify(p)}`)
738
- .join("\n");
739
- return `// ${name} — CONCRETE native ports for node '${node.id}' (${node.component}). Typed fields per the
740
- // static port type; constructed directly (no Vec, no heap key strings, no per-port Value boxing). The
741
- // handler reads the typed fields directly off this concrete struct — no by-name accessor.
742
- #[derive(Clone)]
743
- pub struct ${name} {
744
- ${fields}
745
- }`;
746
- }
747
- /**
748
- * emitMapPortsStructs — element ports struct + batch struct for a covered map node (CONCRETE). The batch
749
- * struct carries the Vec of per-element CONCRETE ports structs (the handler reads them off the concrete
750
- * struct — no by-name accessor, no key-value object).
751
- */
752
- function emitMapPortsStructs(comp, node, typedNodes, plan) {
753
- const m = node.map;
754
- const name = portsStructName(comp.name, node.id);
755
- const batch = `${name}Batch`;
756
- // #108: element ports may read the `$as` binding — resolve the over element type for native typing.
757
- const { elemRef } = mapOverElemInfo(comp, node, typedNodes, plan);
758
- const asBinding = { name: m.as, ref: elemRef, plan };
759
- // #170: a guarded map (`when(ne($e.key,null))`) proves the element key non-null in kept elements — narrow it.
760
- const elemStruct = emitPortsStruct(comp, { id: node.id, component: m.component, ports: m.ports, portSchemas: m.portSchemas }, asBinding, plan, typedNodes, nodeNarrowedPaths(comp, node));
761
- return `${elemStruct}
762
-
763
- // ${batch} — CONCRETE batched ports for map '${node.id}': the Vec of per-element CONCRETE ports structs
764
- // (a Vec<${name}>, NOT a generic key-value container). The consumer's batched handler reads the typed
765
- // element ports off the concrete struct directly.
766
- #[derive(Clone)]
767
- pub struct ${batch} {
768
- pub items: Vec<${name}>,
769
- }`;
770
- }
771
- /** emitFanoutPortsStructs (v3, rust twin) — per-id element ports struct + batch struct for a fanout node. */
772
- function emitFanoutPortsStructs(comp, node, typedNodes, plan) {
773
- const f = node.fanout;
774
- const name = portsStructName(comp.name, node.id);
775
- const batch = `${name}Batch`;
776
- const { elemRef } = fanoutOverElemInfo(comp, node, typedNodes, plan);
777
- const asBinding = { name: f.as, ref: elemRef, plan };
778
- const elemStruct = emitPortsStruct(comp, { id: node.id, component: f.component, ports: f.ports, portSchemas: f.portSchemas }, asBinding, plan, typedNodes);
779
- return `${elemStruct}
780
-
781
- // ${batch} — CONCRETE batched ports for fanout '${node.id}': the Vec of per-id CONCRETE ports structs.
782
- #[derive(Clone)]
783
- pub struct ${batch} {
784
- pub items: Vec<${name}>,
785
- }`;
786
- }
787
739
  // ── native expression compiler backend (#108) — cond `if` / map `when` / cond branches (Rust) ────────
788
740
  //
789
741
  // The runtime-free native expression compiler (native-expr.ts) mirrors run_behavior's cond/guard with
@@ -1561,21 +1513,20 @@ function emitInStruct(comp, plan) {
1561
1513
  // number literal), and a genuinely-dynamic port fails closed. There is no boxed-Value fallback on the
1562
1514
  // covered read plane.
1563
1515
  /**
1564
- * emitPortInit — emit the port field build for one port as a FULLY NATIVE Rust expression (bc#90 /
1565
- * runtime-free). Every covered port lowers to a concrete Rust value assigned straight into the ports
1566
- * struct field — NO `Value`, NO fallback path, NO `match`:
1567
- * - a static string array (projection) → `vec!["a", "b", ...]` (change #2);
1568
- * - a bare int/float number literal (e.g. Query `limit: 20`) → `20i64` / `<n>f64`;
1569
- * - a string/bool/scalar-input port → the native scalar expression (emitNativeScalar).
1570
- * A port that CANNOT lower natively FAILS CLOSED (there is no boxed Value fallback on the covered plane —
1571
- * a boxed escape would re-introduce the bc-runtime coupling this module removes). `fieldRustType` is the
1572
- * ports-struct field type (from portFieldRustType); `resolveRef` resolves a ref head for the scalar path.
1516
+ * emitPortWireField — emit ONE port as a boxed `(name, WireValue)` entry for the op-agnostic transport
1517
+ * payload (#183). The port lowers to its NATIVE value via the ONE port lowering (`compilePortNode`), then
1518
+ * boxes ONCE into the BC-owned `WireValue` through the total box SSoT (`renderRustWireBox` ∘
1519
+ * `buildWirePlan(dir:"in")`) — the SAME renderer every box crossing uses (a `value` / `Vec<WireValue>` port
1520
+ * is already the opaque form, boxed as identity `value` / list-of-`value`, so there is NO double-box). The
1521
+ * entry key is the RAW PORT NAME — the WireRow field-name↔port-name identity is the load-bearing transport
1522
+ * contract (a dynamic-port consumer reads `PK`/`SK`/`GSI1PK` by that name). A FALLIBLE port expr fails closed.
1573
1523
  */
1574
- function emitPortInit(pn, expr, comp, plan, typedNodes, isPrior, expected, opts) {
1524
+ function emitPortWireField(pn, expr, comp, plan, typedNodes, isPrior, expected, opts) {
1575
1525
  const c = compilePortNode(expr, comp, plan, typedNodes, isPrior, `port '${pn}'`, expected, opts);
1576
1526
  if (c.stmts.length > 0)
1577
- throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust typed-native (runtime-free): port '${pn}' ${JSON.stringify(expr)} lowers to a FALLIBLE expression (INT_OVERFLOW / NAN_OR_INF / MOD_ZERO / PRECISION_LOSS) — statements with an early error-return, which a ports-struct literal cannot host. Use a non-fallible port expression.`);
1578
- return `${portFieldName(pn)}: ${c.expr}`;
1527
+ throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust typed-native (runtime-free): port '${pn}' ${JSON.stringify(expr)} lowers to a FALLIBLE expression (INT_OVERFLOW / NAN_OR_INF / MOD_ZERO / PRECISION_LOSS) — statements with an early error-return, which a transport payload literal cannot host. Use a non-fallible port expression.`);
1528
+ const boxed = renderRustWireBox(buildWirePlan(c.ref, { from: "top" }, { model: "port", field: pn, plan }, "in"), c.expr);
1529
+ return `(${rustStrLit(pn)}.to_string(), ${boxed})`;
1579
1530
  }
1580
1531
  // ── the combined runner (STRUCT-returning; INLINE sequential; native ports in; concrete row out) ──
1581
1532
  function rustScalar(s) {
@@ -1728,7 +1679,6 @@ function emitNativeRawRunner(comp, plan, ap, leaf) {
1728
1679
  const node = comp.body[i];
1729
1680
  const meta = metas[i];
1730
1681
  const s = sanitize(node.id);
1731
- const structName = portsStructName(comp.name, node.id);
1732
1682
  const portNames = Object.keys(node.ports);
1733
1683
  const ref = typedNodes.get(node.id);
1734
1684
  lines.push(` // ── op '${node.id}' (${node.component}${node.relationKind ? ", relationKind:" + node.relationKind : ""}${node.parent ? ", parent:" + node.parent : ""}) ──`);
@@ -1767,20 +1717,17 @@ function emitNativeRawRunner(comp, plan, ap, leaf) {
1767
1717
  indent += " ";
1768
1718
  }
1769
1719
  }
1770
- const inits = [];
1771
1720
  const narrowed = nodeNarrowedPaths(comp, node);
1772
- for (const pn of portNames) {
1773
- inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed }));
1774
- }
1721
+ const fields = portNames.map((pn) => emitPortWireField(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed }));
1775
1722
  // bc#97: derived per-node await — this point-read's future is awaited HERE (its result-consumption
1776
1723
  // point) iff THIS node's terminal handler is async. A sync handler in the same async runner is called
1777
1724
  // directly (no `.await`). The runner being `async fn` does not force every call site to await.
1778
1725
  const awaitSfx = ap.nodeIsAsync(node.id) ? ".await" : "";
1779
- // DIRECT leaf transport call: the resolved op-agnostic symbol, the node's port fields spread (Copy→move,
1780
- // non-Copy→borrow). `bound` is NOT passed — it is BC's internal produced/skip gate, already enforced by
1781
- // the surrounding `if bound_<s>.is_some()` / `if produced_<parent>` guards; the leaf never receives it.
1782
- const call = `${resolveLeafSymbol(node.component, leaf)}(${leafCallArgs(`ports_${s}`, portFieldSpread(node.ports, node.portSchemas, comp, plan, typedNodes, undefined, narrowed))})${awaitSfx}`;
1783
- lines.push(`${indent}let ports_${s} = ${structName} { ${inits.join(", ")} };`);
1726
+ // DIRECT leaf transport call: the resolved op-agnostic symbol, ONE WireRow payload (the node's boxed
1727
+ // ports). `bound` is NOT passed — it is BC's internal produced/skip gate, already enforced by the
1728
+ // surrounding `if bound_<s>.is_some()` / `if produced_<parent>` guards; the leaf never receives it.
1729
+ const call = `${resolveLeafSymbol(node.component, leaf, node.leafSymbol)}(payload_${s})${awaitSfx}`;
1730
+ lines.push(`${indent}let payload_${s} = ${rustPayloadRow(fields)};`);
1784
1731
  // uniform seam: every covered node returns a single result WIRE; the inline de-box (renderResultDeBox)
1785
1732
  // classifies it against the STATICALLY declared result type and produces the structured Error Value on a
1786
1733
  // mismatch (byte-equal codes to run_behavior's outType check, so ≡ holds). The wire's concrete type is
@@ -1880,7 +1827,6 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1880
1827
  for (const i of refMembers) {
1881
1828
  const node = comp.body[i];
1882
1829
  const s = sanitize(node.id);
1883
- const structName = portsStructName(comp.name, node.id);
1884
1830
  const gated = node.parent !== undefined && priorNodeAt(node.parent, atPos);
1885
1831
  // #125: a member gated by a PRIOR-stage control gate (`parent=gate, bindField:"ok"`). Its bindField is
1886
1832
  // the gate's skip sentinel, NOT a relation data key — the gate is typeless (no struct field to read).
@@ -1893,7 +1839,7 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1893
1839
  // it is a plain local inside the produced block — NOT a stage-scoped mut (nothing captures it) and no
1894
1840
  // dead None init. A control-gate parent needs no bound at all (produced_<gate> already carries the skip).
1895
1841
  if (gated) {
1896
- lines.push(` let mut ports_${s}: Option<${structName}> = None;`);
1842
+ lines.push(` let mut payload_${s}: Option<WireRow> = None;`);
1897
1843
  lines.push(`${ind}if produced_${sanitize(node.parent)}.get() {`);
1898
1844
  closers.unshift(`${ind}}`);
1899
1845
  ind += " ";
@@ -1912,16 +1858,13 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1912
1858
  ind += " ";
1913
1859
  }
1914
1860
  }
1915
- const inits = [];
1916
1861
  const narrowed = nodeNarrowedPaths(comp, node);
1917
- for (const pn of Object.keys(node.ports)) {
1918
- inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, atPos), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed }));
1919
- }
1862
+ const fields = Object.keys(node.ports).map((pn) => emitPortWireField(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, atPos), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed }));
1920
1863
  if (gated) {
1921
- lines.push(`${ind}ports_${s} = Some(${structName} { ${inits.join(", ")} });`);
1864
+ lines.push(`${ind}payload_${s} = Some(${rustPayloadRow(fields)});`);
1922
1865
  }
1923
1866
  else {
1924
- lines.push(`${ind}let ports_${s}: Option<${structName}> = Some(${structName} { ${inits.join(", ")} });`);
1867
+ lines.push(`${ind}let payload_${s}: Option<WireRow> = Some(${rustPayloadRow(fields)});`);
1925
1868
  }
1926
1869
  for (const c of closers)
1927
1870
  lines.push(c);
@@ -1943,7 +1886,7 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1943
1886
  lines.push(` let mut ${jobsVar}: Vec<usize> = Vec::new();`);
1944
1887
  refMembers.forEach((i, slot) => {
1945
1888
  const s = sanitize(comp.body[i].id);
1946
- lines.push(` if ports_${s}.is_some() { ${jobsVar}.push(${slot}); }`);
1889
+ lines.push(` if payload_${s}.is_some() { ${jobsVar}.push(${slot}); }`);
1947
1890
  });
1948
1891
  lines.push(` let cursor = std::sync::atomic::AtomicUsize::new(0);`);
1949
1892
  lines.push(` let workers = ${boundN}usize.min(${jobsVar}.len());`);
@@ -1957,11 +1900,12 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1957
1900
  refMembers.forEach((i, slot) => {
1958
1901
  const node = comp.body[i];
1959
1902
  const s = sanitize(node.id);
1960
- // DIRECT leaf transport call — the node's port fields spread off the preflight-built ports struct. No
1961
- // `bound` (BC's internal produced/skip gate is already applied in preflight — the leaf never sees it).
1962
- const call = `${resolveLeafSymbol(node.component, leaf)}(${leafCallArgs("ports", portFieldSpread(node.ports, node.portSchemas, comp, plan, typedNodes, undefined, nodeNarrowedPaths(comp, node)))})`;
1903
+ // DIRECT leaf transport call — ONE op-agnostic symbol, ONE WireRow payload (the preflight-built ports,
1904
+ // cloned into the owned-arg call). No `bound` (BC's internal produced/skip gate is already applied in
1905
+ // preflight — the leaf never sees it).
1906
+ const call = `${resolveLeafSymbol(node.component, leaf, node.leafSymbol)}(payload)`;
1963
1907
  lines.push(` ${slot} => {`);
1964
- lines.push(` let ports = ports_${s}.as_ref().expect("runnable member has ports");`);
1908
+ lines.push(` let payload = payload_${s}.as_ref().expect("runnable member has ports").clone();`);
1965
1909
  lines.push(` let row = ${call};`);
1966
1910
  lines.push(` *slot_${s}.lock().unwrap() = Some(row);`);
1967
1911
  lines.push(` }`);
@@ -1977,7 +1921,7 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1977
1921
  const meta = metas[i];
1978
1922
  const s = sanitize(node.id);
1979
1923
  const ref = typedNodes.get(node.id);
1980
- lines.push(` if ports_${s}.is_some() {`);
1924
+ lines.push(` if payload_${s}.is_some() {`);
1981
1925
  lines.push(` let out_${s} = slot_${s}.lock().unwrap().take().expect("runnable member wrote its slot");`);
1982
1926
  if (meta.policy === "continue") {
1983
1927
  // continue: a failed member (leaf failure OR de-box mismatch) commits no Port (defensive — covered
@@ -2031,9 +1975,7 @@ isAsync = false) {
2031
1975
  // skipped elements instead. Byte-equal to run_behavior's applyInto keep-with-null.
2032
1976
  const keepWithNull = hasGuard && hasInto;
2033
1977
  const s = sanitize(node.id);
2034
- const structName = portsStructName(comp.name, node.id);
2035
- const batch = `${structName}Batch`;
2036
- const leafSym = resolveLeafSymbol(m.component, leaf);
1978
+ const leafSym = resolveLeafSymbol(m.component, leaf, m.leafSymbol);
2037
1979
  // #108: over element type + the OWNED over-Vec expression (prior-node arr OR input array w/ elemType).
2038
1980
  const { elemRef: overElemRef, overExpr, optArr: overOptArr } = mapOverElemInfo(comp, node, typedNodes, plan);
2039
1981
  const elemMat = mapElemMaterializerName(comp.name, node.id);
@@ -2062,19 +2004,17 @@ isAsync = false) {
2062
2004
  : elemDeBoxRef.kind === "opt"
2063
2005
  ? "None"
2064
2006
  : `${renderTypeRef(elemDeBoxRef)}::default()`;
2065
- // build the per-element CONCRETE native ports struct. `il` = indent inside the element loop.
2066
- const buildPorts = (il) => {
2067
- const out = [];
2068
- const inits = [];
2007
+ // the per-element boxed port entries (#183) — the SAME box SSoT as a point node, over the $as element.
2008
+ const portFields = () => {
2069
2009
  const asBinding = { name: asName, ref: overElemRef, plan };
2070
2010
  // #170: a guarded map narrows its `when(ne($e.key,null))`-proven element key non-null in kept elements.
2071
2011
  const narrowed = nodeNarrowedPaths(comp, node);
2072
- for (const pn of portNames) {
2073
- inits.push(emitPortInit(pn, m.ports[pn], comp, plan, typedNodes, priorHere, inputPortTypeRef(m.portSchemas?.[pn], plan), { asBinding, asBase: `oel_${s}`, narrowed }));
2074
- }
2075
- out.push(`${il}let ep_${s} = ${structName} { ${inits.join(", ")} };`);
2076
- return out;
2012
+ return portNames.map((pn) => emitPortWireField(pn, m.ports[pn], comp, plan, typedNodes, priorHere, inputPortTypeRef(m.portSchemas?.[pn], plan), { asBinding, asBase: `oel_${s}`, narrowed }));
2077
2013
  };
2014
+ // BATCHED element: `ep_<s>` is a WireRow VALUE (a `WireValue::Row`) collected into the items WireList of
2015
+ // the batch payload. NON-batched element: `ep_<s>` is the per-element transport payload WireRow.
2016
+ const buildBatchElem = (il) => [`${il}let ep_${s} = WireValue::Row(WireRow { entries: vec![${portFields().join(", ")}] });`];
2017
+ const buildPayloadElem = (il) => [`${il}let ep_${s} = ${rustPayloadRow(portFields())};`];
2078
2018
  // #108 guard: compile `when` to a native bool over an element-scoped resolveHead ($as element value,
2079
2019
  // prior node, input port). mkGuard returns the compiled {stmts, expr} (or null when unguarded); the
2080
2020
  // keep-with-null batched path consumes it directly to branch instead of skipping.
@@ -2117,14 +2057,14 @@ isAsync = false) {
2117
2057
  // zips its next deboxed row, a skipped element gets into=None. Byte-equal to run_behavior: batched
2118
2058
  // keptIdx-aligned collect + applyInto (skipped element unaugmented → opt-into null).
2119
2059
  const g = mkGuard();
2120
- lines.push(`${indent}let mut items_${s}: Vec<${structName}> = Vec::with_capacity(over_${s}.len());`);
2060
+ lines.push(`${indent}let mut items_${s}: Vec<WireValue> = Vec::with_capacity(over_${s}.len());`);
2121
2061
  lines.push(`${indent}let mut keep_${s}: Vec<bool> = Vec::with_capacity(over_${s}.len());`);
2122
2062
  lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
2123
2063
  for (const st of g.stmts)
2124
2064
  lines.push(`${indent} ${st}`);
2125
2065
  lines.push(`${indent} let __keep = ${rustStripOuterParens(g.expr)};`);
2126
2066
  lines.push(`${indent} if __keep {`);
2127
- for (const l of buildPorts(indent + " "))
2067
+ for (const l of buildBatchElem(indent + " "))
2128
2068
  lines.push(l);
2129
2069
  lines.push(`${indent} items_${s}.push(ep_${s});`);
2130
2070
  lines.push(`${indent} keep_${s}.push(true);`);
@@ -2135,15 +2075,17 @@ isAsync = false) {
2135
2075
  lines.push(`${indent}let mut decs_${s}: Vec<${renderTypeRef(elemDeBoxRef)}> = Vec::with_capacity(items_${s}.len());`);
2136
2076
  lines.push(`${indent}if !items_${s}.is_empty() {`);
2137
2077
  lines.push(`${indent} let want_${s} = items_${s}.len();`);
2138
- lines.push(`${indent} let bp_${s} = ${batch} { items: items_${s} };`);
2139
- lines.push(`${indent} let row_${s} = match ${leafSym}(&bp_${s})${awaitSfx} {`);
2078
+ // ONE op-agnostic transport call: batch payload WireRow {items:[…]}; result is a WireList unwrapped to
2079
+ // its aligned per-element wires (byte-equal to run_behavior's aligned batch result).
2080
+ lines.push(`${indent} let out_${s} = match ${leafSym}(${rustPayloadBatch(`items_${s}`)})${awaitSfx} {`);
2140
2081
  lines.push(`${indent} Ok(r) => r,`);
2141
2082
  lines.push(`${indent} Err(e) => return Err(op_failed(${rustStrLit(node.id)}, "fail", e)),`);
2142
2083
  lines.push(`${indent} };`);
2143
- lines.push(`${indent} if row_${s}.len() != want_${s} {`);
2084
+ lines.push(`${indent} let rows_${s}: Vec<WireValue> = ${rustListItems(`out_${s}`)};`);
2085
+ lines.push(`${indent} if rows_${s}.len() != want_${s} {`);
2144
2086
  lines.push(`${indent} return Err(BehaviorError::new("MAP_BATCH_RESULT_MISMATCH", format!("map '{}': batched handler must return a list aligned to items (want {})", ${rustStrLit(node.id)}, want_${s})));`);
2145
2087
  lines.push(`${indent} }`);
2146
- lines.push(`${indent} for er_${s} in row_${s}.into_iter() {`);
2088
+ lines.push(`${indent} for er_${s} in rows_${s}.into_iter() {`);
2147
2089
  lines.push(`${indent} let dec_${s} = ${renderElemDeBox(`${indent} `)};`);
2148
2090
  lines.push(`${indent} decs_${s}.push(dec_${s});`);
2149
2091
  lines.push(`${indent} }`);
@@ -2160,13 +2102,13 @@ isAsync = false) {
2160
2102
  }
2161
2103
  else if (batched) {
2162
2104
  // build kept-element ports (+ kept over elements for into). Batched into is never guarded (rejected).
2163
- lines.push(`${indent}let mut items_${s}: Vec<${structName}> = Vec::with_capacity(over_${s}.len());`);
2105
+ lines.push(`${indent}let mut items_${s}: Vec<WireValue> = Vec::with_capacity(over_${s}.len());`);
2164
2106
  if (hasInto)
2165
2107
  lines.push(`${indent}let mut kept_${s}: Vec<${renderTypeRef(overElemRef)}> = Vec::with_capacity(over_${s}.len());`);
2166
2108
  lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
2167
2109
  for (const l of emitGuard(indent + " "))
2168
2110
  lines.push(l);
2169
- for (const l of buildPorts(indent + " "))
2111
+ for (const l of buildBatchElem(indent + " "))
2170
2112
  lines.push(l);
2171
2113
  lines.push(`${indent} items_${s}.push(ep_${s});`);
2172
2114
  if (hasInto)
@@ -2174,21 +2116,19 @@ isAsync = false) {
2174
2116
  lines.push(`${indent}}`);
2175
2117
  lines.push(`${indent}if !items_${s}.is_empty() {`);
2176
2118
  lines.push(`${indent} let want_${s} = items_${s}.len();`);
2177
- lines.push(`${indent} let bp_${s} = ${batch} { items: items_${s} };`);
2178
- // DIRECT transport call — the batched dispatch takes the CONCRETE batch ports struct (shape unchanged
2179
- // from the removed trait method; only the call target changes). Returns the aligned per-element wires
2180
- // (Vec<Wire>). No `bound` (batched maps carry none).
2181
- lines.push(`${indent} let row_${s} = match ${leafSym}(&bp_${s})${awaitSfx} {`);
2119
+ // ONE op-agnostic transport call: batch payload WireRow {items:[…]}; result WireList → aligned wires.
2120
+ lines.push(`${indent} let out_${s} = match ${leafSym}(${rustPayloadBatch(`items_${s}`)})${awaitSfx} {`);
2182
2121
  lines.push(`${indent} Ok(r) => r,`);
2183
2122
  lines.push(`${indent} Err(e) => return Err(op_failed(${rustStrLit(node.id)}, "fail", e)),`);
2184
2123
  lines.push(`${indent} };`);
2185
- lines.push(`${indent} if row_${s}.len() != want_${s} {`);
2124
+ lines.push(`${indent} let rows_${s}: Vec<WireValue> = ${rustListItems(`out_${s}`)};`);
2125
+ lines.push(`${indent} if rows_${s}.len() != want_${s} {`);
2186
2126
  lines.push(`${indent} return Err(BehaviorError::new("MAP_BATCH_RESULT_MISMATCH", format!("map '{}': batched handler must return a list aligned to items (want {})", ${rustStrLit(node.id)}, want_${s})));`);
2187
2127
  lines.push(`${indent} }`);
2188
2128
  if (hasInto) {
2189
2129
  // zip the aligned per-element WIRES onto each KEPT over element: de-box the element wire strictly
2190
2130
  // (into the `into` field's type) then materialize the augmented element.
2191
- lines.push(`${indent} let mut rows_iter_${s} = row_${s}.into_iter();`);
2131
+ lines.push(`${indent} let mut rows_iter_${s} = rows_${s}.into_iter();`);
2192
2132
  lines.push(`${indent} for over_el_${s} in kept_${s}.iter() {`);
2193
2133
  lines.push(`${indent} let er_${s} = rows_iter_${s}.next().expect("aligned batch row");`);
2194
2134
  lines.push(`${indent} let dec_${s} = ${renderElemDeBox(`${indent} `)};`);
@@ -2197,7 +2137,7 @@ isAsync = false) {
2197
2137
  }
2198
2138
  else {
2199
2139
  // no-into: de-box each aligned per-element wire DIRECTLY into the element (result = kept elements).
2200
- lines.push(`${indent} for er_${s} in row_${s}.into_iter() {`);
2140
+ lines.push(`${indent} for er_${s} in rows_${s}.into_iter() {`);
2201
2141
  lines.push(`${indent} let el_${s} = ${renderElemDeBox(`${indent} `)};`);
2202
2142
  lines.push(`${indent} built_${s}.push(el_${s});`);
2203
2143
  lines.push(`${indent} }`);
@@ -2213,13 +2153,12 @@ isAsync = false) {
2213
2153
  const nonBatchedSkip = keepWithNull ? `built_${s}.push(${elemMat}(oel_${s}, ${intoSkipDefault})); continue;` : "continue;";
2214
2154
  for (const l of emitGuard(indent + " ", nonBatchedSkip))
2215
2155
  lines.push(l);
2216
- for (const l of buildPorts(indent + " "))
2156
+ for (const l of buildPayloadElem(indent + " "))
2217
2157
  lines.push(l);
2218
2158
  // Element Error Policy (scp-error.md): `skip` drops the failing element and proceeds (order is
2219
2159
  // preserved; the leaf keeps the Error Value it produced). `error` (default) promotes the element
2220
- // Failure to the map's Component Failure, carrying the leaf's detail through. DIRECT transport call —
2221
- // the element ports fields spread (resolved with the `$as` binding, exactly the element ports struct).
2222
- lines.push(`${indent} let er_${s} = match ${leafSym}(${leafCallArgs(`ep_${s}`, portFieldSpread(m.ports, m.portSchemas, comp, plan, typedNodes, { name: asName, ref: overElemRef, plan }, nodeNarrowedPaths(comp, node)))})${awaitSfx} {`);
2160
+ // Failure to the map's Component Failure. ONE op-agnostic transport call per element, ONE WireRow payload.
2161
+ lines.push(`${indent} let er_${s} = match ${leafSym}(ep_${s})${awaitSfx} {`);
2223
2162
  lines.push(`${indent} Ok(r) => r,`);
2224
2163
  if (m.elementPolicy === "skip") {
2225
2164
  lines.push(`${indent} Err(_) => continue,`);
@@ -2256,9 +2195,7 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
2256
2195
  const f = node.fanout;
2257
2196
  const awaitSfx = isAsync ? ".await" : "";
2258
2197
  const s = sanitize(node.id);
2259
- const structName = portsStructName(comp.name, node.id);
2260
- const batch = `${structName}Batch`;
2261
- const leafSym = resolveLeafSymbol(f.component, leaf);
2198
+ const leafSym = resolveLeafSymbol(f.component, leaf, f.leafSymbol);
2262
2199
  const connRef = typedNodes.get(node.id);
2263
2200
  const elemRef = fanoutItemsElemRef(node, connRef, plan);
2264
2201
  const elemName = renderTypeRef(elemRef);
@@ -2273,13 +2210,11 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
2273
2210
  if (!dkField || dkField.type.kind !== "scalar" || dkField.type.scalar !== "string")
2274
2211
  throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust fanout (v3): node '${node.id}' dedupeKey '${f.dedupeKey}' must be a string field of the connection items element type '${elemRef.name}'.`);
2275
2212
  const dkRust = rustFieldName(f.dedupeKey);
2213
+ // per-id boxed port WireFields — `ep_<s>` is a WireRow VALUE collected into the batch payload's items list.
2276
2214
  const buildPorts = (il) => {
2277
- const inits = [];
2278
2215
  const asBinding = { name: asName, ref: overElemRef, plan };
2279
- for (const pn of portNames) {
2280
- inits.push(emitPortInit(pn, f.ports[pn], comp, plan, typedNodes, priorHere, inputPortTypeRef(f.portSchemas?.[pn], plan), { asBinding, asBase: `oel_${s}` }));
2281
- }
2282
- return [`${il}let ep_${s} = ${structName} { ${inits.join(", ")} };`];
2216
+ const fields = portNames.map((pn) => emitPortWireField(pn, f.ports[pn], comp, plan, typedNodes, priorHere, inputPortTypeRef(f.portSchemas?.[pn], plan), { asBinding, asBase: `oel_${s}` }));
2217
+ return [`${il}let ep_${s} = WireValue::Row(WireRow { entries: vec![${fields.join(", ")}] });`];
2283
2218
  };
2284
2219
  const lines = [];
2285
2220
  const closers = [];
@@ -2292,7 +2227,7 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
2292
2227
  }
2293
2228
  lines.push(`${indent}let over_${s} = ${rustBindOverExpr(overExpr, overOptArr)};`);
2294
2229
  lines.push(`${indent}let mut built_${s}: Vec<${elemName}> = Vec::new();`);
2295
- lines.push(`${indent}let mut pi_${s}: Vec<${structName}> = Vec::with_capacity(over_${s}.len());`);
2230
+ lines.push(`${indent}let mut pi_${s}: Vec<WireValue> = Vec::with_capacity(over_${s}.len());`);
2296
2231
  lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
2297
2232
  for (const l of buildPorts(indent + " "))
2298
2233
  lines.push(l);
@@ -2300,28 +2235,27 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
2300
2235
  lines.push(`${indent}}`);
2301
2236
  lines.push(`${indent}if !pi_${s}.is_empty() {`);
2302
2237
  lines.push(`${indent} let want_${s} = pi_${s}.len();`);
2303
- lines.push(`${indent} let bp_${s} = ${batch} { items: pi_${s} };`);
2304
- // DIRECT transport call — the batched fanout dispatch takes the CONCRETE batch ports struct (shape
2305
- // unchanged; only the call target changes). Returns the aligned per-id element wires
2306
- // (Vec<Option<Wire>> — None = a DANGLING id). No `bound`.
2307
- lines.push(`${indent} let row_${s} = match ${leafSym}(&bp_${s})${awaitSfx} {`);
2238
+ // ONE op-agnostic transport call: batch payload WireRow {items:[…]}; result is a WireList of the aligned
2239
+ // per-id element wires (a WireValue::Null element → a DANGLING id). No `bound`.
2240
+ lines.push(`${indent} let out_${s} = match ${leafSym}(${rustPayloadBatch(`pi_${s}`)})${awaitSfx} {`);
2308
2241
  lines.push(`${indent} Ok(r) => r,`);
2309
2242
  lines.push(`${indent} Err(e) => return Err(op_failed(${rustStrLit(node.id)}, "fail", e)),`);
2310
2243
  lines.push(`${indent} };`);
2311
- // the handler returns the aligned per-id element WIRES (Vec<Option<Self::Wire>>); each present body is
2312
- // de-boxed strictly INLINE (a de-box mismatch fails closed). A DANGLING id is None → the zero element
2313
- // (empty dedupeKey), which the dangling drop excludes.
2314
- lines.push(`${indent} if row_${s}.len() != want_${s} {`);
2244
+ lines.push(`${indent} let rows_${s}: Vec<WireValue> = ${rustListItems(`out_${s}`)};`);
2245
+ // each present body is de-boxed strictly INLINE (a de-box mismatch fails closed). A DANGLING id is a
2246
+ // WireValue::Null → the zero element (empty dedupeKey), which the dangling drop excludes.
2247
+ lines.push(`${indent} if rows_${s}.len() != want_${s} {`);
2315
2248
  lines.push(`${indent} return Err(BehaviorError::new("FANOUT_BATCH_RESULT_MISMATCH", format!("fanout '{}': batched handler must return a list aligned to the deduped id list (want {})", ${rustStrLit(node.id)}, want_${s})));`);
2316
2249
  lines.push(`${indent} }`);
2317
2250
  // ── THE ONE dedupe/drop (mirrors fanoutDedupDrop verbatim): first-seen dedupe by dedupeKey field;
2318
2251
  // drop dangling (empty dedupeKey ≡ interpreter's null/absent-key body); implicitSource strip is
2319
2252
  // structural (the elem type already omits it). cursor is always None (connection wrap).
2320
2253
  lines.push(`${indent} let mut seen_${s}: std::collections::HashSet<String> = std::collections::HashSet::new();`);
2321
- lines.push(`${indent} for opt_er_${s} in row_${s}.into_iter() {`);
2322
- lines.push(`${indent} let el_${s}: ${elemName} = match opt_er_${s} {`);
2323
- lines.push(`${indent} Some(wire_${s}) => ${renderResultDeBox(elemRef, `wire_${s}`, node.id, plan, `${indent} `, returnErrFail, nodeWirePassthrough(node))},`);
2324
- lines.push(`${indent} None => Default::default(),`);
2254
+ lines.push(`${indent} for er_${s} in rows_${s}.into_iter() {`);
2255
+ lines.push(`${indent} let el_${s}: ${elemName} = if matches!(er_${s}, WireValue::Null) {`);
2256
+ lines.push(`${indent} Default::default()`);
2257
+ lines.push(`${indent} } else {`);
2258
+ lines.push(`${indent} ${renderResultDeBox(elemRef, `er_${s}`, node.id, plan, `${indent} `, returnErrFail, nodeWirePassthrough(node))}`);
2325
2259
  lines.push(`${indent} };`);
2326
2260
  lines.push(`${indent} let key_${s} = el_${s}.${dkRust}.clone();`);
2327
2261
  if (f.drop === "dangling") {
@@ -2490,56 +2424,29 @@ fn leaf_failure(message: impl Into<String>) -> BehaviorError {
2490
2424
  BehaviorError::new("LEAF_FAILURE", message)
2491
2425
  }`;
2492
2426
  // ── module assembly ──────────────────────────────────────────────────────────────────
2493
- /** isCrossPackageSharedNode (#165, rust twin of the go predicate) — a node whose ports struct CROSSES the
2494
- * leaf-transport boundary as a whole value (the batch ports struct passed to the transport), so under
2495
- * --shared-types-import it must live in the SHARED crate/module (else the transport crate → covered crate
2496
- * import cycle). Batched maps + fanouts pass a batch struct; every other node passes only primitive port
2497
- * fields, so its ports struct stays local. The SINGLE predicate emit() (skip-local) and
2498
- * {@link rustSharedWireTypesModule} (emit-there) both use — they never disagree (SSoT). */
2499
- function isCrossPackageSharedNode(n) {
2500
- return "fanout" in n || ("map" in n && n.map.batched === true);
2501
- }
2502
2427
  /**
2503
2428
  * rustSharedWireTypesModule (#165, rust twin of goSharedWireTypesPackage) — the BC-GENERATED shared module
2504
2429
  * content emitted when the covered module is generated with --shared-types-import. Carries the SAME wire seam
2505
2430
  * the covered module emits in-crate when the flag is absent (Probe/NumProbe + WireValue/WireRow/WireList +
2506
- * the probe classifiers) so a separate leaf-transport crate can build+return `WireValue` (and the covered
2507
- * module reference it) without an import cycle. When `ir` is given, ALSO emits the batched-map / fanout batch
2508
- * ports structs (the ONLY covered-module types that cross the transport boundary as a whole value) — same
2509
- * emitMapPortsStructs / emitFanoutPortsStructs + same {@link isCrossPackageSharedNode} predicate emit()
2510
- * skip-local uses, so the two never disagree (SSoT). The wire types derive Clone (a cross-crate transport +
2511
- * the #164 passthrough store clone them). Self-contained + runtime-free — drop it in the shared crate's
2512
- * lib.rs (a separate crate) or a module. `pub use` re-exports keep every name reachable unqualified. */
2513
- export function rustSharedWireTypesModule(ir) {
2514
- const portsStructs = [];
2515
- if (ir !== undefined) {
2516
- const components = ir.components;
2517
- const plan = buildTypePlan(ir);
2518
- for (const c of components.filter(isNativeRaw)) {
2519
- const typedNodes = buildTypedNodes(c, plan);
2520
- for (const n of c.body) {
2521
- if (!isCrossPackageSharedNode(n))
2522
- continue;
2523
- portsStructs.push("fanout" in n ? emitFanoutPortsStructs(c, n, typedNodes, plan) : emitMapPortsStructs(c, n, typedNodes, plan));
2524
- }
2525
- }
2526
- }
2527
- const portsSection = portsStructs.length
2528
- ? `\n\n// #165 cross-crate batched/fanout ports structs — the batch ports the covered module's runner passes\n// to the leaf transport as a whole value. Here (not the covered module) so the transport crate can name\n// them without importing the covered crate (cycle-free). Native fields — no boxed Value.\n${portsStructs.filter((s) => s.trim().length > 0).join("\n\n")}`
2529
- : "";
2431
+ * the probe classifiers) so a separate leaf-transport crate can take a `WireRow` payload + build+return
2432
+ * `WireValue` (and the covered module reference them) without an import cycle. #183: the transport ABI is the
2433
+ * generic `WireRow` payload built inline at the call site — there are NO per-node/per-role batch ports structs
2434
+ * to emit here. The wire types derive Clone (a cross-crate transport + the #164 passthrough store clone them).
2435
+ * Self-contained + runtime-free — drop it in the shared crate's lib.rs (a separate crate) or a module. */
2436
+ export function rustSharedWireTypesModule() {
2530
2437
  return `#![allow(dead_code, unused_imports, non_snake_case)]
2531
2438
  // GENERATED by behavior-contracts (rust-typed-native) — the BC-OWNED shared wire types (#165). A covered
2532
2439
  // module generated with --shared-types-import imports these (\`use <path>::*;\`); a separate leaf-transport
2533
- // crate builds + returns the SAME \`WireValue\` (and, on failure, the SAME \`BehaviorError\`). The concrete
2534
- // failure type lives here too so the transport crate returns \`Result<WireValue, BehaviorError>\` WITHOUT
2535
- // importing the covered crate (unlike go's \`error\` interface, rust's runner reads the concrete
2536
- // \`.detail\`/\`.message\`, so the type must be shared). Self-contained + runtime-free.
2440
+ // crate takes a \`WireRow\` payload + builds + returns the SAME \`WireValue\` (and, on failure, the SAME
2441
+ // \`BehaviorError\`). The concrete failure type lives here too so the transport crate returns
2442
+ // \`Result<WireValue, BehaviorError>\` WITHOUT importing the covered crate (unlike go's \`error\` interface,
2443
+ // rust's runner reads the concrete \`.detail\`/\`.message\`, so the type must be shared). Self-contained.
2537
2444
 
2538
2445
  // Local concrete failure type (runtime-free) — the covered runner + the transport crate share it. Only the
2539
2446
  // TYPE lives here; the de-box/op-failure CONSTRUCTORS stay in the covered module (they are called there).
2540
2447
  ${emitErrorTypeDefs()}
2541
2448
 
2542
- ${emitRustProbeWireTypes(true)}${portsSection}
2449
+ ${emitRustProbeWireTypes(true)}
2543
2450
  `;
2544
2451
  }
2545
2452
  function emit(ctx) {
@@ -2585,7 +2492,6 @@ ${emitStructSurface([])}
2585
2492
  // #108: reset the native-expr helper-usage accumulator (set by the cond/guard compiler).
2586
2493
  rustExprUsed.helpers = false;
2587
2494
  const leaf = ctx.leafTransport;
2588
- const structs = [];
2589
2495
  const inStructs = [];
2590
2496
  const elemMaterializers = [];
2591
2497
  // every covered node returns a WireValue the inline de-box classifies — the wire seam (probe enums +
@@ -2604,33 +2510,16 @@ ${emitStructSurface([])}
2604
2510
  for (const n of c.body)
2605
2511
  if (!isControlGate(n))
2606
2512
  typedNodes.set(n.id, "map" in n ? mapNodeArrRef(n, plan) : deriveTypeRef(n.outType, plan)); // #125: control-gate typeless; map は produced-array ref に正規化
2607
- for (const n of c.body) {
2608
- // #165: a cross-package batch ports struct (batched map / fanout) is emitted in the SHARED module
2609
- // instead (rustSharedWireTypesModule), referenced here via the `use <path>::*;` glob — skip local.
2610
- if (crossPackage && isCrossPackageSharedNode(n))
2611
- continue;
2612
- if ("fanout" in n)
2613
- structs.push(emitFanoutPortsStructs(c, n, typedNodes, plan));
2614
- else if ("map" in n)
2615
- structs.push(emitMapPortsStructs(c, n, typedNodes, plan));
2616
- else if ("cond" in n) {
2617
- // #108: a cond node has NO ports struct (pure Expression — no handler dispatch).
2618
- }
2619
- else
2620
- structs.push(emitPortsStruct(c, n, undefined, plan, typedNodes, nodeNarrowedPaths(c, n))); // #129: typedNodes for prior-node arr leaf ports. #170: a gated child narrows its gate-proven opt key.
2621
- }
2513
+ // #183: a covered node's ports cross the transport boundary as ONE op-agnostic `WireRow` payload built
2514
+ // inline at the call site — there are NO per-node ports structs on the covered plane or the shared crate.
2622
2515
  inStructs.push(emitInStruct(c, plan));
2623
2516
  const mm = emitMapElemMaterializers(c, typedNodes, plan);
2624
2517
  if (mm)
2625
2518
  elemMaterializers.push(mm);
2626
2519
  }
2627
- // bc#156/#160: WireValue lands in a Clone-deriving ports struct (the cloning port init + bc#87 parallel
2628
- // dispatch require WireValue: Clone) whenever a node port lowers to `value`/`value[]` — a `value` input
2629
- // port wired through, a `{arr:[value,…]}` array-literal, or an empty `{arr:[]}` params list (bc#160).
2630
- // The ports structs are the ONLY Clone-deriving WireValue-bearing structs (input structs derive Default;
2631
- // outType decls never carry `value` — input-only), so their rendered field types are the total SSoT
2632
- // signal. A value-free module omits the derive to stay byte-identical to pre-#156.
2633
- const hasValuePort = structs.some((s) => s.includes("WireValue"));
2520
+ // #183: the wire types derive Clone — the covered plane always builds `WireRow` payloads (the transport
2521
+ // ABI) and the bc#87 parallel stage clones a member's payload into its owned-arg call; the #164 passthrough
2522
+ // store also clones a `WireValue`. Deriving Clone on the (data-only) wire types is unconditional + harmless.
2634
2523
  const runners = native.map((c) => emitNativeRawRunner(c, plan, asyncPlans.get(c.name), leaf)).join("\n\n");
2635
2524
  const structSurface = emitStructSurface(native);
2636
2525
  // Leaf transport import (SSoT resolution via resolveLeafSymbol): if the consumer names an import module,
@@ -2642,9 +2531,13 @@ ${emitStructSurface([])}
2642
2531
  const syms = new Set();
2643
2532
  for (const c of native)
2644
2533
  for (const n of c.body) {
2645
- const component = "fanout" in n ? n.fanout.component : "map" in n ? n.map.component : "cond" in n ? undefined : n.component;
2646
- if (component !== undefined)
2647
- syms.add(resolveLeafSymbol(component, leaf));
2534
+ if ("cond" in n)
2535
+ continue; // a cond node has no leaf (pure Expression) — no transport symbol.
2536
+ const component = "fanout" in n ? n.fanout.component : "map" in n ? n.map.component : n.component;
2537
+ const specSym = "fanout" in n ? n.fanout.leafSymbol : "map" in n ? n.map.leafSymbol : n.leafSymbol;
2538
+ // #176 SSoT: resolve EXACTLY as the call sites do (spec `node.leafSymbol` FIRST, then CLI override,
2539
+ // then default) so the imported symbol == the called symbol — otherwise cross-crate --from won't compile.
2540
+ syms.add(resolveLeafSymbol(component, leaf, specSym));
2648
2541
  }
2649
2542
  if (syms.size === 0)
2650
2543
  return undefined;
@@ -2695,12 +2588,9 @@ use std::cell::RefCell;`;
2695
2588
  rustExprUsed.helpers
2696
2589
  ? `// #108 native-expr helper library (runtime-free; byte-equal to expr-eval.ts core) — used by\n// cond / map-guard checked arithmetic. NO bc-runtime reference (failures use the LOCAL BehaviorError).\n${emitExprHelpersRust()}`
2697
2590
  : undefined,
2698
- structs.some((r) => r.trim().length > 0)
2699
- ? `// Native ports structs (one per componentRef node; typed per the static port type — CONCRETE).\n${structs.filter((r) => r.trim().length > 0).join("\n\n")}`
2700
- : undefined,
2701
2591
  `// CONCRETE per-component input structs (fields = inputPorts).\n${inStructs.join("\n\n")}`,
2702
2592
  emitsWireTypes
2703
- ? `// strict de-box wire seam — the BC-OWNED, BC-GENERATED concrete WireValue (+ WireRow/WireList): the\n// consumer's single transport builds + returns it, implements NOTHING over it. The generated INLINE de-box\n// classifies it against the STATICALLY declared type and owns strictness (required/optional, present/absent,\n// error assembly, fail-closed). Self-contained concrete types — no trait, no boxed runtime value.\n${emitRustProbeWireTypes(hasValuePort)}`
2593
+ ? `// strict de-box wire seam — the BC-OWNED, BC-GENERATED concrete WireValue (+ WireRow/WireList): the\n// consumer's single transport takes a WireRow payload + builds + returns a WireValue, implements NOTHING over\n// it. The generated INLINE de-box classifies it against the STATICALLY declared type and owns strictness\n// (required/optional, present/absent, error assembly, fail-closed). Self-contained concrete types.\n${emitRustProbeWireTypes(true)}`
2704
2594
  : undefined,
2705
2595
  elemMaterializers.length
2706
2596
  ? `// map augmented-element copiers (pure struct field assignment — no dynamic value read).\n${elemMaterializers.join("\n\n")}`
@@ -2765,10 +2655,14 @@ fn value_to_wire(v: &Value) -> WireValue {
2765
2655
  // returning the scripted wire in EXACTLY the shape the removed per-node trait method returned. bc#87
2766
2656
  // parallel scoped threads share the static (Mutex-guarded); cases run sequentially so a shared static is
2767
2657
  // fine. Echo (#129/#141) reads the spread port params directly. ──
2658
+ // ONE free transport per DISTINCT SPEC-fixed SYMBOL (#176/#183), UNIFORM signature
2659
+ // `<sym>(payload: WireRow) -> Result<WireValue, BehaviorError>`: value_to_wire is recursive, so a
2660
+ // batched/fanout `Value::Arr` result becomes a `WireValue::List` (a `Value::Null` element → WireValue::Null,
2661
+ // the dangling marker) and a single result a scalar/row wire — ONE signature serves every cardinality. Echo
2662
+ // (#129/#141) reads the port back FROM THE PAYLOAD BY NAME. A spec-named leaf used in MULTIPLE roles is
2663
+ // emitted ONCE; two nodes → same symbol but DIFFERENT catalog is a LOUD collision (never silent).
2768
2664
  const transportFns = [];
2769
- const emittedLeaf = new Set();
2770
- const drainStmt = (catalog, echoBind) => `let (is_err, err, ok, ${echoBind}) = next_scripted(${rustStrLit(catalog)}).ok_or_else(|| unknown_component(${rustStrLit(catalog)}))?;\n if is_err {\n return Err(leaf_failure(err));\n }`;
2771
- const spreadParams = (spread) => spread.map((p) => `${p.field}: ${p.isCopy ? p.renderedType : `&${p.renderedType}`}`).join(", ");
2665
+ const bySym = new Map();
2772
2666
  for (const c of native) {
2773
2667
  const ap = asyncPlans.get(c.name);
2774
2668
  const typedNodes = new Map();
@@ -2779,98 +2673,71 @@ fn value_to_wire(v: &Value) -> WireValue {
2779
2673
  if ("cond" in n)
2780
2674
  continue; // #108: a cond node has no leaf (pure Expression) — no transport fn.
2781
2675
  const catalog = "fanout" in n ? n.fanout.component : "map" in n ? n.map.component : n.component;
2782
- if (emittedLeaf.has(catalog))
2783
- continue; // per-module a leaf has ONE consistent shape — emit once.
2784
- emittedLeaf.add(catalog);
2785
- const sym = resolveLeafSymbol(catalog, leaf);
2786
- // async iff this catalog leaf's terminal handler is async (consistent per catalog component).
2787
- const fnKw = ap.nodeIsAsync(n.id) ? "pub async fn" : "pub fn";
2788
- if ("fanout" in n) {
2789
- // fanout: return the aligned per-id element WIRES (Vec<Option<WireValue>>); a null aligned
2790
- // body is a DANGLING id → None (the covered runner maps it to the zero element).
2791
- const portsT = `${portsStructName(c.name, n.id)}Batch`;
2792
- transportFns.push(`${fnKw} ${sym}(_batch: &${portsT}) -> Result<Vec<Option<WireValue>>, BehaviorError> {
2793
- ${drainStmt(catalog, "_echo")}
2794
- let arr = match ok { Some(Value::Arr(a)) => a, _ => Vec::new() };
2795
- let wires = arr
2796
- .into_iter()
2797
- .map(|ev| match ev {
2798
- Value::Null => None,
2799
- _ => Some(value_to_wire(&ev)),
2800
- })
2801
- .collect();
2802
- Ok(wires)
2803
- }`);
2804
- continue;
2805
- }
2806
- if ("map" in n) {
2807
- // map: batched → one WIRE per element (Vec<WireValue>); non-batched → one element WIRE.
2808
- const m = n.map;
2809
- if (m.batched === true) {
2810
- const portsT = `${portsStructName(c.name, n.id)}Batch`;
2811
- transportFns.push(`${fnKw} ${sym}(_batch: &${portsT}) -> Result<Vec<WireValue>, BehaviorError> {
2812
- ${drainStmt(catalog, "_echo")}
2813
- let arr = match ok { Some(Value::Arr(a)) => a, _ => Vec::new() };
2814
- let wires = arr.iter().map(value_to_wire).collect();
2815
- Ok(wires)
2816
- }`);
2817
- }
2818
- else {
2819
- const { elemRef: overElemRef } = mapOverElemInfo(c, n, typedNodes, plan);
2820
- const params = spreadParams(portFieldSpread(m.ports, m.portSchemas, c, plan, typedNodes, { name: m.as, ref: overElemRef, plan }, nodeNarrowedPaths(c, n)));
2821
- transportFns.push(`${fnKw} ${sym}(${params}) -> Result<WireValue, BehaviorError> {
2822
- ${drainStmt(catalog, "_echo")}
2823
- Ok(value_to_wire(&ok.unwrap_or(Value::Null)))
2824
- }`);
2825
- }
2826
- continue;
2827
- }
2828
- // componentRef (point read): spread port fields; supports echo (#129/#141) reading the port params.
2829
- const node = n;
2830
- // #170: the observe transport fn's param types must match the covered module's leaf call args, which
2831
- // narrow a gate-proven opt key — so this reads the SAME node narrowing.
2832
- const crNarrowed = nodeNarrowedPaths(c, node);
2833
- const ref = typedNodes.get(n.id);
2834
- const echoBranches = [];
2835
- if (ref.kind === "named") {
2836
- const decl = findDecl(plan, ref.name);
2837
- const field = decl !== undefined && decl.fields.length === 1 ? decl.fields[0] : undefined;
2838
- const fieldRust = field !== undefined ? renderTypeRef(field.type) : null;
2839
- const recordRust = renderTypeRef(ref);
2840
- for (const pn of Object.keys(node.ports)) {
2841
- let portRust = null;
2842
- try {
2843
- portRust = portFieldRustType(node.ports[pn], c, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[pn], plan), `echo port '${pn}'`, { narrowed: crNarrowed });
2844
- }
2845
- catch {
2846
- portRust = null;
2847
- }
2848
- if (portRust === recordRust) {
2849
- // the port IS the whole record → echo it DIRECTLY (matching run_behavior's plain echo:port).
2850
- const own = typeRefIsCopy(ref) ? `${portFieldName(pn)}` : `${portFieldName(pn)}.clone()`;
2851
- echoBranches.push(` if echo == ${rustStrLit(pn)} {\n let tv = ${own};\n return Ok(value_to_wire(&${serializeTyped("tv", ref, plan)}));\n }`);
2852
- }
2853
- else if (fieldRust !== null && field !== undefined && portRust === fieldRust) {
2854
- // a scalar port wraps into the record's single field ({v: ports.X}).
2855
- const own = typeRefIsCopy(field.type) ? `${portFieldName(pn)}` : `${portFieldName(pn)}.clone()`;
2856
- echoBranches.push(` if echo == ${rustStrLit(pn)} {\n let tv = ${own};\n return Ok(value_to_wire(&Value::Obj(vec![(${rustStrLit(field.name)}.to_string(), ${serializeTyped("tv", field.type, plan)})])));\n }`);
2676
+ const specSym = "fanout" in n ? n.fanout.leafSymbol : "map" in n ? n.map.leafSymbol : n.leafSymbol;
2677
+ const sym = resolveLeafSymbol(catalog, leaf, specSym);
2678
+ const isAsync = ap.nodeIsAsync(n.id);
2679
+ // echo branches (point/componentRef nodes only — a batched/fanout node returns a WireList, not a port).
2680
+ const echo = [];
2681
+ if (!("fanout" in n) && !("map" in n)) {
2682
+ const node = n;
2683
+ const crNarrowed = nodeNarrowedPaths(c, node);
2684
+ const ref = typedNodes.get(n.id);
2685
+ if (ref.kind === "named") {
2686
+ const decl = findDecl(plan, ref.name);
2687
+ const field = decl !== undefined && decl.fields.length === 1 ? decl.fields[0] : undefined;
2688
+ const fieldRust = field !== undefined ? renderTypeRef(field.type) : null;
2689
+ const recordRust = renderTypeRef(ref);
2690
+ for (const pn of Object.keys(node.ports)) {
2691
+ let portRust = null;
2692
+ try {
2693
+ portRust = portFieldRustType(node.ports[pn], c, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[pn], plan), `echo port '${pn}'`, { narrowed: crNarrowed });
2694
+ }
2695
+ catch {
2696
+ portRust = null;
2697
+ }
2698
+ if (portRust === recordRust) {
2699
+ // the port IS the whole record → echo its payload wire DIRECTLY (matching run_behavior's echo:port).
2700
+ echo.push(` if echo == ${rustStrLit(pn)} {\n if let Some((_, v)) = payload.entries.iter().find(|(__k, _)| __k.as_str() == ${rustStrLit(pn)}) {\n return Ok(v.clone());\n }\n }`);
2701
+ }
2702
+ else if (fieldRust !== null && field !== undefined && portRust === fieldRust) {
2703
+ // a scalar port wraps into the record's single field ({v: <port wire>}) — mirrors the scripted `wrap`.
2704
+ echo.push(` if echo == ${rustStrLit(pn)} {\n if let Some((_, v)) = payload.entries.iter().find(|(__k, _)| __k.as_str() == ${rustStrLit(pn)}) {\n return Ok(WireValue::Row(WireRow { entries: vec![(${rustStrLit(field.name)}.to_string(), v.clone())] }));\n }\n }`);
2705
+ }
2857
2706
  }
2858
2707
  }
2708
+ else if (ref.kind === "arr" && Object.prototype.hasOwnProperty.call(node.ports, "items")) {
2709
+ // #129: an arr node with an `items` port echoes the payload's items wire (a WireList) so the
2710
+ // node→leaf array dataflow test is non-vacuous.
2711
+ echo.push(` if echo == "items" {\n if let Some((_, v)) = payload.entries.iter().find(|(__k, _)| __k.as_str() == "items") {\n return Ok(v.clone());\n }\n }`);
2712
+ }
2859
2713
  }
2860
- else if (ref.kind === "arr" && Object.prototype.hasOwnProperty.call(node.ports, "items")) {
2861
- // #129: an arr node with an `items` port echoes the NATIVE port array (serialized element-by-element
2862
- // into a Value::Arr) so the node→leaf array dataflow test is non-vacuous.
2863
- const elemRef = ref.elem;
2864
- echoBranches.push(` if echo == "items" {\n let tv = Value::Arr(${portFieldName("items")}.iter().map(|e| { let ev = e.clone(); ${serializeTyped("ev", elemRef, plan)} }).collect());\n return Ok(value_to_wire(&tv));\n }`);
2714
+ const prev = bySym.get(sym);
2715
+ if (prev !== undefined) {
2716
+ // #176/#183: a spec-fixed symbol MUST map to exactly ONE leaf. The same leaf in multiple roles shares
2717
+ // ONE transport — accumulate its echo branches. Two DIFFERENT catalog components → same symbol is a
2718
+ // codegen error (never silent).
2719
+ if (prev.catalog !== catalog)
2720
+ throw new GeneratorFailure("DUPLICATE_COMPONENT", `rust typed-native observe: leaf transport symbol '${sym}' resolves to TWO different catalog components ('${prev.catalog}' and '${catalog}') — a spec-fixed leaf symbol must map to ONE leaf (collision, fail-closed).`);
2721
+ for (const e of echo)
2722
+ if (!prev.echo.includes(e))
2723
+ prev.echo.push(e);
2724
+ continue;
2865
2725
  }
2866
- const canEcho = echoBranches.length > 0;
2867
- const params = spreadParams(portFieldSpread(node.ports, node.portSchemas, c, plan, typedNodes, undefined, crNarrowed));
2868
- const echoBlock = canEcho ? `${echoBranches.join("\n")}\n` : "";
2869
- transportFns.push(`${fnKw} ${sym}(${params}) -> Result<WireValue, BehaviorError> {
2870
- ${drainStmt(catalog, canEcho ? "echo" : "_echo")}
2726
+ bySym.set(sym, { catalog, async: isAsync, echo });
2727
+ }
2728
+ }
2729
+ for (const [sym, le] of bySym) {
2730
+ const fnKw = le.async ? "pub async fn" : "pub fn";
2731
+ const hasEcho = le.echo.length > 0;
2732
+ const echoBind = hasEcho ? "echo" : "_echo";
2733
+ const echoBlock = hasEcho ? `${le.echo.join("\n")}\n` : "";
2734
+ transportFns.push(`${fnKw} ${sym}(${hasEcho ? "payload" : "_payload"}: WireRow) -> Result<WireValue, BehaviorError> {
2735
+ let (is_err, err, ok, ${echoBind}) = next_scripted(${rustStrLit(le.catalog)}).ok_or_else(|| unknown_component(${rustStrLit(le.catalog)}))?;
2736
+ if is_err {
2737
+ return Err(leaf_failure(err));
2738
+ }
2871
2739
  ${echoBlock} Ok(value_to_wire(&ok.unwrap_or(Value::Null)))
2872
2740
  }`);
2873
- }
2874
2741
  }
2875
2742
  const arms = native
2876
2743
  .map((c) => {