behavior-contracts 0.9.1 → 0.9.3

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 (43) hide show
  1. package/dist/behavior.d.ts +19 -0
  2. package/dist/behavior.d.ts.map +1 -1
  3. package/dist/behavior.js +155 -22
  4. package/dist/behavior.js.map +1 -1
  5. package/dist/generator/emit-shared-go.d.ts.map +1 -1
  6. package/dist/generator/emit-shared-go.js +40 -19
  7. package/dist/generator/emit-shared-go.js.map +1 -1
  8. package/dist/generator/emit-shared-rust.d.ts.map +1 -1
  9. package/dist/generator/emit-shared-rust.js +50 -30
  10. package/dist/generator/emit-shared-rust.js.map +1 -1
  11. package/dist/generator/emit-shared-typescript.d.ts.map +1 -1
  12. package/dist/generator/emit-shared-typescript.js +26 -4
  13. package/dist/generator/emit-shared-typescript.js.map +1 -1
  14. package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
  15. package/dist/generator/emit-typed-native-go.js +136 -70
  16. package/dist/generator/emit-typed-native-go.js.map +1 -1
  17. package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
  18. package/dist/generator/emit-typed-native-rust.js +110 -62
  19. package/dist/generator/emit-typed-native-rust.js.map +1 -1
  20. package/dist/generator/native-expr.d.ts +7 -0
  21. package/dist/generator/native-expr.d.ts.map +1 -1
  22. package/dist/generator/native-expr.js +11 -0
  23. package/dist/generator/native-expr.js.map +1 -1
  24. package/dist/generator/straightline.d.ts +5 -0
  25. package/dist/generator/straightline.d.ts.map +1 -1
  26. package/dist/generator/straightline.js +1 -0
  27. package/dist/generator/straightline.js.map +1 -1
  28. package/dist/generator/typed.d.ts +17 -11
  29. package/dist/generator/typed.d.ts.map +1 -1
  30. package/dist/generator/typed.js +19 -12
  31. package/dist/generator/typed.js.map +1 -1
  32. package/dist/plan.d.ts +7 -0
  33. package/dist/plan.d.ts.map +1 -1
  34. package/dist/plan.js +7 -2
  35. package/dist/plan.js.map +1 -1
  36. package/dist/primitives.d.ts +4 -3
  37. package/dist/primitives.d.ts.map +1 -1
  38. package/dist/primitives.js +8 -7
  39. package/dist/primitives.js.map +1 -1
  40. package/dist/type-gate.d.ts.map +1 -1
  41. package/dist/type-gate.js +6 -56
  42. package/dist/type-gate.js.map +1 -1
  43. package/package.json +1 -1
@@ -2,7 +2,7 @@ import { GeneratorFailure } from "./core.js";
2
2
  import { isControlGate, nodeWirePassthrough } from "../behavior.js";
3
3
  import { rustStraightlineInternals } from "./emit-shared-rust.js";
4
4
  import { rustTypedInternals } from "./emit-shared-rust-typed.js";
5
- import { buildTypePlan, deriveTypeRef, findDecl, guardedMapIntoIsOpt, inputPortIsOptional, inputPortTypeRef } from "./typed.js";
5
+ import { buildTypePlan, deriveTypeRef, findDecl, guardedMapIntoIsCoverable, inputPortIsOptional, inputPortTypeRef } from "./typed.js";
6
6
  import { concurrencyPlan, execPlan, analyzeSequentialOps, classifyExpr, nodeNarrowedPaths } from "./straightline.js";
7
7
  import { NativeExprCompiler } from "./native-expr.js";
8
8
  import { buildAsyncPlans } from "./async-plan.js";
