behavior-contracts 0.8.17 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/authoring.d.ts +26 -0
  2. package/dist/authoring.d.ts.map +1 -1
  3. package/dist/authoring.js +30 -6
  4. package/dist/authoring.js.map +1 -1
  5. package/dist/behavior.d.ts +26 -1
  6. package/dist/behavior.d.ts.map +1 -1
  7. package/dist/behavior.js.map +1 -1
  8. package/dist/builder.d.ts.map +1 -1
  9. package/dist/builder.js +19 -4
  10. package/dist/builder.js.map +1 -1
  11. package/dist/generator/core.js +2 -2
  12. package/dist/generator/core.js.map +1 -1
  13. package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
  14. package/dist/generator/emit-typed-native-go.js +167 -51
  15. package/dist/generator/emit-typed-native-go.js.map +1 -1
  16. package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
  17. package/dist/generator/emit-typed-native-rust.js +172 -46
  18. package/dist/generator/emit-typed-native-rust.js.map +1 -1
  19. package/dist/generator/native-expr.d.ts +35 -27
  20. package/dist/generator/native-expr.d.ts.map +1 -1
  21. package/dist/generator/native-expr.js +59 -59
  22. package/dist/generator/native-expr.js.map +1 -1
  23. package/dist/generator/straightline.d.ts +21 -0
  24. package/dist/generator/straightline.d.ts.map +1 -1
  25. package/dist/generator/straightline.js +68 -0
  26. package/dist/generator/straightline.js.map +1 -1
  27. package/dist/generator/typed.d.ts +19 -1
  28. package/dist/generator/typed.d.ts.map +1 -1
  29. package/dist/generator/typed.js +37 -0
  30. package/dist/generator/typed.js.map +1 -1
  31. package/dist/guard.d.ts.map +1 -1
  32. package/dist/guard.js +30 -0
  33. package/dist/guard.js.map +1 -1
  34. package/dist/provenance.d.ts.map +1 -1
  35. package/dist/provenance.js +3 -0
  36. package/dist/provenance.js.map +1 -1
  37. package/dist/type-gate.d.ts +9 -1
  38. package/dist/type-gate.d.ts.map +1 -1
  39. package/dist/type-gate.js +10 -4
  40. package/dist/type-gate.js.map +1 -1
  41. package/package.json +1 -1
@@ -2,8 +2,8 @@ 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, inputPortIsOptional, inputPortTypeRef } from "./typed.js";
6
- import { concurrencyPlan, execPlan, analyzeSequentialOps, classifyExpr } from "./straightline.js";
5
+ import { buildTypePlan, deriveTypeRef, findDecl, guardedMapIntoIsOpt, inputPortIsOptional, inputPortTypeRef } from "./typed.js";
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";
9
9
  import { buildDeBoxPlan, buildWirePlan, notationOfRef } from "./emit-shared-debox.js";
