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 { goStraightlineInternals } from "./emit-shared-go.js";
4
4
  import { goTypedInternals } from "./emit-shared-go-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, buildComponentPlan, nodeNarrowedPaths, } from "./straightline.js";
7
7
  import { NativeExprCompiler } from "./native-expr.js";
8
8
  import { buildDeBoxPlan, buildWirePlan, notationOfRef } from "./emit-shared-debox.js";
@@ -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";
@@ -815,16 +815,15 @@ function coveredMapNode(n, bodyIds, comp) {
815
815
  return false;
816
816
  const m = n.map;
817
817
  // #86 pt2: batched map...into. #93 shape 2/3: (non-)batched map...into / connection-collect. #108:
818
- // a guarded map (`when`) IS covered when it has NO `into`. #177: a guarded map WITH `into` is covered
819
- // ONLY when the into field is OPT — the augmented list is then homogeneous []ElemWithOptInto (kept
820
- // element → present into, guard-skipped element → into=nil), which is EXACTLY run_behavior's applyInto
821
- // pass-through (behavior.ts:846 — a skipped element is pushed unaugmented) followed by output
822
- // conformance materializing the absent opt-into field as null (behavior.ts:597 — keep-with-null). A
823
- // REQUIRED into field stays fail-closed: run_behavior FAILS MISSING_PROP on a skipped element there,
824
- // so rejecting is byte-equal. Opt-ness is read from the into field's declared type (the map node's
825
- // element outType); an element type that does not resolve to a named struct with the into field →
826
- // fail-closed (the resolvers below would reject it anyway).
827
- if (m.when !== undefined && m.into !== undefined && !guardedMapIntoIsOpt(n, comp))
818
+ // a guarded map (`when`) IS covered when it has NO `into`. #177/#182: a guarded map WITH `into` is
819
+ // covered when the guard-skipped element has a well-defined skip value — the into field is OPT
820
+ // (skip → nil, #177) OR relationKind:connection (skip → the empty connection {items:[],cursor:null},
821
+ // #182). The augmented list is then homogeneous (kept element → present into, skipped → the skip
822
+ // value), EXACTLY run_behavior's applyInto (a skipped connection into is filled with unproducedValue
823
+ // ("connection"), an opt into stays absent → output conformance null). A REQUIRED non-connection into
824
+ // stays fail-closed: run_behavior FAILS MISSING_PROP on a skipped element there, so rejecting is
825
+ // byte-equal. The skip value below (goZero of the into row type) yields nil / connection-struct-zero.
826
+ if (m.when !== undefined && m.into !== undefined && !guardedMapIntoIsCoverable(n, comp))
828
827
  return false;
829
828
  if (m.policy !== undefined && m.policy !== "fail")
830
829
  return false;
@@ -1034,36 +1033,6 @@ function assertTypedCoverage(comp) {
1034
1033
  return;
1035
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).`);
1036
1035
  }
1037
- // ── native ports struct + PortReader ──────────────────────────────────────────────────
1038
- function emitPortsStruct(comp, node, asBinding, plan, typedNodes, narrowed) {
1039
- const structName = portsStructName(comp.name, node.id);
1040
- const portNames = Object.keys(node.ports);
1041
- if (portNames.length === 0) {
1042
- return `// ${structName} — native ports for node '${node.id}' (${node.component}); no ports.\ntype ${structName} struct{}`;
1043
- }
1044
- // a node WITH ports always resolves through the one port lowering, which needs the type plan + the
1045
- // prior-node map (both are supplied by every caller — narrow the optional params for the fields below).
1046
- if (plan === undefined || typedNodes === undefined) {
1047
- throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `go typed-native: ports struct for node '${node.id}' needs a type plan + prior-node map`);
1048
- }
1049
- // #170: the field TYPE reads the SAME lowering (incl. gate/guard narrowing) the init does, so a narrowed
1050
- // opt-in-required port is a non-opt field AND a non-opt initializer — they can never disagree.
1051
- const portOpts = asBinding !== undefined ? { asBinding, asBase: asBinding.name, narrowed } : narrowed !== undefined ? { narrowed } : undefined;
1052
- const fieldTypes = portNames.map((p) => portFieldGoType(node.ports[p], comp, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[p], plan), `port '${p}' of node '${node.id}'`, portOpts));
1053
- const fieldNames = portNames.map(goPortFieldName);
1054
- const fields = portNames
1055
- .map((p, i) => `\t${fieldNames[i]} ${fieldTypes[i]} // ${JSON.stringify(p)}`)
1056
- .join("\n");
1057
- // NO PortReader `Port(name)` method: the covered handler reads the TYPED struct fields (ports.F_PK)
1058
- // DIRECTLY, so the boxed-Value PortReader impl (the last per-port `dslcontracts.Value` wrap on the
1059
- // covered plane) is DEAD — dropping it makes the ports struct fully native (bc#90 / runtime-free).
1060
- return `// ${structName} — NATIVE ports for node '${node.id}' (${node.component}). Typed fields per the
1061
- // static port type; built by direct field assignment (no map alloc, no per-port boxing). The consumer
1062
- // reads the typed fields DIRECTLY (no PortReader / boxed-Value accessor) — the covered read is native.
1063
- type ${structName} struct {
1064
- ${fields}
1065
- }`;
1066
- }
1067
1036
  /**
1068
1037
  * resolveLeafSymbol — the op-agnostic transport symbol a covered leaf (= catalog component) is called
1069
1038
  * through at its execution point. A consumer-supplied override (`leafTransport.symbols[component]`) wins;
@@ -1074,36 +1043,41 @@ ${fields}
1074
1043
  function goLeafSel(leaf) {
1075
1044
  return leaf?.import !== undefined ? `${leaf.import.split("/").pop().replace(/[^A-Za-z0-9_]/g, "_")}.` : "";
1076
1045
  }
1077
- /** leafSymbolBare — the UNQUALIFIED transport symbol name (consumer override or the default Leaf_<comp>).
1078
- * The ONE source for the name: call sites qualify it with the package selector (resolveLeafSymbol); the
1079
- * observe companion DEFINES the fn under this bare name (a definition carries no selector). */
1080
- function leafSymbolBare(component, leaf) {
1081
- 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)}`;
1053
+ }
1054
+ function resolveLeafSymbol(component, leaf, specSymbol) {
1055
+ return `${goLeafSel(leaf)}${leafSymbolBare(component, leaf, specSymbol)}`;
1082
1056
  }
1083
- function resolveLeafSymbol(component, leaf) {
1084
- return `${goLeafSel(leaf)}${leafSymbolBare(component, leaf)}`;
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}.` : "";
1085
1060
  }
1086
1061
  /**
1087
- * portFieldSpread — the covered node's port fields, in declared `Object.keys(ports)` order, each carrying
1088
- * its native ports-struct field name + Go type. The ONE place the transport-call port spread is derived
1089
- * (SSoT): a runner call site spreads `<var>.<F>`; the test observe transport fn declares matching params.
1090
- * Types come from the SAME `portFieldGoType` lowering `emitPortsStruct` uses, so the spread can never
1091
- * 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).
1092
1067
  */