@@ -548,14 +548,23 @@ ${probeArms}
548
548
  ${I}}`;
549
549
  }
550
550
  /**
551
- * renderRustWireBox — the ONE inline BOX renderer (typed→wire), the mirror of renderRustDeBox. Folds a
552
- * language-neutral {@link WirePlan} (the SAME SSoT walk, `dir:"in"`) into a Rust EXPRESSION evaluating to an
553
- * owned `WireValue` built from `srcExpr` (an OWNED native typed value of the plan's type). `value` is
554
- * identity (already the opaque wire); a native scalar wraps in its wire ctor. A `value[]` bound-value list
555
- * carries scalar / opaque elements, so those are the covered element shapes; a nested opt / collection /
556
- * record element is fail-closed here (C1 — the compound box lands with the batched WireRow contract).
551
+ * renderRustWireBox — the ONE inline BOX renderer (typed→wire), the mirror of renderRustDeBox and the twin of
552
+ * renderGoWireBox. Folds a language-neutral {@link WirePlan} (the SAME SSoT walk {@link buildWirePlan},
553
+ * `dir:"in"`) into a Rust EXPRESSION evaluating to an owned `WireValue` built from the OWNED `srcExpr`. The
554
+ * walk is TOTAL over the plan's non-opt kinds (bc#178) and RECURSIVE over the declared element type, so a
555
+ * compound bound value crosses the leaf-param boundary EXACTLY ONCE (box-once; NO decode→re-box round-trip —
556
+ * `srcExpr` is already the native typed value):
557
+ * - `value` identity (already the opaque BC wire);
558
+ * - `scalar` wrap in its wire ctor (WireValue::Str/int/float/Bool);
559
+ * - `record` box each declared field recursively, assemble `WireValue::Row(WireRow{ entries })` — the typed
560
+ * `obj<…>` → wire map ("M") crossing (the real op-agnostic `arr<value>` batch-write param fed a
561
+ * typed `arr<obj>`);
562
+ * - `list` box each element recursively into `WireValue::List(WireList{ items })` ("L").
563
+ * A `map` value or an OPT-wrapped element (optDepth > 0) boxes AMBIGUOUSLY (map key order / opt present-vs-null
564
+ * on the wire are not statically pinned to run_behavior's Value pass-through), so it stays FAIL-CLOSED LOUD —
565
+ * strict-typing, no silent box. `depth` names the per-element closure binding uniquely across nesting.
557
566
  */
558
- function renderRustWireBox(plan, srcExpr) {
567
+ function renderRustWireBox(plan, srcExpr, depth = 0) {
559
568
  if (plan.optDepth === 0) {
560
569
  if (plan.k === "value")
561
570
  return srcExpr; // identity — already the opaque BC wire.
@@ -571,8 +580,29 @@ function renderRustWireBox(plan, srcExpr) {
571
580
  return `WireValue::Bool(${srcExpr})`;
572
581
  }
573
582
  }
583
+ if (plan.k === "record") {
584
+ // typed struct → wire map: box each declared field off its native struct field (moving it out of the owned
585
+ // srcExpr — no probe), assemble a WireRow of (name, WireValue) in declared-field order.
586
+ const entries = plan.fields.map((f) => `(${rustStrLit(f.name)}.to_string(), ${renderRustWireBox(f.plan, `${srcExpr}.${rustFieldName(f.name)}`, depth + 1)})`);
587
+ return `WireValue::Row(WireRow { entries: vec![${entries.join(", ")}] })`;
588
+ }
589
+ if (plan.k === "list") {
590
+ // typed Vec → wire list: consume the owned Vec, box each element recursively (box-once, no round-trip).
591
+ const e = `e${depth}`;
592
+ return `WireValue::List(WireList { items: ${srcExpr}.into_iter().map(|${e}| ${renderRustWireBox(plan.elem, e, depth + 1)}).collect() })`;
593
+ }
594
+ if (plan.k === "map") {
595
+ // bc#181: typed map<V> → wire map, represented as a dynamic-keyed WireRow (there is NO WireMap type; a
596
+ // declared map<V> is the dynamic-keyed twin of a record — the READ side de-boxes a WireRow INTO map<V>
597
+ // the SAME way, emit-shared-debox `mapval`). Box EACH entry's VALUE recursively (box-once, no round-trip);
598
+ // keys carried as dynamic strings. BTreeMap<String,_> iterates in ascending key order, so the WireRow is
599
+ // deterministic (matching the rust typed map's canonical key order).
600
+ const k = `k${depth}`;
601
+ const v = `v${depth}`;
602
+ return `WireValue::Row(WireRow { entries: ${srcExpr}.into_iter().map(|(${k}, ${v})| (${k}, ${renderRustWireBox(plan.value, v, depth + 1)})).collect() })`;
603
+ }
574
604
  }
575
- throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust wire box: a value[] element of type '${plan.expectedType}' is not a scalar / opaque value (a nested opt/collection/record bound-value is not native-covered)`);
605
+ throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust wire box: a value[] element of type '${plan.expectedType}' is not native-covered by the typed→wire box (an OPT-wrapped element boxes ambiguously — opt present-vs-null on the wire is not statically pinned to run_behavior's Value pass-through — so it stays fail-closed rather than risk a divergence)`);
576
606
  }
