behavior-contracts 0.8.16 → 0.9.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 (64) hide show
  1. package/cli-contract.yaml +43 -4
  2. package/dist/authoring.d.ts +26 -0
  3. package/dist/authoring.d.ts.map +1 -1
  4. package/dist/authoring.js +30 -6
  5. package/dist/authoring.js.map +1 -1
  6. package/dist/behavior.d.ts +26 -1
  7. package/dist/behavior.d.ts.map +1 -1
  8. package/dist/behavior.js.map +1 -1
  9. package/dist/builder.d.ts.map +1 -1
  10. package/dist/builder.js +19 -4
  11. package/dist/builder.js.map +1 -1
  12. package/dist/cli.js +66 -27
  13. package/dist/cli.js.map +1 -1
  14. package/dist/commands/codegen.d.ts +8 -0
  15. package/dist/commands/codegen.d.ts.map +1 -1
  16. package/dist/commands/codegen.js +31 -0
  17. package/dist/commands/codegen.js.map +1 -1
  18. package/dist/generated/commands.d.ts.map +1 -1
  19. package/dist/generated/commands.js +4 -0
  20. package/dist/generated/commands.js.map +1 -1
  21. package/dist/generated/contract.d.ts.map +1 -1
  22. package/dist/generated/contract.js +2 -2
  23. package/dist/generated/contract.js.map +1 -1
  24. package/dist/generated/program.d.ts +2 -0
  25. package/dist/generated/program.d.ts.map +1 -1
  26. package/dist/generated/program.js +4 -2
  27. package/dist/generated/program.js.map +1 -1
  28. package/dist/generated/types.d.ts +3 -1
  29. package/dist/generated/types.d.ts.map +1 -1
  30. package/dist/generator/core.js +2 -2
  31. package/dist/generator/core.js.map +1 -1
  32. package/dist/generator/emit-typed-native-go.d.ts +6 -0
  33. package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
  34. package/dist/generator/emit-typed-native-go.js +101 -41
  35. package/dist/generator/emit-typed-native-go.js.map +1 -1
  36. package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
  37. package/dist/generator/emit-typed-native-rust.js +82 -34
  38. package/dist/generator/emit-typed-native-rust.js.map +1 -1
  39. package/dist/generator/index.d.ts +1 -1
  40. package/dist/generator/index.d.ts.map +1 -1
  41. package/dist/generator/index.js +1 -1
  42. package/dist/generator/index.js.map +1 -1
  43. package/dist/generator/native-expr.d.ts +35 -27
  44. package/dist/generator/native-expr.d.ts.map +1 -1
  45. package/dist/generator/native-expr.js +59 -59
  46. package/dist/generator/native-expr.js.map +1 -1
  47. package/dist/generator/straightline.d.ts +21 -0
  48. package/dist/generator/straightline.d.ts.map +1 -1
  49. package/dist/generator/straightline.js +68 -0
  50. package/dist/generator/straightline.js.map +1 -1
  51. package/dist/generator/typed.d.ts.map +1 -1
  52. package/dist/generator/typed.js +13 -0
  53. package/dist/generator/typed.js.map +1 -1
  54. package/dist/guard.d.ts.map +1 -1
  55. package/dist/guard.js +30 -0
  56. package/dist/guard.js.map +1 -1
  57. package/dist/provenance.d.ts.map +1 -1
  58. package/dist/provenance.js +3 -0
  59. package/dist/provenance.js.map +1 -1
  60. package/dist/type-gate.d.ts +9 -1
  61. package/dist/type-gate.d.ts.map +1 -1
  62. package/dist/type-gate.js +10 -4
  63. package/dist/type-gate.js.map +1 -1
  64. package/package.json +1 -1
@@ -3,7 +3,7 @@ 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
5
  import { buildTypePlan, deriveTypeRef, findDecl, inputPortIsOptional, inputPortTypeRef } from "./typed.js";