1093
- function portFieldSpread(ports, portSchemas, comp, plan, typedNodes, asBinding, narrowed) {
1094
- // #170: the transport-call spread reads the SAME lowering (incl. gate/guard narrowing) as the ports
1095
- // struct fields — a narrowed opt-in-required port is a non-opt arg, matching the non-opt struct field.
1096
- // #173: `expected` (declared port type from portSchemas) drives the SAME materialization the struct
1097
- // field type uses, so the spread arg type can never disagree with the field type.
1098
- const opts = asBinding !== undefined ? { asBinding, asBase: asBinding.name, narrowed } : narrowed !== undefined ? { narrowed } : undefined;
1099
- return Object.keys(ports).map((pn) => ({
1100
- field: goPortFieldName(pn),
1101
- goType: portFieldGoType(ports[pn], comp, plan, typedNodes, inputPortTypeRef(portSchemas?.[pn], plan), `port '${pn}' of node '${comp.name}'`, opts),
1102
- }));
1103
- }
1104
- /** leafCallArgs — the spread transport-call arguments for a ports-struct var (Go: by value, no borrow). */
1105
- function leafCallArgs(varExpr, spread) {
1106
- 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})}})`;
1107
1081
  }
1108
1082
  /** RunNativeRawStruct_<comp> — the EXPORTED name of the per-component struct-returning combined runner
1109
1083
  * (bc#102). It MUST be an exported Go identifier so a consumer in a DIFFERENT package can call it (a
@@ -1117,50 +1091,6 @@ function runnerName(compName) {
1117
1091
  function mapElemMaterializerName(compName, nodeId) {
1118
1092
  return `materializeMapElemNR_${sanitize(compName)}_${nodeId.replace(/[^A-Za-z0-9_]/g, "_")}`;
1119
1093
  }
1120
- /**
1121
- * emitMapPortsStructs — the per-element native ports struct + the batch struct for a covered map
1122
- * node (bc#90 / runtime-free). The element struct is the same shape as a componentRef ports struct
1123
- * (typed fields per the static port type). The batch struct carries `Items []<elemStruct>` — a NATIVE
1124
- * slice of the concrete per-element ports structs (NO `[]dslcontracts.Value`, NO PortReader accessor);
1125
- * the consumer reads `bp.Items[i].F_PK` directly.
1126
- */
1127
- function emitMapPortsStructs(comp, node, typedNodes, plan) {
1128
- const m = node.map;
1129
- const structName = portsStructName(comp.name, node.id);
1130
- // #108: the element ports may read the `$as` binding ($id / $g.field) — resolve the over element
1131
- // type so those ports type their struct field natively (map-over-input scalar element / prior-node
1132
- // struct element). A pure-static/concat port ignores the binding.
1133
- const { elemRef } = mapOverElemInfo(comp, node, typedNodes, plan);
1134
- const asBinding = { name: m.as, ref: elemRef, plan };
1135
- // #170: a guarded map (`when(ne($e.key,null))`) proves the element key non-null in kept elements — narrow it.
1136
- const elemStruct = emitPortsStruct(comp, { id: node.id, component: m.component, ports: m.ports, portSchemas: m.portSchemas }, asBinding, plan, typedNodes, nodeNarrowedPaths(comp, node));
1137
- const batchStruct = `${structName}_batch`;
1138
- return `${elemStruct}
1139
-
1140
- // ${batchStruct} — NATIVE batched ports for map '${node.id}': Items is a native slice of the concrete
1141
- // per-element ports structs (${structName}). The consumer reads Items[i].<Field> DIRECTLY — no boxed
1142
- // []Value, no PortReader accessor, no key-value object (bc#90 / runtime-free).
1143
- type ${batchStruct} struct {
1144
- Items []${structName}
1145
- }`;
1146
- }
1147
- /** emitFanoutPortsStructs (v3) — the per-body element ports struct + the batch struct for a covered
1148
- * fanout node (identical shape to a batched map's ports). The element ports read the `$as` id binding. */
1149
- function emitFanoutPortsStructs(comp, node, typedNodes, plan) {
1150
- const f = node.fanout;
1151
- const structName = portsStructName(comp.name, node.id);
1152
- const { elemRef } = fanoutOverElemInfo(comp, node, typedNodes, plan);
1153
- const asBinding = { name: f.as, ref: elemRef, plan };
1154
- const elemStruct = emitPortsStruct(comp, { id: node.id, component: f.component, ports: f.ports, portSchemas: f.portSchemas }, asBinding, plan, typedNodes);
1155
- const batchStruct = `${structName}_batch`;
1156
- return `${elemStruct}
1157
-
1158
- // ${batchStruct} — NATIVE batched ports for fanout '${node.id}': Items is a native slice of the concrete
1159
- // per-id ports structs (${structName}). The consumer reads Items[i].<Field> DIRECTLY (bc#90 / runtime-free).
1160
- type ${batchStruct} struct {
1161
- Items []${structName}
1162
- }`;
1163
- }
1164
1094
  /**
1165
1095
  * fanoutItemsElemRef (v3) — the connection items ELEMENT TypeRef for a covered fanout node. The fanout
1166
1096
  * outType is a connection struct `{items:[]Elem, cursor:*string}`; this returns Elem (the per-body row
@@ -1493,21 +1423,26 @@ function emitInDecoder(comp, plan) {
1493
1423
  * when the ref does not resolve to a REQUIRED (non-opt) native scalar (then the caller falls back to
1494
1424
  * the nvVE Value path — which keeps the runtime null/opt/TYPE_MISMATCH semantics). */
1495
1425
  /**
1496
- * emitPortInit — emit the port field build for one port as a FULLY NATIVE Go expression (bc#90 /
1497
- * runtime-free). Every covered port lowers to a concrete Go value assigned straight into the ports
1498
- * struct field — NO `dslcontracts.Value`, NO nvVE helper, NO `.(T)` type-assert:
1499
- * - a static string array (projection) → `[]string{"a", "b", ...}` (change #2);
1500
- * - a bare int/float number literal (e.g. Query `limit: 20`) → `int64(20)` / `float64(...)`;
1501
- * - a string/bool/scalar-input port → the native scalar expression (emitNativeScalar).
1502
- * A port that CANNOT lower natively FAILS CLOSED (there is no boxed Value fallback on the covered
1503
- * plane — a boxed escape would re-introduce the bc-runtime coupling this module removes). Returns the
1504
- * 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.
1505
1438
  */
1506
- function emitPortInit(pn, expr, comp, plan, typedNodes, isPrior, expected, opts) {
1439
+ function emitPortWireField(pn, expr, comp, plan, typedNodes, isPrior, expected, opts) {
1507
1440
  const c = compilePortNode(expr, comp, plan, typedNodes, isPrior, `port '${pn}'`, expected, opts);
1508
1441
  if (c.stmts.length > 0)
1509
- 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.`);
1510
- 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}}`;
1511
1446
  }
1512
1447
  /**
1513
1448
  * emitParallelStageArm (bc#87) — EXPLICIT static parallel orchestration for a real-concurrency stage.
@@ -1566,14 +1501,15 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1566
1501
  for (const i of refMembers) {
1567
1502
  const node = comp.body[i];
1568
1503
  const s = sanitize(node.id);
1569
- const structName = portsStructName(comp.name, comp.body[i].id);
1570
1504
  // every member's goroutine returns the result WIRE (a single WireValue); the ascending COMMIT phase
1571
1505
  // de-boxes it INLINE (so the wire — not the decode — is what the goroutine writes to its slot).
1572
1506
  lines.push(`\t\tvar wire_${s} ${wire.value}`);
1573
1507
  lines.push(`\t\tvar row_${s}Err error`);
1574
1508
  lines.push(`\t\trun_${s} := false`);
1575
- lines.push(`\t\tvar ps_${s} ${structName}`);
1576
- 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}`);
1577
1513
  }
1578
1514
  // 1) PREFLIGHT (ascending): parent-produced gate (+ #114 bindField bound-key gate) + ports build,
