behavior-contracts 0.9.2 → 0.10.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 (88) hide show
  1. package/cli-contract.yaml +116 -24
  2. package/dist/authoring.d.ts +18 -1
  3. package/dist/authoring.d.ts.map +1 -1
  4. package/dist/authoring.js +11 -0
  5. package/dist/authoring.js.map +1 -1
  6. package/dist/behavior.d.ts +23 -0
  7. package/dist/behavior.d.ts.map +1 -1
  8. package/dist/behavior.js +18 -10
  9. package/dist/behavior.js.map +1 -1
  10. package/dist/bind.d.ts +1 -1
  11. package/dist/bind.d.ts.map +1 -1
  12. package/dist/builder.d.ts.map +1 -1
  13. package/dist/builder.js +21 -6
  14. package/dist/builder.js.map +1 -1
  15. package/dist/cli.js +65 -40
  16. package/dist/cli.js.map +1 -1
  17. package/dist/commands/codegen.d.ts +18 -12
  18. package/dist/commands/codegen.d.ts.map +1 -1
  19. package/dist/commands/codegen.js +111 -27
  20. package/dist/commands/codegen.js.map +1 -1
  21. package/dist/commands/ts-extract.d.ts +26 -0
  22. package/dist/commands/ts-extract.d.ts.map +1 -0
  23. package/dist/commands/ts-extract.js +265 -0
  24. package/dist/commands/ts-extract.js.map +1 -0
  25. package/dist/generated/commands.d.ts.map +1 -1
  26. package/dist/generated/commands.js +8 -0
  27. package/dist/generated/commands.js.map +1 -1
  28. package/dist/generated/contract.d.ts.map +1 -1
  29. package/dist/generated/contract.js +2 -2
  30. package/dist/generated/contract.js.map +1 -1
  31. package/dist/generated/program.d.ts +4 -0
  32. package/dist/generated/program.d.ts.map +1 -1
  33. package/dist/generated/program.js +7 -3
  34. package/dist/generated/program.js.map +1 -1
  35. package/dist/generated/types.d.ts +6 -2
  36. package/dist/generated/types.d.ts.map +1 -1
  37. package/dist/generator/emit-shared-go.d.ts.map +1 -1
  38. package/dist/generator/emit-shared-go.js +40 -19
  39. package/dist/generator/emit-shared-go.js.map +1 -1
  40. package/dist/generator/emit-shared-rust.d.ts.map +1 -1
  41. package/dist/generator/emit-shared-rust.js +50 -30
  42. package/dist/generator/emit-shared-rust.js.map +1 -1
  43. package/dist/generator/emit-shared-typescript.d.ts.map +1 -1
  44. package/dist/generator/emit-shared-typescript.js +26 -4
  45. package/dist/generator/emit-shared-typescript.js.map +1 -1
  46. package/dist/generator/emit-typed-native-go.d.ts +5 -7
  47. package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
  48. package/dist/generator/emit-typed-native-go.js +292 -420
  49. package/dist/generator/emit-typed-native-go.js.map +1 -1
  50. package/dist/generator/emit-typed-native-rust.d.ts +6 -8
  51. package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
  52. package/dist/generator/emit-typed-native-rust.js +275 -382
  53. package/dist/generator/emit-typed-native-rust.js.map +1 -1
  54. package/dist/generator/native-expr.d.ts +7 -0
  55. package/dist/generator/native-expr.d.ts.map +1 -1
  56. package/dist/generator/native-expr.js +11 -0
  57. package/dist/generator/native-expr.js.map +1 -1
  58. package/dist/generator/straightline.d.ts +5 -0
  59. package/dist/generator/straightline.d.ts.map +1 -1
  60. package/dist/generator/straightline.js +1 -0
  61. package/dist/generator/straightline.js.map +1 -1
  62. package/dist/generator/typed.d.ts +17 -11
  63. package/dist/generator/typed.d.ts.map +1 -1
  64. package/dist/generator/typed.js +19 -12
  65. package/dist/generator/typed.js.map +1 -1
  66. package/dist/guard.d.ts +23 -0
  67. package/dist/guard.d.ts.map +1 -1
  68. package/dist/guard.js +52 -0
  69. package/dist/guard.js.map +1 -1
  70. package/dist/index.d.ts +3 -32
  71. package/dist/index.d.ts.map +1 -1
  72. package/dist/index.js +10 -5
  73. package/dist/index.js.map +1 -1
  74. package/dist/ir-handle.d.ts +30 -0
  75. package/dist/ir-handle.d.ts.map +1 -0
  76. package/dist/ir-handle.js +2 -0
  77. package/dist/ir-handle.js.map +1 -0
  78. package/dist/plan.d.ts +7 -0
  79. package/dist/plan.d.ts.map +1 -1
  80. package/dist/plan.js +7 -2
  81. package/dist/plan.js.map +1 -1
  82. package/dist/primitives.d.ts +4 -3
  83. package/dist/primitives.d.ts.map +1 -1
  84. package/dist/primitives.js +8 -7
  85. package/dist/primitives.js.map +1 -1
  86. package/dist/provenance.d.ts +1 -1
  87. package/dist/provenance.d.ts.map +1 -1
  88. package/package.json +9 -1
@@ -2,7 +2,7 @@ import { GeneratorFailure } from "./core.js";
2
2
  import { isControlGate, nodeWirePassthrough } from "../behavior.js";
3
3
  import { rustStraightlineInternals } from "./emit-shared-rust.js";
4
4
  import { rustTypedInternals } from "./emit-shared-rust-typed.js";
5
- import { buildTypePlan, deriveTypeRef, findDecl, guardedMapIntoIsOpt, inputPortIsOptional, inputPortTypeRef } from "./typed.js";
5
+ import { buildTypePlan, deriveTypeRef, findDecl, guardedMapIntoIsCoverable, inputPortIsOptional, inputPortTypeRef } from "./typed.js";
6
6
  import { concurrencyPlan, execPlan, analyzeSequentialOps, classifyExpr, nodeNarrowedPaths } from "./straightline.js";
7
7
  import { NativeExprCompiler } from "./native-expr.js";
8
8
  import { buildAsyncPlans } from "./async-plan.js";