6
- import { concurrencyPlan, execPlan, analyzeSequentialOps, classifyExpr } from "./straightline.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 {
@@ -1228,8 +1264,10 @@ function coveredMapNode(n, bodyIds, comp) {
1228
1264
  const plan = planForComp(comp);
1229
1265
  const typedNodes = buildTypedNodes(comp, plan);
1230
1266
  const asBinding = mapAsBinding(comp, n, typedNodes, plan);
1267
+ const narrowed = nodeNarrowedPaths(comp, n);
1268
+ const mSchemas = m.portSchemas;
1231
1269
  for (const p of Object.keys(ports))
1232
- if (!portIsStatic(ports[p], comp, plan, typedNodes, asBinding))
1270
+ if (!portIsStatic(ports[p], comp, plan, typedNodes, inputPortTypeRef(mSchemas?.[p], plan), asBinding, narrowed))
1233
1271
  return false;
1234
1272
  return true;
1235
1273
  }
@@ -1264,8 +1302,9 @@ function coveredFanoutNode(n, bodyIds, comp) {
1264
1302
  catch {
1265
1303
  asBinding = undefined;
1266
1304
  }
1305
+ const fSchemas = f.portSchemas;
1267
1306
  for (const p of Object.keys(ports))
1268
- if (!portIsStatic(ports[p], comp, plan, typedNodes, asBinding))
1307
+ if (!portIsStatic(ports[p], comp, plan, typedNodes, inputPortTypeRef(fSchemas?.[p], plan), asBinding))
1269
1308
  return false;
1270
1309
  return true;
1271
1310
  }
@@ -1377,8 +1416,10 @@ function coverageRejectReason(comp) {
1377
1416
  return `node '${n.id}' relationKind '${cr.relationKind ?? "point"}' not native-covered (bindField only supports single|connection)`;
1378
1417
  if (cr.relationKind !== undefined && cr.relationKind !== "single" && cr.relationKind !== "connection")
1379
1418
  return `relationKind '${cr.relationKind}' not native-covered (node '${n.id}')`;
1419
+ // #170: a control-gate child's ports may narrow a gate-proven opt ref to non-null (the (a3) gated read).
1420
+ const crNarrowed = nodeNarrowedPaths(comp, cr);
1380
1421
  for (const p of Object.keys(cr.ports))
1381
- if (portIsStatic(cr.ports[p], comp, crPlan, crTypedNodes) === false)
1422
+ if (portIsStatic(cr.ports[p], comp, crPlan, crTypedNodes, inputPortTypeRef(cr.portSchemas?.[p], crPlan), undefined, crNarrowed) === false)
1382
1423
  return `node '${n.id}' port '${p}' is not statically resolvable`;
1383
1424
  }
1384
1425
  if (!outputIsNativeLowerable(comp))
@@ -1484,8 +1525,8 @@ function emitInStruct(comp, plan) {
1484
1525
  * a boxed escape would re-introduce the bc-runtime coupling this module removes). `fieldRustType` is the
1485
1526
  * ports-struct field type (from portFieldRustType); `resolveRef` resolves a ref head for the scalar path.
1486
1527
  */
1487
- function emitPortInit(pn, expr, comp, plan, typedNodes, isPrior, opts) {
1488
- const c = compilePortNode(expr, comp, plan, typedNodes, isPrior, `port '${pn}'`, opts);
1528
+ function emitPortInit(pn, expr, comp, plan, typedNodes, isPrior, expected, opts) {
1529
+ const c = compilePortNode(expr, comp, plan, typedNodes, isPrior, `port '${pn}'`, expected, opts);
1489
1530
  if (c.stmts.length > 0)
1490
1531
  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
1532
  return `${portFieldName(pn)}: ${c.expr}`;
@@ -1681,8 +1722,9 @@ function emitNativeRawRunner(comp, plan, ap, leaf) {
1681
1722
  }
1682
1723
  }
1683
1724
  const inits = [];
1725
+ const narrowed = nodeNarrowedPaths(comp, node);
1684
1726
  for (const pn of portNames) {
1685
- inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k)));
1727
+ inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed }));
1686
1728
  }
1687
1729
  // bc#97: derived per-node await — this point-read's future is awaited HERE (its result-consumption