1579
1515
  // per member (BEFORE dispatch). For a bindField relation child the bound key is read from the SETTLED
@@ -1582,7 +1518,6 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1582
1518
  for (const i of refMembers) {
1583
1519
  const node = comp.body[i];
1584
1520
  const s = sanitize(node.id);
1585
- const structName = portsStructName(comp.name, node.id);
1586
1521
  let ind = "\t\t";
1587
1522
  const closers = [];
1588
1523
  // #125: a stage member gated by a PRIOR-stage control gate (`parent=gate, bindField:"ok"`). Its
@@ -1614,12 +1549,9 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1614
1549
  ind += "\t";
1615
1550
  }
1616
1551
  }
1617
- const inits = [];
1618
1552
  const narrowed = nodeNarrowedPaths(comp, node);
1619
- for (const pn of Object.keys(node.ports)) {
1620
- inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, atPos), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed, wireSel: wire.selector }));
1621
- }
1622
- 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)}`);
1623
1555
  lines.push(`${ind}run_${s} = true`);
1624
1556
  for (const c of closers)
1625
1557
  lines.push(c);
@@ -1637,9 +1569,9 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1637
1569
  lines.push(`\t\t\tgo func() {`);
1638
1570
  lines.push(`\t\t\t\tdefer wg.Done()`);
1639
1571
  lines.push(`\t\t\t\tdefer func() { <-sem }()`);
1640
- // DIRECT leaf transport call — the node's port fields spread off the preflight-built ports struct. No
1641
- // `bound` (BC's internal produced/skip gate is already applied in preflight — the leaf never sees it).
1642
- 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})`;
1643
1575
  lines.push(`\t\t\t\twire_${s}, row_${s}Err = ${call}`);
1644
1576
  lines.push(`\t\t\t}()`);
1645
1577
  lines.push(`\t\t}`);
@@ -1697,15 +1629,6 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1697
1629
  * consumer (graphddb) drives it and keeps the struct native. A Value observation is produced ONLY
1698
1630
  * by the separate serialize wrapper (run_native_raw_<comp>, below), the single outer Value boundary.
1699
1631
  */
1700
- /** isCrossPackageSharedNode — a node whose ports struct CROSSES the leaf-transport boundary as a whole
1701
- * value (the batch ports struct passed to the transport), so under --shared-types-import it must live in
1702
- * the shared package (else the transport package → covered package import cycle). Batched maps + fanouts
1703
- * pass `${struct}_batch{Items: []${struct}}`; every other node passes only primitive port fields, so its
1704
- * ports struct stays local. The SINGLE predicate emit() (skip-local) and the shared package (emit-there)
1705
- * both use — they never disagree. */
1706
- function isCrossPackageSharedNode(n) {
1707
- return "fanout" in n || ("map" in n && n.map.batched === true);
1708
- }
1709
1632
  function emitNativeRawRunner(comp, plan, flags, wire, leaf) {
1710
1633
  const ep = execPlan(comp);
1711
1634
  const order = ep.order;
@@ -1794,7 +1717,6 @@ function emitNativeRawRunner(comp, plan, flags, wire, leaf) {
1794
1717
  const node = comp.body[i];
1795
1718
  const meta = metas[i];
1796
1719
  const s = sanitize(node.id);
1797
- const structName = portsStructName(comp.name, node.id);
1798
1720
  const portNames = Object.keys(node.ports);
1799
1721
  const ref = typedNodes.get(node.id);
1800
1722
  lines.push(`\t// ── op '${node.id}' (${node.component}${node.relationKind ? ", relationKind:" + node.relationKind : ""}${node.parent ? ", parent:" + node.parent : ""}) ──`);
@@ -1833,20 +1755,16 @@ function emitNativeRawRunner(comp, plan, flags, wire, leaf) {
1833
1755
  indent += "\t";
1834
1756
  }
1835
1757
  }
1836
- // ports: build the native struct by direct field assignment (bc#90 / runtime-free). Every covered
1837
- // port lowers to a concrete Go value (literal / input-param ref / cross-node typed field / concat /
1838
- // static string array / number literal) assigned straight into the ports field — ZERO
1839
- // dslcontracts.Value, ZERO nvVE helper, ZERO `.(T)`. A genuinely-dynamic port FAILS CLOSED.
1840
- 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.
1841
1761
  const narrowed = nodeNarrowedPaths(comp, node);
1842
- for (const pn of portNames) {
1843
- inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed, wireSel: wire.selector }));
1844
- }
1845
- // DIRECT leaf transport call: the resolved op-agnostic symbol, the node's port fields spread. `bound` is
1846
- // 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
1847
1765
  // `if bound_<s> != nil` / `if produced_<parent>` guards; the leaf never receives it.
1848
- const call = `${resolveLeafSymbol(node.component, leaf)}(${leafCallArgs(`ports_${s}`, portFieldSpread(node.ports, node.portSchemas, comp, plan, typedNodes, undefined, nodeNarrowedPaths(comp, node)))})`;
1849
- 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)}`);
1850
1768
  // uniform seam: the transport returns a single result WIRE (${wire.value}); the inline de-box
1851
1769
  // (renderResultDeBox) classifies it against the STATICALLY declared result type and produces the
1852
1770
  // structured Error Value on a mismatch (byte-equal codes to run_behavior's outType check, so ≡ holds).
@@ -1938,13 +1856,7 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1938
1856
  // guarded NO-into map, which DROPs skipped elements. Byte-equal to run_behavior's applyInto keep-with-null.
1939
1857
  const keepWithNull = hasGuard && hasInto;
1940
1858
  const s = sanitize(node.id);
1941
- // #154 cross-package: a BATCHED map's element + batch ports structs live in the shared package (they
1942
- // cross the transport boundary as a whole value), so reference them selector-qualified here. A
1943
- // non-batched map passes only primitive fields, so its ports struct stays local (unqualified).
1944
- const q = wireSel !== undefined && batched ? `${wireSel}.` : "";
1945
- const structName = `${q}${portsStructName(comp.name, node.id)}`;
1946
- const batchStruct = `${structName}_batch`;
1947
- const leafSym = resolveLeafSymbol(m.component, leaf);
1859
+ const leafSym = resolveLeafSymbol(m.component, leaf, m.leafSymbol);
1948
1860
  const arrRef = typedNodes.get(node.id);
1949
1861
  const elemGo = renderTypeRef(arrRef);
1950
1862
  const asName = m.as;
@@ -1966,15 +1878,20 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1966
1878
  const be = makeGoExprBackend(zeroOut, resolveHead, plan);
1967
1879
  return new NativeExprCompiler(be).compileBool(m.when);
1968
1880
  };
1969
- // emit the per-element native ports struct build (shared; `il` is the indent inside the element
1970
- // loop, `elemVar` the over element loop variable). Returns the lines building `ep_<s>`.
1971
- 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) => {
1972
1883
  const asBinding = { name: asName, ref: overElemRef, plan };
1973
1884
  // #170: a guarded map narrows its `when(ne($e.key,null))`-proven element key non-null in kept elements.
1974
1885
  const narrowed = nodeNarrowedPaths(comp, node);
1975
- const inits = portNames.map((pn) => emitPortInit(pn, m.ports[pn], comp, plan, typedNodes, priorHere, inputPortTypeRef(m.portSchemas?.[pn], plan), { asBinding, asBase: elemVar, narrowed, wireSel }));
1976
- 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 }));
1977
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)}`];
1978
1895
  const lines = [];
1979
1896
  const closers = [];