@@ -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,40 +552,84 @@ ${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
- }
595
- 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 or map element boxes ambiguously — fail-closed rather than risk a run_behavior divergence)`);
609
+ if (plan.k === "map") {
610
+ // bc#181: typed map<V> → wire map, represented as a dynamic-keyed WireRow (there is NO WireMap type; a
611
+ // declared map<V> is the dynamic-keyed twin of a record — the READ side de-boxes a WireRow INTO map<V>
612
+ // the SAME way, emit-shared-debox `mapval`). Box EACH entry's VALUE recursively (box-once, no round-trip);
613
+ // keys carried as dynamic strings. BTreeMap<String,_> iterates in ascending key order, so the WireRow is
614
+ // deterministic (matching the rust typed map's canonical key order).
615
+ const k = `k${depth}`;
616
+ const v = `v${depth}`;
617
+ return `WireValue::Row(WireRow { entries: ${baseSrc}.into_iter().map(|(${k}, ${v})| (${k}, ${renderRustWireBox(plan.value, v, depth + 1)})).collect() })`;
618
+ }
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);
596
633
  }
597
634
  /** returnErrFail — the default de-box mismatch control flow: propagate the structured Error Value out of
598
635
  * the enclosing runner (fail/retry componentRef results + map/fanout element de-box, which fails closed
@@ -699,81 +736,6 @@ function portFieldRustType(node, comp, plan, typedNodes, expected, where = "port
699
736
  const c = compilePortNode(node, comp, plan, typedNodes, (h) => typedNodes.has(h), where, expected, opts);
700
737
  return renderTypeRef(c.ref);
701
738
  }
702
- /**
703
- * emitPortsStruct — the CONCRETE native ports struct for a componentRef node. Typed fields per the
704
- * static port type, constructed directly. NO `impl PortReaderT` / by-name `port()` — the covered runner
705
- * passes `&PortsNR…` to the concrete `node_*` method by direct generic instantiation, and the handler
706
- * reads `ports.f_<field>` DIRECTLY. The struct derives Clone (a bc#87 parallel stage clones it into the
707
- * per-worker dispatch). Every field is a NATIVE Rust type (bc#90 / runtime-free) — NO boxed `Value`.
708
- */
709
- function emitPortsStruct(comp, node, asBinding, plan, typedNodes, narrowed) {
710
- const name = portsStructName(comp.name, node.id);
711
- const portNames = Object.keys(node.ports);
712
- if (portNames.length === 0) {
713
- return `// ${name} — native ports for node '${node.id}' (${node.component}); no ports.\n#[derive(Clone)]\npub struct ${name};`;
714
- }
715
- // a node WITH ports always resolves through the one port lowering, which needs the type plan + the
716
- // prior-node map (both are supplied by every caller — narrow the optional params for the fields below).
717
- if (plan === undefined || typedNodes === undefined) {
718
- throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust typed-native: ports struct for node '${node.id}' needs a type plan + prior-node map`);
719
- }
720
- // #170: the field TYPE reads the SAME lowering (incl. gate/guard narrowing) the init does, so a narrowed
721
- // opt-in-required port is a non-opt field AND a non-opt initializer — they can never disagree.
722
- // #173: the field TYPE is the DECLARED port type (portSchemas → inputPortTypeRef), materialized by the
723
- // SAME compilePortTo the init uses — field and init read one lowering, so they cannot diverge.
724
- const portOpts = asBinding !== undefined ? { asBinding, asBase: asBinding.name, narrowed } : narrowed !== undefined ? { narrowed } : undefined;
725
- const types = portNames.map((p) => portFieldRustType(node.ports[p], comp, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[p], plan), `port '${p}' of node '${node.id}'`, portOpts));
726
- const fields = portNames
727
- .map((p, i) => ` pub ${portFieldName(p)}: ${types[i]}, // ${JSON.stringify(p)}`)
728
- .join("\n");
729
- return `// ${name} — CONCRETE native ports for node '${node.id}' (${node.component}). Typed fields per the
730
- // static port type; constructed directly (no Vec, no heap key strings, no per-port Value boxing). The
731
- // handler reads the typed fields directly off this concrete struct — no by-name accessor.
732
- #[derive(Clone)]
733
- pub struct ${name} {
734
- ${fields}
735
- }`;
736
- }
737
- /**
738
- * emitMapPortsStructs — element ports struct + batch struct for a covered map node (CONCRETE). The batch
739
- * struct carries the Vec of per-element CONCRETE ports structs (the handler reads them off the concrete
740
- * struct — no by-name accessor, no key-value object).
741
- */
742
- function emitMapPortsStructs(comp, node, typedNodes, plan) {
743
- const m = node.map;
744
- const name = portsStructName(comp.name, node.id);
745
- const batch = `${name}Batch`;
746
- // #108: element ports may read the `$as` binding — resolve the over element type for native typing.
747
- const { elemRef } = mapOverElemInfo(comp, node, typedNodes, plan);
748
- const asBinding = { name: m.as, ref: elemRef, plan };
749
- // #170: a guarded map (`when(ne($e.key,null))`) proves the element key non-null in kept elements — narrow it.
750
- const elemStruct = emitPortsStruct(comp, { id: node.id, component: m.component, ports: m.ports, portSchemas: m.portSchemas }, asBinding, plan, typedNodes, nodeNarrowedPaths(comp, node));
751
- return `${elemStruct}
752
-
753
- // ${batch} — CONCRETE batched ports for map '${node.id}': the Vec of per-element CONCRETE ports structs
754
- // (a Vec<${name}>, NOT a generic key-value container). The consumer's batched handler reads the typed
755
- // element ports off the concrete struct directly.
756
- #[derive(Clone)]
757
- pub struct ${batch} {
758
- pub items: Vec<${name}>,
759
- }`;
760
- }
761
- /** emitFanoutPortsStructs (v3, rust twin) — per-id element ports struct + batch struct for a fanout node. */
762
- function emitFanoutPortsStructs(comp, node, typedNodes, plan) {
763
- const f = node.fanout;
764
- const name = portsStructName(comp.name, node.id);
765
- const batch = `${name}Batch`;
766
- const { elemRef } = fanoutOverElemInfo(comp, node, typedNodes, plan);
767
- const asBinding = { name: f.as, ref: elemRef, plan };
768
- const elemStruct = emitPortsStruct(comp, { id: node.id, component: f.component, ports: f.ports, portSchemas: f.portSchemas }, asBinding, plan, typedNodes);
769
- return `${elemStruct}
770
-
771
- // ${batch} — CONCRETE batched ports for fanout '${node.id}': the Vec of per-id CONCRETE ports structs.
772
- #[derive(Clone)]
773
- pub struct ${batch} {
774
- pub items: Vec<${name}>,
775
- }`;
776
- }
777
739
  // ── native expression compiler backend (#108) — cond `if` / map `when` / cond branches (Rust) ────────
778
740
  //
779
741
  // The runtime-free native expression compiler (native-expr.ts) mirrors run_behavior's cond/guard with