1688
1730
  // point) iff THIS node's terminal handler is async. A sync handler in the same async runner is called
@@ -1691,7 +1733,7 @@ function emitNativeRawRunner(comp, plan, ap, leaf) {
1691
1733
  // DIRECT leaf transport call: the resolved op-agnostic symbol, the node's port fields spread (Copy→move,
1692
1734
  // non-Copy→borrow). `bound` is NOT passed — it is BC's internal produced/skip gate, already enforced by
1693
1735
  // 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}`;
1736
+ const call = `${resolveLeafSymbol(node.component, leaf)}(${leafCallArgs(`ports_${s}`, portFieldSpread(node.ports, node.portSchemas, comp, plan, typedNodes, undefined, narrowed))})${awaitSfx}`;
1695
1737
  lines.push(`${indent}let ports_${s} = ${structName} { ${inits.join(", ")} };`);
1696
1738
  // uniform seam: every covered node returns a single result WIRE; the inline de-box (renderResultDeBox)
1697
1739
  // classifies it against the STATICALLY declared result type and produces the structured Error Value on a
@@ -1825,8 +1867,9 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1825
1867
  }
1826
1868
  }
1827
1869
  const inits = [];
1870
+ const narrowed = nodeNarrowedPaths(comp, node);
1828
1871
  for (const pn of Object.keys(node.ports)) {
1829
- inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, atPos)));
1872
+ inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, atPos), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed }));
1830
1873
  }
1831
1874
  if (gated) {
1832
1875
  lines.push(`${ind}ports_${s} = Some(${structName} { ${inits.join(", ")} });`);
@@ -1870,7 +1913,7 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1870
1913
  const s = sanitize(node.id);
1871
1914
  // DIRECT leaf transport call — the node's port fields spread off the preflight-built ports struct. No
1872
1915
  // `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))})`;
1916
+ const call = `${resolveLeafSymbol(node.component, leaf)}(${leafCallArgs("ports", portFieldSpread(node.ports, node.portSchemas, comp, plan, typedNodes, undefined, nodeNarrowedPaths(comp, node)))})`;
1874
1917
  lines.push(` ${slot} => {`);
1875
1918
  lines.push(` let ports = ports_${s}.as_ref().expect("runnable member has ports");`);
1876
1919
  lines.push(` let row = ${call};`);
@@ -1959,8 +2002,10 @@ isAsync = false) {
1959
2002
  const out = [];
1960
2003
  const inits = [];
1961
2004
  const asBinding = { name: asName, ref: overElemRef, plan };
2005
+ // #170: a guarded map narrows its `when(ne($e.key,null))`-proven element key non-null in kept elements.
2006
+ const narrowed = nodeNarrowedPaths(comp, node);
1962
2007
  for (const pn of portNames) {
1963
- inits.push(emitPortInit(pn, m.ports[pn], comp, plan, typedNodes, priorHere, { asBinding, asBase: `oel_${s}` }));
2008
+ inits.push(emitPortInit(pn, m.ports[pn], comp, plan, typedNodes, priorHere, inputPortTypeRef(m.portSchemas?.[pn], plan), { asBinding, asBase: `oel_${s}`, narrowed }));
1964
2009
  }
1965
2010
  out.push(`${il}let ep_${s} = ${structName} { ${inits.join(", ")} };`);
1966
2011
  return out;
@@ -2049,7 +2094,7 @@ isAsync = false) {
2049
2094
  // preserved; the leaf keeps the Error Value it produced). `error` (default) promotes the element
2050
2095
  // Failure to the map's Component Failure, carrying the leaf's detail through. DIRECT transport call —
2051
2096
  // 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} {`);
2097
+ 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
2098
  lines.push(`${indent} Ok(r) => r,`);
2054
2099
  if (m.elementPolicy === "skip") {
2055
2100
  lines.push(`${indent} Err(_) => continue,`);
@@ -2107,7 +2152,7 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, i
2107
2152
  const inits = [];
2108
2153
  const asBinding = { name: asName, ref: overElemRef, plan };
2109
2154
  for (const pn of portNames) {
2110
- inits.push(emitPortInit(pn, f.ports[pn], comp, plan, typedNodes, priorHere, { asBinding, asBase: `oel_${s}` }));
2155
+ inits.push(emitPortInit(pn, f.ports[pn], comp, plan, typedNodes, priorHere, inputPortTypeRef(f.portSchemas?.[pn], plan), { asBinding, asBase: `oel_${s}` }));
2111
2156
  }
2112
2157
  return [`${il}let ep_${s} = ${structName} { ${inits.join(", ")} };`];
2113
2158
  };
@@ -2447,7 +2492,7 @@ ${emitStructSurface([])}
2447
2492
  // #108: a cond node has NO ports struct (pure Expression — no handler dispatch).
2448
2493
  }