1980
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 : ""}) ──`);
@@ -1998,6 +1915,14 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1998
1915
  const elemRowRef = mapElemRowRef(node, arrRef, plan);
1999
1916
  const elemRowGo = renderTypeRef(elemRowRef);
2000
1917
  const renderElemDeBox = (target, src, il) => renderResultDeBox(elemRowRef, target, src, node.id, plan, il, returnZeroFail(zeroOut), nodeWirePassthrough(node));
1918
+ // #177/#182 keep-with-skip-value: the into value for a guard-skipped element is driven by relationKind,
1919
+ // NOT by opt-ness (matching run_behavior applyInto, which fills a connection into with the empty
1920
+ // connection UNCONDITIONALLY on relationKind==="connection"):
1921
+ // - connection into → the connection-zero in the field's typed rep (goConnectionUnproduced): a required
1922
+ // `Conn` field → `Tn{}`, an OPT `*Conn` field → a non-nil `&Tn{}` (Some(empty connection), NOT nil).
1923
+ // `Tn{}`'s serializer normalizes nil items to [] → {items:[],cursor:null} (#182).
1924
+ // - non-connection into → the go zero (opt → nil = null, #177 keep-with-null; unchanged).
1925
+ const intoSkipZero = m.relationKind === "connection" ? goConnectionUnproduced(elemRowRef, elemRowRef) : goZero(elemRowRef);
2001
1926
  // emit the per-element guard keep-gate (#108). `il` = indent, `elemVar` = the over element loop var.
2002
1927
  // On skip: batched → `continue` (element excluded from items + keptOver); non-batched → `continue`.
2003
1928
  const emitGuard = (il, elemVar, onSkip = ["continue"]) => {
@@ -2020,29 +1945,31 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
2020
1945
  // ports, then the aligned rows are de-boxed and zipped back onto their over-index slots. Byte-equal to
2021
1946
  // run_behavior: batched keptIdx-aligned collect + applyInto (skipped element unaugmented → opt-into null).
2022
1947
  const g = mkGuard(elemLocal(s));
2023
- lines.push(`${indent}items_${s} := make([]${structName}, 0, len(over_${s}))`);
1948
+ lines.push(`${indent}items_${s} := make([]${wvQ}WireValue, 0, len(over_${s}))`);
2024
1949
  lines.push(`${indent}keptIdx_${s} := make([]int, 0, len(over_${s}))`);
2025
1950
  lines.push(`${indent}for oi_${s} := range over_${s} {`);
2026
1951
  lines.push(`${indent}\t${elemLocal(s)} := over_${s}[oi_${s}]`);
2027
1952
  for (const st of g.stmts)
2028
1953
  lines.push(`${indent}\t${st}`);
2029
1954
  lines.push(`${indent}\tif ${g.expr} {`);
2030
- for (const l of buildPorts(indent + "\t\t", elemLocal(s)))
1955
+ for (const l of buildBatchElem(indent + "\t\t", elemLocal(s)))
2031
1956
  lines.push(l);
2032
1957
  lines.push(`${indent}\t\titems_${s} = append(items_${s}, ep_${s})`);
2033
1958
  lines.push(`${indent}\t\tkeptIdx_${s} = append(keptIdx_${s}, oi_${s})`);
2034
1959
  lines.push(`${indent}\t} else {`);
2035
- lines.push(`${indent}\t\t${typedLocal(node.id)}[oi_${s}] = ${elemMat}(${elemLocal(s)}, nil)`);
1960
+ lines.push(`${indent}\t\t${typedLocal(node.id)}[oi_${s}] = ${elemMat}(${elemLocal(s)}, ${intoSkipZero})`);
2036
1961
  lines.push(`${indent}\t}`);
2037
1962
  lines.push(`${indent}}`);
2038
1963
  lines.push(`${indent}if len(items_${s}) > 0 {`);
2039
- lines.push(`${indent}\tbp_${s} := ${batchStruct}{Items: items_${s}}`);
2040
- 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)})`);
2041
1967
  lines.push(`${indent}\tif mo_${s}Err != nil {`, `${indent}\t\treturn ${zeroOut}, opFailed(${JSON.stringify(node.id)}, "fail", mo_${s}Err)`, `${indent}\t}`);
2042
- 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}`);
2043
1970
  lines.push(`${indent}\tfor mk_${s} := range items_${s} {`);
2044
1971
  lines.push(`${indent}\t\tvar dec_${s} ${elemRowGo}`);
2045
- 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`));
2046
1973
  lines.push(`${indent}\t\t${typedLocal(node.id)}[keptIdx_${s}[mk_${s}]] = ${elemMat}(over_${s}[keptIdx_${s}[mk_${s}]], dec_${s})`);
2047
1974
  lines.push(`${indent}\t}`);
2048
1975
  lines.push(`${indent}}`);
@@ -2052,13 +1979,13 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
2052
1979
  // dispatch ONCE. The concrete Node_* returns the aligned per-element WIRES ([]WireValue) or an error.
2053
1980
  // With a guard, `items` (and, for into, `keptOver`) hold only kept elements — matching run_behavior's
2054
1981
  // keptIdx-aligned batch. `into` is never combined with a guard (rejected). Each wire is de-boxed inline.
2055
- lines.push(`${indent}items_${s} := make([]${structName}, 0, len(over_${s}))`);
1982
+ lines.push(`${indent}items_${s} := make([]${wvQ}WireValue, 0, len(over_${s}))`);
2056
1983
  if (hasInto)
2057
1984
  lines.push(`${indent}keptOver_${s} := make([]${overElemGo}, 0, len(over_${s}))`);
2058
1985
  lines.push(`${indent}for _, ${elemLocal(s)} := range over_${s} {`);
2059
1986
  for (const l of emitGuard(indent + "\t", elemLocal(s)))
2060
1987
  lines.push(l);
2061
- for (const l of buildPorts(indent + "\t", elemLocal(s)))
1988
+ for (const l of buildBatchElem(indent + "\t", elemLocal(s)))
2062
1989
  lines.push(l);
2063
1990
  lines.push(`${indent}\titems_${s} = append(items_${s}, ep_${s})`);
2064
1991
  if (hasInto)
@@ -2066,27 +1993,26 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
2066
1993
  lines.push(`${indent}}`);
2067
1994
  // empty items => empty result (handler not called), matching run_behavior.
2068
1995
  lines.push(`${indent}if len(items_${s}) > 0 {`);
2069
- lines.push(`${indent}\tbp_${s} := ${batchStruct}{Items: items_${s}}`);
2070
- // DIRECT transport call — the batched dispatch takes the CONCRETE batch ports struct (shape unchanged;
2071
- // only the call target changes). Returns the aligned per-element wires ([]WireValue). No `bound`.
2072
- 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)})`);
2073
1998
  lines.push(`${indent}\tif mo_${s}Err != nil {`, `${indent}\t\treturn ${zeroOut}, opFailed(${JSON.stringify(node.id)}, "fail", mo_${s}Err)`, `${indent}\t}`);
2074
- 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}`);
2075
2001
  if (hasInto) {
2076
2002
  // #86 pt2: de-box each aligned element wire (into the `into` field's type), then zip-attach onto the
2077
2003
  // kept over element (augmented element copier).
2078
2004
  lines.push(`${indent}\tfor mk_${s} := range keptOver_${s} {`);
2079
2005
  lines.push(`${indent}\t\tvar dec_${s} ${elemRowGo}`);
2080
- 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`));
2081
2007
  lines.push(`${indent}\t\tel_${s} := ${elemMat}(keptOver_${s}[mk_${s}], dec_${s})`);
2082
2008
  lines.push(`${indent}\t\t${typedLocal(node.id)} = append(${typedLocal(node.id)}, el_${s})`);
2083
2009
  lines.push(`${indent}\t}`);
2084
2010
  }
2085
2011
  else {
2086
2012
  // #93 shape 3 / #108: de-box each aligned per-element wire DIRECTLY into the element (result = kept).
2087
- 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}++ {`);
2088
2014
  lines.push(`${indent}\t\tvar el_${s} ${renderTypeRef(arrRef.elem)}`);