@@ -811,6 +773,9 @@ function makeRustExprBackend(resolveHead, plan) {
811
773
  wireType: () => renderTypeRef({ kind: "value" }),
812
774
  // bc#156/#160: box a value[] element into the opaque BC wire via the ONE box SSoT (owned element expr).
813
775
  wireBox: (item) => renderRustWireBox(buildWirePlan(item.ref, { from: "top" }, { model: "port", field: "port", plan }, "in"), item.expr),
776
+ // bc#178: box EACH element of the owned typed Vec into an arr<value> (Vec<WireValue>) — the same
777
+ // per-element box renderer as wireBox's list case, applied over the referenced array (box-once/element).
778
+ wireBoxEachElem: (srcExpr, elemRef) => `${srcExpr}.into_iter().map(|__be| ${renderRustWireBox(buildWirePlan(elemRef, { from: "elem" }, { model: "port", field: "port", plan }, "in"), "__be")}).collect::<Vec<${renderTypeRef({ kind: "value" })}>>()`,
814
779
  scalarType: (s) => rustScalar(s),
815
780
  strLit: (s) => `${rustStrLit(s)}.to_string()`,
816
781
  boolLit: (b) => (b ? "true" : "false"),
@@ -1272,13 +1237,14 @@ function coveredMapNode(n, bodyIds, comp) {
1272
1237
  if (n === null || typeof n !== "object" || !("map" in n))
1273
1238
  return false;
1274
1239
  const m = n.map;
1275
- // #108 (rust twin of the go predicate): a guarded map (`when`) IS covered with NO `into`. #177: a
1276
- // guarded map WITH `into` is covered ONLY when the into field is OPT (keep-with-null — kept element →
1277
- // present into, guard-skipped element → into=None), byte-equal to run_behavior applyInto pass-through +
1278
- // opt-into null. A REQUIRED into field → run_behavior FAILS MISSING_PROP on a skipped element, so
1279
- // fail-close is byte-equal. over element type must be statically resolvable: prior-node arr field, or
1280
- // an input array port carrying `elemType` (BC does not infer — consumer-interface C3).
1281
- if (m.when !== undefined && m.into !== undefined && !guardedMapIntoIsOpt(n, comp))
1240
+ // #108 (rust twin of the go predicate): a guarded map (`when`) IS covered with NO `into`. #177/#182: a
1241
+ // guarded map WITH `into` is covered when the guard-skipped element has a well-defined skip value — the
1242
+ // into field is OPT (skip → None, #177) OR relationKind:connection (skip → the empty connection
1243
+ // {items:[],cursor:null}, #182). Byte-equal to run_behavior applyInto (opt-into → null / connection-into
1244
+ // → unproducedValue("connection")). A REQUIRED non-connection into → run_behavior FAILS MISSING_PROP on a
1245
+ // skipped element, so fail-close is byte-equal. over element type must be statically resolvable: prior-node
1246
+ // arr field, or an input array port carrying `elemType` (BC does not infer — consumer-interface C3).
1247
+ if (m.when !== undefined && m.into !== undefined && !guardedMapIntoIsCoverable(n, comp))
1282
1248
  return false;
1283
1249
  if (m.policy !== undefined && m.policy !== "fail")
1284
1250
  return false;
@@ -1547,21 +1513,20 @@ function emitInStruct(comp, plan) {
1547
1513
  // number literal), and a genuinely-dynamic port fails closed. There is no boxed-Value fallback on the
1548
1514
  // covered read plane.
1549
1515
  /**
1550
- * emitPortInit — emit the port field build for one port as a FULLY NATIVE Rust expression (bc#90 /
1551
- * runtime-free). Every covered port lowers to a concrete Rust value assigned straight into the ports
1552
- * struct field — NO `Value`, NO fallback path, NO `match`:
1553
- * - a static string array (projection) → `vec!["a", "b", ...]` (change #2);
1554
- * - a bare int/float number literal (e.g. Query `limit: 20`) → `20i64` / `<n>f64`;
1555
- * - a string/bool/scalar-input port → the native scalar expression (emitNativeScalar).
1556
- * A port that CANNOT lower natively FAILS CLOSED (there is no boxed Value fallback on the covered plane —
1557
- * a boxed escape would re-introduce the bc-runtime coupling this module removes). `fieldRustType` is the
1558
- * 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.
1559
1523
  */
1560
- function emitPortInit(pn, expr, comp, plan, typedNodes, isPrior, expected, opts) {
1524
+ function emitPortWireField(pn, expr, comp, plan, typedNodes, isPrior, expected, opts) {
1561
1525
  const c = compilePortNode(expr, comp, plan, typedNodes, isPrior, `port '${pn}'`, expected, opts);
1562
1526
  if (c.stmts.length > 0)
1563
- 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.`);
1564
- 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})`;
1565
1530
  }
1566
1531
  // ── the combined runner (STRUCT-returning; INLINE sequential; native ports in; concrete row out) ──
1567
1532
  function rustScalar(s) {
@@ -1714,7 +1679,6 @@ function emitNativeRawRunner(comp, plan, ap, leaf) {
1714
1679
  const node = comp.body[i];
1715
1680
  const meta = metas[i];
1716
1681
  const s = sanitize(node.id);
1717
- const structName = portsStructName(comp.name, node.id);
1718
1682
  const portNames = Object.keys(node.ports);
1719
1683
  const ref = typedNodes.get(node.id);
1720
1684
  lines.push(` // ── op '${node.id}' (${node.component}${node.relationKind ? ", relationKind:" + node.relationKind : ""}${node.parent ? ", parent:" + node.parent : ""}) ──`);
@@ -1753,20 +1717,17 @@ function emitNativeRawRunner(comp, plan, ap, leaf) {
1753
1717
  indent += " ";
1754
1718
  }
1755
1719
  }
1756
- const inits = [];
1757
1720
  const narrowed = nodeNarrowedPaths(comp, node);
1758
- for (const pn of portNames) {
1759
- inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed }));
1760
- }
1721
+ const fields = portNames.map((pn) => emitPortWireField(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed }));
1761
1722
  // bc#97: derived per-node await — this point-read's future is awaited HERE (its result-consumption
1762
1723
  // point) iff THIS node's terminal handler is async. A sync handler in the same async runner is called
1763
1724
  // directly (no `.await`). The runner being `async fn` does not force every call site to await.
1764
1725
  const awaitSfx = ap.nodeIsAsync(node.id) ? ".await" : "";
1765
- // DIRECT leaf transport call: the resolved op-agnostic symbol, the node's port fields spread (Copy→move,
1766
- // non-Copy→borrow). `bound` is NOT passed — it is BC's internal produced/skip gate, already enforced by
1767
- // the surrounding `if bound_<s>.is_some()` / `if produced_<parent>` guards; the leaf never receives it.
1768
- const call = `${resolveLeafSymbol(node.component, leaf)}(${leafCallArgs(`ports_${s}`, portFieldSpread(node.ports, node.portSchemas, comp, plan, typedNodes, undefined, narrowed))})${awaitSfx}`;
1769
- 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)};`);
1770
1731
  // uniform seam: every covered node returns a single result WIRE; the inline de-box (renderResultDeBox)
1771
1732
  // classifies it against the STATICALLY declared result type and produces the structured Error Value on a
1772
1733
  // mismatch (byte-equal codes to run_behavior's outType check, so ≡ holds). The wire's concrete type is
@@ -1866,7 +1827,6 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1866
1827
  for (const i of refMembers) {
1867
1828
  const node = comp.body[i];
1868
1829
  const s = sanitize(node.id);
1869
- const structName = portsStructName(comp.name, node.id);
1870
1830
  const gated = node.parent !== undefined && priorNodeAt(node.parent, atPos);
1871
1831
  // #125: a member gated by a PRIOR-stage control gate (`parent=gate, bindField:"ok"`). Its bindField is
1872
1832
  // the gate's skip sentinel, NOT a relation data key — the gate is typeless (no struct field to read).
@@ -1879,7 +1839,7 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1879
1839
  // it is a plain local inside the produced block — NOT a stage-scoped mut (nothing captures it) and no
1880
1840
  // dead None init. A control-gate parent needs no bound at all (produced_<gate> already carries the skip).
1881
1841
  if (gated) {
1882
- lines.push(` let mut ports_${s}: Option<${structName}> = None;`);
1842
+ lines.push(` let mut payload_${s}: Option<WireRow> = None;`);
1883
1843
  lines.push(`${ind}if produced_${sanitize(node.parent)}.get() {`);
1884
1844
  closers.unshift(`${ind}}`);
1885
1845
  ind += " ";
@@ -1898,16 +1858,13 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1898
1858
  ind += " ";
1899
1859
  }
1900
1860
  }
1901
- const inits = [];
1902
1861
  const narrowed = nodeNarrowedPaths(comp, node);
1903
- for (const pn of Object.keys(node.ports)) {
1904
- inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, atPos), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed }));
1905
- }
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 }));
1906
1863
  if (gated) {
1907
- lines.push(`${ind}ports_${s} = Some(${structName} { ${inits.join(", ")} });`);
1864
+ lines.push(`${ind}payload_${s} = Some(${rustPayloadRow(fields)});`);
1908
1865
  }
1909
1866
  else {
1910
- lines.push(`${ind}let ports_${s}: Option<${structName}> = Some(${structName} { ${inits.join(", ")} });`);
1867
+ lines.push(`${ind}let payload_${s}: Option<WireRow> = Some(${rustPayloadRow(fields)});`);
1911
1868
  }
1912
1869
  for (const c of closers)
1913
1870
  lines.push(c);
@@ -1929,7 +1886,7 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1929
1886
  lines.push(` let mut ${jobsVar}: Vec<usize> = Vec::new();`);
1930
1887
  refMembers.forEach((i, slot) => {
1931
1888
  const s = sanitize(comp.body[i].id);
1932
- lines.push(` if ports_${s}.is_some() { ${jobsVar}.push(${slot}); }`);
1889
+ lines.push(` if payload_${s}.is_some() { ${jobsVar}.push(${slot}); }`);
1933
1890
  });
1934
1891
  lines.push(` let cursor = std::sync::atomic::AtomicUsize::new(0);`);
1935
1892
  lines.push(` let workers = ${boundN}usize.min(${jobsVar}.len());`);
@@ -1943,11 +1900,12 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1943
1900
  refMembers.forEach((i, slot) => {
1944
1901
  const node = comp.body[i];
1945
1902
  const s = sanitize(node.id);
1946
- // DIRECT leaf transport call — the node's port fields spread off the preflight-built ports struct. No
1947
- // `bound` (BC's internal produced/skip gate is already applied in preflight — the leaf never sees it).
1948
- 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)`;
1949
1907
  lines.push(` ${slot} => {`);
