behavior-contracts 0.9.3 → 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 (58) 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.map +1 -1
  9. package/dist/bind.d.ts +1 -1
  10. package/dist/bind.d.ts.map +1 -1
  11. package/dist/builder.d.ts.map +1 -1
  12. package/dist/builder.js +21 -6
  13. package/dist/builder.js.map +1 -1
  14. package/dist/cli.js +65 -40
  15. package/dist/cli.js.map +1 -1
  16. package/dist/commands/codegen.d.ts +18 -12
  17. package/dist/commands/codegen.d.ts.map +1 -1
  18. package/dist/commands/codegen.js +111 -27
  19. package/dist/commands/codegen.js.map +1 -1
  20. package/dist/commands/ts-extract.d.ts +26 -0
  21. package/dist/commands/ts-extract.d.ts.map +1 -0
  22. package/dist/commands/ts-extract.js +265 -0
  23. package/dist/commands/ts-extract.js.map +1 -0
  24. package/dist/generated/commands.d.ts.map +1 -1
  25. package/dist/generated/commands.js +8 -0
  26. package/dist/generated/commands.js.map +1 -1
  27. package/dist/generated/contract.d.ts.map +1 -1
  28. package/dist/generated/contract.js +2 -2
  29. package/dist/generated/contract.js.map +1 -1
  30. package/dist/generated/program.d.ts +4 -0
  31. package/dist/generated/program.d.ts.map +1 -1
  32. package/dist/generated/program.js +7 -3
  33. package/dist/generated/program.js.map +1 -1
  34. package/dist/generated/types.d.ts +6 -2
  35. package/dist/generated/types.d.ts.map +1 -1
  36. package/dist/generator/emit-typed-native-go.d.ts +5 -7
  37. package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
  38. package/dist/generator/emit-typed-native-go.js +244 -404
  39. package/dist/generator/emit-typed-native-go.js.map +1 -1
  40. package/dist/generator/emit-typed-native-rust.d.ts +6 -8
  41. package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
  42. package/dist/generator/emit-typed-native-rust.js +234 -371
  43. package/dist/generator/emit-typed-native-rust.js.map +1 -1
  44. package/dist/guard.d.ts +23 -0
  45. package/dist/guard.d.ts.map +1 -1
  46. package/dist/guard.js +52 -0
  47. package/dist/guard.js.map +1 -1
  48. package/dist/index.d.ts +3 -32
  49. package/dist/index.d.ts.map +1 -1
  50. package/dist/index.js +10 -5
  51. package/dist/index.js.map +1 -1
  52. package/dist/ir-handle.d.ts +30 -0
  53. package/dist/ir-handle.d.ts.map +1 -0
  54. package/dist/ir-handle.js +2 -0
  55. package/dist/ir-handle.js.map +1 -0
  56. package/dist/provenance.d.ts +1 -1
  57. package/dist/provenance.d.ts.map +1 -1
  58. package/package.json +9 -1
@@ -432,6 +432,16 @@ func WireNull() WireValue { return WireValue{kind: wireNull} }
432
432
  func WireRowOf(fields []WireField) WireValue { return WireValue{kind: wireRow, Entries: fields} }
433
433
  func WireListOf(items []WireValue) WireValue { return WireValue{kind: wireList, Items: items} }
434
434
 