@@ -202,11 +202,16 @@ function resolveLeafSymbol(component, leaf) {
202
202
  * from the SAME `compilePortNode` lowering `emitPortsStruct` uses, so the spread can never disagree with
203
203
  * the field types the ports struct declares.
204
204
  */
205
- function portFieldSpread(ports, comp, plan, typedNodes, asBinding) {
206
- const opts = asBinding !== undefined ? { asBinding, asBase: asBinding.name } : undefined;
205
+ function portFieldSpread(ports, portSchemas, comp, plan, typedNodes, asBinding, narrowed) {
206
+ // #170: the transport-call spread reads the SAME lowering (incl. gate/guard narrowing) as the ports
207
+ // struct fields — a narrowed opt-in-required port is a non-opt arg, matching the non-opt struct field.
208
+ // #173: `expected` (declared port type from portSchemas) drives the SAME materialization the struct
209
+ // field type uses, so the spread arg type can never disagree with the field type.
210
+ const opts = asBinding !== undefined ? { asBinding, asBase: asBinding.name, narrowed } : narrowed !== undefined ? { narrowed } : undefined;
207
211
  return Object.keys(ports).map((pn) => {
208
- const c = compilePortNode(ports[pn], comp, plan, typedNodes, (h) => typedNodes.has(h), `port '${pn}' of node '${comp.name}'`, opts);
209
- return { field: portFieldName(pn), isCopy: typeRefIsCopy(c.ref), renderedType: c.renderedType ?? renderTypeRef(c.ref) };
212
+ const expected = inputPortTypeRef(portSchemas?.[pn], plan);
213
+ const c = compilePortNode(ports[pn], comp, plan, typedNodes, (h) => typedNodes.has(h), `port '${pn}' of node '${comp.name}'`, expected, opts);
214
+ return { field: portFieldName(pn), isCopy: typeRefIsCopy(c.ref), renderedType: renderTypeRef(c.ref) };
210
215
  });
211
216
  }
212
217
  /** leafCallArgs — the spread transport-call arguments for a ports-struct var (Copy→move, non-Copy→borrow). */
@@ -636,25 +641,43 @@ function nativeResolveHead(comp, plan, typedNodes, isPrior, opts) {
636
641
  * initializer the compiled `expr` — derived from a SINGLE lowering, so they cannot disagree. A port that
637
642
  * cannot lower FAILS CLOSED; a FALLIBLE lowering (hoists statements) is returned as-is (only emitPortInit
638
643
  * rejects it). Reuses the same nativeResolveHead cond/guard/port share, with `ownArrays` (a port owns). */
639
- function compilePortNode(node, comp, plan, typedNodes, isPrior, where, opts) {
644
+ function compilePortNode(node, comp, plan, typedNodes, isPrior, where, expected, opts) {
645
+ // #173: the port boundary is declared-type-driven. `expected` is the referenced leaf's declared port
646
+ // type (node.portSchemas[port] → inputPortTypeRef). It is MANDATORY (the guard requires portSchemas on
647
+ // every port); an `undefined` here means the declared port type is not statically resolvable (e.g. an
648
+ // object port / array-without-elemType) — a LOUD fail-close, never a silent inference.
649
+ if (expected === undefined)
650
+ throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust typed-native (runtime-free): ${where}: the declared port type is not statically resolvable (portSchemas type has no native lowering) — fail-closed`);
640
651
  const resolveHead = nativeResolveHead(comp, plan, typedNodes, isPrior, { ...opts, ownArrays: true });
652
+ const resolveDecl = (name) => findDecl(plan, name).fields;
653
+ let c;
641
654
  try {
642
- return new NativeExprCompiler(makeRustExprBackend(resolveHead, plan)).compilePort(node);
655
+ // #170: opts.narrowed carries the gate/guard-proven-non-null ref paths for THIS node's port scope, so an
656
+ // opt-in-required operand it proves non-null narrows instead of failing closed (the ONE narrowing site).
657
+ // #173: lower to the DECLARED port type via compilePortTo → compileTo (no element-kind inference).
658
+ c = new NativeExprCompiler(makeRustExprBackend(resolveHead, plan), opts?.narrowed).compilePortTo(node, expected, resolveDecl);
643
659
  }
644
660
  catch (e) {
645
661
  if (!(e instanceof GeneratorFailure))
646
662
  throw e;
647
663
  throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust typed-native (runtime-free): ${where} ${JSON.stringify(node)} does not lower to a native Rust value: ${e.message}`);
648
664
  }
665
+ // #173: the port field type equals the declared port type BY CONSTRUCTION — compilePortTo → compileTo
666
+ // materializes the node to exactly `expected` (the value/opt/obj/arr branches return `ref: expected`; the
667
+ // scalar/ref/operator branch requires `typeRefEqual(ref, expected)` or throws UNSUPPORTED_NODE_STRAIGHTLINE
668
+ // first). There is no independent second source that could diverge (unlike the OUTPUT boundary, whose
669
+ // node-type SSoT and declared outputType can disagree → the reachable OUTPUT_TYPE_INCONSISTENT gate), so
670
+ // no separate input-side integrity gate exists.
671
+ return c;
649
672
  }
650
673
  /**
651
674
  * portFieldRustType — the NATIVE Rust type for a covered port field, read off the ONE port lowering
652
675
  * (compilePortNode / native-expr). Field type = the compiled TypeRef, so it can never disagree with the
653
676
  * initializer (emitPortInit), which reads the SAME lowering for its value. `where` names the site.
654
677
  */
655
- function portFieldRustType(node, comp, plan, typedNodes, where = "port", opts) {
656
- const c = compilePortNode(node, comp, plan, typedNodes, (h) => typedNodes.has(h), where, opts);
657
- return c.renderedType ?? renderTypeRef(c.ref);
678
+ function portFieldRustType(node, comp, plan, typedNodes, expected, where = "port", opts) {
679
+ const c = compilePortNode(node, comp, plan, typedNodes, (h) => typedNodes.has(h), where, expected, opts);
680
+ return renderTypeRef(c.ref);
658
681
  }
659
682
  /**
660
683
  * emitPortsStruct — the CONCRETE native ports struct for a componentRef node. Typed fields per the
@@ -663,7 +686,7 @@ function portFieldRustType(node, comp, plan, typedNodes, where = "port", opts) {
663
686
  * reads `ports.f_<field>` DIRECTLY. The struct derives Clone (a bc#87 parallel stage clones it into the
664
687
  * per-worker dispatch). Every field is a NATIVE Rust type (bc#90 / runtime-free) — NO boxed `Value`.
665
688
  */
666
- function emitPortsStruct(comp, node, asBinding, plan, typedNodes) {
689
+ function emitPortsStruct(comp, node, asBinding, plan, typedNodes, narrowed) {
667
690
  const name = portsStructName(comp.name, node.id);
668
691
  const portNames = Object.keys(node.ports);
669
692
  if (portNames.length === 0) {
@@ -674,7 +697,12 @@ function emitPortsStruct(comp, node, asBinding, plan, typedNodes) {
674
697
  if (plan === undefined || typedNodes === undefined) {
675
698
  throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust typed-native: ports struct for node '${node.id}' needs a type plan + prior-node map`);
676
699
  }
677
- const types = portNames.map((p) => portFieldRustType(node.ports[p], comp, plan, typedNodes, `port '${p}' of node '${node.id}'`, asBinding !== undefined ? { asBinding, asBase: asBinding.name } : undefined));
700
+ // #170: the field TYPE reads the SAME lowering (incl. gate/guard narrowing) the init does, so a narrowed
701
+ // opt-in-required port is a non-opt field AND a non-opt initializer — they can never disagree.
702
+ // #173: the field TYPE is the DECLARED port type (portSchemas → inputPortTypeRef), materialized by the
703
+ // SAME compilePortTo the init uses — field and init read one lowering, so they cannot diverge.
704
+ const portOpts = asBinding !== undefined ? { asBinding, asBase: asBinding.name, narrowed } : narrowed !== undefined ? { narrowed } : undefined;
705
+ const types = portNames.map((p) => portFieldRustType(node.ports[p], comp, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[p], plan), `port '${p}' of node '${node.id}'`, portOpts));
678
706
  const fields = portNames
679
707
  .map((p, i) => ` pub ${portFieldName(p)}: ${types[i]}, // ${JSON.stringify(p)}`)
680
708
  .join("\n");
@@ -698,7 +726,8 @@ function emitMapPortsStructs(comp, node, typedNodes, plan) {
698
726
  // #108: element ports may read the `$as` binding — resolve the over element type for native typing.
699
727
  const { elemRef } = mapOverElemInfo(comp, node, typedNodes, plan);
700
728
  const asBinding = { name: m.as, ref: elemRef, plan };
701
- const elemStruct = emitPortsStruct(comp, { id: node.id, component: m.component, ports: m.ports }, asBinding, plan, typedNodes);
729
+ // #170: a guarded map (`when(ne($e.key,null))`) proves the element key non-null in kept elements — narrow it.
730
+ const elemStruct = emitPortsStruct(comp, { id: node.id, component: m.component, ports: m.ports, portSchemas: m.portSchemas }, asBinding, plan, typedNodes, nodeNarrowedPaths(comp, node));
702
731
  return `${elemStruct}
703
732
 
704
733
  // ${batch} — CONCRETE batched ports for map '${node.id}': the Vec of per-element CONCRETE ports structs
@@ -716,7 +745,7 @@ function emitFanoutPortsStructs(comp, node, typedNodes, plan) {
716
745
  const batch = `${name}Batch`;
717
746
  const { elemRef } = fanoutOverElemInfo(comp, node, typedNodes, plan);
718
747
  const asBinding = { name: f.as, ref: elemRef, plan };
719
- const elemStruct = emitPortsStruct(comp, { id: node.id, component: f.component, ports: f.ports }, asBinding, plan, typedNodes);
748
+ const elemStruct = emitPortsStruct(comp, { id: node.id, component: f.component, ports: f.ports, portSchemas: f.portSchemas }, asBinding, plan, typedNodes);
720
749
  return `${elemStruct}
721
750
 
722
751
  // ${batch} — CONCRETE batched ports for fanout '${node.id}': the Vec of per-id CONCRETE ports structs.
@@ -798,7 +827,6 @@ function makeRustExprBackend(resolveHead, plan) {
798
827
  arrLit: (elemTy, items) => `{ let __v: Vec<${elemTy}> = vec![${items.join(", ")}]; __v }`,
799
828
  // a projection port of static string literals — `vec!["a", "b"]` infers `&'static str` (the field is
800
829
  // Vec<&'static str>), ZERO heap allocation.
801
- staticStrArr: (literals) => ({ expr: `vec![${literals.map((s) => rustStrLit(s)).join(", ")}]`, type: "Vec<&'static str>" }),
802
830
  // opt (Option<T>) defaulted to a PURE default — eager unwrap_or for a plain copy/path, else the lazy
803
831
  // unwrap_or_else closure (defers an allocating default to the absent branch; clippy or_fun_call).
804
832
  optUnwrapOr: (optExpr, defaultExpr, _innerTy) => /^[A-Za-z0-9_.:]+$/.test(defaultExpr) ? `${optExpr}.unwrap_or(${defaultExpr})` : `${optExpr}.unwrap_or_else(|| ${defaultExpr})`,
@@ -816,6 +844,10 @@ function makeRustExprBackend(resolveHead, plan) {
816
844
  // opt (`Option<T>`) null-presence test: present = `expr.is_some()`, absent = `expr.is_none()`.
817
845
  optIsSome: (expr) => `${rustStripTrailingClone(expr)}.is_some()`,
818
846
  optIsNone: (expr) => `${rustStripTrailingClone(expr)}.is_none()`,
847
+ // #170: narrow a gate/guard-proven-non-null opt to its inner value — `Option<T>` → `T` via `.unwrap()`.
848
+ // Safe by construction: the gated child / guarded element only runs when the ref is non-null (the None
849
+ // arm is statically unreachable in the proven scope). NOT a default — there is no fallback value.
850
+ narrowUnwrap: (optExpr, _innerRef) => `${optExpr}.unwrap()`,
819
851
  ternary: (cond, t, e, _ty) => `(if ${rustStripOuterParens(cond)} { ${rustStripOuterParens(t)} } else { ${rustStripOuterParens(e)} })`,
820
852
  shortCircuitBool: (op, temp, left, rStmts, rExpr) => {
821
853
  // and: let temp = if left { <rStmts> rExpr } else { false }; or: if left { true } else { <rStmts> rExpr }.
@@ -1124,7 +1156,7 @@ function numLiteralRustExpr(node) {
1124
1156
  * resolvable to a native Value with no Obj / no evaluate interpreter. */
1125
1157
  /** planForComp — a TypePlan for a single component (its named types are component-scoped). */
1126
1158
  function planForComp(comp) {
1127
- return buildTypePlan({ irVersion: 1, exprVersion: 2, components: [comp] });
1159
+ return buildTypePlan({ irVersion: 2, exprVersion: 2, components: [comp] });
1128
1160
  }
1129
1161
  /** buildTypedNodes — the prior-node typed-cell TypeRef map (control-gate nodes typeless; a map node
1130
1162
  * carries its produced-array ref). An untyped node is omitted. */
@@ -1153,9 +1185,13 @@ function mapAsBinding(comp, node, typedNodes, plan) {
1153
1185
  }
1154
1186
  /** portIsStatic — the ELIGIBILITY gate ASKS the one port lowering (compilePortNode / native-expr) whether
1155
1187
  * it can lower this port. A port that does not lower (or lowers fallibly) fails closed. */
1156
- function portIsStatic(node, comp, plan, typedNodes, asBinding) {
1188
+ function portIsStatic(node, comp, plan, typedNodes, expected, asBinding, narrowed) {
1157
1189
  try {
1158
- compilePortNode(node, comp, plan, typedNodes, (h) => typedNodes.has(h), "port", asBinding !== undefined ? { asBinding, asBase: asBinding.name } : undefined);
1190
+ // #170: eligibility asks the SAME lowering emission uses, with the SAME node narrowing — so a
1191
+ // gate/guard-proven opt-in-required port is judged covered iff it also emits (they cannot disagree).
1192
+ // #173: with the SAME declared `expected` port type (so covered iff it materializes to that type).
1193
+ const opts = asBinding !== undefined ? { asBinding, asBase: asBinding.name, narrowed } : narrowed !== undefined ? { narrowed } : undefined;
1194
+ compilePortNode(node, comp, plan, typedNodes, (h) => typedNodes.has(h), "port", expected, opts);
1159
1195
  return true;
1160
1196
  }
1161
1197
  catch {
@@ -1197,10 +1233,13 @@ function coveredMapNode(n, bodyIds, comp) {
1197
1233
  if (n === null || typeof n !== "object" || !("map" in n))
1198
1234
  return false;
1199
1235
  const m = n.map;
1200
- // #108 (rust twin of the go predicate): a guarded map (`when`) IS covered with NO `into` (guard+into
1201
- // is heterogeneous — fail-closed). over element type must be statically resolvable: prior-node arr
1202
- // field, or an input array port carrying `elemType` (BC does not infer — consumer-interface C3).
1203
- if (m.when !== undefined && m.into !== undefined)
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))
1204
1243
  return false;
1205
1244
  if (m.policy !== undefined && m.policy !== "fail")
1206
1245
  return false;
@@ -1218,18 +1257,26 @@ function coveredMapNode(n, bodyIds, comp) {
1218
1257
  return false;
1219
1258
  const head = overE.path[0];
1220
1259
  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).
1221
1264
  if (overE.path.length !== 1)
1222
1265
  return false;
1223
1266
  const schema = comp.inputPorts?.[head];
1224
1267
  if (schema === undefined || schema.elemType === undefined)
1225
1268
  return false;
1269
+ if (inputPortIsOptional(schema))
1270
+ return false;
1226
1271
  }
1227
1272
  const ports = m.ports;
1228
1273
  const plan = planForComp(comp);
1229
1274
  const typedNodes = buildTypedNodes(comp, plan);
1230
1275
  const asBinding = mapAsBinding(comp, n, typedNodes, plan);
1276
+ const narrowed = nodeNarrowedPaths(comp, n);
1277
+ const mSchemas = m.portSchemas;
1231
1278
  for (const p of Object.keys(ports))
1232
- if (!portIsStatic(ports[p], comp, plan, typedNodes, asBinding))
1279
+ if (!portIsStatic(ports[p], comp, plan, typedNodes, inputPortTypeRef(mSchemas?.[p], plan), asBinding, narrowed))
1233
1280
  return false;
1234
1281
  return true;
1235
1282
  }
@@ -1248,11 +1295,17 @@ function coveredFanoutNode(n, bodyIds, comp) {
1248
1295
  return false;
1249
1296
  const head = overE.path[0];
1250
1297
  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).
1251
1302
  if (overE.path.length !== 1)
1252
1303
  return false;
1253
1304
  const schema = comp.inputPorts?.[head];
1254
1305
  if (schema === undefined || schema.elemType === undefined)
1255
1306
  return false;
1307
+ if (inputPortIsOptional(schema))
1308
+ return false;
1256
1309
  }
1257
1310
  const ports = f.ports;
1258
1311
  const plan = planForComp(comp);
@@ -1264,8 +1317,9 @@ function coveredFanoutNode(n, bodyIds, comp) {
1264
1317
  catch {
1265
1318
  asBinding = undefined;
1266
1319
  }
1320
+ const fSchemas = f.portSchemas;
1267
1321
  for (const p of Object.keys(ports))
1268
- if (!portIsStatic(ports[p], comp, plan, typedNodes, asBinding))
1322
+ if (!portIsStatic(ports[p], comp, plan, typedNodes, inputPortTypeRef(fSchemas?.[p], plan), asBinding))
1269
1323
  return false;
1270
1324
  return true;
1271
1325
  }
@@ -1377,8 +1431,10 @@ function coverageRejectReason(comp) {
1377
1431
  return `node '${n.id}' relationKind '${cr.relationKind ?? "point"}' not native-covered (bindField only supports single|connection)`;
1378
1432
  if (cr.relationKind !== undefined && cr.relationKind !== "single" && cr.relationKind !== "connection")
1379
1433
  return `relationKind '${cr.relationKind}' not native-covered (node '${n.id}')`;
1434
+ // #170: a control-gate child's ports may narrow a gate-proven opt ref to non-null (the (a3) gated read).
1435
+ const crNarrowed = nodeNarrowedPaths(comp, cr);
1380
1436
  for (const p of Object.keys(cr.ports))
1381
- if (portIsStatic(cr.ports[p], comp, crPlan, crTypedNodes) === false)
1437
+ if (portIsStatic(cr.ports[p], comp, crPlan, crTypedNodes, inputPortTypeRef(cr.portSchemas?.[p], crPlan), undefined, crNarrowed) === false)
1382
1438
  return `node '${n.id}' port '${p}' is not statically resolvable`;
1383
1439
  }
1384
1440
  if (!outputIsNativeLowerable(comp))
@@ -1484,8 +1540,8 @@ function emitInStruct(comp, plan) {
1484
1540
  * a boxed escape would re-introduce the bc-runtime coupling this module removes). `fieldRustType` is the
1485
1541
  * ports-struct field type (from portFieldRustType); `resolveRef` resolves a ref head for the scalar path.
1486
1542
  */
1487
- function emitPortInit(pn, expr, comp, plan, typedNodes, isPrior, opts) {
1488
- const c = compilePortNode(expr, comp, plan, typedNodes, isPrior, `port '${pn}'`, opts);
1543
+ function emitPortInit(pn, expr, comp, plan, typedNodes, isPrior, expected, opts) {
1544
+ const c = compilePortNode(expr, comp, plan, typedNodes, isPrior, `port '${pn}'`, expected, opts);
1489
1545
  if (c.stmts.length > 0)
1490
1546
  throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust typed-native (runtime-free): port '${pn}' ${JSON.stringify(expr)} lowers to a FALLIBLE expression (INT_OVERFLOW / NAN_OR_INF / MOD_ZERO / PRECISION_LOSS) — statements with an early error-return, which a ports-struct literal cannot host. Use a non-fallible port expression.`);
1491
1547
  return `${portFieldName(pn)}: ${c.expr}`;
@@ -1681,8 +1737,9 @@ function emitNativeRawRunner(comp, plan, ap, leaf) {
1681
1737
  }
1682
1738
  }
1683
1739
  const inits = [];
1740
+ const narrowed = nodeNarrowedPaths(comp, node);
1684
1741
  for (const pn of portNames) {
1685
- inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k)));
1742
+ inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed }));
1686
1743
  }
1687
1744
  // bc#97: derived per-node await — this point-read's future is awaited HERE (its result-consumption
1688
1745
  // point) iff THIS node's terminal handler is async. A sync handler in the same async runner is called
@@ -1691,7 +1748,7 @@ function emitNativeRawRunner(comp, plan, ap, leaf) {
1691
1748
  // DIRECT leaf transport call: the resolved op-agnostic symbol, the node's port fields spread (Copy→move,
1692
1749
  // non-Copy→borrow). `bound` is NOT passed — it is BC's internal produced/skip gate, already enforced by
1693
1750
  // the surrounding `if bound_<s>.is_some()` / `if produced_<parent>` guards; the leaf never receives it.
1694
- const call = `${resolveLeafSymbol(node.component, leaf)}(${leafCallArgs(`ports_${s}`, portFieldSpread(node.ports, comp, plan, typedNodes))})${awaitSfx}`;
1751
+ const call = `${resolveLeafSymbol(node.component, leaf)}(${leafCallArgs(`ports_${s}`, portFieldSpread(node.ports, node.portSchemas, comp, plan, typedNodes, undefined, narrowed))})${awaitSfx}`;
1695
1752
  lines.push(`${indent}let ports_${s} = ${structName} { ${inits.join(", ")} };`);
1696
1753
  // uniform seam: every covered node returns a single result WIRE; the inline de-box (renderResultDeBox)
1697
1754
  // classifies it against the STATICALLY declared result type and produces the structured Error Value on a
@@ -1825,8 +1882,9 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1825
1882
  }
1826
1883
  }
1827
1884
  const inits = [];
1885
+ const narrowed = nodeNarrowedPaths(comp, node);
1828
1886
  for (const pn of Object.keys(node.ports)) {
1829
- inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, atPos)));
1887
+ inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, atPos), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed }));
1830
1888
  }
1831
1889
  if (gated) {
1832
1890
  lines.push(`${ind}ports_${s} = Some(${structName} { ${inits.join(", ")} });`);
@@ -1870,7 +1928,7 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1870
1928
  const s = sanitize(node.id);
1871
1929
  // DIRECT leaf transport call — the node's port fields spread off the preflight-built ports struct. No
1872
1930
  // `bound` (BC's internal produced/skip gate is already applied in preflight — the leaf never sees it).
1873
- const call = `${resolveLeafSymbol(node.component, leaf)}(${leafCallArgs("ports", portFieldSpread(node.ports, comp, plan, typedNodes))})`;
1931
+ const call = `${resolveLeafSymbol(node.component, leaf)}(${leafCallArgs("ports", portFieldSpread(node.ports, node.portSchemas, comp, plan, typedNodes, undefined, nodeNarrowedPaths(comp, node)))})`;
1874
1932
  lines.push(` ${slot} => {`);
1875
1933
  lines.push(` let ports = ports_${s}.as_ref().expect("runnable member has ports");`);
1876
1934
  lines.push(` let row = ${call};`);
@@ -1937,6 +1995,10 @@ isAsync = false) {
1937
1995
  const batched = m.batched === true;
1938
1996
  const hasInto = m.into !== undefined;
1939
1997
  const hasGuard = m.when !== undefined;
1998
+ // #177 keep-with-null: a guarded map WITH `into` keeps guard-skipped elements with the (opt) into field
1999
+ // set to None (coveredMapNode only admits this when the into field is opt). A guarded NO-into map DROPs
2000
+ // skipped elements instead. Byte-equal to run_behavior's applyInto keep-with-null.
2001
+ const keepWithNull = hasGuard && hasInto;
1940
2002
  const s = sanitize(node.id);
1941
2003
  const structName = portsStructName(comp.name, node.id);
1942
2004
  const batch = `${structName}Batch`;
@@ -1959,26 +2021,36 @@ isAsync = false) {
1959
2021
  const out = [];
1960
2022
  const inits = [];
1961
2023
  const asBinding = { name: asName, ref: overElemRef, plan };
2024
+ // #170: a guarded map narrows its `when(ne($e.key,null))`-proven element key non-null in kept elements.
2025
+ const narrowed = nodeNarrowedPaths(comp, node);
1962
2026
  for (const pn of portNames) {
1963
- inits.push(emitPortInit(pn, m.ports[pn], comp, plan, typedNodes, priorHere, { asBinding, asBase: `oel_${s}` }));
2027
+ inits.push(emitPortInit(pn, m.ports[pn], comp, plan, typedNodes, priorHere, inputPortTypeRef(m.portSchemas?.[pn], plan), { asBinding, asBase: `oel_${s}`, narrowed }));
1964
2028
  }
1965
2029
  out.push(`${il}let ep_${s} = ${structName} { ${inits.join(", ")} };`);
1966
2030
  return out;
1967
2031
  };
1968
2032
  // #108 guard: compile `when` to a native bool over an element-scoped resolveHead ($as element value,
1969
- // prior node, input port). On skip: `continue` (element excluded — matches run_behavior's keep-gate).
1970
- const emitGuard = (il) => {
2033
+ // prior node, input port). mkGuard returns the compiled {stmts, expr} (or null when unguarded); the
2034
+ // keep-with-null batched path consumes it directly to branch instead of skipping.
2035
+ const mkGuard = () => {
1971
2036
  if (!hasGuard)
1972
- return [];
2037
+ return null;
1973
2038
  const resolveHead = nativeResolveHead(comp, plan, typedNodes, priorHere, { asBinding: { name: asName, ref: overElemRef, plan }, asBase: `oel_${s}` });
1974
- const g = new NativeExprCompiler(makeRustExprBackend(resolveHead, plan)).compileBool(m.when);
2039
+ return new NativeExprCompiler(makeRustExprBackend(resolveHead, plan)).compileBool(m.when);
2040
+ };
2041
+ // On skip: `continue;` by default (element excluded — matches run_behavior's keep-gate); #177
2042
+ // keep-with-null non-batched passes a skip that first pushes the into=None element.
2043
+ const emitGuard = (il, onSkip = "continue;") => {
2044
+ const g = mkGuard();
2045
+ if (g === null)
2046
+ return [];
1975
2047
  const out = [];
1976
2048
  for (const st of g.stmts)
1977
2049
  out.push(`${il}${st}`);
1978
2050
  // bind the keep flag to a var so clippy's nonminimal_bool doesn't rewrite `!(a > b)` (the `when`
1979
2051
  // expr must stay verbatim = run_behavior's `{cond:[when,true,false]}` strict-bool keep-gate).
1980
2052
  out.push(`${il}let __keep = ${rustStripOuterParens(g.expr)};`);
1981
- out.push(`${il}if !__keep { continue; }`);
2053
+ out.push(`${il}if !__keep { ${onSkip} }`);
1982
2054
  return out;
1983
2055
  };
1984
2056
  const lines = [];
@@ -1992,7 +2064,55 @@ isAsync = false) {
1992
2064
  }
1993
2065
  lines.push(`${indent}let over_${s} = ${overExpr};`);
1994
2066
  lines.push(`${indent}let mut built_${s}: Vec<${elemName}> = Vec::with_capacity(over_${s}.len());`);
1995
- if (batched) {
2067
+ if (batched && keepWithNull) {
2068
+ // #177 BATCHED keep-with-null (guarded map...into, opt into): pass 1 records, per over element, whether
2069
+ // it is kept (guard true → build ports) or skipped, preserving ORDER. ONE batched dispatch over the
2070
+ // kept ports, its aligned rows de-boxed into `decs`. Pass 2 re-walks over IN ORDER: a kept element
2071
+ // zips its next deboxed row, a skipped element gets into=None. Byte-equal to run_behavior: batched
2072
+ // keptIdx-aligned collect + applyInto (skipped element unaugmented → opt-into null).
2073
+ const g = mkGuard();
2074
+ lines.push(`${indent}let mut items_${s}: Vec<${structName}> = Vec::with_capacity(over_${s}.len());`);
2075
+ lines.push(`${indent}let mut keep_${s}: Vec<bool> = Vec::with_capacity(over_${s}.len());`);
2076
+ lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
2077
+ for (const st of g.stmts)
2078
+ lines.push(`${indent} ${st}`);
2079
+ lines.push(`${indent} let __keep = ${rustStripOuterParens(g.expr)};`);
2080
+ lines.push(`${indent} if __keep {`);
2081
+ for (const l of buildPorts(indent + " "))
2082
+ lines.push(l);
2083
+ lines.push(`${indent} items_${s}.push(ep_${s});`);
2084
+ lines.push(`${indent} keep_${s}.push(true);`);
2085
+ lines.push(`${indent} } else {`);
2086
+ lines.push(`${indent} keep_${s}.push(false);`);
2087
+ lines.push(`${indent} }`);
2088
+ lines.push(`${indent}}`);
2089
+ lines.push(`${indent}let mut decs_${s}: Vec<${renderTypeRef(elemDeBoxRef)}> = Vec::with_capacity(items_${s}.len());`);
2090
+ lines.push(`${indent}if !items_${s}.is_empty() {`);
2091
+ lines.push(`${indent} let want_${s} = items_${s}.len();`);
2092
+ lines.push(`${indent} let bp_${s} = ${batch} { items: items_${s} };`);
2093
+ lines.push(`${indent} let row_${s} = match ${leafSym}(&bp_${s})${awaitSfx} {`);
2094
+ lines.push(`${indent} Ok(r) => r,`);
2095
+ lines.push(`${indent} Err(e) => return Err(op_failed(${rustStrLit(node.id)}, "fail", e)),`);
2096
+ lines.push(`${indent} };`);
2097
+ lines.push(`${indent} if row_${s}.len() != want_${s} {`);
2098
+ lines.push(`${indent} return Err(BehaviorError::new("MAP_BATCH_RESULT_MISMATCH", format!("map '{}': batched handler must return a list aligned to items (want {})", ${rustStrLit(node.id)}, want_${s})));`);
2099
+ lines.push(`${indent} }`);
2100
+ lines.push(`${indent} for er_${s} in row_${s}.into_iter() {`);
2101
+ lines.push(`${indent} let dec_${s} = ${renderElemDeBox(`${indent} `)};`);
2102
+ lines.push(`${indent} decs_${s}.push(dec_${s});`);
2103
+ lines.push(`${indent} }`);
2104
+ lines.push(`${indent}}`);
2105
+ lines.push(`${indent}let mut decs_iter_${s} = decs_${s}.into_iter();`);
2106
+ lines.push(`${indent}for (oel_${s}, kept_${s}) in over_${s}.iter().zip(keep_${s}.iter()) {`);
2107
+ lines.push(`${indent} if *kept_${s} {`);
2108
+ lines.push(`${indent} let dec_${s} = decs_iter_${s}.next().expect("aligned kept row");`);
2109
+ lines.push(`${indent} built_${s}.push(${elemMat}(oel_${s}, dec_${s}));`);
2110
+ lines.push(`${indent} } else {`);
2111
+ lines.push(`${indent} built_${s}.push(${elemMat}(oel_${s}, None));`);
2112
+ lines.push(`${indent} }`);
2113
+ lines.push(`${indent}}`);
2114
+ }
2115
+ else if (batched) {
1996
2116
  // build kept-element ports (+ kept over elements for into). Batched into is never guarded (rejected).
1997
2117
  lines.push(`${indent}let mut items_${s}: Vec<${structName}> = Vec::with_capacity(over_${s}.len());`);
1998
2118
  if (hasInto)
@@ -2041,7 +2161,10 @@ isAsync = false) {
2041
2161
  else {
2042
2162
  // #93 shape 2 / #108: NON-batched map — dispatch ONCE PER KEPT ELEMENT.
2043
2163
  lines.push(`${indent}for oel_${s} in over_${s}.iter() {`);
2044
- for (const l of emitGuard(indent + " "))
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;";
2167
+ for (const l of emitGuard(indent + " ", nonBatchedSkip))
2045
2168
  lines.push(l);
2046
2169
  for (const l of buildPorts(indent + " "))
2047
2170
  lines.push(l);
@@ -2049,7 +2172,7 @@ isAsync = false) {
2049
2172
  // preserved; the leaf keeps the Error Value it produced). `error` (default) promotes the element
2050
2173
  // Failure to the map's Component Failure, carrying the leaf's detail through. DIRECT transport call —
2051
2174
  // the element ports fields spread (resolved with the `$as` binding, exactly the element ports struct).
2052
- lines.push(`${indent} let er_${s} = match ${leafSym}(${leafCallArgs(`ep_${s}`, portFieldSpread(m.ports, comp, plan, typedNodes, { name: asName, ref: overElemRef, plan }))})${awaitSfx} {`);
2175
+ lines.push(`${indent} let er_${s} = match ${leafSym}(${leafCallArgs(`ep_${s}`, portFieldSpread(m.ports, m.portSchemas, comp, plan, typedNodes, { name: asName, ref: overElemRef, plan }, nodeNarrowedPaths(comp, node)))})${awaitSfx} {`);
2053
2176
  lines.push(`${indent} Ok(r) => r,`);
2054
2177
  if (m.elementPolicy === "skip") {
2055
2178
  lines.push(`${indent} Err(_) => continue,`);
@@ -2107,7 +2230,7 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
2107
2230
  const inits = [];
2108
2231
  const asBinding = { name: asName, ref: overElemRef, plan };
2109
2232
  for (const pn of portNames) {
2110
- inits.push(emitPortInit(pn, f.ports[pn], comp, plan, typedNodes, priorHere, { asBinding, asBase: `oel_${s}` }));
2233
+ inits.push(emitPortInit(pn, f.ports[pn], comp, plan, typedNodes, priorHere, inputPortTypeRef(f.portSchemas?.[pn], plan), { asBinding, asBase: `oel_${s}` }));
2111
2234
  }
2112
2235
  return [`${il}let ep_${s} = ${structName} { ${inits.join(", ")} };`];
2113
2236
  };
@@ -2447,7 +2570,7 @@ ${emitStructSurface([])}
2447
2570
  // #108: a cond node has NO ports struct (pure Expression — no handler dispatch).
2448
2571
  }
2449
2572
  else
2450
- structs.push(emitPortsStruct(c, n, undefined, plan, typedNodes)); // #129: typedNodes for prior-node arr leaf ports.
2573
+ structs.push(emitPortsStruct(c, n, undefined, plan, typedNodes, nodeNarrowedPaths(c, n))); // #129: typedNodes for prior-node arr leaf ports. #170: a gated child narrows its gate-proven opt key.
2451
2574
  }
2452
2575
  inStructs.push(emitInStruct(c, plan));
2453
2576
  const mm = emitMapElemMaterializers(c, typedNodes, plan);
@@ -2647,7 +2770,7 @@ fn value_to_wire(v: &Value) -> WireValue {
2647
2770
  }
2648
2771
  else {
2649
2772
  const { elemRef: overElemRef } = mapOverElemInfo(c, n, typedNodes, plan);
2650
- const params = spreadParams(portFieldSpread(m.ports, c, plan, typedNodes, { name: m.as, ref: overElemRef, plan }));
2773
+ const params = spreadParams(portFieldSpread(m.ports, m.portSchemas, c, plan, typedNodes, { name: m.as, ref: overElemRef, plan }, nodeNarrowedPaths(c, n)));
2651
2774
  transportFns.push(`${fnKw} ${sym}(${params}) -> Result<WireValue, BehaviorError> {
2652
2775
  ${drainStmt(catalog, "_echo")}
2653
2776
  Ok(value_to_wire(&ok.unwrap_or(Value::Null)))
@@ -2657,6 +2780,9 @@ fn value_to_wire(v: &Value) -> WireValue {
2657
2780
  }
2658
2781
  // componentRef (point read): spread port fields; supports echo (#129/#141) reading the port params.
2659
2782
  const node = n;
2783
+ // #170: the observe transport fn's param types must match the covered module's leaf call args, which
2784
+ // narrow a gate-proven opt key — so this reads the SAME node narrowing.
2785
+ const crNarrowed = nodeNarrowedPaths(c, node);
2660
2786
  const ref = typedNodes.get(n.id);
2661
2787
  const echoBranches = [];
2662
2788
  if (ref.kind === "named") {
@@ -2667,7 +2793,7 @@ fn value_to_wire(v: &Value) -> WireValue {
2667
2793
  for (const pn of Object.keys(node.ports)) {
2668
2794
  let portRust = null;
2669
2795
  try {
2670
- portRust = portFieldRustType(node.ports[pn], c, plan, typedNodes, `echo port '${pn}'`);
2796
+ portRust = portFieldRustType(node.ports[pn], c, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[pn], plan), `echo port '${pn}'`, { narrowed: crNarrowed });
2671
2797
  }
2672
2798
  catch {
2673
2799
  portRust = null;
@@ -2691,7 +2817,7 @@ fn value_to_wire(v: &Value) -> WireValue {
2691
2817
  echoBranches.push(` if echo == "items" {\n let tv = Value::Arr(${portFieldName("items")}.iter().map(|e| { let ev = e.clone(); ${serializeTyped("ev", elemRef, plan)} }).collect());\n return Ok(value_to_wire(&tv));\n }`);
2692
2818
  }
2693
2819
  const canEcho = echoBranches.length > 0;
2694
- const params = spreadParams(portFieldSpread(node.ports, c, plan, typedNodes));
2820
+ const params = spreadParams(portFieldSpread(node.ports, node.portSchemas, c, plan, typedNodes, undefined, crNarrowed));
2695
2821
  const echoBlock = canEcho ? `${echoBranches.join("\n")}\n` : "";
2696
2822
  transportFns.push(`${fnKw} ${sym}(${params}) -> Result<WireValue, BehaviorError> {
2697
2823
  ${drainStmt(catalog, canEcho ? "echo" : "_echo")}