577
607
  /** returnErrFail — the default de-box mismatch control flow: propagate the structured Error Value out of
578
608
  * the enclosing runner (fail/retry componentRef results + map/fanout element de-box, which fails closed
@@ -791,6 +821,9 @@ function makeRustExprBackend(resolveHead, plan) {
791
821
  wireType: () => renderTypeRef({ kind: "value" }),
792
822
  // bc#156/#160: box a value[] element into the opaque BC wire via the ONE box SSoT (owned element expr).
793
823
  wireBox: (item) => renderRustWireBox(buildWirePlan(item.ref, { from: "top" }, { model: "port", field: "port", plan }, "in"), item.expr),
824
+ // bc#178: box EACH element of the owned typed Vec into an arr<value> (Vec<WireValue>) — the same
825
+ // per-element box renderer as wireBox's list case, applied over the referenced array (box-once/element).
826
+ wireBoxEachElem: (srcExpr, elemRef) => `${srcExpr}.into_iter().map(|__be| ${renderRustWireBox(buildWirePlan(elemRef, { from: "elem" }, { model: "port", field: "port", plan }, "in"), "__be")}).collect::<Vec<${renderTypeRef({ kind: "value" })}>>()`,
794
827
  scalarType: (s) => rustScalar(s),
795
828
  strLit: (s) => `${rustStrLit(s)}.to_string()`,
796
829
  boolLit: (b) => (b ? "true" : "false"),
@@ -1089,24 +1122,43 @@ ${inits.join("\n")}
1089
1122
  * expression that yields the over Vec (#108, rust twin): prior-node arr field (cell clone) or an input
1090
1123
  * array port with elemType (`in_.<field>.clone()`). Fail-closed for an input array without elemType.
1091
1124
  */