1950
- 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();`);
1951
1909
  lines.push(` let row = ${call};`);
1952
1910
  lines.push(` *slot_${s}.lock().unwrap() = Some(row);`);
1953
1911
  lines.push(` }`);
@@ -1963,7 +1921,7 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1963
1921
  const meta = metas[i];
1964
1922
  const s = sanitize(node.id);
1965
1923
  const ref = typedNodes.get(node.id);
1966
- lines.push(` if ports_${s}.is_some() {`);
1924
+ lines.push(` if payload_${s}.is_some() {`);
1967
1925
  lines.push(` let out_${s} = slot_${s}.lock().unwrap().take().expect("runnable member wrote its slot");`);
1968
1926
  if (meta.policy === "continue") {
1969
1927
  // continue: a failed member (leaf failure OR de-box mismatch) commits no Port (defensive — covered
@@ -2017,9 +1975,7 @@ isAsync = false) {
2017
1975
  // skipped elements instead. Byte-equal to run_behavior's applyInto keep-with-null.
2018
1976
  const keepWithNull = hasGuard && hasInto;
2019
1977
  const s = sanitize(node.id);
2020
- const structName = portsStructName(comp.name, node.id);
2021
- const batch = `${structName}Batch`;
2022
- const leafSym = resolveLeafSymbol(m.component, leaf);
1978
+ const leafSym = resolveLeafSymbol(m.component, leaf, m.leafSymbol);
2023
1979
  // #108: over element type + the OWNED over-Vec expression (prior-node arr OR input array w/ elemType).
2024
1980
  const { elemRef: overElemRef, overExpr, optArr: overOptArr } = mapOverElemInfo(comp, node, typedNodes, plan);
2025
1981
  const elemMat = mapElemMaterializerName(comp.name, node.id);
@@ -2033,19 +1989,32 @@ isAsync = false) {
2033
1989
  // mismatch fails closed regardless of elementPolicy (matching the interpreter's whole-node outType throw).
2034
1990
  const elemDeBoxRef = mapElemRowRef(node, elemArrRef, plan);
2035
1991
  const renderElemDeBox = (il) => renderResultDeBox(elemDeBoxRef, `er_${s}`, node.id, plan, il, returnErrFail, nodeWirePassthrough(node));
2036
- // build the per-element CONCRETE native ports struct. `il` = indent inside the element loop.
2037
- const buildPorts = (il) => {
2038
- const out = [];
2039
- const inits = [];
1992
+ // #177/#182 keep-with-skip-value: the into value for a guard-skipped element is driven by relationKind,
1993
+ // NOT by opt-ness (matching run_behavior applyInto, which fills a connection into with the empty
1994
+ // connection UNCONDITIONALLY on relationKind==="connection"):
1995
+ // - connection into → the connection-zero in the field's typed rep (same shape emitProducedAwareValue
1996
+ // uses for a skipped connection node): a required `Conn` field → `Conn::default()`, an OPT
1997
+ // `Option<Conn>` field → `Some(Conn::default())` (empty connection, NOT None). `Conn::default()`'s
1998
+ // derived Default serializes to {items:[],cursor:null} (#182).
1999
+ // - non-connection into → opt → None = null (#177 keep-with-null; unchanged).
2000
+ const intoSkipDefault = m.relationKind === "connection"
2001
+ ? elemDeBoxRef.kind === "opt"
2002
+ ? `Some(${renderTypeRef(elemDeBoxRef.inner)}::default())`
2003
+ : `${renderTypeRef(elemDeBoxRef)}::default()`
2004
+ : elemDeBoxRef.kind === "opt"
2005
+ ? "None"
2006
+ : `${renderTypeRef(elemDeBoxRef)}::default()`;
2007
+ // the per-element boxed port entries (#183) — the SAME box SSoT as a point node, over the $as element.
2008
+ const portFields = () => {
2040
2009
  const asBinding = { name: asName, ref: overElemRef, plan };
2041
2010
  // #170: a guarded map narrows its `when(ne($e.key,null))`-proven element key non-null in kept elements.
2042
2011
  const narrowed = nodeNarrowedPaths(comp, node);
2043
- for (const pn of portNames) {
2044
- inits.push(emitPortInit(pn, m.ports[pn], comp, plan, typedNodes, priorHere, inputPortTypeRef(m.portSchemas?.[pn], plan), { asBinding, asBase: `oel_${s}`, narrowed }));
2045
- }
2046
- out.push(`${il}let ep_${s} = ${structName} { ${inits.join(", ")} };`);
2047
- 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 }));
2048
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())};`];
2049
2018
  // #108 guard: compile `when` to a native bool over an element-scoped resolveHead ($as element value,
2050
2019
  // prior node, input port). mkGuard returns the compiled {stmts, expr} (or null when unguarded); the
2051
2020
  // keep-with-null batched path consumes it directly to branch instead of skipping.
@@ -2088,14 +2057,14 @@ isAsync = false) {
2088
2057
  // zips its next deboxed row, a skipped element gets into=None. Byte-equal to run_behavior: batched
2089
2058
  // keptIdx-aligned collect + applyInto (skipped element unaugmented → opt-into null).
2090
2059
  const g = mkGuard();
2091
- 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());`);
2092
2061
  lines.push(`${indent}let mut keep_${s}: Vec<bool> = Vec::with_capacity(over_${s}.len());`);
2093
2062
  lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
2094
2063
  for (const st of g.stmts)
2095
2064
  lines.push(`${indent} ${st}`);
2096
2065
  lines.push(`${indent} let __keep = ${rustStripOuterParens(g.expr)};`);
2097
2066
  lines.push(`${indent} if __keep {`);
2098
- for (const l of buildPorts(indent + " "))
2067
+ for (const l of buildBatchElem(indent + " "))
2099
2068
  lines.push(l);
2100
2069
  lines.push(`${indent} items_${s}.push(ep_${s});`);
2101
2070
  lines.push(`${indent} keep_${s}.push(true);`);
@@ -2106,15 +2075,17 @@ isAsync = false) {
2106
2075
  lines.push(`${indent}let mut decs_${s}: Vec<${renderTypeRef(elemDeBoxRef)}> = Vec::with_capacity(items_${s}.len());`);
2107
2076
  lines.push(`${indent}if !items_${s}.is_empty() {`);
2108
2077
  lines.push(`${indent} let want_${s} = items_${s}.len();`);
2109
- lines.push(`${indent} let bp_${s} = ${batch} { items: items_${s} };`);
2110
- 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} {`);
2111
2081
  lines.push(`${indent} Ok(r) => r,`);
2112
2082
  lines.push(`${indent} Err(e) => return Err(op_failed(${rustStrLit(node.id)}, "fail", e)),`);
2113
2083
  lines.push(`${indent} };`);
2114
- 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} {`);
2115
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})));`);
2116
2087
  lines.push(`${indent} }`);