2089
- 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`));
2090
2016
  lines.push(`${indent}\t\t${typedLocal(node.id)} = append(${typedLocal(node.id)}, el_${s})`);
2091
2017
  lines.push(`${indent}\t}`);
2092
2018
  }
@@ -2098,22 +2024,22 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
2098
2024
  // (no dispatch, excluded from the result). The concrete Node_* returns ONE element WIRE (WireValue).
2099
2025
  lines.push(`${indent}for mk_${s} := range over_${s} {`);
2100
2026
  lines.push(`${indent}\t${elemLocal(s)} := over_${s}[mk_${s}]`);
2101
- // #177 keep-with-null: a guard-skipped element is KEPT with into=nil (elemMat(over,nil)) instead of
2102
- // dropped — byte-equal to run_behavior's applyInto pass-through + opt-into null.
2027
+ // #177/#182 keep-with-skip-value: a guard-skipped element is KEPT with into=intoSkipZero
2028
+ // (elemMat(over, nil | connZero)) instead of dropped — byte-equal to run_behavior's applyInto
2029
+ // (opt-into → null / connection-into → empty connection).
2103
2030
  const nonBatchedSkip = keepWithNull
2104
- ? [`${typedLocal(node.id)} = append(${typedLocal(node.id)}, ${elemMat}(${elemLocal(s)}, nil))`, "continue"]
2031
+ ? [`${typedLocal(node.id)} = append(${typedLocal(node.id)}, ${elemMat}(${elemLocal(s)}, ${intoSkipZero}))`, "continue"]
2105
2032
  : ["continue"];
2106
2033
  for (const l of emitGuard(indent + "\t", elemLocal(s), nonBatchedSkip))
2107
2034
  lines.push(l);
2108
- for (const l of buildPorts(indent + "\t", elemLocal(s)))
2035
+ for (const l of buildPayloadElem(indent + "\t", elemLocal(s)))
2109
2036
  lines.push(l);
2110
- // per-element dispatch (ONE physical request per element). run_behavior passes the over element
2111
- // as the bound value; the element data is fully conveyed by the native ports struct here, so bound
2112
- // stays nil. Byte-equivalence holds because the bound value only feeds handler-internal logic.
2113
- // Element Error Policy (scp-error.md): `skip` drops the failing element and proceeds (order is
2114
- // preserved; the leaf keeps the Error Value it produced). `error` (default) promotes the element
2115
- // Failure to the map's Component Failure, carrying the leaf's detail through.
2116
- 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})`);
2117
2043
  if (m.elementPolicy === "skip") {
2118
2044
  lines.push(`${indent}\tif mo_${s}Err != nil {`, `${indent}\t\tcontinue`, `${indent}\t}`);
2119
2045
  }
@@ -2157,12 +2083,8 @@ function elemLocal(s) {
2157
2083
  function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, leaf, wireSel) {
2158
2084
  const f = node.fanout;
2159
2085
  const s = sanitize(node.id);
2160
- // #154 cross-package: a fanout's element + batch ports structs cross the transport boundary as a whole
2161
- // value, so they live in the shared package — reference them selector-qualified here (else in-package).
2162
- const q = wireSel !== undefined ? `${wireSel}.` : "";
2163
- const structName = `${q}${portsStructName(comp.name, node.id)}`;
2164
- const batchStruct = `${structName}_batch`;
2165
- const leafSym = resolveLeafSymbol(f.component, leaf);
2086
+ const wvQ = goWireQ(wireSel);
2087
+ const leafSym = resolveLeafSymbol(f.component, leaf, f.leafSymbol);
2166
2088
  const connRef = typedNodes.get(node.id);
2167
2089
  const elemRef = fanoutItemsElemRef(node, connRef, plan);
2168
2090
  const elemGo = renderTypeRef(elemRef);
@@ -2179,11 +2101,12 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut
2179
2101
  if (!dkField || dkField.type.kind !== "scalar" || dkField.type.scalar !== "string")
2180
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}'.`);
2181
2103
  const dkGo = goFieldName(f.dedupeKey);
2182
- // 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.
2183
2106
  const buildPorts = (il, elemVar) => {
2184
2107
  const asBinding = { name: asName, ref: overElemRef, plan };
2185
- const inits = portNames.map((pn) => emitPortInit(pn, f.ports[pn], comp, plan, typedNodes, priorHere, inputPortTypeRef(f.portSchemas?.[pn], plan), { asBinding, asBase: elemVar, wireSel }));
2186
- 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(", ")}})`];
2187
2110
  };
2188
2111
  const lines = [];
2189
2112
  const closers = [];
@@ -2198,7 +2121,7 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut
2198
2121
  for (const l of goBindOver(indent, s, overExpr, overOptArr, overElemGo))
2199
2122
  lines.push(l);
2200
2123
  lines.push(`${indent}var items_${s} []${elemGo}`);
2201
- lines.push(`${indent}pi_${s} := make([]${structName}, 0, len(over_${s}))`);
2124
+ lines.push(`${indent}pi_${s} := make([]${wvQ}WireValue, 0, len(over_${s}))`);
2202
2125
  lines.push(`${indent}for _, ${elemLocal(s)} := range over_${s} {`);
2203
2126
  for (const l of buildPorts(indent + "\t", elemLocal(s)))
2204
2127
  lines.push(l);
@@ -2206,24 +2129,22 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut
2206
2129
  lines.push(`${indent}}`);
2207
2130
  // empty id-list => empty connection (handler not called), matching run_behavior.
2208
2131
  lines.push(`${indent}if len(pi_${s}) > 0 {`);
2209
- lines.push(`${indent}\tbp_${s} := ${batchStruct}{Items: pi_${s}}`);
2210
- // the handler returns the aligned per-id element WIRES (one nilable WireValue per id); each present
2211
- // body is de-boxed strictly INLINE (a de-box mismatch fails closed). A DANGLING id is a nil wire → the
2212
- // zero element (empty dedupeKey), which the dangling drop below excludes.
2213
- // DIRECT transport call — the batched fanout dispatch takes the CONCRETE batch ports struct (shape
2214
- // unchanged; only the call target changes). Returns the aligned per-id element wires. No `bound`.
2215
- 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)})`);
2216
2136
  lines.push(`${indent}\tif fo_${s}Err != nil {`, `${indent}\t\treturn ${zeroOut}, opFailed(${JSON.stringify(node.id)}, "fail", fo_${s}Err)`, `${indent}\t}`);
2217
- 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}`);
2218
2139
  // ── THE ONE dedupe/drop (mirrors fanoutDedupDrop verbatim): first-seen dedupe by dedupeKey field;
2219
2140
  // drop dangling (zero dedupeKey ≡ interpreter's null/absent-key body); implicitSource strip is
2220
2141
  // structural (the elem type already omits it). cursor is always nil (connection wrap).
2221
- lines.push(`${indent}\tseen_${s} := make(map[string]struct{}, len(fo_${s}))`);
2222
- lines.push(`${indent}\titems_${s} = make([]${elemGo}, 0, len(fo_${s}))`);
2223
- 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} {`);
2224
2145
  lines.push(`${indent}\t\tvar el_${s} ${elemGo}`);