2449
2494
  else
2450
- structs.push(emitPortsStruct(c, n, undefined, plan, typedNodes)); // #129: typedNodes for prior-node arr leaf ports.
2495
+ 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
2496
  }
2452
2497
  inStructs.push(emitInStruct(c, plan));
2453
2498
  const mm = emitMapElemMaterializers(c, typedNodes, plan);
@@ -2647,7 +2692,7 @@ fn value_to_wire(v: &Value) -> WireValue {
2647
2692
  }
2648
2693
  else {
2649
2694
  const { elemRef: overElemRef } = mapOverElemInfo(c, n, typedNodes, plan);
2650
- const params = spreadParams(portFieldSpread(m.ports, c, plan, typedNodes, { name: m.as, ref: overElemRef, plan }));
2695
+ const params = spreadParams(portFieldSpread(m.ports, m.portSchemas, c, plan, typedNodes, { name: m.as, ref: overElemRef, plan }, nodeNarrowedPaths(c, n)));
2651
2696
  transportFns.push(`${fnKw} ${sym}(${params}) -> Result<WireValue, BehaviorError> {
2652
2697
  ${drainStmt(catalog, "_echo")}
2653
2698
  Ok(value_to_wire(&ok.unwrap_or(Value::Null)))
@@ -2657,6 +2702,9 @@ fn value_to_wire(v: &Value) -> WireValue {
2657
2702
  }
2658
2703
  // componentRef (point read): spread port fields; supports echo (#129/#141) reading the port params.
2659
2704
  const node = n;
2705
+ // #170: the observe transport fn's param types must match the covered module's leaf call args, which
2706
+ // narrow a gate-proven opt key — so this reads the SAME node narrowing.
2707
+ const crNarrowed = nodeNarrowedPaths(c, node);
2660
2708
  const ref = typedNodes.get(n.id);
2661
2709
  const echoBranches = [];
2662
2710
  if (ref.kind === "named") {
@@ -2667,7 +2715,7 @@ fn value_to_wire(v: &Value) -> WireValue {
2667
2715
  for (const pn of Object.keys(node.ports)) {
2668
2716
  let portRust = null;
2669
2717
  try {
2670
- portRust = portFieldRustType(node.ports[pn], c, plan, typedNodes, `echo port '${pn}'`);
2718
+ portRust = portFieldRustType(node.ports[pn], c, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[pn], plan), `echo port '${pn}'`, { narrowed: crNarrowed });
2671
2719
  }
2672
2720
  catch {
2673
2721
  portRust = null;
@@ -2691,7 +2739,7 @@ fn value_to_wire(v: &Value) -> WireValue {
2691
2739
  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
2740
  }
2693
2741
  const canEcho = echoBranches.length > 0;
2694
- const params = spreadParams(portFieldSpread(node.ports, c, plan, typedNodes));
2742
+ const params = spreadParams(portFieldSpread(node.ports, node.portSchemas, c, plan, typedNodes, undefined, crNarrowed));
2695
2743
  const echoBlock = canEcho ? `${echoBranches.join("\n")}\n` : "";
2696
2744
  transportFns.push(`${fnKw} ${sym}(${params}) -> Result<WireValue, BehaviorError> {
2697
2745
  ${drainStmt(catalog, canEcho ? "echo" : "_echo")}