2117
- lines.push(`${indent} for er_${s} in row_${s}.into_iter() {`);
2088
+ lines.push(`${indent} for er_${s} in rows_${s}.into_iter() {`);
2118
2089
  lines.push(`${indent} let dec_${s} = ${renderElemDeBox(`${indent} `)};`);
2119
2090
  lines.push(`${indent} decs_${s}.push(dec_${s});`);
2120
2091
  lines.push(`${indent} }`);
@@ -2125,19 +2096,19 @@ isAsync = false) {
2125
2096
  lines.push(`${indent} let dec_${s} = decs_iter_${s}.next().expect("aligned kept row");`);
2126
2097
  lines.push(`${indent} built_${s}.push(${elemMat}(oel_${s}, dec_${s}));`);
2127
2098
  lines.push(`${indent} } else {`);
2128
- lines.push(`${indent} built_${s}.push(${elemMat}(oel_${s}, None));`);
2099
+ lines.push(`${indent} built_${s}.push(${elemMat}(oel_${s}, ${intoSkipDefault}));`);
2129
2100
  lines.push(`${indent} }`);
2130
2101
  lines.push(`${indent}}`);
2131
2102
  }
2132
2103
  else if (batched) {
2133
2104
  // build kept-element ports (+ kept over elements for into). Batched into is never guarded (rejected).
2134
- 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());`);
2135
2106
  if (hasInto)
2136
2107
  lines.push(`${indent}let mut kept_${s}: Vec<${renderTypeRef(overElemRef)}> = Vec::with_capacity(over_${s}.len());`);
2137
2108
  lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
2138
2109
  for (const l of emitGuard(indent + " "))
2139
2110
  lines.push(l);
2140
- for (const l of buildPorts(indent + " "))
2111
+ for (const l of buildBatchElem(indent + " "))
2141
2112
  lines.push(l);
2142
2113
  lines.push(`${indent} items_${s}.push(ep_${s});`);
2143
2114
  if (hasInto)
@@ -2145,21 +2116,19 @@ isAsync = false) {
2145
2116
  lines.push(`${indent}}`);
2146
2117
  lines.push(`${indent}if !items_${s}.is_empty() {`);
2147
2118
  lines.push(`${indent} let want_${s} = items_${s}.len();`);
2148
- lines.push(`${indent} let bp_${s} = ${batch} { items: items_${s} };`);
2149
- // DIRECT transport call — the batched dispatch takes the CONCRETE batch ports struct (shape unchanged
2150
- // from the removed trait method; only the call target changes). Returns the aligned per-element wires
2151
- // (Vec<Wire>). No `bound` (batched maps carry none).
2152
- 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} {`);
2153
2121
  lines.push(`${indent} Ok(r) => r,`);
2154
2122
  lines.push(`${indent} Err(e) => return Err(op_failed(${rustStrLit(node.id)}, "fail", e)),`);
2155
2123
  lines.push(`${indent} };`);
2156
- 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} {`);
2157
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})));`);
2158
2127
  lines.push(`${indent} }`);
2159
2128
  if (hasInto) {
2160
2129
  // zip the aligned per-element WIRES onto each KEPT over element: de-box the element wire strictly
2161
2130
  // (into the `into` field's type) then materialize the augmented element.
2162
- 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();`);
2163
2132
  lines.push(`${indent} for over_el_${s} in kept_${s}.iter() {`);
2164
2133
  lines.push(`${indent} let er_${s} = rows_iter_${s}.next().expect("aligned batch row");`);
2165
2134
  lines.push(`${indent} let dec_${s} = ${renderElemDeBox(`${indent} `)};`);
@@ -2168,7 +2137,7 @@ isAsync = false) {
2168
2137
  }
2169
2138
  else {
2170
2139
  // no-into: de-box each aligned per-element wire DIRECTLY into the element (result = kept elements).
2171
- lines.push(`${indent} for er_${s} in row_${s}.into_iter() {`);
2140
+ lines.push(`${indent} for er_${s} in rows_${s}.into_iter() {`);
2172
2141
  lines.push(`${indent} let el_${s} = ${renderElemDeBox(`${indent} `)};`);
2173
2142
  lines.push(`${indent} built_${s}.push(el_${s});`);
2174
2143
  lines.push(`${indent} }`);
@@ -2178,18 +2147,18 @@ isAsync = false) {
2178
2147
  else {
2179
2148
  // #93 shape 2 / #108: NON-batched map — dispatch ONCE PER KEPT ELEMENT.
2180
2149
  lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
2181
- // #177 keep-with-null: a guard-skipped element is KEPT with into=None instead of dropped — byte-equal
2182
- // to run_behavior's applyInto pass-through + opt-into null.
2183
- const nonBatchedSkip = keepWithNull ? `built_${s}.push(${elemMat}(oel_${s}, None)); continue;` : "continue;";
2150
+ // #177/#182 keep-with-skip-value: a guard-skipped element is KEPT with into=intoSkipDefault (None /
2151
+ // Conn::default()) instead of dropped — byte-equal to run_behavior's applyInto (opt-into → null /
2152
+ // connection-into → empty connection).
2153
+ const nonBatchedSkip = keepWithNull ? `built_${s}.push(${elemMat}(oel_${s}, ${intoSkipDefault})); continue;` : "continue;";
2184
2154
  for (const l of emitGuard(indent + " ", nonBatchedSkip))
2185
2155
  lines.push(l);
2186
- for (const l of buildPorts(indent + " "))
2156
+ for (const l of buildPayloadElem(indent + " "))
2187
2157
  lines.push(l);
2188
2158
  // Element Error Policy (scp-error.md): `skip` drops the failing element and proceeds (order is
2189
2159
  // preserved; the leaf keeps the Error Value it produced). `error` (default) promotes the element
2190
- // Failure to the map's Component Failure, carrying the leaf's detail through. DIRECT transport call —
2191
- // the element ports fields spread (resolved with the `$as` binding, exactly the element ports struct).
2192
- 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} {`);
2193
2162
  lines.push(`${indent} Ok(r) => r,`);
2194
2163
  if (m.elementPolicy === "skip") {
2195
2164
  lines.push(`${indent} Err(_) => continue,`);
@@ -2226,9 +2195,7 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
2226
2195
  const f = node.fanout;
2227
2196
  const awaitSfx = isAsync ? ".await" : "";
2228
2197
  const s = sanitize(node.id);
2229
- const structName = portsStructName(comp.name, node.id);
2230
- const batch = `${structName}Batch`;
2231
- const leafSym = resolveLeafSymbol(f.component, leaf);
2198
+ const leafSym = resolveLeafSymbol(f.component, leaf, f.leafSymbol);
2232
2199
  const connRef = typedNodes.get(node.id);
2233
2200
  const elemRef = fanoutItemsElemRef(node, connRef, plan);
2234
2201
  const elemName = renderTypeRef(elemRef);
@@ -2243,13 +2210,11 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
2243
2210
  if (!dkField || dkField.type.kind !== "scalar" || dkField.type.scalar !== "string")
2244
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}'.`);
2245
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.
2246
2214
  const buildPorts = (il) => {
2247
- const inits = [];
2248
2215
  const asBinding = { name: asName, ref: overElemRef, plan };
2249
- for (const pn of portNames) {
2250
- inits.push(emitPortInit(pn, f.ports[pn], comp, plan, typedNodes, priorHere, inputPortTypeRef(f.portSchemas?.[pn], plan), { asBinding, asBase: `oel_${s}` }));
2251
- }
2252
- 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(", ")}] });`];
2253
2218
  };
2254
2219
  const lines = [];
2255
2220
  const closers = [];
@@ -2262,7 +2227,7 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
2262
2227
  }
2263
2228
  lines.push(`${indent}let over_${s} = ${rustBindOverExpr(overExpr, overOptArr)};`);
2264
2229
  lines.push(`${indent}let mut built_${s}: Vec<${elemName}> = Vec::new();`);
2265
- 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());`);
2266
2231
  lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