435
+ // WireRowOfFields — build a WireRow (the op-agnostic transport PAYLOAD type, #183) from named fields. The
436
+ // covered runner assembles the payload; the spec-named leaf transport reads its fields BY NAME
437
+ // (payload.ProbeString("PK") …), so divergent port SETS across roles are just different field lists in the
438
+ // SAME WireRow — ONE transport signature <Leaf>(payload WireRow) (WireValue, error) serves every role.
439
+ func WireRowOfFields(fields []WireField) WireRow { return WireRow{entries: fields} }
440
+
441
+ // IsNull — is this the wire null value? A batched/fanout transport returns a WireList of aligned results; a
442
+ // DANGLING fanout id is a WireNull element the covered runner detects here (drop:dangling) before de-box.
443
+ func (w WireValue) IsNull() bool { return w.kind == wireNull }
444
+
435
445
  func (w *WireValue) wireTag() string {
436
446
  switch w.kind {
437
447
  case wireStr:
@@ -576,16 +586,6 @@ function mapFanoutElemRef(node, typedNodes, plan) {
576
586
  return fanoutItemsElemRef(node, ref, plan);
577
587
  return mapElemRowRef(node, ref, plan);
578
588
  }
579
- function goPortFieldName(wire) {
580
- const safe = wire.replace(/[^A-Za-z0-9_]/g, "_");
581
- const head = safe.charAt(0);
582
- return /[a-z]/.test(head) ? head.toUpperCase() + safe.slice(1) : "F_" + safe;
583
- }
584
- function portsStructName(compName, nodeId) {
585
- // EXPORTED so a consumer (and the test bench, both in a DIFFERENT Go package) can name the ports type
586
- // in their leaf transport symbols (the batched/fanout transport takes the batch ports struct).
587
- return `PortsNR_${sanitize(compName)}_${nodeId.replace(/[^A-Za-z0-9_]/g, "_")}`;
588
- }
589
589
  /** scalar TypeRef → PortFieldType (native go scalar kind). */
590
590
  function goScalarPortField(scalar) {
591
591
  return scalar === "string" ? "string" : scalar === "int" ? "int64" : scalar === "float" ? "float64" : "bool";
@@ -1033,36 +1033,6 @@ function assertTypedCoverage(comp) {
1033
1033
  return;
1034
1034
  throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `go combined read (bc#77): component '${comp.name}' is a sequential componentRef read but lacks outType/outputType on every node — the combined emitter de-boxes the RESULT into the node's outType struct, so a covered read MUST be fully typed (bc#45). Add outType annotations, or regenerate on go-straightline-native (boxed result).`);
1035
1035
  }
1036
- // ── native ports struct + PortReader ──────────────────────────────────────────────────
1037
- function emitPortsStruct(comp, node, asBinding, plan, typedNodes, narrowed) {
1038
- const structName = portsStructName(comp.name, node.id);
1039
- const portNames = Object.keys(node.ports);
1040
- if (portNames.length === 0) {
1041
- return `// ${structName} — native ports for node '${node.id}' (${node.component}); no ports.\ntype ${structName} struct{}`;
1042
- }
1043
- // a node WITH ports always resolves through the one port lowering, which needs the type plan + the
1044
- // prior-node map (both are supplied by every caller — narrow the optional params for the fields below).
1045
- if (plan === undefined || typedNodes === undefined) {
1046
- throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `go typed-native: ports struct for node '${node.id}' needs a type plan + prior-node map`);
1047
- }
1048
- // #170: the field TYPE reads the SAME lowering (incl. gate/guard narrowing) the init does, so a narrowed
1049
- // opt-in-required port is a non-opt field AND a non-opt initializer — they can never disagree.
1050
- const portOpts = asBinding !== undefined ? { asBinding, asBase: asBinding.name, narrowed } : narrowed !== undefined ? { narrowed } : undefined;
1051
- const fieldTypes = portNames.map((p) => portFieldGoType(node.ports[p], comp, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[p], plan), `port '${p}' of node '${node.id}'`, portOpts));
1052
- const fieldNames = portNames.map(goPortFieldName);
1053
- const fields = portNames
1054
- .map((p, i) => `\t${fieldNames[i]} ${fieldTypes[i]} // ${JSON.stringify(p)}`)
1055
- .join("\n");
1056
- // NO PortReader `Port(name)` method: the covered handler reads the TYPED struct fields (ports.F_PK)
1057
- // DIRECTLY, so the boxed-Value PortReader impl (the last per-port `dslcontracts.Value` wrap on the
1058
- // covered plane) is DEAD — dropping it makes the ports struct fully native (bc#90 / runtime-free).
1059
- return `// ${structName} — NATIVE ports for node '${node.id}' (${node.component}). Typed fields per the
1060
- // static port type; built by direct field assignment (no map alloc, no per-port boxing). The consumer
1061
- // reads the typed fields DIRECTLY (no PortReader / boxed-Value accessor) — the covered read is native.
1062
- type ${structName} struct {
1063
- ${fields}
1064
- }`;
1065
- }
1066
1036
  /**
1067
1037
  * resolveLeafSymbol — the op-agnostic transport symbol a covered leaf (= catalog component) is called
1068
1038
  * through at its execution point. A consumer-supplied override (`leafTransport.symbols[component]`) wins;
@@ -1073,36 +1043,41 @@ ${fields}
1073
1043
  function goLeafSel(leaf) {
1074
1044
  return leaf?.import !== undefined ? `${leaf.import.split("/").pop().replace(/[^A-Za-z0-9_]/g, "_")}.` : "";
1075
1045
  }
1076
- /** leafSymbolBare — the UNQUALIFIED transport symbol name (consumer override or the default Leaf_<comp>).
1077
- * The ONE source for the name: call sites qualify it with the package selector (resolveLeafSymbol); the
1078
- * observe companion DEFINES the fn under this bare name (a definition carries no selector). */
1079
- function leafSymbolBare(component, leaf) {
1080
- return leaf?.symbols[component] ?? `Leaf_${sanitize(component)}`;
1046
+ /** leafSymbolBare — the UNQUALIFIED transport symbol name. Resolution order (#176): the SPEC-fixed
1047
+ * `node.leafSymbol` (from `defineLeaf` meta.transport, baked per node) FIRST, then the CLI
1048
+ * `--leaf-transport` override (`leaf.symbols[component]`), then the default `Leaf_<comp>`. The ONE source
1049
+ * for the name: call sites qualify it with the package selector (resolveLeafSymbol); the observe companion
1050
+ * DEFINES the fn under this bare name (a definition carries no selector). */
1051
+ function leafSymbolBare(component, leaf, specSymbol) {
1052
+ return specSymbol ?? leaf?.symbols[component] ?? `Leaf_${sanitize(component)}`;
1081
1053
  }
1082
- function resolveLeafSymbol(component, leaf) {
1083
- return `${goLeafSel(leaf)}${leafSymbolBare(component, leaf)}`;
1054
+ function resolveLeafSymbol(component, leaf, specSymbol) {
1055
+ return `${goLeafSel(leaf)}${leafSymbolBare(component, leaf, specSymbol)}`;
1056
+ }
1057
+ /** goWireQ — the shared-package selector qualifier (`wire.`) for the BC-owned wire ctors/types, or "" in-package. */
1058
+ function goWireQ(wireSel) {
1059
+ return wireSel !== undefined && wireSel !== "" ? `${wireSel}.` : "";
1084
1060
  }
1085
1061
  /**
1086
- * portFieldSpread — the covered node's port fields, in declared `Object.keys(ports)` order, each carrying
1087
- * its native ports-struct field name + Go type. The ONE place the transport-call port spread is derived
1088
- * (SSoT): a runner call site spreads `<var>.<F>`; the test observe transport fn declares matching params.
1089
- * Types come from the SAME `portFieldGoType` lowering `emitPortsStruct` uses, so the spread can never
1090
- * disagree with the ports struct field types. (Go has no borrow — every field is passed by value.)
1062
+ * goPayloadRow — assemble the op-agnostic transport payload `WireRow` from the node's boxed port `WireField`
1063
+ * entries (#183). The ONE place a transport payload is wrapped: every call site (point / map-element /
1064
+ * fanout-element / batched item) builds its fields via {@link emitPortWireField} and wraps them here. The
1065
+ * WireRow is the SOLE arg the spec-named leaf transport takes — divergent port SETS across roles are just
1066
+ * different field lists in the SAME WireRow shape (the #183 fix — no per-role positional signature).
1091
1067
  */
1092
- function portFieldSpread(ports, portSchemas, comp, plan, typedNodes, asBinding, narrowed) {
1093
- // #170: the transport-call spread reads the SAME lowering (incl. gate/guard narrowing) as the ports
1094
- // struct fields — a narrowed opt-in-required port is a non-opt arg, matching the non-opt struct field.
1095
- // #173: `expected` (declared port type from portSchemas) drives the SAME materialization the struct
1096
- // field type uses, so the spread arg type can never disagree with the field type.
1097
- const opts = asBinding !== undefined ? { asBinding, asBase: asBinding.name, narrowed } : narrowed !== undefined ? { narrowed } : undefined;
1098
- return Object.keys(ports).map((pn) => ({
1099
- field: goPortFieldName(pn),
1100
- goType: portFieldGoType(ports[pn], comp, plan, typedNodes, inputPortTypeRef(portSchemas?.[pn], plan), `port '${pn}' of node '${comp.name}'`, opts),
1101
- }));
1102
- }
1103
- /** leafCallArgs — the spread transport-call arguments for a ports-struct var (Go: by value, no borrow). */
1104
- function leafCallArgs(varExpr, spread) {
1105
- return spread.map((p) => `${varExpr}.${p.field}`).join(", ");
1068
+ function goPayloadRow(fields, wireSel) {
1069
+ const q = goWireQ(wireSel);
1070
+ return `${q}WireRowOfFields([]${q}WireField{${fields.join(", ")}})`;
1071
+ }
1072
+ /**
1073
+ * goPayloadBatch — the BATCHED/fanout transport payload: ONE WireRow `{items:[<per-element ports rows>…]}`
1074
+ * over an already-built `[]WireValue` of per-element WireRows (#183). Byte-equal to run_behavior's batched
1075
+ * handler contract `handler({items:[…]})`; the aligned result is a WireList the runner reads via `.Items`.
1076
+ * ONE signature covers single AND batched uses of the same spec-named leaf (the #183 "one write transport").
1077
+ */
1078
+ function goPayloadBatch(itemsExpr, wireSel) {
1079
+ const q = goWireQ(wireSel);
1080
+ return `${q}WireRowOfFields([]${q}WireField{{Key: "items", Val: ${q}WireListOf(${itemsExpr})}})`;
1106
1081
  }
1107
1082
  /** RunNativeRawStruct_<comp> — the EXPORTED name of the per-component struct-returning combined runner
1108
1083
  * (bc#102). It MUST be an exported Go identifier so a consumer in a DIFFERENT package can call it (a
@@ -1116,50 +1091,6 @@ function runnerName(compName) {
1116
1091
  function mapElemMaterializerName(compName, nodeId) {
1117
1092
  return `materializeMapElemNR_${sanitize(compName)}_${nodeId.replace(/[^A-Za-z0-9_]/g, "_")}`;
1118
1093
  }
1119
- /**
1120
- * emitMapPortsStructs — the per-element native ports struct + the batch struct for a covered map
1121
- * node (bc#90 / runtime-free). The element struct is the same shape as a componentRef ports struct
1122
- * (typed fields per the static port type). The batch struct carries `Items []<elemStruct>` — a NATIVE
1123
- * slice of the concrete per-element ports structs (NO `[]dslcontracts.Value`, NO PortReader accessor);
1124
- * the consumer reads `bp.Items[i].F_PK` directly.
1125
- */
1126
- function emitMapPortsStructs(comp, node, typedNodes, plan) {
1127
- const m = node.map;
1128
- const structName = portsStructName(comp.name, node.id);
1129
- // #108: the element ports may read the `$as` binding ($id / $g.field) — resolve the over element
1130
- // type so those ports type their struct field natively (map-over-input scalar element / prior-node
1131
- // struct element). A pure-static/concat port ignores the binding.
1132
- const { elemRef } = mapOverElemInfo(comp, node, typedNodes, plan);
1133
- const asBinding = { name: m.as, ref: elemRef, plan };
1134
- // #170: a guarded map (`when(ne($e.key,null))`) proves the element key non-null in kept elements — narrow it.
1135
- const elemStruct = emitPortsStruct(comp, { id: node.id, component: m.component, ports: m.ports, portSchemas: m.portSchemas }, asBinding, plan, typedNodes, nodeNarrowedPaths(comp, node));
1136
- const batchStruct = `${structName}_batch`;
1137
- return `${elemStruct}
1138
-
1139
- // ${batchStruct} — NATIVE batched ports for map '${node.id}': Items is a native slice of the concrete
1140
- // per-element ports structs (${structName}). The consumer reads Items[i].<Field> DIRECTLY — no boxed
1141
- // []Value, no PortReader accessor, no key-value object (bc#90 / runtime-free).
1142
- type ${batchStruct} struct {
1143
- Items []${structName}
1144
- }`;
1145
- }
1146
- /** emitFanoutPortsStructs (v3) — the per-body element ports struct + the batch struct for a covered
1147
- * fanout node (identical shape to a batched map's ports). The element ports read the `$as` id binding. */
1148
- function emitFanoutPortsStructs(comp, node, typedNodes, plan) {
1149
- const f = node.fanout;
1150
- const structName = portsStructName(comp.name, node.id);
1151
- const { elemRef } = fanoutOverElemInfo(comp, node, typedNodes, plan);
1152
- const asBinding = { name: f.as, ref: elemRef, plan };
1153
- const elemStruct = emitPortsStruct(comp, { id: node.id, component: f.component, ports: f.ports, portSchemas: f.portSchemas }, asBinding, plan, typedNodes);
1154
- const batchStruct = `${structName}_batch`;
1155
- return `${elemStruct}
1156
-
1157
- // ${batchStruct} — NATIVE batched ports for fanout '${node.id}': Items is a native slice of the concrete
1158
- // per-id ports structs (${structName}). The consumer reads Items[i].<Field> DIRECTLY (bc#90 / runtime-free).
1159
- type ${batchStruct} struct {
1160
- Items []${structName}
1161
- }`;
1162
- }
1163
1094
  /**
1164
1095
  * fanoutItemsElemRef (v3) — the connection items ELEMENT TypeRef for a covered fanout node. The fanout
1165
1096
  * outType is a connection struct `{items:[]Elem, cursor:*string}`; this returns Elem (the per-body row
@@ -1492,21 +1423,26 @@ function emitInDecoder(comp, plan) {
1492
1423
  * when the ref does not resolve to a REQUIRED (non-opt) native scalar (then the caller falls back to
1493
1424
  * the nvVE Value path — which keeps the runtime null/opt/TYPE_MISMATCH semantics). */
1494
1425
  /**
1495
- * emitPortInit — emit the port field build for one port as a FULLY NATIVE Go expression (bc#90 /
1496
- * runtime-free). Every covered port lowers to a concrete Go value assigned straight into the ports
1497
- * struct field — NO `dslcontracts.Value`, NO nvVE helper, NO `.(T)` type-assert:
1498
- * - a static string array (projection) → `[]string{"a", "b", ...}` (change #2);
1499
- * - a bare int/float number literal (e.g. Query `limit: 20`) → `int64(20)` / `float64(...)`;
1500
- * - a string/bool/scalar-input port → the native scalar expression (emitNativeScalar).
1501
- * A port that CANNOT lower natively FAILS CLOSED (there is no boxed Value fallback on the covered
1502
- * plane — a boxed escape would re-introduce the bc-runtime coupling this module removes). Returns the
1503
- * struct field initializer (`Field: <expr>`). `resolveRef` resolves a ref head for the scalar path.
1426
+ * emitPortWireField — emit ONE port as a boxed `WireField{Key:"<port>", Val:<wire>}` entry for the
1427
+ * op-agnostic transport payload (#183). The port lowers to its NATIVE value via the ONE port lowering
1428
+ * (`compilePortNode`), then boxes ONCE into the BC-owned `WireValue` through the total box SSoT
1429
+ * (`renderGoWireBox` ∘ `buildWirePlan(dir:"in")`) — the SAME renderer every other box crossing uses.
1430
+ * For a `value` / `arr<value>` port `compilePortNode` already materialized the opaque `WireValue` /
1431
+ * `[]WireValue` (the only native form of a heterogeneous bound value); `buildWirePlan` boxes it as an
1432
+ * identity `value` / list-of-`value`, so there is NO double-box.
1433
+ *
1434
+ * The `Key` is the RAW PORT NAME (`Object.keys(ports)`), NOT the Go field name — this WireRow field-name
1435
+ * ↔ port-name identity is the load-bearing transport contract (a dynamic-port consumer, e.g. graphddb,
1436
+ * reads `PK`/`SK`/`GSI1PK` by that name). A FALLIBLE port expr (one hoisting statements) fails closed —
1437
+ * a port is built inline in the payload literal, which cannot host early-return statements.
1504
1438
  */
1505
- function emitPortInit(pn, expr, comp, plan, typedNodes, isPrior, expected, opts) {
1439
+ function emitPortWireField(pn, expr, comp, plan, typedNodes, isPrior, expected, opts) {
1506
1440
  const c = compilePortNode(expr, comp, plan, typedNodes, isPrior, `port '${pn}'`, expected, opts);
1507
1441
  if (c.stmts.length > 0)
1508
- throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `go typed-native (runtime-free): port '${pn}' ${JSON.stringify(expr)} lowers to a FALLIBLE expression (one that can raise INT_OVERFLOW / NAN_OR_INF / MOD_ZERO / PRECISION_LOSS). Such an expression lowers to STATEMENTS carrying an early error-return, and a port is built inline in the ports-struct literal — a position that cannot host them. Use a non-fallible port expression.`);
1509
- return `${goPortFieldName(pn)}: ${c.expr}`;
1442
+ throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `go typed-native (runtime-free): port '${pn}' ${JSON.stringify(expr)} lowers to a FALLIBLE expression (one that can raise INT_OVERFLOW / NAN_OR_INF / MOD_ZERO / PRECISION_LOSS). Such an expression lowers to STATEMENTS carrying an early error-return, and a port is built inline in the transport payload literal — a position that cannot host them. Use a non-fallible port expression.`);
1443
+ const q = opts?.wireSel !== undefined && opts.wireSel !== "" ? `${opts.wireSel}.` : "";
1444
+ const boxed = renderGoWireBox(buildWirePlan(c.ref, { from: "top" }, { model: "port", field: pn, plan }, "in"), c.expr, opts?.wireSel);
1445
+ return `${q}WireField{Key: ${JSON.stringify(pn)}, Val: ${boxed}}`;
1510
1446
  }
1511
1447
  /**
1512
1448
  * emitParallelStageArm (bc#87) — EXPLICIT static parallel orchestration for a real-concurrency stage.
@@ -1565,14 +1501,15 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1565
1501
  for (const i of refMembers) {
1566
1502
  const node = comp.body[i];
1567
1503
  const s = sanitize(node.id);
1568
- const structName = portsStructName(comp.name, comp.body[i].id);
1569
1504
  // every member's goroutine returns the result WIRE (a single WireValue); the ascending COMMIT phase
1570
1505
  // de-boxes it INLINE (so the wire — not the decode — is what the goroutine writes to its slot).
1571
1506
  lines.push(`\t\tvar wire_${s} ${wire.value}`);
1572
1507
  lines.push(`\t\tvar row_${s}Err error`);
1573
1508
  lines.push(`\t\trun_${s} := false`);
1574
- lines.push(`\t\tvar ps_${s} ${structName}`);
1575
- lines.push(`\t\t_ = ps_${s}`);
1509
+ // the op-agnostic transport payload (#183): a WireRow of the node's boxed ports, built in preflight and
1510
+ // read (by value) inside the goroutine — the ONE arg the spec-named leaf transport takes for ALL roles.
1511
+ lines.push(`\t\tvar payload_${s} ${wire.row}`);
1512
+ lines.push(`\t\t_ = payload_${s}`);
1576
1513
  }
1577
1514
  // 1) PREFLIGHT (ascending): parent-produced gate (+ #114 bindField bound-key gate) + ports build,
1578
1515
  // per member (BEFORE dispatch). For a bindField relation child the bound key is read from the SETTLED
@@ -1581,7 +1518,6 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1581
1518
  for (const i of refMembers) {
1582
1519
  const node = comp.body[i];
1583
1520
  const s = sanitize(node.id);
1584
- const structName = portsStructName(comp.name, node.id);
1585
1521
  let ind = "\t\t";
1586
1522
  const closers = [];
1587
1523
  // #125: a stage member gated by a PRIOR-stage control gate (`parent=gate, bindField:"ok"`). Its
@@ -1613,12 +1549,9 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1613
1549
  ind += "\t";
1614
1550
  }
1615
1551
  }
1616
- const inits = [];
1617
1552
  const narrowed = nodeNarrowedPaths(comp, node);
1618
- for (const pn of Object.keys(node.ports)) {
1619
- inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, atPos), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed, wireSel: wire.selector }));
1620
- }
1621
- lines.push(`${ind}ps_${s} = ${structName}{${inits.join(", ")}}`);
1553
+ 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, wireSel: wire.selector }));
1554
+ lines.push(`${ind}payload_${s} = ${goPayloadRow(fields, wire.selector)}`);
1622
1555
  lines.push(`${ind}run_${s} = true`);
1623
1556
  for (const c of closers)
1624
1557
  lines.push(c);
@@ -1636,9 +1569,9 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1636
1569
  lines.push(`\t\t\tgo func() {`);
1637
1570
  lines.push(`\t\t\t\tdefer wg.Done()`);
1638
1571
  lines.push(`\t\t\t\tdefer func() { <-sem }()`);
1639
- // DIRECT leaf transport call — the node's port fields spread off the preflight-built ports struct. No
1640
- // `bound` (BC's internal produced/skip gate is already applied in preflight — the leaf never sees it).
1641
- const call = `${resolveLeafSymbol(node.component, leaf)}(${leafCallArgs(`ps_${s}`, portFieldSpread(node.ports, node.portSchemas, comp, plan, typedNodes, undefined, nodeNarrowedPaths(comp, node)))})`;
1572
+ // DIRECT leaf transport call — ONE op-agnostic symbol, ONE WireRow payload (the preflight-built ports).
1573
+ // No `bound` (BC's internal produced/skip gate is already applied in preflight — the leaf never sees it).
1574
+ const call = `${resolveLeafSymbol(node.component, leaf, node.leafSymbol)}(payload_${s})`;
1642
1575
  lines.push(`\t\t\t\twire_${s}, row_${s}Err = ${call}`);
1643
1576
  lines.push(`\t\t\t}()`);
1644
1577
  lines.push(`\t\t}`);
@@ -1696,15 +1629,6 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1696
1629
  * consumer (graphddb) drives it and keeps the struct native. A Value observation is produced ONLY
1697
1630
  * by the separate serialize wrapper (run_native_raw_<comp>, below), the single outer Value boundary.
1698
1631
  */
1699
- /** isCrossPackageSharedNode — a node whose ports struct CROSSES the leaf-transport boundary as a whole
1700
- * value (the batch ports struct passed to the transport), so under --shared-types-import it must live in
1701
- * the shared package (else the transport package → covered package import cycle). Batched maps + fanouts
1702
- * pass `${struct}_batch{Items: []${struct}}`; every other node passes only primitive port fields, so its
1703
- * ports struct stays local. The SINGLE predicate emit() (skip-local) and the shared package (emit-there)
1704
- * both use — they never disagree. */
1705
- function isCrossPackageSharedNode(n) {
1706
- return "fanout" in n || ("map" in n && n.map.batched === true);
1707
- }
1708
1632
  function emitNativeRawRunner(comp, plan, flags, wire, leaf) {
1709
1633
  const ep = execPlan(comp);
1710
1634
  const order = ep.order;
@@ -1793,7 +1717,6 @@ function emitNativeRawRunner(comp, plan, flags, wire, leaf) {
1793
1717
  const node = comp.body[i];
1794
1718
  const meta = metas[i];
1795
1719
  const s = sanitize(node.id);
1796
- const structName = portsStructName(comp.name, node.id);
1797
1720
  const portNames = Object.keys(node.ports);
1798
1721
  const ref = typedNodes.get(node.id);
1799
1722
  lines.push(`\t// ── op '${node.id}' (${node.component}${node.relationKind ? ", relationKind:" + node.relationKind : ""}${node.parent ? ", parent:" + node.parent : ""}) ──`);
@@ -1832,20 +1755,16 @@ function emitNativeRawRunner(comp, plan, flags, wire, leaf) {
1832
1755
  indent += "\t";
1833
1756
  }
1834
1757
  }
1835
- // ports: build the native struct by direct field assignment (bc#90 / runtime-free). Every covered
1836
- // port lowers to a concrete Go value (literal / input-param ref / cross-node typed field / concat /
1837
- // static string array / number literal) assigned straight into the ports field — ZERO
1838
- // dslcontracts.Value, ZERO nvVE helper, ZERO `.(T)`. A genuinely-dynamic port FAILS CLOSED.
1839
- const inits = [];
1758
+ // ports: build the op-agnostic transport payload (#183) — a WireRow of the node's boxed ports (each
1759
+ // port lowered to its native value then boxed ONCE via the box SSoT). ZERO dslcontracts.Value, ZERO
1760
+ // nvVE helper, ZERO `.(T)`; a genuinely-dynamic port still FAILS CLOSED in the lowering.
1840
1761
  const narrowed = nodeNarrowedPaths(comp, node);
1841
- for (const pn of portNames) {
1842
- inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed, wireSel: wire.selector }));
1843
- }
1844
- // DIRECT leaf transport call: the resolved op-agnostic symbol, the node's port fields spread. `bound` is
1845
- // NOT passed — it is BC's internal produced/skip gate, already enforced by the surrounding
1762
+ const fields = portNames.map((pn) => emitPortWireField(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed, wireSel: wire.selector }));
1763
+ // DIRECT leaf transport call: the resolved op-agnostic symbol, ONE WireRow payload. `bound` is NOT
1764
+ // passed — it is BC's internal produced/skip gate, already enforced by the surrounding
1846
1765
  // `if bound_<s> != nil` / `if produced_<parent>` guards; the leaf never receives it.