2225
- lines.push(`${indent}\t\tif fo_${s}[fi_${s}] != nil {`);
2226
- 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)));
2227
2148
  lines.push(`${indent}\t\t}`);
2228
2149
  lines.push(`${indent}\t\tkey_${s} := el_${s}.${dkGo}`);
2229
2150
  if (f.drop === "dangling") {
@@ -2489,10 +2410,12 @@ const goExprUsed = { helpers: false };
2489
2410
  * - `record` box each declared field to its wire ctor recursively, assemble a WireRow of (name, WireValue)
2490
2411
  * entries — the typed `obj<…>` → wire map ("M") crossing (the real op-agnostic `arr<value>`
2491
2412
  * batch-write param fed a typed `arr<obj>`);
2492
- * - `list` box each element recursively into a WireList ("L").
2493
- * A `map` value or an OPT-wrapped element (optDepth > 0) boxes AMBIGUOUSLY (map key order / opt present-vs-null
2494
- * on the wire are not statically pinned to run_behavior's Value pass-through), so it stays FAIL-CLOSED LOUD
2495
- * 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.
2496
2419
  */
2497
2420
  function renderGoWireBox(plan, srcExpr, wireSel, depth = 0) {
2498
2421
  // #174: cross-package (`--shared-types-import`) the wire CONSTRUCTORS + composite TYPES live in the shared
@@ -2500,36 +2423,68 @@ function renderGoWireBox(plan, srcExpr, wireSel, depth = 0) {
2500
2423
  // `[]wire.WireField{…}`); in-package they are local (bare). Without this the type is `wire.WireValue` but the
2501
2424
  // ctor is a bare `WireFloat` → does not compile.
2502
2425
  const q = wireSel !== undefined && wireSel !== "" ? `${wireSel}.` : "";
2503
- 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) => {
2504
2431
  if (plan.k === "value")
2505
- return srcExpr; // identity — already the opaque BC wire.
2432
+ return baseSrc; // identity — already the opaque BC wire.
2506
2433
  if (plan.k === "scalar") {
2507
2434
  switch (plan.scalar) {
2508
2435
  case "string":
2509
- return `${q}WireStr(${srcExpr})`;
2436
+ return `${q}WireStr(${baseSrc})`;
2510
2437
  case "int":
2511
- return `${q}WireInt(${srcExpr})`;
2438
+ return `${q}WireInt(${baseSrc})`;
2512
2439
  case "float":
2513
- return `${q}WireFloat(${srcExpr})`;
2440
+ return `${q}WireFloat(${baseSrc})`;
2514
2441
  case "bool":
2515
- return `${q}WireBool(${srcExpr})`;
2442
+ return `${q}WireBool(${baseSrc})`;
2516
2443
  }
2517
2444
  }
2518
2445
  if (plan.k === "record") {
2519
2446
  // typed struct → wire map: box each declared field off its native struct field (no probe — the value is
2520
2447
  // already typed), assemble a WireRow of (name, WireValue) in declared-field order.
2521
- 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)}}`);
2522
2449
  return `${q}WireRowOf([]${q}WireField{${entries.join(", ")}})`;
2523
2450
  }
2524
2451
  if (plan.k === "list") {
2525
2452
  // typed slice → wire list: box each element recursively (box-once, no round-trip). An empty slice yields
2526
2453
  // an empty (non-nil) WireList — byte-equal to run_behavior's [] pass-through.
2527
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})`;
2528
2460
  const items = `it${depth}`;
2529
- 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}) }()`;
2530
2462
  }
2531
- }
2532
- 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 or map element boxes ambiguously — fail-closed rather than risk a run_behavior divergence)`);
2463
+ if (plan.k === "map") {
2464
+ // bc#181: typed map<V> → wire map, represented as a dynamic-keyed WireRow (there is NO WireMap type; a
2465
+ // declared map<V> is the dynamic-keyed twin of a record — the READ side de-boxes a WireRow INTO map<V>
2466
+ // the SAME way, emit-shared-debox `mapval`). Box EACH entry's VALUE recursively (box-once); keys carried
2467
+ // as dynamic strings, SORTED (Go map iteration is randomized) so the WireRow is DETERMINISTIC — matching
2468
+ // the canonical code-point key order the typed serialize / de-box use.
2469
+ const keys = `mk${depth}`;
2470
+ const key = `k${depth}`;
2471
+ const fields = `mf${depth}`;
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}) }()`;
2473
+ }
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);
2533
2488
  }
2534
2489
  function makeGoExprBackend(zeroOut, resolveHead, plan,
2535
2490
  // #174: cross-package selector for the shared wire constructors (`wire`); undefined/"" ⇒ in-package (bare).
@@ -2542,6 +2497,13 @@ wireSel) {
2542
2497
  wireType: () => renderTypeRef({ kind: "value" }),
2543
2498
  // bc#156/#160: box a value[] element into the opaque BC wire via the ONE box SSoT (owned element expr).
2544
2499
  wireBox: (item) => renderGoWireBox(buildWirePlan(item.ref, { from: "top" }, { model: "port", field: "port", plan }, "in"), item.expr, wireSel),
2500
+ // bc#178: box EACH element of the typed slice into an arr<value> ([]WireValue) — the same per-element box
2501
+ // renderer as wireBox's list case, applied over the referenced array (box-once/element).
2502
+ wireBoxEachElem: (srcExpr, elemRef) => {
2503
+ const vt = renderTypeRef({ kind: "value" });
2504
+ const box = renderGoWireBox(buildWirePlan(elemRef, { from: "elem" }, { model: "port", field: "port", plan }, "in"), "__be", wireSel);
2505
+ return `func() []${vt} { __out := []${vt}{}; for _, __be := range ${srcExpr} { __out = append(__out, ${box}) }; return __out }()`;
2506
+ },
2545
2507
  scalarType: (s) => goScalar(s),
2546
2508
  strLit: (s) => JSON.stringify(s),
2547
2509
  boolLit: (b) => (b ? "true" : "false"),
@@ -2747,13 +2709,17 @@ var ComponentNamesNativeRaw = []string{${native.map((c) => JSON.stringify(c.name
2747
2709
  * mismatch Sprintf, `strings` for a concat builder, `sync` for a parallel stage). ExpectedSpecVersions
2748
2710
  * stays as a local `var` for provenance, but the old `dslcontracts.SpecVersions` skew `init()` is GONE
2749
2711
  * (change #5 — there is no runtime to skew against once the module is runtime-free). */
2750
- function emitMinimalHeader(ctx, needStrings, needSync, needFmt, needMath, needStrconv = false, wireImport, leafImport) {
2712
+ function emitMinimalHeader(ctx, needStrings, needSync, needFmt, needMath, needStrconv = false, wireImport, leafImport, needSort = false) {
2751
2713
  const sv = ctx.specVersions;
2752
2714
  const imports = [];
2753
2715
  if (needFmt)
2754
2716
  imports.push(`\t"fmt"`);
2755
2717
  if (needMath)
2756
2718
  imports.push(`\t"math"`);
2719
+ // bc#181: `sort` is imported iff a generated typed→wire map box emits `sort.Strings` (deterministic
2720
+ // dynamic-key WireRow). Kept in std alphabetical order (math < sort < strconv) so gofmt is a no-op.
2721
+ if (needSort)
2722
+ imports.push(`\t"sort"`);
2757
2723
  if (needStrconv)
2758
2724
  imports.push(`\t"strconv"`);
2759
2725
  if (needStrings)
@@ -2802,44 +2768,19 @@ function emit(ctx) {
2802
2768
  const leaf = ctx.leafTransport;
2803
2769
  // Emit the runners first so the nv* helper usage flags are known.
2804
2770
  const flags = { bind: false, field: false, cat: false, arr: false };
2805
- const structs = [];
2806
2771
  const inStructs = [];
2807
2772
  const elemCopiers = [];
2808
2773
  const runnerCodes = [];
2809
2774
  // every covered node returns a WireValue the inline de-box classifies — the wire seam (probe kind
2810
2775
  // consts + probe RESULT structs) is emitted once whenever any handler node exists.
2811
2776
  const anyWire = native.some((c) => c.body.some((n) => !("cond" in n)));
2812
- // #154 cross-package (--shared-types-import): a batched-map / fanout batch ports struct crosses the
2813
- // transport boundary as a whole value, so it lives in the SHARED package (goSharedWireTypesPackage),
2814
- // NOT the covered module — else the transport package would import the covered package (cycle). Every
2815
- // other ports struct passes only primitive fields and stays local.
2816
- 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.
2817
2780
  for (const c of native) {
2818
2781
  inStructs.push(emitInStruct(c, plan));
2819
2782
  // build the full typed-node map FIRST so a map's over-element resolution can see every node.
2820
2783
  const typedNodes = buildTypedNodes(c, plan);
2821
- for (const n of c.body) {
2822
- if (crossPackage && isCrossPackageSharedNode(n)) {
2823
- // emitted in the shared package instead (goSharedWireTypesPackage), referenced here as <sel>.<T>.
2824
- }
2825
- else if ("fanout" in n) {
2826
- // v3: a fanout node emits a per-id element ports struct + a batch struct (like a batched map).
2827
- structs.push(emitFanoutPortsStructs(c, n, typedNodes, plan));
2828
- }
2829
- else if ("map" in n) {
2830
- // #86 pt2 / #108: a map node emits an element ports struct + a batch struct. The element ports
2831
- // may read the `$as` binding — resolved via the over-element type (prior node / input array).
2832
- structs.push(emitMapPortsStructs(c, n, typedNodes, plan));
2833
- }
2834
- else if ("cond" in n) {
2835
- // #108: a cond node has NO ports struct (it is a pure Expression — no handler dispatch).
2836
- }
2837
- else {
2838
- // #129: pass typedNodes so a leaf array port fed by a prior node's arr outType types as []ElemT.
2839
- // #170: a gated child narrows its gate-proven opt key (field type must match the narrowed init).
2840
- structs.push(emitPortsStruct(c, n, undefined, plan, typedNodes, nodeNarrowedPaths(c, n)));
2841
- }
2842
- }
2843
2784
  // augmented-element copiers for covered map...into nodes (over fields + the de-boxed into value).
2844
2785
  const mm = emitMapElemMaterializers(c, typedNodes, plan);
2845
2786
  if (mm)
@@ -2883,7 +2824,9 @@ function emit(ctx) {
2883
2824
  // probe consts, so it references nothing from the shared package and must NOT import it (an unused import
2884
2825
  // is a Go compile error). The `<sel>.` prefix covers both (wire.value is `<sel>.WireValue`).
2885
2826
  const needWireImport = wire.import !== undefined && wire.selector !== undefined && runnerCodes.some((c) => c.includes(`${wire.selector}.`));
2886
- const header = emitMinimalHeader(ctx, false, needSync, needFmt, needMath, needStrconv, needWireImport ? wire.import : undefined, leaf?.import);
2827
+ // bc#181: `sort` iff a generated typed→wire map box emitted `sort.Strings` (deterministic dynamic-key WireRow).
2828
+ const needSort = runnerCodes.some((c) => c.includes("sort.Strings"));
2829
+ const header = emitMinimalHeader(ctx, false, needSync, needFmt, needMath, needStrconv, needWireImport ? wire.import : undefined, leaf?.import, needSort);
2887
2830
  const banner = `// COMBINED READ layer (bc#90 — the RUNTIME-FREE read de-box; STRUCT-ONLY, FULLY-NATIVE surface). A