2267
2232
  for (const l of buildPorts(indent + " "))
2268
2233
  lines.push(l);
@@ -2270,28 +2235,27 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
2270
2235
  lines.push(`${indent}}`);
2271
2236
  lines.push(`${indent}if !pi_${s}.is_empty() {`);
2272
2237
  lines.push(`${indent} let want_${s} = pi_${s}.len();`);
2273
- lines.push(`${indent} let bp_${s} = ${batch} { items: pi_${s} };`);
2274
- // DIRECT transport call — the batched fanout dispatch takes the CONCRETE batch ports struct (shape
2275
- // unchanged; only the call target changes). Returns the aligned per-id element wires
2276
- // (Vec<Option<Wire>> — None = a DANGLING id). No `bound`.
2277
- 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} {`);
2278
2241
  lines.push(`${indent} Ok(r) => r,`);
2279
2242
  lines.push(`${indent} Err(e) => return Err(op_failed(${rustStrLit(node.id)}, "fail", e)),`);
2280
2243
  lines.push(`${indent} };`);
2281
- // the handler returns the aligned per-id element WIRES (Vec<Option<Self::Wire>>); each present body is
2282
- // de-boxed strictly INLINE (a de-box mismatch fails closed). A DANGLING id is None → the zero element
2283
- // (empty dedupeKey), which the dangling drop excludes.
2284
- 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} {`);
2285
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})));`);
2286
2249
  lines.push(`${indent} }`);
2287
2250
  // ── THE ONE dedupe/drop (mirrors fanoutDedupDrop verbatim): first-seen dedupe by dedupeKey field;
2288
2251
  // drop dangling (empty dedupeKey ≡ interpreter's null/absent-key body); implicitSource strip is
2289
2252
  // structural (the elem type already omits it). cursor is always None (connection wrap).
2290
2253
  lines.push(`${indent} let mut seen_${s}: std::collections::HashSet<String> = std::collections::HashSet::new();`);
2291
- lines.push(`${indent} for opt_er_${s} in row_${s}.into_iter() {`);
2292
- lines.push(`${indent} let el_${s}: ${elemName} = match opt_er_${s} {`);
2293
- lines.push(`${indent} Some(wire_${s}) => ${renderResultDeBox(elemRef, `wire_${s}`, node.id, plan, `${indent} `, returnErrFail, nodeWirePassthrough(node))},`);
2294
- 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))}`);
2295
2259
  lines.push(`${indent} };`);
2296
2260
  lines.push(`${indent} let key_${s} = el_${s}.${dkRust}.clone();`);
2297
2261
  if (f.drop === "dangling") {
@@ -2460,56 +2424,29 @@ fn leaf_failure(message: impl Into<String>) -> BehaviorError {
2460
2424
  BehaviorError::new("LEAF_FAILURE", message)
2461
2425
  }`;
2462
2426
  // ── module assembly ──────────────────────────────────────────────────────────────────
2463
- /** isCrossPackageSharedNode (#165, rust twin of the go predicate) — a node whose ports struct CROSSES the
2464
- * leaf-transport boundary as a whole value (the batch ports struct passed to the transport), so under
2465
- * --shared-types-import it must live in the SHARED crate/module (else the transport crate → covered crate
2466
- * import cycle). Batched maps + fanouts pass a batch struct; every other node passes only primitive port
2467
- * fields, so its ports struct stays local. The SINGLE predicate emit() (skip-local) and
2468
- * {@link rustSharedWireTypesModule} (emit-there) both use — they never disagree (SSoT). */
2469
- function isCrossPackageSharedNode(n) {
2470
- return "fanout" in n || ("map" in n && n.map.batched === true);
2471
- }
2472
2427
  /**
2473
2428
  * rustSharedWireTypesModule (#165, rust twin of goSharedWireTypesPackage) — the BC-GENERATED shared module
2474
2429
  * content emitted when the covered module is generated with --shared-types-import. Carries the SAME wire seam
2475
2430
  * the covered module emits in-crate when the flag is absent (Probe/NumProbe + WireValue/WireRow/WireList +
2476
- * the probe classifiers) so a separate leaf-transport crate can build+return `WireValue` (and the covered
2477
- * module reference it) without an import cycle. When `ir` is given, ALSO emits the batched-map / fanout batch
2478
- * ports structs (the ONLY covered-module types that cross the transport boundary as a whole value) — same
2479
- * emitMapPortsStructs / emitFanoutPortsStructs + same {@link isCrossPackageSharedNode} predicate emit()
2480
- * skip-local uses, so the two never disagree (SSoT). The wire types derive Clone (a cross-crate transport +
2481
- * the #164 passthrough store clone them). Self-contained + runtime-free — drop it in the shared crate's
2482
- * lib.rs (a separate crate) or a module. `pub use` re-exports keep every name reachable unqualified. */
2483
- export function rustSharedWireTypesModule(ir) {
2484
- const portsStructs = [];
2485
- if (ir !== undefined) {
2486
- const components = ir.components;
2487
- const plan = buildTypePlan(ir);
2488
- for (const c of components.filter(isNativeRaw)) {
2489
- const typedNodes = buildTypedNodes(c, plan);
2490
- for (const n of c.body) {
2491
- if (!isCrossPackageSharedNode(n))
2492
- continue;
2493
- portsStructs.push("fanout" in n ? emitFanoutPortsStructs(c, n, typedNodes, plan) : emitMapPortsStructs(c, n, typedNodes, plan));
2494
- }
2495
- }
2496
- }
2497
- const portsSection = portsStructs.length
2498
- ? `\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")}`
2499
- : "";
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() {
2500
2437
  return `#![allow(dead_code, unused_imports, non_snake_case)]
2501
2438
  // GENERATED by behavior-contracts (rust-typed-native) — the BC-OWNED shared wire types (#165). A covered
2502
2439
  // module generated with --shared-types-import imports these (\`use <path>::*;\`); a separate leaf-transport
2503
- // crate builds + returns the SAME \`WireValue\` (and, on failure, the SAME \`BehaviorError\`). The concrete
2504
- // failure type lives here too so the transport crate returns \`Result<WireValue, BehaviorError>\` WITHOUT
2505
- // importing the covered crate (unlike go's \`error\` interface, rust's runner reads the concrete
2506
- // \`.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.
2507
2444
 
2508
2445
  // Local concrete failure type (runtime-free) — the covered runner + the transport crate share it. Only the
2509
2446
  // TYPE lives here; the de-box/op-failure CONSTRUCTORS stay in the covered module (they are called there).
2510
2447
  ${emitErrorTypeDefs()}
2511
2448
 
2512
- ${emitRustProbeWireTypes(true)}${portsSection}
2449
+ ${emitRustProbeWireTypes(true)}
2513
2450
  `;
2514
2451
  }
2515
2452
  function emit(ctx) {
@@ -2555,7 +2492,6 @@ ${emitStructSurface([])}
2555
2492
  // #108: reset the native-expr helper-usage accumulator (set by the cond/guard compiler).
2556
2493
  rustExprUsed.helpers = false;
2557
2494
  const leaf = ctx.leafTransport;
2558
- const structs = [];
2559
2495
  const inStructs = [];
2560
2496
  const elemMaterializers = [];
2561
2497
  // every covered node returns a WireValue the inline de-box classifies — the wire seam (probe enums +
@@ -2574,33 +2510,16 @@ ${emitStructSurface([])}
2574
2510
  for (const n of c.body)
2575
2511
  if (!isControlGate(n))
2576
2512
  typedNodes.set(n.id, "map" in n ? mapNodeArrRef(n, plan) : deriveTypeRef(n.outType, plan)); // #125: control-gate typeless; map は produced-array ref に正規化
2577
- for (const n of c.body) {
2578
- // #165: a cross-package batch ports struct (batched map / fanout) is emitted in the SHARED module
2579
- // instead (rustSharedWireTypesModule), referenced here via the `use <path>::*;` glob — skip local.
2580
- if (crossPackage && isCrossPackageSharedNode(n))
2581
- continue;
2582
- if ("fanout" in n)
2583
- structs.push(emitFanoutPortsStructs(c, n, typedNodes, plan));
2584
- else if ("map" in n)
2585
- structs.push(emitMapPortsStructs(c, n, typedNodes, plan));
2586
- else if ("cond" in n) {
2587
- // #108: a cond node has NO ports struct (pure Expression — no handler dispatch).
2588
- }
2589
- else
2590
- 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.
2591
- }
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.
2592
2515
  inStructs.push(emitInStruct(c, plan));
2593
2516
  const mm = emitMapElemMaterializers(c, typedNodes, plan);
2594
2517
  if (mm)
2595
2518
  elemMaterializers.push(mm);
2596
2519
  }
2597
- // bc#156/#160: WireValue lands in a Clone-deriving ports struct (the cloning port init + bc#87 parallel
2598
- // dispatch require WireValue: Clone) whenever a node port lowers to `value`/`value[]` — a `value` input
2599
- // port wired through, a `{arr:[value,…]}` array-literal, or an empty `{arr:[]}` params list (bc#160).
2600
- // The ports structs are the ONLY Clone-deriving WireValue-bearing structs (input structs derive Default;
2601
- // outType decls never carry `value` — input-only), so their rendered field types are the total SSoT
2602
- // signal. A value-free module omits the derive to stay byte-identical to pre-#156.
2603
- 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.
2604
2523
  const runners = native.map((c) => emitNativeRawRunner(c, plan, asyncPlans.get(c.name), leaf)).join("\n\n");
2605
2524
  const structSurface = emitStructSurface(native);
2606
2525
  // Leaf transport import (SSoT resolution via resolveLeafSymbol): if the consumer names an import module,
@@ -2665,12 +2584,9 @@ use std::cell::RefCell;`;
2665
2584
  rustExprUsed.helpers
2666
2585
  ? `// #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()}`
2667
2586
  : undefined,
2668
- structs.some((r) => r.trim().length > 0)
2669
- ? `// 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")}`
2670
- : undefined,
2671
2587
  `// CONCRETE per-component input structs (fields = inputPorts).\n${inStructs.join("\n\n")}`,
2672
2588
  emitsWireTypes
2673
- ? `// 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)}`
2589
+ ? `// 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)}`
2674
2590
  : undefined,
2675
2591
  elemMaterializers.length
2676
2592
  ? `// map augmented-element copiers (pure struct field assignment — no dynamic value read).\n${elemMaterializers.join("\n\n")}`
@@ -2735,10 +2651,14 @@ fn value_to_wire(v: &Value) -> WireValue {
2735
2651
  // returning the scripted wire in EXACTLY the shape the removed per-node trait method returned. bc#87
2736
2652
  // parallel scoped threads share the static (Mutex-guarded); cases run sequentially so a shared static is
2737
2653
  // fine. Echo (#129/#141) reads the spread port params directly. ──
2654
+ // ONE free transport per DISTINCT SPEC-fixed SYMBOL (#176/#183), UNIFORM signature
2655
+ // `<sym>(payload: WireRow) -> Result<WireValue, BehaviorError>`: value_to_wire is recursive, so a
2656
+ // batched/fanout `Value::Arr` result becomes a `WireValue::List` (a `Value::Null` element → WireValue::Null,
2657
+ // the dangling marker) and a single result a scalar/row wire — ONE signature serves every cardinality. Echo
2658
+ // (#129/#141) reads the port back FROM THE PAYLOAD BY NAME. A spec-named leaf used in MULTIPLE roles is
2659
+ // emitted ONCE; two nodes → same symbol but DIFFERENT catalog is a LOUD collision (never silent).
2738
2660
  const transportFns = [];
2739
- const emittedLeaf = new Set();
2740
- 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 }`;
2741
- const spreadParams = (spread) => spread.map((p) => `${p.field}: ${p.isCopy ? p.renderedType : `&${p.renderedType}`}`).join(", ");
2661
+ const bySym = new Map();
2742
2662
  for (const c of native) {
2743
2663
  const ap = asyncPlans.get(c.name);
2744
2664
  const typedNodes = new Map();
@@ -2749,98 +2669,71 @@ fn value_to_wire(v: &Value) -> WireValue {
2749
2669
  if ("cond" in n)
2750
2670
  continue; // #108: a cond node has no leaf (pure Expression) — no transport fn.
2751
2671
  const catalog = "fanout" in n ? n.fanout.component : "map" in n ? n.map.component : n.component;
2752
- if (emittedLeaf.has(catalog))
2753
- continue; // per-module a leaf has ONE consistent shape — emit once.
2754
- emittedLeaf.add(catalog);
2755
- const sym = resolveLeafSymbol(catalog, leaf);
2756
- // async iff this catalog leaf's terminal handler is async (consistent per catalog component).
2757
- const fnKw = ap.nodeIsAsync(n.id) ? "pub async fn" : "pub fn";
2758
- if ("fanout" in n) {
2759
- // fanout: return the aligned per-id element WIRES (Vec<Option<WireValue>>); a null aligned
2760
- // body is a DANGLING id → None (the covered runner maps it to the zero element).
2761
- const portsT = `${portsStructName(c.name, n.id)}Batch`;
2762
- transportFns.push(`${fnKw} ${sym}(_batch: &${portsT}) -> Result<Vec<Option<WireValue>>, BehaviorError> {
2763
- ${drainStmt(catalog, "_echo")}
2764
- let arr = match ok { Some(Value::Arr(a)) => a, _ => Vec::new() };
2765
- let wires = arr
2766
- .into_iter()
2767
- .map(|ev| match ev {
2768
- Value::Null => None,
2769
- _ => Some(value_to_wire(&ev)),
2770
- })
2771
- .collect();
2772
- Ok(wires)
2773
- }`);
2774
- continue;
2775
- }
2776
- if ("map" in n) {
2777
- // map: batched → one WIRE per element (Vec<WireValue>); non-batched → one element WIRE.
2778
- const m = n.map;
2779
- if (m.batched === true) {
2780
- const portsT = `${portsStructName(c.name, n.id)}Batch`;
2781
- transportFns.push(`${fnKw} ${sym}(_batch: &${portsT}) -> Result<Vec<WireValue>, BehaviorError> {
2782
- ${drainStmt(catalog, "_echo")}
2783
- let arr = match ok { Some(Value::Arr(a)) => a, _ => Vec::new() };
2784
- let wires = arr.iter().map(value_to_wire).collect();
2785
- Ok(wires)
2786
- }`);
2787
- }
2788
- else {
2789
- const { elemRef: overElemRef } = mapOverElemInfo(c, n, typedNodes, plan);
2790
- const params = spreadParams(portFieldSpread(m.ports, m.portSchemas, c, plan, typedNodes, { name: m.as, ref: overElemRef, plan }, nodeNarrowedPaths(c, n)));
2791
- transportFns.push(`${fnKw} ${sym}(${params}) -> Result<WireValue, BehaviorError> {
2792
- ${drainStmt(catalog, "_echo")}
2793
- Ok(value_to_wire(&ok.unwrap_or(Value::Null)))
2794
- }`);
2795
- }
2796
- continue;
2797
- }
2798
- // componentRef (point read): spread port fields; supports echo (#129/#141) reading the port params.
2799
- const node = n;
2800
- // #170: the observe transport fn's param types must match the covered module's leaf call args, which
2801
- // narrow a gate-proven opt key — so this reads the SAME node narrowing.
2802
- const crNarrowed = nodeNarrowedPaths(c, node);
2803
- const ref = typedNodes.get(n.id);
2804
- const echoBranches = [];
2805
- if (ref.kind === "named") {
2806
- const decl = findDecl(plan, ref.name);
2807
- const field = decl !== undefined && decl.fields.length === 1 ? decl.fields[0] : undefined;
2808
- const fieldRust = field !== undefined ? renderTypeRef(field.type) : null;
2809
- const recordRust = renderTypeRef(ref);
2810
- for (const pn of Object.keys(node.ports)) {
2811
- let portRust = null;
2812
- try {
2813
- portRust = portFieldRustType(node.ports[pn], c, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[pn], plan), `echo port '${pn}'`, { narrowed: crNarrowed });
2814
- }
2815
- catch {
2816
- portRust = null;
2817
- }
2818
- if (portRust === recordRust) {
2819
- // the port IS the whole record → echo it DIRECTLY (matching run_behavior's plain echo:port).
2820
- const own = typeRefIsCopy(ref) ? `${portFieldName(pn)}` : `${portFieldName(pn)}.clone()`;
2821
- echoBranches.push(` if echo == ${rustStrLit(pn)} {\n let tv = ${own};\n return Ok(value_to_wire(&${serializeTyped("tv", ref, plan)}));\n }`);
2822
- }
2823
- else if (fieldRust !== null && field !== undefined && portRust === fieldRust) {
2824
- // a scalar port wraps into the record's single field ({v: ports.X}).
2825
- const own = typeRefIsCopy(field.type) ? `${portFieldName(pn)}` : `${portFieldName(pn)}.clone()`;
2826
- 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 }`);
2672
+ const specSym = "fanout" in n ? n.fanout.leafSymbol : "map" in n ? n.map.leafSymbol : n.leafSymbol;
2673
+ const sym = resolveLeafSymbol(catalog, leaf, specSym);
2674
+ const isAsync = ap.nodeIsAsync(n.id);
2675
+ // echo branches (point/componentRef nodes only — a batched/fanout node returns a WireList, not a port).
2676
+ const echo = [];
2677
+ if (!("fanout" in n) && !("map" in n)) {
2678
+ const node = n;
2679
+ const crNarrowed = nodeNarrowedPaths(c, node);
2680
+ const ref = typedNodes.get(n.id);
2681
+ if (ref.kind === "named") {
2682
+ const decl = findDecl(plan, ref.name);
2683
+ const field = decl !== undefined && decl.fields.length === 1 ? decl.fields[0] : undefined;
2684
+ const fieldRust = field !== undefined ? renderTypeRef(field.type) : null;
2685
+ const recordRust = renderTypeRef(ref);
2686
+ for (const pn of Object.keys(node.ports)) {
2687
+ let portRust = null;
2688
+ try {
2689
+ portRust = portFieldRustType(node.ports[pn], c, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[pn], plan), `echo port '${pn}'`, { narrowed: crNarrowed });
2690
+ }
2691
+ catch {
2692
+ portRust = null;
2693
+ }
2694
+ if (portRust === recordRust) {
2695
+ // the port IS the whole record → echo its payload wire DIRECTLY (matching run_behavior's echo:port).
2696
+ 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 }`);
2697
+ }
2698
+ else if (fieldRust !== null && field !== undefined && portRust === fieldRust) {
2699
+ // a scalar port wraps into the record's single field ({v: <port wire>}) — mirrors the scripted `wrap`.
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(WireValue::Row(WireRow { entries: vec![(${rustStrLit(field.name)}.to_string(), v.clone())] }));\n }\n }`);
2701
+ }
2827
2702
  }