1847
- const call = `${resolveLeafSymbol(node.component, leaf)}(${leafCallArgs(`ports_${s}`, portFieldSpread(node.ports, node.portSchemas, comp, plan, typedNodes, undefined, nodeNarrowedPaths(comp, node)))})`;
1848
- lines.push(`${indent}ports_${s} := ${structName}{${inits.join(", ")}}`);
1766
+ const call = `${resolveLeafSymbol(node.component, leaf, node.leafSymbol)}(payload_${s})`;
1767
+ lines.push(`${indent}payload_${s} := ${goPayloadRow(fields, wire.selector)}`);
1849
1768
  // uniform seam: the transport returns a single result WIRE (${wire.value}); the inline de-box
1850
1769
  // (renderResultDeBox) classifies it against the STATICALLY declared result type and produces the
1851
1770
  // structured Error Value on a mismatch (byte-equal codes to run_behavior's outType check, so ≡ holds).
@@ -1937,13 +1856,7 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1937
1856
  // guarded NO-into map, which DROPs skipped elements. Byte-equal to run_behavior's applyInto keep-with-null.
1938
1857
  const keepWithNull = hasGuard && hasInto;
1939
1858
  const s = sanitize(node.id);
1940
- // #154 cross-package: a BATCHED map's element + batch ports structs live in the shared package (they
1941
- // cross the transport boundary as a whole value), so reference them selector-qualified here. A
1942
- // non-batched map passes only primitive fields, so its ports struct stays local (unqualified).
1943
- const q = wireSel !== undefined && batched ? `${wireSel}.` : "";
1944
- const structName = `${q}${portsStructName(comp.name, node.id)}`;
1945
- const batchStruct = `${structName}_batch`;
1946
- const leafSym = resolveLeafSymbol(m.component, leaf);
1859
+ const leafSym = resolveLeafSymbol(m.component, leaf, m.leafSymbol);
1947
1860
  const arrRef = typedNodes.get(node.id);