1092
- function mapOverElemInfo(comp, node, typedNodes, plan) {
1093
- const m = node.map;
1094
- const e = classifyExpr(m.over);
1125
+ /**
1126
+ * rustOverElemInfo — the ONE resolver of a fanout/map `over` to its element TypeRef + the OWNED Rust
1127
+ * over expression (map/fanout twins both delegate — single definition, no forked copy).
1128
+ *
1129
+ * `optArr` is true when the over's declared type is `{opt:{arr}}` (a prior-node opt-arr field OR an OPT
1130
+ * input array port). #177 (A): a null opt-arr over then iterates EMPTY — the emitted `overExpr` is an
1131
+ * `Option<Vec<E>>`, which the arm binds via `.unwrap_or_default()` (None → empty Vec), byte-equal to
1132
+ * run_behavior. A REQUIRED arr (None) still fails run_behavior FANOUT/MAP_OVER_NOT_ARRAY → optArr:false.
1133
+ */
1134
+ function rustOverElemInfo(comp, over, typedNodes, plan, nodeId, label) {
1135
+ const e = classifyExpr(over);
1095
1136
  if (e.kind === "ref" && e.path.length >= 1 && typedNodes.has(e.path[0])) {
1096
1137
  const baseRef = typedNodes.get(e.path[0]);
1097
1138
  const { ref } = typedFieldAccess(`${typedCell(e.path[0])}.borrow()`, baseRef, e.path.slice(1), plan);
1139
+ const fieldPath = e.path.slice(1).map((p) => `.${rustFieldName(p)}`).join("");
1098
1140
  if (ref.kind === "arr") {
1099
- const fieldPath = e.path.slice(1).map((p) => `.${rustFieldName(p)}`).join("");
1100
- return { elemRef: ref.elem, overExpr: `${typedCell(e.path[0])}.borrow()${fieldPath}.clone()` };
1141
+ return { elemRef: ref.elem, overExpr: `${typedCell(e.path[0])}.borrow()${fieldPath}.clone()`, optArr: false };
1142
+ }
1143
+ if (ref.kind === "opt" && ref.inner.kind === "arr") {
1144
+ return { elemRef: ref.inner.elem, overExpr: `${typedCell(e.path[0])}.borrow()${fieldPath}.clone()`, optArr: true };
1101
1145
  }
1102
1146
  }
1103
1147
  if (e.kind === "ref" && e.path.length === 1) {
1104
1148
  const schema = comp.inputPorts?.[e.path[0]];
1105
1149
  const et = schema?.elemType;
1106
1150
  if (et !== undefined)
1107
- return { elemRef: deriveTypeRef(et, plan), overExpr: `in_.${rustFieldName(e.path[0])}.clone()` };
1151
+ return { elemRef: deriveTypeRef(et, plan), overExpr: `in_.${rustFieldName(e.path[0])}.clone()`, optArr: inputPortIsOptional(schema) };
1108
1152
  }
1109
- throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust combined map (#108): map '${node.id}' 'over' must be a ref to a prior node's typed arr field OR an input array port with a declared elemType. BC does not infer input-array element types (consumer-interface C3).`);
1153
+ throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust ${label}: '${nodeId}' 'over' must be a ref to a prior node's typed arr field OR an input array port with a declared elemType. BC does not infer input-array element types (consumer-interface C3).`);
1154
+ }
1155
+ /** rustBindOverExpr — the RHS `let over_<s> = …;` expr. An opt-arr over (#177 (A)) unwraps its
1156
+ * `Option<Vec<E>>` to an empty Vec on None so iteration is 0-length (byte-equal to run_behavior). */
1157
+ function rustBindOverExpr(overExpr, optArr) {
1158
+ return optArr ? `${overExpr}.unwrap_or_default()` : overExpr;
1159
+ }
1160
+ function mapOverElemInfo(comp, node, typedNodes, plan) {
1161
+ return rustOverElemInfo(comp, node.map.over, typedNodes, plan, node.id, "combined map (#108)");
1110
1162
  }
1111
1163
  /** The Rust type of the over-element (back-compat shim). */
1112
1164
  function mapOverElemType(comp, node, typedNodes, plan) {
@@ -1233,13 +1285,14 @@ function coveredMapNode(n, bodyIds, comp) {
1233
1285
  if (n === null || typeof n !== "object" || !("map" in n))
1234
1286
  return false;
1235
1287
  const m = n.map;
1236
- // #108 (rust twin of the go predicate): a guarded map (`when`) IS covered with NO `into`. #177: a
1237
- // guarded map WITH `into` is covered ONLY when the into field is OPT (keep-with-null — kept element →
1238
- // present into, guard-skipped element → into=None), byte-equal to run_behavior applyInto pass-through +
1239
- // opt-into null. A REQUIRED into field → run_behavior FAILS MISSING_PROP on a skipped element, so
1240
- // fail-close is byte-equal. over element type must be statically resolvable: prior-node arr field, or
1241
- // an input array port carrying `elemType` (BC does not infer — consumer-interface C3).
1242
- if (m.when !== undefined && m.into !== undefined && !guardedMapIntoIsOpt(n, comp))
1288
+ // #108 (rust twin of the go predicate): a guarded map (`when`) IS covered with NO `into`. #177/#182: a
1289
+ // guarded map WITH `into` is covered when the guard-skipped element has a well-defined skip value — the
1290
+ // into field is OPT (skip → None, #177) OR relationKind:connection (skip → the empty connection
1291
+ // {items:[],cursor:null}, #182). Byte-equal to run_behavior applyInto (opt-into → null / connection-into
1292
+ // → unproducedValue("connection")). A REQUIRED non-connection into → run_behavior FAILS MISSING_PROP on a
1293
+ // skipped element, so fail-close is byte-equal. over element type must be statically resolvable: prior-node
1294
+ // arr field, or an input array port carrying `elemType` (BC does not infer — consumer-interface C3).
1295
+ if (m.when !== undefined && m.into !== undefined && !guardedMapIntoIsCoverable(n, comp))
1243
1296
  return false;
1244
1297
  if (m.policy !== undefined && m.policy !== "fail")
1245
1298
  return false;
@@ -1257,17 +1310,14 @@ function coveredMapNode(n, bodyIds, comp) {
1257
1310
  return false;
1258
1311
  const head = overE.path[0];
1259
1312
  if (!bodyIds.has(head)) {
1260
- // input-array over: covered only when the port declares elemType (#108) AND is REQUIRED. #177: an OPT
1261
- // input-array (`{opt:{arr}}`, required:false) resolves to `in_.<field>` of `Option<Vec<E>>` — iterating
1262
- // it does not yield the element type, and run_behavior FAILS MAP_OVER_NOT_ARRAY on a null opt
1263
- // collection — so fail-close here is byte-equal (a faithful nil→empty over is an owner-level decision).
1313
+ // input-array over: covered only when the port declares elemType (#108 — C3, no inference). #177 (A):
1314
+ // an OPT input array (`{opt:{arr}}`, required:false) IS covered — its null iterates EMPTY
1315
+ // (rustOverElemInfo.optArr → `.unwrap_or_default()`, None → empty Vec), byte-equal to run_behavior.
1264
1316
  if (overE.path.length !== 1)
1265
1317
  return false;
1266
1318
  const schema = comp.inputPorts?.[head];
1267
1319
  if (schema === undefined || schema.elemType === undefined)
1268
1320
  return false;
1269
- if (inputPortIsOptional(schema))
1270
- return false;
1271
1321
  }
1272
1322
  const ports = m.ports;
1273
1323
  const plan = planForComp(comp);
@@ -1295,17 +1345,14 @@ function coveredFanoutNode(n, bodyIds, comp) {
1295
1345
  return false;
1296
1346
  const head = overE.path[0];
1297
1347
  if (!bodyIds.has(head)) {
1298
- // input-array over: covered only when the port declares elemType AND is REQUIRED. #177: an OPT
1299
- // input-array (`{opt:{arr}}`, required:false) resolves to `in_.<field>` of `Option<Vec<E>>` —
1300
- // iterating it does not yield the element type, and run_behavior FAILS FANOUT_OVER_NOT_ARRAY on a
1301
- // null opt collection — so fail-close here is byte-equal (a faithful nil→empty over is owner-level).
1348
+ // input-array over: covered only when the port declares elemType (C3 — no inference). #177 (A): an OPT
1349
+ // input array (`{opt:{arr}}`, required:false) IS covered — its null iterates EMPTY
1350
+ // (rustOverElemInfo.optArr → `.unwrap_or_default()`, None → empty Vec), byte-equal to run_behavior.
1302
1351
  if (overE.path.length !== 1)
1303
1352
  return false;
1304
1353
  const schema = comp.inputPorts?.[head];
1305
1354
  if (schema === undefined || schema.elemType === undefined)
1306
1355
  return false;
1307
- if (inputPortIsOptional(schema))
1308
- return false;
1309
1356
  }
1310
1357
  const ports = f.ports;
1311
1358
  const plan = planForComp(comp);
@@ -1333,25 +1380,9 @@ function fanoutItemsElemRef(node, connRef, plan) {
1333
1380
  throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust fanout (v3): node '${node.id}' connection struct '${connRef.name}' has no 'items' array field.`);
1334
1381
  return itemsField.type.elem;
1335
1382
  }
1336
- /** fanoutOverElemInfo (v3, rust twin) — the over id-list element TypeRef + the OWNED over-Vec expr. */
1383
+ /** fanoutOverElemInfo (v3, rust twin) — delegates to {@link rustOverElemInfo} reading the fanout spec. */
1337
1384
  function fanoutOverElemInfo(comp, node, typedNodes, plan) {
1338
- const f = node.fanout;
1339
- const e = classifyExpr(f.over);
1340
- if (e.kind === "ref" && e.path.length >= 1 && typedNodes.has(e.path[0])) {
1341
- const baseRef = typedNodes.get(e.path[0]);
1342
- const { ref } = typedFieldAccess(`${typedCell(e.path[0])}.borrow()`, baseRef, e.path.slice(1), plan);
1343
- if (ref.kind === "arr") {
1344
- const fieldPath = e.path.slice(1).map((p) => `.${rustFieldName(p)}`).join("");
1345
- return { elemRef: ref.elem, overExpr: `${typedCell(e.path[0])}.borrow()${fieldPath}.clone()` };
1346
- }
1347
- }
1348
- if (e.kind === "ref" && e.path.length === 1) {
1349
- const schema = comp.inputPorts?.[e.path[0]];
1350
- const et = schema?.elemType;
1351
- if (et !== undefined)
1352
- return { elemRef: deriveTypeRef(et, plan), overExpr: `in_.${rustFieldName(e.path[0])}.clone()` };
1353
- }
1354
- throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust fanout (v3): fanout '${node.id}' 'over' must be a ref to a prior node's typed arr field OR an input array port with a declared elemType.`);
1385
+ return rustOverElemInfo(comp, node.fanout.over, typedNodes, plan, node.id, "fanout (v3)");
1355
1386
  }
1356
1387
  /** A covered read SHAPE with static ports + native-lowerable output (+ covered map...into), OR a
1357
1388
  * real-concurrency staged plan (bc#87) whose parallel-stage members are plain componentRef point reads. */
@@ -2004,7 +2035,7 @@ isAsync = false) {
2004
2035
  const batch = `${structName}Batch`;
2005
2036
  const leafSym = resolveLeafSymbol(m.component, leaf);
2006
2037
  // #108: over element type + the OWNED over-Vec expression (prior-node arr OR input array w/ elemType).
2007
- const { elemRef: overElemRef, overExpr } = mapOverElemInfo(comp, node, typedNodes, plan);
2038
+ const { elemRef: overElemRef, overExpr, optArr: overOptArr } = mapOverElemInfo(comp, node, typedNodes, plan);
2008
2039
  const elemMat = mapElemMaterializerName(comp.name, node.id);
2009
2040
  const priorHere = (head) => priorNodeAt(head, atPos);
2010
2041
  const asName = m.as;
@@ -2016,6 +2047,21 @@ isAsync = false) {
2016
2047
  // mismatch fails closed regardless of elementPolicy (matching the interpreter's whole-node outType throw).
2017
2048
  const elemDeBoxRef = mapElemRowRef(node, elemArrRef, plan);
2018
2049
  const renderElemDeBox = (il) => renderResultDeBox(elemDeBoxRef, `er_${s}`, node.id, plan, il, returnErrFail, nodeWirePassthrough(node));
2050
+ // #177/#182 keep-with-skip-value: the into value for a guard-skipped element is driven by relationKind,
2051
+ // NOT by opt-ness (matching run_behavior applyInto, which fills a connection into with the empty
2052
+ // connection UNCONDITIONALLY on relationKind==="connection"):
2053
+ // - connection into → the connection-zero in the field's typed rep (same shape emitProducedAwareValue
2054
+ // uses for a skipped connection node): a required `Conn` field → `Conn::default()`, an OPT
2055
+ // `Option<Conn>` field → `Some(Conn::default())` (empty connection, NOT None). `Conn::default()`'s
2056
+ // derived Default serializes to {items:[],cursor:null} (#182).
2057
+ // - non-connection into → opt → None = null (#177 keep-with-null; unchanged).
2058
+ const intoSkipDefault = m.relationKind === "connection"
2059
+ ? elemDeBoxRef.kind === "opt"
2060
+ ? `Some(${renderTypeRef(elemDeBoxRef.inner)}::default())`
2061
+ : `${renderTypeRef(elemDeBoxRef)}::default()`
2062
+ : elemDeBoxRef.kind === "opt"
2063
+ ? "None"
2064
+ : `${renderTypeRef(elemDeBoxRef)}::default()`;
2019
2065
  // build the per-element CONCRETE native ports struct. `il` = indent inside the element loop.
2020
2066
  const buildPorts = (il) => {
2021
2067
  const out = [];
@@ -2062,7 +2108,7 @@ isAsync = false) {
2062
2108
  closers.unshift(`${indent}}`);
2063
2109
  indent += " ";
2064
2110
  }
2065
- lines.push(`${indent}let over_${s} = ${overExpr};`);
2111
+ lines.push(`${indent}let over_${s} = ${rustBindOverExpr(overExpr, overOptArr)};`);
2066
2112
  lines.push(`${indent}let mut built_${s}: Vec<${elemName}> = Vec::with_capacity(over_${s}.len());`);
2067
2113
  if (batched && keepWithNull) {
2068
2114
  // #177 BATCHED keep-with-null (guarded map...into, opt into): pass 1 records, per over element, whether
@@ -2108,7 +2154,7 @@ isAsync = false) {
2108
2154
  lines.push(`${indent} let dec_${s} = decs_iter_${s}.next().expect("aligned kept row");`);
2109
2155
  lines.push(`${indent} built_${s}.push(${elemMat}(oel_${s}, dec_${s}));`);
2110
2156
  lines.push(`${indent} } else {`);
2111
- lines.push(`${indent} built_${s}.push(${elemMat}(oel_${s}, None));`);
2157
+ lines.push(`${indent} built_${s}.push(${elemMat}(oel_${s}, ${intoSkipDefault}));`);
2112
2158
  lines.push(`${indent} }`);
2113
2159
  lines.push(`${indent}}`);
2114
2160
  }
@@ -2161,9 +2207,10 @@ isAsync = false) {
2161
2207
  else {
2162
2208
  // #93 shape 2 / #108: NON-batched map — dispatch ONCE PER KEPT ELEMENT.
2163
2209
  lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
2164
- // #177 keep-with-null: a guard-skipped element is KEPT with into=None instead of dropped — byte-equal
2165
- // to run_behavior's applyInto pass-through + opt-into null.
2166
- const nonBatchedSkip = keepWithNull ? `built_${s}.push(${elemMat}(oel_${s}, None)); continue;` : "continue;";
2210
+ // #177/#182 keep-with-skip-value: a guard-skipped element is KEPT with into=intoSkipDefault (None /
2211
+ // Conn::default()) instead of dropped — byte-equal to run_behavior's applyInto (opt-into → null /
2212
+ // connection-into → empty connection).
2213
+ const nonBatchedSkip = keepWithNull ? `built_${s}.push(${elemMat}(oel_${s}, ${intoSkipDefault})); continue;` : "continue;";
2167
2214
  for (const l of emitGuard(indent + " ", nonBatchedSkip))
2168
2215
  lines.push(l);
2169
2216
  for (const l of buildPorts(indent + " "))
@@ -2215,7 +2262,7 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
2215
2262
  const connRef = typedNodes.get(node.id);
2216
2263
  const elemRef = fanoutItemsElemRef(node, connRef, plan);
2217
2264
  const elemName = renderTypeRef(elemRef);
2218
- const { elemRef: overElemRef, overExpr } = fanoutOverElemInfo(comp, node, typedNodes, plan);
2265
+ const { elemRef: overElemRef, overExpr, optArr: overOptArr } = fanoutOverElemInfo(comp, node, typedNodes, plan);
2219
2266
  const asName = f.as;
2220
2267
  const priorHere = (head) => priorNodeAt(head, atPos);
2221
2268
  const portNames = Object.keys(f.ports);
@@ -2243,7 +2290,7 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
2243
2290
  closers.unshift(`${indent}}`);
2244
2291
  indent += " ";
2245
2292
  }
2246
- lines.push(`${indent}let over_${s} = ${overExpr};`);
2293
+ lines.push(`${indent}let over_${s} = ${rustBindOverExpr(overExpr, overOptArr)};`);
2247
2294
  lines.push(`${indent}let mut built_${s}: Vec<${elemName}> = Vec::new();`);
2248
2295
  lines.push(`${indent}let mut pi_${s}: Vec<${structName}> = Vec::with_capacity(over_${s}.len());`);
2249
2296
  lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
@@ -3033,7 +3080,8 @@ function emitInDecoder(comp, plan) {
3033
3080
  lines.push(` Value::Arr(a) => {`);
3034
3081
  lines.push(` let mut dec: Vec<${elemTy}> = Vec::with_capacity(a.len());`);
3035
3082
  lines.push(` for ev in a.iter() { dec.push(${mat}); }`);
3036
- lines.push(` in_.${field} = dec;`);
3083
+ // #177 (A): an OPTIONAL array port field is `Option<Vec<E>>` (inputPortTypeRef opt), so wrap in Some.
3084
+ lines.push(` in_.${field} = ${inputPortIsOptional(schema) ? "Some(dec)" : "dec"};`);
3037
3085
  lines.push(` }`);
3038
3086
  lines.push(` other => return Err(marshal_type_error(${rustStrLit(`decode input ${p}: expected array, got `)}, other.type_name())),`);
3039
3087
  lines.push(` }`);