2828
2703
  }
2704
+ else if (ref.kind === "arr" && Object.prototype.hasOwnProperty.call(node.ports, "items")) {
2705
+ // #129: an arr node with an `items` port echoes the payload's items wire (a WireList) so the
2706
+ // node→leaf array dataflow test is non-vacuous.
2707
+ 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 }`);
2708
+ }
2829
2709
  }
2830
- else if (ref.kind === "arr" && Object.prototype.hasOwnProperty.call(node.ports, "items")) {
2831
- // #129: an arr node with an `items` port echoes the NATIVE port array (serialized element-by-element
2832
- // into a Value::Arr) so the node→leaf array dataflow test is non-vacuous.
2833
- const elemRef = ref.elem;
2834
- 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 }`);
2710
+ const prev = bySym.get(sym);
2711
+ if (prev !== undefined) {
2712
+ // #176/#183: a spec-fixed symbol MUST map to exactly ONE leaf. The same leaf in multiple roles shares
2713
+ // ONE transport — accumulate its echo branches. Two DIFFERENT catalog components → same symbol is a
2714
+ // codegen error (never silent).
2715
+ if (prev.catalog !== catalog)
2716
+ 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).`);
2717
+ for (const e of echo)
2718
+ if (!prev.echo.includes(e))
2719
+ prev.echo.push(e);
2720
+ continue;
2835
2721
  }
2836
- const canEcho = echoBranches.length > 0;
2837
- const params = spreadParams(portFieldSpread(node.ports, node.portSchemas, c, plan, typedNodes, undefined, crNarrowed));
2838
- const echoBlock = canEcho ? `${echoBranches.join("\n")}\n` : "";
2839
- transportFns.push(`${fnKw} ${sym}(${params}) -> Result<WireValue, BehaviorError> {
2840
- ${drainStmt(catalog, canEcho ? "echo" : "_echo")}
2722
+ bySym.set(sym, { catalog, async: isAsync, echo });
2723
+ }
2724
+ }
2725
+ for (const [sym, le] of bySym) {
2726
+ const fnKw = le.async ? "pub async fn" : "pub fn";
2727
+ const hasEcho = le.echo.length > 0;
2728
+ const echoBind = hasEcho ? "echo" : "_echo";
2729
+ const echoBlock = hasEcho ? `${le.echo.join("\n")}\n` : "";
2730
+ transportFns.push(`${fnKw} ${sym}(${hasEcho ? "payload" : "_payload"}: WireRow) -> Result<WireValue, BehaviorError> {
2731
+ let (is_err, err, ok, ${echoBind}) = next_scripted(${rustStrLit(le.catalog)}).ok_or_else(|| unknown_component(${rustStrLit(le.catalog)}))?;
2732
+ if is_err {
2733
+ return Err(leaf_failure(err));
2734
+ }
2841
2735
  ${echoBlock} Ok(value_to_wire(&ok.unwrap_or(Value::Null)))
2842
2736
  }`);
2843
- }
2844
2737
  }
2845
2738
  const arms = native
2846
2739
  .map((c) => {