2888
2831
  // covered read is a strictly-sequential typed componentRef chain (point reads + relationKind:single
2889
2832
  // children), emitted ONLY here: each node builds a native ports struct by direct field assignment (every
@@ -2914,9 +2857,6 @@ function emit(ctx) {
2914
2857
  elemCopiers.length
2915
2858
  ? `// Augmented map-element copiers (over element fields + the concrete into row — pure assignment).\n${elemCopiers.join("\n\n")}`
2916
2859
  : undefined,
2917
- structs.some((r) => r.trim().length > 0)
2918
- ? `// Native ports structs (one per componentRef node; typed per the static port type).\n${structs.filter((r) => r.trim().length > 0).join("\n\n")}`
2919
- : undefined,
2920
2860
  goExprUsed.helpers
2921
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()}`
2922
2862
  : undefined,
@@ -2928,34 +2868,14 @@ function emit(ctx) {
2928
2868
  /**
2929
2869
  * goSharedWireTypesPackage — the BC-GENERATED shared package (Task A cross-package). Emits the SAME seam the
2930
2870
  * covered module emits in-package (emitGoProbeKinds + emitProbeWireTypes + emitGoWireTypes) into a standalone
2931
- * package, so a separate leaf-transport package can return `WireValue` (and the covered module reference it)
2932
- * without an import cycle. When `ir` is given, ALSO emits the batched-map / fanout batch ports structs (the
2933
- * ONLY covered-module types that cross the transport boundary as a whole value) — same `emitMapPortsStructs`
2934
- * / `emitFanoutPortsStructs` + same `isCrossPackageSharedNode` predicate `emit()` uses to skip them locally,
2935
- * so the two never disagree (SSoT). Self-contained (only `strconv` for the numeric constructors). `pkgName`
2936
- * is the package's Go identifier (the last path segment of `sharedTypesImport`). */
2937
- export function goSharedWireTypesPackage(pkgName, ir) {
2938
- const portsStructs = [];
2939
- if (ir !== undefined) {
2940
- const components = ir.components;
2941
- const plan = buildTypePlan(ir);
2942
- for (const c of components.filter(isNativeRaw)) {
2943
- const typedNodes = buildTypedNodes(c, plan);
2944
- for (const n of c.body) {
2945
- if (!isCrossPackageSharedNode(n))
2946
- continue;
2947
- portsStructs.push("fanout" in n
2948
- ? emitFanoutPortsStructs(c, n, typedNodes, plan)
2949
- : emitMapPortsStructs(c, n, typedNodes, plan));
2950
- }
2951
- }
2952
- }
2953
- const portsSection = portsStructs.length
2954
- ? `\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")}`
2955
- : "";
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) {
2956
2876
  return `// GENERATED by behavior-contracts (go-typed-native) — the BC-OWNED shared wire types. A covered module
2957
- // generated with --shared-types-import imports this; a separate leaf-transport package returns its
2958
- // 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.
2959
2879
  package ${pkgName}
2960
2880
 
2961
2881
  import "strconv"
@@ -2964,7 +2884,7 @@ ${emitGoProbeKinds()}
2964
2884
 
2965
2885
  ${emitProbeWireTypes({ row: "WireRow", list: "WireList" })}
2966
2886
 
2967
- ${emitGoWireTypes()}${portsSection}
2887
+ ${emitGoWireTypes()}
2968
2888
  `;
2969
2889
  }