1948
1861
  const elemGo = renderTypeRef(arrRef);
1949
1862
  const asName = m.as;
@@ -1965,15 +1878,20 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1965
1878
  const be = makeGoExprBackend(zeroOut, resolveHead, plan);
1966
1879
  return new NativeExprCompiler(be).compileBool(m.when);
1967
1880
  };
1968
- // emit the per-element native ports struct build (shared; `il` is the indent inside the element
1969
- // loop, `elemVar` the over element loop variable). Returns the lines building `ep_<s>`.
1970
- const buildPorts = (il, elemVar) => {
1881
+ // the per-element boxed port WireFields (#183) — the SAME box SSoT as a point node, over the $as element.
1882
+ const portFields = (elemVar) => {
1971
1883
  const asBinding = { name: asName, ref: overElemRef, plan };
1972
1884
  // #170: a guarded map narrows its `when(ne($e.key,null))`-proven element key non-null in kept elements.
1973
1885
  const narrowed = nodeNarrowedPaths(comp, node);
1974
- const inits = portNames.map((pn) => emitPortInit(pn, m.ports[pn], comp, plan, typedNodes, priorHere, inputPortTypeRef(m.portSchemas?.[pn], plan), { asBinding, asBase: elemVar, narrowed, wireSel }));
1975
- return [`${il}ep_${s} := ${structName}{${inits.join(", ")}}`];
1886
+ return portNames.map((pn) => emitPortWireField(pn, m.ports[pn], comp, plan, typedNodes, priorHere, inputPortTypeRef(m.portSchemas?.[pn], plan), { asBinding, asBase: elemVar, narrowed, wireSel }));
1976
1887
  };
1888
+ // BATCHED element: `ep_<s>` is a WireRow VALUE (a `WireValue`) collected into the items WireList — the
1889
+ // batch payload is ONE WireRow `{items:[<per-element ports rows>…]}` (byte-equal to run_behavior's
1890
+ // `handler({items:[…]})`). NON-batched element: `ep_<s>` is the per-element transport payload WireRow
1891
+ // (`WireRowOfFields`) — ONE physical dispatch per element, the SAME op-agnostic signature.
1892
+ const wvQ = goWireQ(wireSel);
1893
+ const buildBatchElem = (il, elemVar) => [`${il}ep_${s} := ${wvQ}WireRowOf([]${wvQ}WireField{${portFields(elemVar).join(", ")}})`];
1894
+ const buildPayloadElem = (il, elemVar) => [`${il}ep_${s} := ${goPayloadRow(portFields(elemVar), wireSel)}`];
1977
1895
  const lines = [];
1978
1896
  const closers = [];
1979
1897
  lines.push(`\t// ── map '${node.id}' (${m.component}, ${batched ? "batched" : "per-element"}, into:${JSON.stringify(m.into ?? null)}${m.relationKind ? ", relationKind:" + m.relationKind : ""}${m.parent ? ", parent:" + m.parent : ""}) ──`);
@@ -2027,14 +1945,14 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
2027
1945
  // ports, then the aligned rows are de-boxed and zipped back onto their over-index slots. Byte-equal to
2028
1946
  // run_behavior: batched keptIdx-aligned collect + applyInto (skipped element unaugmented → opt-into null).
2029
1947
  const g = mkGuard(elemLocal(s));
2030
- lines.push(`${indent}items_${s} := make([]${structName}, 0, len(over_${s}))`);
1948
+ lines.push(`${indent}items_${s} := make([]${wvQ}WireValue, 0, len(over_${s}))`);
2031
1949
  lines.push(`${indent}keptIdx_${s} := make([]int, 0, len(over_${s}))`);
2032
1950
  lines.push(`${indent}for oi_${s} := range over_${s} {`);
2033
1951
  lines.push(`${indent}\t${elemLocal(s)} := over_${s}[oi_${s}]`);
2034
1952
  for (const st of g.stmts)
2035
1953
  lines.push(`${indent}\t${st}`);
2036
1954
  lines.push(`${indent}\tif ${g.expr} {`);
2037
- for (const l of buildPorts(indent + "\t\t", elemLocal(s)))
1955
+ for (const l of buildBatchElem(indent + "\t\t", elemLocal(s)))
2038
1956
  lines.push(l);
2039
1957
  lines.push(`${indent}\t\titems_${s} = append(items_${s}, ep_${s})`);
2040
1958
  lines.push(`${indent}\t\tkeptIdx_${s} = append(keptIdx_${s}, oi_${s})`);
@@ -2043,13 +1961,15 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
2043
1961
  lines.push(`${indent}\t}`);
2044
1962
  lines.push(`${indent}}`);
2045
1963
  lines.push(`${indent}if len(items_${s}) > 0 {`);
2046
- lines.push(`${indent}\tbp_${s} := ${batchStruct}{Items: items_${s}}`);
2047
- lines.push(`${indent}\tmo_${s}, mo_${s}Err := ${leafSym}(bp_${s})`);
1964
+ // ONE op-agnostic transport call: the batch is a WireRow {items:[…]}; the result is a WireList whose
1965
+ // aligned elements are read via `.Items` (byte-equal to run_behavior's aligned batch result).
1966
+ lines.push(`${indent}\tmo_${s}, mo_${s}Err := ${leafSym}(${goPayloadBatch(`items_${s}`, wireSel)})`);
2048
1967
  lines.push(`${indent}\tif mo_${s}Err != nil {`, `${indent}\t\treturn ${zeroOut}, opFailed(${JSON.stringify(node.id)}, "fail", mo_${s}Err)`, `${indent}\t}`);
2049
- lines.push(`${indent}\tif len(mo_${s}) != len(items_${s}) {`, `${indent}\t\treturn ${zeroOut}, ${goErr("MAP_BATCH_RESULT_MISMATCH", `fmt.Sprintf("map '${node.id}': batched handler must return a list aligned to items (want %d)", len(items_${s}))`)}`, `${indent}\t}`);
1968
+ lines.push(`${indent}\tmi_${s} := mo_${s}.Items`);
1969
+ lines.push(`${indent}\tif len(mi_${s}) != len(items_${s}) {`, `${indent}\t\treturn ${zeroOut}, ${goErr("MAP_BATCH_RESULT_MISMATCH", `fmt.Sprintf("map '${node.id}': batched handler must return a list aligned to items (want %d)", len(items_${s}))`)}`, `${indent}\t}`);
2050
1970
  lines.push(`${indent}\tfor mk_${s} := range items_${s} {`);
2051
1971
  lines.push(`${indent}\t\tvar dec_${s} ${elemRowGo}`);
2052
- lines.push(renderElemDeBox(`dec_${s}`, `mo_${s}[mk_${s}]`, `${indent}\t\t`));
1972
+ lines.push(renderElemDeBox(`dec_${s}`, `mi_${s}[mk_${s}]`, `${indent}\t\t`));
2053
1973
  lines.push(`${indent}\t\t${typedLocal(node.id)}[keptIdx_${s}[mk_${s}]] = ${elemMat}(over_${s}[keptIdx_${s}[mk_${s}]], dec_${s})`);
2054
1974
  lines.push(`${indent}\t}`);
2055
1975
  lines.push(`${indent}}`);
@@ -2059,13 +1979,13 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
2059
1979
  // dispatch ONCE. The concrete Node_* returns the aligned per-element WIRES ([]WireValue) or an error.
2060
1980
  // With a guard, `items` (and, for into, `keptOver`) hold only kept elements — matching run_behavior's
2061
1981
  // keptIdx-aligned batch. `into` is never combined with a guard (rejected). Each wire is de-boxed inline.
2062
- lines.push(`${indent}items_${s} := make([]${structName}, 0, len(over_${s}))`);
1982
+ lines.push(`${indent}items_${s} := make([]${wvQ}WireValue, 0, len(over_${s}))`);
2063
1983
  if (hasInto)
2064
1984
  lines.push(`${indent}keptOver_${s} := make([]${overElemGo}, 0, len(over_${s}))`);
2065
1985
  lines.push(`${indent}for _, ${elemLocal(s)} := range over_${s} {`);
2066
1986
  for (const l of emitGuard(indent + "\t", elemLocal(s)))
2067
1987
  lines.push(l);
2068
- for (const l of buildPorts(indent + "\t", elemLocal(s)))
1988
+ for (const l of buildBatchElem(indent + "\t", elemLocal(s)))
2069
1989
  lines.push(l);
2070
1990
  lines.push(`${indent}\titems_${s} = append(items_${s}, ep_${s})`);
2071
1991
  if (hasInto)
@@ -2073,27 +1993,26 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
2073
1993
  lines.push(`${indent}}`);
2074
1994
  // empty items => empty result (handler not called), matching run_behavior.
2075
1995
  lines.push(`${indent}if len(items_${s}) > 0 {`);
2076
- lines.push(`${indent}\tbp_${s} := ${batchStruct}{Items: items_${s}}`);
2077
- // DIRECT transport call — the batched dispatch takes the CONCRETE batch ports struct (shape unchanged;
2078
- // only the call target changes). Returns the aligned per-element wires ([]WireValue). No `bound`.
2079
- lines.push(`${indent}\tmo_${s}, mo_${s}Err := ${leafSym}(bp_${s})`);
1996
+ // ONE op-agnostic transport call: batch payload WireRow {items:[…]}; result WireList read via `.Items`.
1997
+ lines.push(`${indent}\tmo_${s}, mo_${s}Err := ${leafSym}(${goPayloadBatch(`items_${s}`, wireSel)})`);
2080
1998
  lines.push(`${indent}\tif mo_${s}Err != nil {`, `${indent}\t\treturn ${zeroOut}, opFailed(${JSON.stringify(node.id)}, "fail", mo_${s}Err)`, `${indent}\t}`);
2081
- lines.push(`${indent}\tif len(mo_${s}) != len(items_${s}) {`, `${indent}\t\treturn ${zeroOut}, ${goErr("MAP_BATCH_RESULT_MISMATCH", `fmt.Sprintf("map '${node.id}': batched handler must return a list aligned to items (want %d)", len(items_${s}))`)}`, `${indent}\t}`);
1999
+ lines.push(`${indent}\tmi_${s} := mo_${s}.Items`);
2000
+ lines.push(`${indent}\tif len(mi_${s}) != len(items_${s}) {`, `${indent}\t\treturn ${zeroOut}, ${goErr("MAP_BATCH_RESULT_MISMATCH", `fmt.Sprintf("map '${node.id}': batched handler must return a list aligned to items (want %d)", len(items_${s}))`)}`, `${indent}\t}`);
2082
2001
  if (hasInto) {
2083
2002
  // #86 pt2: de-box each aligned element wire (into the `into` field's type), then zip-attach onto the
2084
2003
  // kept over element (augmented element copier).
2085
2004
  lines.push(`${indent}\tfor mk_${s} := range keptOver_${s} {`);
2086
2005
  lines.push(`${indent}\t\tvar dec_${s} ${elemRowGo}`);
2087
- lines.push(renderElemDeBox(`dec_${s}`, `mo_${s}[mk_${s}]`, `${indent}\t\t`));
2006
+ lines.push(renderElemDeBox(`dec_${s}`, `mi_${s}[mk_${s}]`, `${indent}\t\t`));
2088
2007
  lines.push(`${indent}\t\tel_${s} := ${elemMat}(keptOver_${s}[mk_${s}], dec_${s})`);
2089
2008
  lines.push(`${indent}\t\t${typedLocal(node.id)} = append(${typedLocal(node.id)}, el_${s})`);
2090
2009
  lines.push(`${indent}\t}`);
2091
2010
  }
2092
2011
  else {
2093
2012
  // #93 shape 3 / #108: de-box each aligned per-element wire DIRECTLY into the element (result = kept).
2094
- lines.push(`${indent}\tfor mk_${s} := 0; mk_${s} < len(mo_${s}); mk_${s}++ {`);
2013
+ lines.push(`${indent}\tfor mk_${s} := 0; mk_${s} < len(mi_${s}); mk_${s}++ {`);
2095
2014
  lines.push(`${indent}\t\tvar el_${s} ${renderTypeRef(arrRef.elem)}`);
2096
- lines.push(renderElemDeBox(`el_${s}`, `mo_${s}[mk_${s}]`, `${indent}\t\t`));
2015
+ lines.push(renderElemDeBox(`el_${s}`, `mi_${s}[mk_${s}]`, `${indent}\t\t`));
2097
2016
  lines.push(`${indent}\t\t${typedLocal(node.id)} = append(${typedLocal(node.id)}, el_${s})`);
2098
2017
  lines.push(`${indent}\t}`);
2099
2018
  }
@@ -2113,15 +2032,14 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
2113
2032
  : ["continue"];
2114
2033
  for (const l of emitGuard(indent + "\t", elemLocal(s), nonBatchedSkip))
2115
2034
  lines.push(l);
2116
- for (const l of buildPorts(indent + "\t", elemLocal(s)))
2035
+ for (const l of buildPayloadElem(indent + "\t", elemLocal(s)))
2117
2036
  lines.push(l);
2118
- // per-element dispatch (ONE physical request per element). run_behavior passes the over element
2119
- // as the bound value; the element data is fully conveyed by the native ports struct here, so bound
2120
- // stays nil. Byte-equivalence holds because the bound value only feeds handler-internal logic.
2121
- // Element Error Policy (scp-error.md): `skip` drops the failing element and proceeds (order is
2122
- // preserved; the leaf keeps the Error Value it produced). `error` (default) promotes the element
2123
- // Failure to the map's Component Failure, carrying the leaf's detail through.
2124
- lines.push(`${indent}\tmo_${s}, mo_${s}Err := ${leafSym}(${leafCallArgs(`ep_${s}`, portFieldSpread(m.ports, m.portSchemas, comp, plan, typedNodes, { name: asName, ref: overElemRef, plan }, nodeNarrowedPaths(comp, node)))})`);
2037
+ // per-element dispatch (ONE physical request per element) through the ONE op-agnostic transport, ONE
2038
+ // WireRow payload. run_behavior passes the over element as the bound value; the element data is fully
2039
+ // conveyed by the payload here, so bound stays nil. Byte-equivalence holds because the bound value only
2040
+ // feeds handler-internal logic. Element Error Policy (scp-error.md): `skip` drops the failing element
2041
+ // and proceeds (order preserved); `error` (default) promotes the element Failure to the map's Failure.
2042
+ lines.push(`${indent}\tmo_${s}, mo_${s}Err := ${leafSym}(ep_${s})`);
2125
2043
  if (m.elementPolicy === "skip") {
2126
2044
  lines.push(`${indent}\tif mo_${s}Err != nil {`, `${indent}\t\tcontinue`, `${indent}\t}`);
2127
2045
  }
@@ -2165,12 +2083,8 @@ function elemLocal(s) {
2165
2083
  function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, leaf, wireSel) {
2166
2084
  const f = node.fanout;
2167
2085
  const s = sanitize(node.id);
2168
- // #154 cross-package: a fanout's element + batch ports structs cross the transport boundary as a whole
2169
- // value, so they live in the shared package — reference them selector-qualified here (else in-package).
2170
- const q = wireSel !== undefined ? `${wireSel}.` : "";
2171
- const structName = `${q}${portsStructName(comp.name, node.id)}`;
2172
- const batchStruct = `${structName}_batch`;
2173
- const leafSym = resolveLeafSymbol(f.component, leaf);
2086
+ const wvQ = goWireQ(wireSel);
2087
+ const leafSym = resolveLeafSymbol(f.component, leaf, f.leafSymbol);
2174
2088
  const connRef = typedNodes.get(node.id);
2175
2089
  const elemRef = fanoutItemsElemRef(node, connRef, plan);
2176
2090
  const elemGo = renderTypeRef(elemRef);
@@ -2187,11 +2101,12 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut
2187
2101
  if (!dkField || dkField.type.kind !== "scalar" || dkField.type.scalar !== "string")
2188
2102
  throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `go fanout (v3): node '${node.id}' dedupeKey '${f.dedupeKey}' must be a string field of the connection items element type '${elemRef.name}'.`);
2189
2103
  const dkGo = goFieldName(f.dedupeKey);
2190
- // per-id native ports build (same as a batched map's per-element ports). $as → the over id value.
2104
+ // per-id boxed port WireFields (same as a batched map's per-element ports). $as → the over id value.
2105
+ // `ep_<s>` is a WireRow VALUE (a `WireValue`) collected into the items WireList of the batch payload.
2191
2106
  const buildPorts = (il, elemVar) => {
2192
2107
  const asBinding = { name: asName, ref: overElemRef, plan };
2193
- const inits = portNames.map((pn) => emitPortInit(pn, f.ports[pn], comp, plan, typedNodes, priorHere, inputPortTypeRef(f.portSchemas?.[pn], plan), { asBinding, asBase: elemVar, wireSel }));
2194
- return [`${il}ep_${s} := ${structName}{${inits.join(", ")}}`];
2108
+ const fields = portNames.map((pn) => emitPortWireField(pn, f.ports[pn], comp, plan, typedNodes, priorHere, inputPortTypeRef(f.portSchemas?.[pn], plan), { asBinding, asBase: elemVar, wireSel }));
2109
+ return [`${il}ep_${s} := ${wvQ}WireRowOf([]${wvQ}WireField{${fields.join(", ")}})`];
2195
2110
  };
2196
2111
  const lines = [];
2197
2112
  const closers = [];
@@ -2206,7 +2121,7 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut
2206
2121
  for (const l of goBindOver(indent, s, overExpr, overOptArr, overElemGo))
2207
2122
  lines.push(l);
2208
2123
  lines.push(`${indent}var items_${s} []${elemGo}`);
2209
- lines.push(`${indent}pi_${s} := make([]${structName}, 0, len(over_${s}))`);
2124
+ lines.push(`${indent}pi_${s} := make([]${wvQ}WireValue, 0, len(over_${s}))`);
2210
2125
  lines.push(`${indent}for _, ${elemLocal(s)} := range over_${s} {`);
2211
2126
  for (const l of buildPorts(indent + "\t", elemLocal(s)))
2212
2127
  lines.push(l);
@@ -2214,24 +2129,22 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut
2214
2129
  lines.push(`${indent}}`);
2215
2130
  // empty id-list => empty connection (handler not called), matching run_behavior.
2216
2131
  lines.push(`${indent}if len(pi_${s}) > 0 {`);
2217
- lines.push(`${indent}\tbp_${s} := ${batchStruct}{Items: pi_${s}}`);
2218
- // the handler returns the aligned per-id element WIRES (one nilable WireValue per id); each present
2219
- // body is de-boxed strictly INLINE (a de-box mismatch fails closed). A DANGLING id is a nil wire → the
2220
- // zero element (empty dedupeKey), which the dangling drop below excludes.
2221
- // DIRECT transport call — the batched fanout dispatch takes the CONCRETE batch ports struct (shape
2222
- // unchanged; only the call target changes). Returns the aligned per-id element wires. No `bound`.
2223
- lines.push(`${indent}\tfo_${s}, fo_${s}Err := ${leafSym}(bp_${s})`);
2132
+ // ONE op-agnostic transport call: batch payload WireRow {items:[…]}; result is a WireList of the aligned
2133
+ // per-id element wires (read via `.Items`). A DANGLING id is a WireNull element → the zero element (empty
2134
+ // dedupeKey), which the dangling drop below excludes. No `bound`.
2135
+ lines.push(`${indent}\tfo_${s}, fo_${s}Err := ${leafSym}(${goPayloadBatch(`pi_${s}`, wireSel)})`);
2224
2136
  lines.push(`${indent}\tif fo_${s}Err != nil {`, `${indent}\t\treturn ${zeroOut}, opFailed(${JSON.stringify(node.id)}, "fail", fo_${s}Err)`, `${indent}\t}`);
2225
- lines.push(`${indent}\tif len(fo_${s}) != len(pi_${s}) {`, `${indent}\t\treturn ${zeroOut}, ${goErr("FANOUT_BATCH_RESULT_MISMATCH", `fmt.Sprintf("fanout '${node.id}': batched handler must return a list aligned to the deduped id list (want %d)", len(pi_${s}))`)}`, `${indent}\t}`);
2137
+ lines.push(`${indent}\tfw_${s} := fo_${s}.Items`);
2138
+ lines.push(`${indent}\tif len(fw_${s}) != len(pi_${s}) {`, `${indent}\t\treturn ${zeroOut}, ${goErr("FANOUT_BATCH_RESULT_MISMATCH", `fmt.Sprintf("fanout '${node.id}': batched handler must return a list aligned to the deduped id list (want %d)", len(pi_${s}))`)}`, `${indent}\t}`);
2226
2139
  // ── THE ONE dedupe/drop (mirrors fanoutDedupDrop verbatim): first-seen dedupe by dedupeKey field;
2227
2140
  // drop dangling (zero dedupeKey ≡ interpreter's null/absent-key body); implicitSource strip is
2228
2141
  // structural (the elem type already omits it). cursor is always nil (connection wrap).
2229
- lines.push(`${indent}\tseen_${s} := make(map[string]struct{}, len(fo_${s}))`);
2230
- lines.push(`${indent}\titems_${s} = make([]${elemGo}, 0, len(fo_${s}))`);
2231
- lines.push(`${indent}\tfor fi_${s} := range fo_${s} {`);
2142
+ lines.push(`${indent}\tseen_${s} := make(map[string]struct{}, len(fw_${s}))`);
2143
+ lines.push(`${indent}\titems_${s} = make([]${elemGo}, 0, len(fw_${s}))`);
2144
+ lines.push(`${indent}\tfor fi_${s} := range fw_${s} {`);
2232
2145
  lines.push(`${indent}\t\tvar el_${s} ${elemGo}`);
2233
- lines.push(`${indent}\t\tif fo_${s}[fi_${s}] != nil {`);
2234
- lines.push(renderResultDeBox(elemRef, `el_${s}`, `(*fo_${s}[fi_${s}])`, node.id, plan, `${indent}\t\t\t`, returnZeroFail(zeroOut), nodeWirePassthrough(node)));
2146
+ lines.push(`${indent}\t\tif !fw_${s}[fi_${s}].IsNull() {`);
2147
+ lines.push(renderResultDeBox(elemRef, `el_${s}`, `fw_${s}[fi_${s}]`, node.id, plan, `${indent}\t\t\t`, returnZeroFail(zeroOut), nodeWirePassthrough(node)));
2235
2148
  lines.push(`${indent}\t\t}`);
2236
2149
  lines.push(`${indent}\t\tkey_${s} := el_${s}.${dkGo}`);
2237
2150
  if (f.drop === "dangling") {
@@ -2497,10 +2410,12 @@ const goExprUsed = { helpers: false };
2497
2410
  * - `record` box each declared field to its wire ctor recursively, assemble a WireRow of (name, WireValue)
2498
2411
  * entries — the typed `obj<…>` → wire map ("M") crossing (the real op-agnostic `arr<value>`
2499
2412
  * batch-write param fed a typed `arr<obj>`);
2500
- * - `list` box each element recursively into a WireList ("L").
2501
- * A `map` value or an OPT-wrapped element (optDepth > 0) boxes AMBIGUOUSLY (map key order / opt present-vs-null
2502
- * on the wire are not statically pinned to run_behavior's Value pass-through), so it stays FAIL-CLOSED LOUD
2503
- * rather than risk a divergence — strict-typing, no silent box. `depth` names the loop/element locals uniquely.
2413
+ * - `list` box each element recursively into a WireList ("L");
2414
+ * - `map` (bc#181) box each entry's VALUE into a dynamic-keyed WireRow (sorted keys — no WireMap type);
2415
+ * - `opt` (bc#185) TOTAL: absent/null (nil pointer) ⇒ WireNull(); present ⇒ deref to the base and box it
2416
+ * through the SAME per-kind walk (`boxBase`) — byte-equal to run_behavior's `Value` pass-through
2417
+ * (null stays null), the write-side mirror of the read de-box's opt (`wrapAssign`).
2418
+ * `depth` names the loop/element locals uniquely.
2504
2419
  */
2505
2420
  function renderGoWireBox(plan, srcExpr, wireSel, depth = 0) {
2506
2421
  // #174: cross-package (`--shared-types-import`) the wire CONSTRUCTORS + composite TYPES live in the shared
@@ -2508,33 +2423,42 @@ function renderGoWireBox(plan, srcExpr, wireSel, depth = 0) {
2508
2423
  // `[]wire.WireField{…}`); in-package they are local (bare). Without this the type is `wire.WireValue` but the
2509
2424
  // ctor is a bare `WireFloat` → does not compile.
2510
2425
  const q = wireSel !== undefined && wireSel !== "" ? `${wireSel}.` : "";
2511
- if (plan.optDepth === 0) {
2426
+ // boxBase — box a BASE-typed (non-opt) expr per the plan's kind. Both the required (optDepth 0) path and the
2427
+ // opt arm (after its null-guard + deref) fold through this ONE walk, so the opt element reuses the SAME
2428
+ // per-kind box (no parallel path). The union is exhausted below; the trailing throw is a bare exhaustiveness
2429
+ // guard, never a silent hole.
2430
+ const boxBase = (baseSrc) => {
2512
2431
  if (plan.k === "value")
2513
- return srcExpr; // identity — already the opaque BC wire.
2432
+ return baseSrc; // identity — already the opaque BC wire.
2514
2433
  if (plan.k === "scalar") {
2515
2434
  switch (plan.scalar) {
2516
2435
  case "string":
2517
- return `${q}WireStr(${srcExpr})`;
2436
+ return `${q}WireStr(${baseSrc})`;
2518
2437
  case "int":
2519
- return `${q}WireInt(${srcExpr})`;
2438
+ return `${q}WireInt(${baseSrc})`;
2520
2439
  case "float":
2521
- return `${q}WireFloat(${srcExpr})`;
2440
+ return `${q}WireFloat(${baseSrc})`;
2522
2441
  case "bool":
2523
- return `${q}WireBool(${srcExpr})`;
2442
+ return `${q}WireBool(${baseSrc})`;
2524
2443
  }
2525
2444
  }
2526
2445
  if (plan.k === "record") {
2527
2446
  // typed struct → wire map: box each declared field off its native struct field (no probe — the value is
2528
2447
  // already typed), assemble a WireRow of (name, WireValue) in declared-field order.
2529
- const entries = plan.fields.map((f) => `{Key: ${JSON.stringify(f.name)}, Val: ${renderGoWireBox(f.plan, `${srcExpr}.${goFieldName(f.name)}`, wireSel, depth + 1)}}`);
2448
+ const entries = plan.fields.map((f) => `{Key: ${JSON.stringify(f.name)}, Val: ${renderGoWireBox(f.plan, `${baseSrc}.${goFieldName(f.name)}`, wireSel, depth + 1)}}`);
2530
2449
  return `${q}WireRowOf([]${q}WireField{${entries.join(", ")}})`;
2531
2450
  }
2532
2451
  if (plan.k === "list") {
2533
2452
  // typed slice → wire list: box each element recursively (box-once, no round-trip). An empty slice yields
2534
2453
  // an empty (non-nil) WireList — byte-equal to run_behavior's [] pass-through.
2535
2454
  const e = `e${depth}`;
2455
+ const elemBox = renderGoWireBox(plan.elem, e, wireSel, depth + 1);
2456
+ // an IDENTITY element box (a `value` list — already `[]WireValue`) needs no per-element loop; wrap the
2457
+ // slice directly (box-once already happened when the []WireValue was built).
2458
+ if (elemBox === e)
2459
+ return `${q}WireListOf(${baseSrc})`;
2536
2460
  const items = `it${depth}`;
2537
- return `func() ${q}WireValue { ${items} := []${q}WireValue{}; for _, ${e} := range ${srcExpr} { ${items} = append(${items}, ${renderGoWireBox(plan.elem, e, wireSel, depth + 1)}) }; return ${q}WireListOf(${items}) }()`;
2461
+ return `func() ${q}WireValue { ${items} := []${q}WireValue{}; for _, ${e} := range ${baseSrc} { ${items} = append(${items}, ${elemBox}) }; return ${q}WireListOf(${items}) }()`;
2538
2462
  }
2539
2463
  if (plan.k === "map") {
2540
2464
  // bc#181: typed map<V> → wire map, represented as a dynamic-keyed WireRow (there is NO WireMap type; a
@@ -2545,10 +2469,22 @@ function renderGoWireBox(plan, srcExpr, wireSel, depth = 0) {
2545
2469
  const keys = `mk${depth}`;
2546
2470
  const key = `k${depth}`;
2547
2471
  const fields = `mf${depth}`;
2548
- return `func() ${q}WireValue { ${keys} := make([]string, 0, len(${srcExpr})); for ${key} := range ${srcExpr} { ${keys} = append(${keys}, ${key}) }; sort.Strings(${keys}); ${fields} := []${q}WireField{}; for _, ${key} := range ${keys} { ${fields} = append(${fields}, ${q}WireField{Key: ${key}, Val: ${renderGoWireBox(plan.value, `${srcExpr}[${key}]`, wireSel, depth + 1)}}) }; return ${q}WireRowOf(${fields}) }()`;
2472
+ return `func() ${q}WireValue { ${keys} := make([]string, 0, len(${baseSrc})); for ${key} := range ${baseSrc} { ${keys} = append(${keys}, ${key}) }; sort.Strings(${keys}); ${fields} := []${q}WireField{}; for _, ${key} := range ${keys} { ${fields} = append(${fields}, ${q}WireField{Key: ${key}, Val: ${renderGoWireBox(plan.value, `${baseSrc}[${key}]`, wireSel, depth + 1)}}) }; return ${q}WireRowOf(${fields}) }()`;
2549
2473
  }
2550
- }
2551
- throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `go 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)`);
2474
+ throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `go wire box: unexpected plan kind '${plan.k}'`);
2475
+ };
2476
+ if (plan.optDepth > 0) {
2477
+ // bc#185: typed opt<T> → wire, TOTAL. `srcExpr` is a `*…*Base` (optDepth pointer wraps — the mirror of the
2478
+ // read-side de-box `wrapAssign`). Presence is SINGLE-BIT on the wire and run_behavior passes the `Value`
2479
+ // THROUGH (null stays null), so: absent/null (nil outer pointer) ⇒ WireNull() (byte-equal to valueToWire(nil));
2480
+ // present ⇒ deref ALL optDepth layers to the base value and box it through the SAME per-kind walk (box-once,
2481
+ // no decode→re-box). A present nested opt is a fully non-nil pointer chain (the read side never builds a
2482
+ // partially-nil present), so the full deref is safe.
2483
+ const o = `o${depth}`;
2484
+ const deref = `(${"*".repeat(plan.optDepth)}${o})`;
2485
+ return `func() ${q}WireValue { ${o} := ${srcExpr}; if ${o} == nil { return ${q}WireNull() }; return ${boxBase(deref)} }()`;
2486
+ }
2487
+ return boxBase(srcExpr);
2552
2488
  }
2553
2489
  function makeGoExprBackend(zeroOut, resolveHead, plan,
2554
2490
  // #174: cross-package selector for the shared wire constructors (`wire`); undefined/"" ⇒ in-package (bare).
@@ -2832,44 +2768,19 @@ function emit(ctx) {
2832
2768
  const leaf = ctx.leafTransport;
2833
2769
  // Emit the runners first so the nv* helper usage flags are known.
2834
2770
  const flags = { bind: false, field: false, cat: false, arr: false };
2835
- const structs = [];
2836
2771
  const inStructs = [];
2837
2772
  const elemCopiers = [];
2838
2773
  const runnerCodes = [];
2839
2774
  // every covered node returns a WireValue the inline de-box classifies — the wire seam (probe kind
2840
2775
  // consts + probe RESULT structs) is emitted once whenever any handler node exists.
2841
2776
  const anyWire = native.some((c) => c.body.some((n) => !("cond" in n)));
2842
- // #154 cross-package (--shared-types-import): a batched-map / fanout batch ports struct crosses the
2843
- // transport boundary as a whole value, so it lives in the SHARED package (goSharedWireTypesPackage),
2844
- // NOT the covered module — else the transport package would import the covered package (cycle). Every
2845
- // other ports struct passes only primitive fields and stays local.
2846
- const crossPackage = wire.import !== undefined;
2777
+ // #183: a covered node's ports cross the transport boundary as ONE op-agnostic `WireRow` payload (built
2778
+ // inline at the call site), so there are NO per-node ports structs on either the covered plane or the
2779
+ // shared package — the transport ABI is the generic WireRow, not a per-node/per-role concrete struct.
2847
2780
  for (const c of native) {
2848
2781
  inStructs.push(emitInStruct(c, plan));
2849
2782
  // build the full typed-node map FIRST so a map's over-element resolution can see every node.
2850
2783
  const typedNodes = buildTypedNodes(c, plan);
2851
- for (const n of c.body) {
2852
- if (crossPackage && isCrossPackageSharedNode(n)) {
2853
- // emitted in the shared package instead (goSharedWireTypesPackage), referenced here as <sel>.<T>.
2854
- }
2855
- else if ("fanout" in n) {
2856
- // v3: a fanout node emits a per-id element ports struct + a batch struct (like a batched map).
2857
- structs.push(emitFanoutPortsStructs(c, n, typedNodes, plan));
2858
- }
2859
- else if ("map" in n) {
2860
- // #86 pt2 / #108: a map node emits an element ports struct + a batch struct. The element ports
2861
- // may read the `$as` binding — resolved via the over-element type (prior node / input array).
2862
- structs.push(emitMapPortsStructs(c, n, typedNodes, plan));
2863
- }
2864
- else if ("cond" in n) {
2865
- // #108: a cond node has NO ports struct (it is a pure Expression — no handler dispatch).
2866
- }
2867
- else {
2868
- // #129: pass typedNodes so a leaf array port fed by a prior node's arr outType types as []ElemT.
2869
- // #170: a gated child narrows its gate-proven opt key (field type must match the narrowed init).
2870
- structs.push(emitPortsStruct(c, n, undefined, plan, typedNodes, nodeNarrowedPaths(c, n)));
2871
- }
2872
- }
2873
2784
  // augmented-element copiers for covered map...into nodes (over fields + the de-boxed into value).
2874
2785
  const mm = emitMapElemMaterializers(c, typedNodes, plan);
2875
2786
  if (mm)
@@ -2946,9 +2857,6 @@ function emit(ctx) {
2946
2857
  elemCopiers.length
2947
2858
  ? `// Augmented map-element copiers (over element fields + the concrete into row — pure assignment).\n${elemCopiers.join("\n\n")}`
2948
2859
  : undefined,
2949
- structs.some((r) => r.trim().length > 0)
2950
- ? `// Native ports structs (one per componentRef node; typed per the static port type).\n${structs.filter((r) => r.trim().length > 0).join("\n\n")}`
2951
- : undefined,
2952
2860
  goExprUsed.helpers
2953
2861
  ? `// #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${emitExprHelpers()}`
2954
2862
  : undefined,
@@ -2960,34 +2868,14 @@ function emit(ctx) {
2960
2868
  /**
2961
2869
  * goSharedWireTypesPackage — the BC-GENERATED shared package (Task A cross-package). Emits the SAME seam the
2962
2870
  * covered module emits in-package (emitGoProbeKinds + emitProbeWireTypes + emitGoWireTypes) into a standalone
2963
- * package, so a separate leaf-transport package can return `WireValue` (and the covered module reference it)
2964
- * without an import cycle. When `ir` is given, ALSO emits the batched-map / fanout batch ports structs (the
2965
- * ONLY covered-module types that cross the transport boundary as a whole value) — same `emitMapPortsStructs`
2966
- * / `emitFanoutPortsStructs` + same `isCrossPackageSharedNode` predicate `emit()` uses to skip them locally,
2967
- * so the two never disagree (SSoT). Self-contained (only `strconv` for the numeric constructors). `pkgName`
2968
- * is the package's Go identifier (the last path segment of `sharedTypesImport`). */
2969
- export function goSharedWireTypesPackage(pkgName, ir) {
2970
- const portsStructs = [];
2971
- if (ir !== undefined) {
2972
- const components = ir.components;
2973
- const plan = buildTypePlan(ir);
2974
- for (const c of components.filter(isNativeRaw)) {
2975
- const typedNodes = buildTypedNodes(c, plan);
2976
- for (const n of c.body) {
2977
- if (!isCrossPackageSharedNode(n))
2978
- continue;
2979
- portsStructs.push("fanout" in n
2980
- ? emitFanoutPortsStructs(c, n, typedNodes, plan)
2981
- : emitMapPortsStructs(c, n, typedNodes, plan));
2982
- }
2983
- }
2984
- }
2985
- const portsSection = portsStructs.length
2986
- ? `\n\n// #154 cross-package batched/fanout ports structs — the batch ports the covered module's runner\n// passes to the leaf transport as a whole value. Here (not the covered module) so the transport package\n// can name them without importing the covered package (cycle-free). Native fields — no boxed Value.\n${portsStructs.join("\n\n")}`
2987
- : "";
2871
+ * package, so a separate leaf-transport package can take a `WireRow` payload + return `WireValue` (and the
2872
+ * covered module reference them) without an import cycle. #183: the transport ABI is the generic `WireRow`
2873
+ * payload built inline at the call site — there are NO per-node/per-role batch ports structs to emit here.
2874
+ * Self-contained (only `strconv` for the numeric constructors). `pkgName` is the package's Go identifier. */
2875
+ export function goSharedWireTypesPackage(pkgName) {
2988
2876
  return `// GENERATED by behavior-contracts (go-typed-native) — the BC-OWNED shared wire types. A covered module
2989
- // generated with --shared-types-import imports this; a separate leaf-transport package returns its
2990
- // WireValue. Self-contained + runtime-free.
2877
+ // generated with --shared-types-import imports this; a separate leaf-transport package takes a WireRow
2878
+ // payload + returns its WireValue. Self-contained + runtime-free.
2991
2879
  package ${pkgName}
2992
2880
 
2993
2881
  import "strconv"
@@ -2996,7 +2884,7 @@ ${emitGoProbeKinds()}
2996
2884
 
2997
2885
  ${emitProbeWireTypes({ row: "WireRow", list: "WireList" })}
2998
2886
 
2999
- ${emitGoWireTypes()}${portsSection}
2887
+ ${emitGoWireTypes()}
3000
2888
  `;
3001
2889
  }
3002
2890
  /**
@@ -3090,13 +2978,16 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
3090
2978
  }`
3091
2979
  : "";
3092
2980
  // ── op-agnostic leaf TRANSPORT funcs (TEST glue) — the scripted analog of the consumer's transport
3093
- // symbols. ONE free `Leaf_<component>` per DISTINCT covered leaf (catalog component) in the IR (a
3094
- // per-module leaf has one consistent shape — verified), draining the shared package-level scripted queue
3095
- // and returning the scripted wire in EXACTLY the shape the removed per-node method returned. bc#87
3096
- // parallel goroutines share the queue (mutex-guarded); cases run sequentially so a shared package var is
3097
- // fine. Echo (#129/#141) reads the spread port params directly. ──
2981
+ // symbols. ONE free transport per DISTINCT SPEC-fixed SYMBOL (#176/#183), UNIFORM signature
2982
+ // `<sym>(payload WireRow) (WireValue, error)`: it drains the shared scripted queue (keyed by the catalog
2983
+ // component) and returns the scripted wire — a WireList for a batched/fanout result (`src.ok` = `[]Value`,
2984
+ // a nil element → WireNull, the dangling marker), else a single WireValue. Echo (#129/#141) reads the port
2985
+ // back FROM THE PAYLOAD BY NAME (payload.get("<port>")) — proving the WireRow field-name↔port-name contract.
2986
+ // A single spec-named leaf used in MULTIPLE roles/cardinalities is emitted ONCE (the #183 fix); two nodes
2987
+ // resolving to the SAME symbol but DIFFERENT catalog components is a LOUD collision (never a silent
2988
+ // collapse). bc#87 parallel goroutines share the queue (mutex-guarded). ──
3098
2989
  const transportFns = [];
3099
- const emittedLeaf = new Set();
2990
+ const bySym = new Map();
3100
2991
  for (const c of native) {
3101
2992
  const typedNodes = new Map();
3102
2993
  for (const n of c.body)
@@ -3106,125 +2997,74 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
3106
2997
  if ("cond" in n)
3107
2998
  continue; // #108: cond has no leaf (pure Expression) — no transport fn.
3108
2999
  const catalog = "fanout" in n ? n.fanout.component : "map" in n ? n.map.component : n.component;
3109
- if (emittedLeaf.has(catalog))
3110
- continue; // per-module a leaf has ONE consistent shape — emit once.
3111
- emittedLeaf.add(catalog);
3112
- const sym = leafSymbolBare(catalog, leaf);
3113
- if ("fanout" in n) {
3114
- // fanout: return the aligned per-id element WIRES ([]*WireValue); a null aligned body is a
3115
- // DANGLING id → nil (the covered runner maps it to the zero element).
3116
- const portsT = `${portsStructName(c.name, n.id)}_batch`;
3117
- transportFns.push(`func ${sym}(_ ${portsT}) ([]*WireValue, error) {
3118
- src, ok := nextScripted(${JSON.stringify(catalog)})
3119
- if !ok {
3120
- return nil, unknownComponent(${JSON.stringify(catalog)})
3121
- }
3122
- if src.isErr {
3123
- return nil, leafFailure(src.err)
3124
- }
3125
- arr, _ := src.ok.([]${PKG}.Value)
3126
- wires := make([]*WireValue, 0, len(arr))
3127
- for _, ev := range arr {
3128
- if ev == nil {
3129
- wires = append(wires, nil)
3130
- continue
3131
- }
3132
- wv := valueToWire(ev)
3133
- wires = append(wires, &wv)
3134
- }
3135
- return wires, nil
3136
- }`);
3137
- continue;
3138
- }
3139
- if ("map" in n) {
3140
- // map: batched → one WIRE per element ([]WireValue); non-batched → one element WIRE (WireValue).
3141
- const m = n.map;
3142
- if (m.batched === true) {
3143
- const portsT = `${portsStructName(c.name, n.id)}_batch`;
3144
- transportFns.push(`func ${sym}(_ ${portsT}) ([]WireValue, error) {
3145
- src, ok := nextScripted(${JSON.stringify(catalog)})
3146
- if !ok {
3147
- return nil, unknownComponent(${JSON.stringify(catalog)})
3148
- }
3149
- if src.isErr {
3150
- return nil, leafFailure(src.err)
3151
- }
3152
- arr, _ := src.ok.([]${PKG}.Value)
3153
- wires := make([]WireValue, 0, len(arr))
3154
- for _, ev := range arr {
3155
- wires = append(wires, valueToWire(ev))
3156
- }
3157
- return wires, nil
3158
- }`);
3159
- }
3160
- else {
3161
- const { elemRef: overElemRef } = mapOverElemInfo(c, n, typedNodes, plan);
3162
- const spread = portFieldSpread(m.ports, m.portSchemas, c, plan, typedNodes, { name: m.as, ref: overElemRef, plan }, nodeNarrowedPaths(c, n));
3163
- const params = spread.map((pf) => `_${pf.field} ${pf.goType}`).join(", ");
3164
- transportFns.push(`func ${sym}(${params}) (WireValue, error) {
3165
- src, ok := nextScripted(${JSON.stringify(catalog)})
3166
- if !ok {
3167
- return WireValue{}, unknownComponent(${JSON.stringify(catalog)})
3168
- }
3169
- if src.isErr {
3170
- return WireValue{}, leafFailure(src.err)
3171
- }
3172
- return valueToWire(src.ok), nil
3173
- }`);
3174
- }
3175
- continue;
3176
- }
3177
- // componentRef (point read): spread port fields; supports echo (#129/#141) reading the port params.
3178
- const node = n;
3179
- // #170: the observe transport fn's param types must match the covered module's leaf call args, which
3180
- // narrow a gate-proven opt key — so this reads the SAME node narrowing.
3181
- const crNarrowed = nodeNarrowedPaths(c, node);
3182
- const ref = typedNodes.get(n.id);
3183
- const spread = portFieldSpread(node.ports, node.portSchemas, c, plan, typedNodes, undefined, crNarrowed);
3184
- const echoBranches = [];
3185
- if (ref.kind === "named") {
3186
- const decl = findDecl(plan, ref.name);
3187
- const field = decl !== undefined && decl.fields.length === 1 ? decl.fields[0] : undefined;
3188
- const fieldGo = field !== undefined ? renderTypeRef(field.type) : null;
3189
- const recordGo = renderTypeRef(ref);
3190
- for (const pn of Object.keys(node.ports)) {
3191
- let portGo = null;
3192
- try {
3193
- portGo = portFieldGoType(node.ports[pn], c, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[pn], plan), `echo port '${pn}'`, { narrowed: crNarrowed });
3194
- }
3195
- catch {
3196
- portGo = null;
3197
- }
3198
- if (portGo === recordGo) {
3199
- // the port IS the whole record → echo it DIRECTLY (matching run_behavior's plain echo:port).
3200
- echoBranches.push(`\tif src.echo == ${JSON.stringify(pn)} {\n\t\treturn valueToWire(${serializeTyped(goPortFieldName(pn), ref, plan)}), nil\n\t}`);
3201
- }
3202
- else if (fieldGo !== null && field !== undefined && portGo === fieldGo) {
3203
- // a scalar port wraps into the record's single field ({v: ports.X}).
3204
- echoBranches.push(`\tif src.echo == ${JSON.stringify(pn)} {\n\t\treturn valueToWire(${serializeTyped(`${recordGo}{${goFieldName(field.name)}: ${goPortFieldName(pn)}}`, ref, plan)}), nil\n\t}`);
3000
+ const specSym = "fanout" in n ? n.fanout.leafSymbol : "map" in n ? n.map.leafSymbol : n.leafSymbol;
3001
+ const sym = leafSymbolBare(catalog, leaf, specSym);
3002
+ // echo branches (point/componentRef nodes only — a batched/fanout node returns a WireList, not a port).
3003
+ const echo = [];
3004
+ if (!("fanout" in n) && !("map" in n)) {
3005
+ const node = n;
3006
+ const crNarrowed = nodeNarrowedPaths(c, node);
3007
+ const ref = typedNodes.get(n.id);
3008
+ if (ref.kind === "named") {
3009
+ const decl = findDecl(plan, ref.name);
3010
+ const field = decl !== undefined && decl.fields.length === 1 ? decl.fields[0] : undefined;
3011
+ const fieldGo = field !== undefined ? renderTypeRef(field.type) : null;
3012
+ const recordGo = renderTypeRef(ref);
3013
+ for (const pn of Object.keys(node.ports)) {
3014
+ let portGo = null;
3015
+ try {
3016
+ portGo = portFieldGoType(node.ports[pn], c, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[pn], plan), `echo port '${pn}'`, { narrowed: crNarrowed });
3017
+ }
3018
+ catch {
3019
+ portGo = null;
3020
+ }
3021
+ if (portGo === recordGo) {
3022
+ // the port IS the whole record → echo its payload wire DIRECTLY (matching run_behavior's echo:port).
3023
+ echo.push(`\tif src.echo == ${JSON.stringify(pn)} {\n\t\tif v := payload.get(${JSON.stringify(pn)}); v != nil {\n\t\t\treturn *v, nil\n\t\t}\n\t}`);
3024
+ }
3025
+ else if (fieldGo !== null && field !== undefined && portGo === fieldGo) {
3026
+ // a scalar port wraps into the record's single field ({v: <port wire>}) — mirrors the scripted `wrap`.
3027
+ echo.push(`\tif src.echo == ${JSON.stringify(pn)} {\n\t\tif v := payload.get(${JSON.stringify(pn)}); v != nil {\n\t\t\treturn WireRowOf([]WireField{{Key: ${JSON.stringify(field.name)}, Val: *v}}), nil\n\t\t}\n\t}`);
3028
+ }
3205
3029
  }
3206
3030
  }
3031
+ else if (ref.kind === "arr" && Object.prototype.hasOwnProperty.call(node.ports, "items")) {
3032
+ // #129: an arr node with an `items` port echoes the payload's items wire (a WireList) so the
3033
+ // node→leaf array dataflow test is non-vacuous.
3034
+ echo.push(`\tif src.echo == "items" {\n\t\tif v := payload.get("items"); v != nil {\n\t\t\treturn *v, nil\n\t\t}\n\t}`);
3035
+ }
3207
3036
  }
3208
- else if (ref.kind === "arr" && Object.prototype.hasOwnProperty.call(node.ports, "items")) {
3209
- // #129: an arr node with an `items` port echoes the NATIVE port array (serialized to a Value array)
3210
- // so the node→leaf array dataflow test is non-vacuous.
3211
- echoBranches.push(`\tif src.echo == "items" {\n\t\treturn valueToWire(${serializeTyped(goPortFieldName("items"), ref, plan)}), nil\n\t}`);
3037
+ const prev = bySym.get(sym);
3038
+ if (prev !== undefined) {
3039
+ // #176/#183: a spec-fixed symbol MUST map to exactly ONE leaf (catalog component). The same leaf in
3040
+ // multiple roles shares ONE transport (byte-uniform signature) — accumulate its echo branches. Two
3041
+ // DIFFERENT catalog components colliding to the same symbol is a codegen error (never silent).
3042
+ if (prev.catalog !== catalog)
3043
+ throw new GeneratorFailure("DUPLICATE_COMPONENT", `go 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).`);
3044
+ for (const e of echo)
3045
+ if (!prev.echo.includes(e))
3046
+ prev.echo.push(e);
3047
+ continue;
3212
3048
  }
3213
- const canEcho = echoBranches.length > 0;
3214
- // params keep their field names (echo reads them); Go allows unused params, so no underscore needed.
3215
- const params = spread.map((pf) => `${pf.field} ${pf.goType}`).join(", ");
3216
- const echoBlock = canEcho ? `${echoBranches.join("\n")}\n` : "";
3217
- transportFns.push(`func ${sym}(${params}) (WireValue, error) {
3218
- src, ok := nextScripted(${JSON.stringify(catalog)})
3049
+ bySym.set(sym, { catalog, echo });
3050
+ }
3051
+ }
3052
+ for (const [sym, le] of bySym) {
3053
+ const echoBlock = le.echo.length > 0 ? `${le.echo.join("\n")}\n` : "";
3054
+ transportFns.push(`func ${sym}(payload WireRow) (WireValue, error) {
3055
+ _ = payload
3056
+ src, ok := nextScripted(${JSON.stringify(le.catalog)})
3219
3057
  if !ok {
3220
- return WireValue{}, unknownComponent(${JSON.stringify(catalog)})
3058
+ return WireValue{}, unknownComponent(${JSON.stringify(le.catalog)})
3221
3059
  }
3222
3060
  if src.isErr {
3223
3061
  return WireValue{}, leafFailure(src.err)
3224
3062
  }
3225
- ${echoBlock} return valueToWire(src.ok), nil
3063
+ ${echoBlock} // valueToWire is recursive: a batched/fanout []Value result becomes a WireList (a nil element ->
3064
+ // WireNull, the dangling marker), a single result a scalar/row wire -- ONE signature serves every
3065
+ // cardinality (the covered runner reads .Items for batched/fanout, the single wire for a point read).
3066
+ return valueToWire(src.ok), nil
3226
3067
  }`);
3227
- }
3228
3068
  }
3229
3069
  const adapter = `// scriptSrc — a scripted per-component outcome (an ok Value or an error), drained in order.
3230
3070
  // #129: \`echo\` carries the reference scriptedHandlers' \`echo\` directive (e.g. "items") so a scripted