2970
2890
  /**
@@ -3058,13 +2978,16 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
3058
2978
  }`
3059
2979
  : "";
3060
2980
  // ── op-agnostic leaf TRANSPORT funcs (TEST glue) — the scripted analog of the consumer's transport
3061
- // symbols. ONE free `Leaf_<component>` per DISTINCT covered leaf (catalog component) in the IR (a
3062
- // per-module leaf has one consistent shape — verified), draining the shared package-level scripted queue
3063
- // and returning the scripted wire in EXACTLY the shape the removed per-node method returned. bc#87
3064
- // parallel goroutines share the queue (mutex-guarded); cases run sequentially so a shared package var is
3065
- // 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). ──
3066
2989
  const transportFns = [];
3067
- const emittedLeaf = new Set();
2990
+ const bySym = new Map();
3068
2991
  for (const c of native) {
3069
2992
  const typedNodes = new Map();
3070
2993
  for (const n of c.body)
@@ -3074,125 +2997,74 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
3074
2997
  if ("cond" in n)
3075
2998
  continue; // #108: cond has no leaf (pure Expression) — no transport fn.
3076
2999
  const catalog = "fanout" in n ? n.fanout.component : "map" in n ? n.map.component : n.component;
3077
- if (emittedLeaf.has(catalog))
3078
- continue; // per-module a leaf has ONE consistent shape — emit once.
3079
- emittedLeaf.add(catalog);
3080
- const sym = leafSymbolBare(catalog, leaf);
3081
- if ("fanout" in n) {
3082
- // fanout: return the aligned per-id element WIRES ([]*WireValue); a null aligned body is a
3083
- // DANGLING id → nil (the covered runner maps it to the zero element).
3084
- const portsT = `${portsStructName(c.name, n.id)}_batch`;
3085
- transportFns.push(`func ${sym}(_ ${portsT}) ([]*WireValue, error) {
3086
- src, ok := nextScripted(${JSON.stringify(catalog)})
3087
- if !ok {
3088
- return nil, unknownComponent(${JSON.stringify(catalog)})
3089
- }
3090
- if src.isErr {
3091
- return nil, leafFailure(src.err)
3092
- }
3093
- arr, _ := src.ok.([]${PKG}.Value)
3094
- wires := make([]*WireValue, 0, len(arr))
3095
- for _, ev := range arr {
3096
- if ev == nil {
3097
- wires = append(wires, nil)
3098
- continue
3099
- }
3100
- wv := valueToWire(ev)
3101
- wires = append(wires, &wv)
3102
- }
3103
- return wires, nil
3104
- }`);
3105
- continue;
3106
- }
3107
- if ("map" in n) {
3108
- // map: batched → one WIRE per element ([]WireValue); non-batched → one element WIRE (WireValue).
3109
- const m = n.map;
3110
- if (m.batched === true) {
3111
- const portsT = `${portsStructName(c.name, n.id)}_batch`;
3112
- transportFns.push(`func ${sym}(_ ${portsT}) ([]WireValue, error) {
3113
- src, ok := nextScripted(${JSON.stringify(catalog)})
3114
- if !ok {
3115
- return nil, unknownComponent(${JSON.stringify(catalog)})
3116
- }
3117
- if src.isErr {
3118
- return nil, leafFailure(src.err)
3119
- }
3120
- arr, _ := src.ok.([]${PKG}.Value)
3121
- wires := make([]WireValue, 0, len(arr))
3122
- for _, ev := range arr {
3123
- wires = append(wires, valueToWire(ev))
3124
- }
3125
- return wires, nil
3126
- }`);
3127
- }
3128
- else {
3129
- const { elemRef: overElemRef } = mapOverElemInfo(c, n, typedNodes, plan);
3130
- const spread = portFieldSpread(m.ports, m.portSchemas, c, plan, typedNodes, { name: m.as, ref: overElemRef, plan }, nodeNarrowedPaths(c, n));
3131
- const params = spread.map((pf) => `_${pf.field} ${pf.goType}`).join(", ");
3132
- transportFns.push(`func ${sym}(${params}) (WireValue, error) {
3133
- src, ok := nextScripted(${JSON.stringify(catalog)})
3134
- if !ok {
3135
- return WireValue{}, unknownComponent(${JSON.stringify(catalog)})
3136
- }
3137
- if src.isErr {
3138
- return WireValue{}, leafFailure(src.err)
3139
- }
3140
- return valueToWire(src.ok), nil
3141
- }`);
3142
- }
3143
- continue;
3144
- }
3145
- // componentRef (point read): spread port fields; supports echo (#129/#141) reading the port params.
3146
- const node = n;
3147
- // #170: the observe transport fn's param types must match the covered module's leaf call args, which
3148
- // narrow a gate-proven opt key — so this reads the SAME node narrowing.
3149
- const crNarrowed = nodeNarrowedPaths(c, node);
3150
- const ref = typedNodes.get(n.id);
3151
- const spread = portFieldSpread(node.ports, node.portSchemas, c, plan, typedNodes, undefined, crNarrowed);
3152
- const echoBranches = [];
3153
- if (ref.kind === "named") {
3154
- const decl = findDecl(plan, ref.name);
3155
- const field = decl !== undefined && decl.fields.length === 1 ? decl.fields[0] : undefined;
3156
- const fieldGo = field !== undefined ? renderTypeRef(field.type) : null;
3157
- const recordGo = renderTypeRef(ref);
3158
- for (const pn of Object.keys(node.ports)) {
3159
- let portGo = null;
3160
- try {
3161
- portGo = portFieldGoType(node.ports[pn], c, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[pn], plan), `echo port '${pn}'`, { narrowed: crNarrowed });
3162
- }
3163
- catch {
3164
- portGo = null;
3165
- }
3166
- if (portGo === recordGo) {
3167
- // the port IS the whole record → echo it DIRECTLY (matching run_behavior's plain echo:port).
3168
- echoBranches.push(`\tif src.echo == ${JSON.stringify(pn)} {\n\t\treturn valueToWire(${serializeTyped(goPortFieldName(pn), ref, plan)}), nil\n\t}`);
3169
- }
3170
- else if (fieldGo !== null && field !== undefined && portGo === fieldGo) {
3171
- // a scalar port wraps into the record's single field ({v: ports.X}).
3172
- 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
+ }
3173
3029
  }
3174
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
+ }
3175
3036
  }
3176
- else if (ref.kind === "arr" && Object.prototype.hasOwnProperty.call(node.ports, "items")) {
3177
- // #129: an arr node with an `items` port echoes the NATIVE port array (serialized to a Value array)
3178
- // so the node→leaf array dataflow test is non-vacuous.
3179
- 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;
3180
3048
  }
3181
- const canEcho = echoBranches.length > 0;
3182
- // params keep their field names (echo reads them); Go allows unused params, so no underscore needed.
3183
- const params = spread.map((pf) => `${pf.field} ${pf.goType}`).join(", ");
3184
- const echoBlock = canEcho ? `${echoBranches.join("\n")}\n` : "";
3185
- transportFns.push(`func ${sym}(${params}) (WireValue, error) {
3186
- 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)})
3187
3057
  if !ok {
3188
- return WireValue{}, unknownComponent(${JSON.stringify(catalog)})
3058
+ return WireValue{}, unknownComponent(${JSON.stringify(le.catalog)})
3189
3059
  }
3190
3060
  if src.isErr {
3191
3061
  return WireValue{}, leafFailure(src.err)
3192
3062
  }
3193
- ${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
3194
3067
  }`);
3195
- }
3196
3068
  }
3197
3069
  const adapter = `// scriptSrc — a scripted per-component outcome (an ok Value or an error), drained in order.
3198
3070
  // #129: \`echo\` carries the reference scriptedHandlers' \`echo\` directive (e.g. "items") so a scripted