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 { goStraightlineInternals } from "./emit-shared-go.js";
4
4
  import { goTypedInternals } from "./emit-shared-go-typed.js";
5
- import { buildTypePlan, deriveTypeRef, findDecl, inputPortIsOptional, inputPortTypeRef } from "./typed.js";
6
- import { concurrencyPlan, execPlan, analyzeSequentialOps, classifyExpr, buildComponentPlan, } from "./straightline.js";
5
+ import { buildTypePlan, deriveTypeRef, findDecl, guardedMapIntoIsOpt, inputPortIsOptional, inputPortTypeRef } from "./typed.js";
6
+ import { concurrencyPlan, execPlan, analyzeSequentialOps, classifyExpr, buildComponentPlan, nodeNarrowedPaths, } from "./straightline.js";
7
7
  import { NativeExprCompiler } from "./native-expr.js";
8
8
  import { buildDeBoxPlan, buildWirePlan, notationOfRef } from "./emit-shared-debox.js";
9
9
  const PKG = "dslcontracts";
@@ -613,16 +613,33 @@ function goNativeResolveHead(comp, plan, typedNodes, isPrior, opts) {
613
613
  * field), a concat, a static array, an optional-input read — all resolve here. A port that cannot lower
614
614
  * FAILS CLOSED. A FALLIBLE lowering (hoists statements) is returned as-is; only emitPortInit rejects it.
615
615
  */
616
- function compilePortNode(node, comp, plan, typedNodes, isPrior, where, opts) {
616
+ function compilePortNode(node, comp, plan, typedNodes, isPrior, where, expected, opts) {
617
+ // #173: the port boundary is declared-type-driven (twin of the go rust emitter). `expected` is the
618
+ // referenced leaf's declared port type (node.portSchemas[port] → inputPortTypeRef). Mandatory (the guard
619
+ // requires portSchemas on every port); `undefined` = a declared type with no native lowering → LOUD fail.
620
+ if (expected === undefined)
621
+ throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `go typed-native (runtime-free): ${where}: the declared port type is not statically resolvable (portSchemas type has no native lowering) — fail-closed`);
617
622
  const resolveHead = goNativeResolveHead(comp, plan, typedNodes, isPrior, opts);
623
+ const resolveDecl = (name) => findDecl(plan, name).fields;
624
+ let c;
618
625
  try {
619
- return new NativeExprCompiler(makeGoExprBackend("", resolveHead, plan)).compilePort(node);
626
+ // #170: opts.narrowed carries the gate/guard-proven-non-null ref paths for THIS node's port scope, so an
627
+ // opt-in-required operand it proves non-null narrows instead of failing closed (the ONE narrowing site).
628
+ // #173: lower to the DECLARED port type via compilePortTo → compileTo (no element-kind inference).
629
+ c = new NativeExprCompiler(makeGoExprBackend("", resolveHead, plan, opts?.wireSel), opts?.narrowed).compilePortTo(node, expected, resolveDecl);
620
630
  }
621
631
  catch (e) {
622
632
  if (!(e instanceof GeneratorFailure))
623
633
  throw e;
624
634
  throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `go typed-native (runtime-free): ${where} ${JSON.stringify(node)} does not lower to a native Go value: ${e.message}`);
625
635
  }
636
+ // #173: the port field type equals the declared port type BY CONSTRUCTION — compilePortTo → compileTo
637
+ // materializes the node to exactly `expected` (the value/opt/obj/arr branches return `ref: expected`; the
638
+ // scalar/ref/operator branch requires `typeRefEqual(ref, expected)` or throws UNSUPPORTED_NODE_STRAIGHTLINE
639
+ // first). There is no independent second source that could diverge (unlike the OUTPUT boundary, whose
640
+ // node-type SSoT and declared outputType can disagree → the reachable OUTPUT_TYPE_INCONSISTENT gate), so
641
+ // no separate input-side integrity gate exists.
642
+ return c;
626
643
  }
627
644
  /**
628
645
  * portFieldGoType — the NATIVE Go type for a covered port field (bc#90 / runtime-free). The covered
@@ -634,9 +651,9 @@ function compilePortNode(node, comp, plan, typedNodes, isPrior, where, opts) {
634
651
  * Value-typed input) FAILS CLOSED — the covered read plane admits NO boxed escape (there is no
635
652
  * `dslcontracts.Value` fallback on the native module). `where` names the emission site for the error.
636
653
  */
637
- function portFieldGoType(node, comp, plan, typedNodes, where = "port", opts) {
638
- const c = compilePortNode(node, comp, plan, typedNodes, (h) => typedNodes.has(h), where, opts);
639
- return c.renderedType ?? renderTypeRef(c.ref);
654
+ function portFieldGoType(node, comp, plan, typedNodes, expected, where = "port", opts) {
655
+ const c = compilePortNode(node, comp, plan, typedNodes, (h) => typedNodes.has(h), where, expected, opts);
656
+ return renderTypeRef(c.ref);
640
657
  }
641
658
  function staticArrElems(node) {
642
659
  if (node === null || typeof node !== "object" || Array.isArray(node))
@@ -687,7 +704,7 @@ function numLiteralGoExpr(node) {
687
704
  /** planForComp — a TypePlan for a single component (its named types are component-scoped, so a
688
705
  * one-component IR yields the same plan the full-IR build would for this component). */
689
706
  function planForComp(comp) {
690
- return buildTypePlan({ irVersion: 1, exprVersion: 2, components: [comp] });
707
+ return buildTypePlan({ irVersion: 2, exprVersion: 2, components: [comp] });
691
708
  }
692
709
  /** buildTypedNodes — the prior-node typed-local TypeRef map for a component (control-gate nodes are
693
710
  * typeless; a map node carries its produced-array ref). An untyped node is omitted (not an error here). */
@@ -718,9 +735,14 @@ function mapAsBinding(comp, node, typedNodes, plan) {
718
735
  /** portIsStatic — the ELIGIBILITY gate ASKS the one port lowering (compilePortNode / native-expr)
719
736
  * whether it can lower this port, rather than re-deriving the shape rules — so the gate and the emitter
720
737
  * can never disagree. A port that does not lower (or lowers fallibly) fails closed. */
721
- function portIsStatic(node, comp, plan, typedNodes, asBinding) {
738
+ function portIsStatic(node, comp, plan, typedNodes, expected, asBinding, narrowed) {
722
739
  try {
723
- compilePortNode(node, comp, plan, typedNodes, (h) => typedNodes.has(h), "port", asBinding !== undefined ? { asBinding, asBase: asBinding.name } : undefined);
740
+ void 0;
741
+ // #170: eligibility asks the SAME lowering emission uses, with the SAME node narrowing — so a
742
+ // gate/guard-proven opt-in-required port is judged covered iff it also emits (they cannot disagree).
743
+ // #173: with the SAME declared `expected` port type (covered iff it materializes to that type).
744
+ const opts = asBinding !== undefined ? { asBinding, asBase: asBinding.name, narrowed } : narrowed !== undefined ? { narrowed } : undefined;
745
+ compilePortNode(node, comp, plan, typedNodes, (h) => typedNodes.has(h), "port", expected, opts);
724
746
  return true;
725
747
  }
726
748
  catch {
@@ -793,10 +815,16 @@ function coveredMapNode(n, bodyIds, comp) {
793
815
  return false;
794
816
  const m = n.map;
795
817
  // #86 pt2: batched map...into. #93 shape 2/3: (non-)batched map...into / connection-collect. #108:
796
- // a guarded map (`when`) IS covered when it has NO `into` (guard+into is heterogeneous — skipped
797
- // elements lack the into field, cannot de-box into one []T; keep it fail-closed, matching the typed
798
- // straightline reject). A guarded map over a native-typed element collection drops skipped elements.
799
- if (m.when !== undefined && m.into !== undefined)
818
+ // a guarded map (`when`) IS covered when it has NO `into`. #177: a guarded map WITH `into` is covered
819
+ // ONLY when the into field is OPT — the augmented list is then homogeneous []ElemWithOptInto (kept
820
+ // element → present into, guard-skipped element → into=nil), which is EXACTLY run_behavior's applyInto
821
+ // pass-through (behavior.ts:846 — a skipped element is pushed unaugmented) followed by output
822
+ // conformance materializing the absent opt-into field as null (behavior.ts:597 — keep-with-null). A
823
+ // REQUIRED into field stays fail-closed: run_behavior FAILS MISSING_PROP on a skipped element there,
824
+ // so rejecting is byte-equal. Opt-ness is read from the into field's declared type (the map node's
825
+ // element outType); an element type that does not resolve to a named struct with the into field →
826
+ // fail-closed (the resolvers below would reject it anyway).
827
+ if (m.when !== undefined && m.into !== undefined && !guardedMapIntoIsOpt(n, comp))
800
828
  return false;
801
829
  if (m.policy !== undefined && m.policy !== "fail")
802
830
  return false;
@@ -817,19 +845,27 @@ function coveredMapNode(n, bodyIds, comp) {
817
845
  return false;
818
846
  const head = overE.path[0];
819
847
  if (!bodyIds.has(head)) {
820
- // input-array over: covered only when the input port declares elemType (#108).
848
+ // input-array over: covered only when the input port declares elemType (#108) AND is REQUIRED.
849
+ // #177: an OPT input-array (`{opt:{arr}}`, required:false) is NOT natively coverable — the over would
850
+ // resolve to `in.<Field>` of native `*[]E` and `range` over a pointer-to-slice does not compile;
851
+ // run_behavior itself FAILS MAP_OVER_NOT_ARRAY on a null opt collection, so fail-close here is
852
+ // byte-equal. (A faithful nil→empty iteration is an owner-level semantics decision, not an emitter fix.)
821
853
  if (overE.path.length !== 1)
822
854
  return false;
823
855
  const schema = comp.inputPorts?.[head];
824
856
  if (schema === undefined || schema.elemType === undefined)
825
857
  return false;
858
+ if (inputPortIsOptional(schema))
859
+ return false;
826
860
  }
827
861
  const ports = m.ports;
828
862
  const plan = planForComp(comp);
829
863
  const typedNodes = buildTypedNodes(comp, plan);
830
864
  const asBinding = mapAsBinding(comp, n, typedNodes, plan);
865
+ const narrowed = nodeNarrowedPaths(comp, n);
866
+ const mSchemas = m.portSchemas;
831
867
  for (const p of Object.keys(ports))
832
- if (!portIsStatic(ports[p], comp, plan, typedNodes, asBinding))
868
+ if (!portIsStatic(ports[p], comp, plan, typedNodes, inputPortTypeRef(mSchemas?.[p], plan), asBinding, narrowed))
833
869
  return false;
834
870
  return true;
835
871
  }
@@ -854,11 +890,17 @@ function coveredFanoutNode(n, bodyIds, comp) {
854
890
  return false;
855
891
  const head = overE.path[0];
856
892
  if (!bodyIds.has(head)) {
893
+ // input-array over: covered only when the port declares elemType AND is REQUIRED. #177: an OPT
894
+ // input-array (`{opt:{arr}}`, required:false) resolves to `in.<Field>` of native `*[]E` — `len`/
895
+ // `range` over a pointer-to-slice does not compile, and run_behavior FAILS FANOUT_OVER_NOT_ARRAY on
896
+ // a null opt collection — so fail-close here is byte-equal (the faithful nil→empty is owner-level).
857
897
  if (overE.path.length !== 1)
858
898
  return false;
859
899
  const schema = comp.inputPorts?.[head];
860
900
  if (schema === undefined || schema.elemType === undefined)
861
901
  return false;
902
+ if (inputPortIsOptional(schema))
903
+ return false;
862
904
  }
863
905
  const ports = f.ports;
864
906
  const plan = planForComp(comp);
@@ -870,8 +912,9 @@ function coveredFanoutNode(n, bodyIds, comp) {
870
912
  catch {
871
913
  asBinding = undefined;
872
914
  }
915
+ const fSchemas = f.portSchemas;
873
916
  for (const p of Object.keys(ports))
874
- if (!portIsStatic(ports[p], comp, plan, typedNodes, asBinding))
917
+ if (!portIsStatic(ports[p], comp, plan, typedNodes, inputPortTypeRef(fSchemas?.[p], plan), asBinding))
875
918
  return false;
876
919
  return true;
877
920
  }
@@ -979,8 +1022,10 @@ function coverageRejectReason(comp) {
979
1022
  return `node '${n.id}' relationKind '${cr.relationKind ?? "point"}' not native-covered (bindField only supports single|connection)`;
980
1023
  if (cr.relationKind !== undefined && cr.relationKind !== "single" && cr.relationKind !== "connection")
981
1024
  return `relationKind '${cr.relationKind}' not native-covered (node '${n.id}')`;
1025
+ // #170: a control-gate child's ports may narrow a gate-proven opt ref to non-null (the (a3) gated read).
1026
+ const crNarrowed = nodeNarrowedPaths(comp, cr);
982
1027
  for (const p of Object.keys(cr.ports))
983
- if (portIsStatic(cr.ports[p], comp, crPlan, crTypedNodes) === false)
1028
+ if (portIsStatic(cr.ports[p], comp, crPlan, crTypedNodes, inputPortTypeRef(cr.portSchemas?.[p], crPlan), undefined, crNarrowed) === false)
984
1029
  return `node '${n.id}' port '${p}' is not statically resolvable`;
985
1030
  }
986
1031
  if (!outputIsNativeLowerable(comp))
@@ -996,7 +1041,7 @@ function assertTypedCoverage(comp) {
996
1041
  throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `go combined read (bc#77): component '${comp.name}' is a sequential componentRef read but lacks outType/outputType on every node — the combined emitter de-boxes the RESULT into the node's outType struct, so a covered read MUST be fully typed (bc#45). Add outType annotations, or regenerate on go-straightline-native (boxed result).`);
997
1042
  }
998
1043
  // ── native ports struct + PortReader ──────────────────────────────────────────────────
999
- function emitPortsStruct(comp, node, asBinding, plan, typedNodes) {
1044
+ function emitPortsStruct(comp, node, asBinding, plan, typedNodes, narrowed) {
1000
1045
  const structName = portsStructName(comp.name, node.id);
1001
1046
  const portNames = Object.keys(node.ports);
1002
1047
  if (portNames.length === 0) {
@@ -1007,7 +1052,10 @@ function emitPortsStruct(comp, node, asBinding, plan, typedNodes) {
1007
1052
  if (plan === undefined || typedNodes === undefined) {
1008
1053
  throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `go typed-native: ports struct for node '${node.id}' needs a type plan + prior-node map`);
1009
1054
  }
1010
- const fieldTypes = portNames.map((p) => portFieldGoType(node.ports[p], comp, plan, typedNodes, `port '${p}' of node '${node.id}'`, asBinding !== undefined ? { asBinding, asBase: asBinding.name } : undefined));
1055
+ // #170: the field TYPE reads the SAME lowering (incl. gate/guard narrowing) the init does, so a narrowed
1056
+ // opt-in-required port is a non-opt field AND a non-opt initializer — they can never disagree.
1057
+ const portOpts = asBinding !== undefined ? { asBinding, asBase: asBinding.name, narrowed } : narrowed !== undefined ? { narrowed } : undefined;
1058
+ const fieldTypes = portNames.map((p) => portFieldGoType(node.ports[p], comp, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[p], plan), `port '${p}' of node '${node.id}'`, portOpts));
1011
1059
  const fieldNames = portNames.map(goPortFieldName);
1012
1060
  const fields = portNames
1013
1061
  .map((p, i) => `\t${fieldNames[i]} ${fieldTypes[i]} // ${JSON.stringify(p)}`)
@@ -1048,11 +1096,15 @@ function resolveLeafSymbol(component, leaf) {
1048
1096
  * Types come from the SAME `portFieldGoType` lowering `emitPortsStruct` uses, so the spread can never
1049
1097
  * disagree with the ports struct field types. (Go has no borrow — every field is passed by value.)
1050
1098
  */
1051
- function portFieldSpread(ports, comp, plan, typedNodes, asBinding) {
1052
- const opts = asBinding !== undefined ? { asBinding, asBase: asBinding.name } : undefined;
1099
+ function portFieldSpread(ports, portSchemas, comp, plan, typedNodes, asBinding, narrowed) {
1100
+ // #170: the transport-call spread reads the SAME lowering (incl. gate/guard narrowing) as the ports
1101
+ // struct fields — a narrowed opt-in-required port is a non-opt arg, matching the non-opt struct field.
1102
+ // #173: `expected` (declared port type from portSchemas) drives the SAME materialization the struct
1103
+ // field type uses, so the spread arg type can never disagree with the field type.
1104
+ const opts = asBinding !== undefined ? { asBinding, asBase: asBinding.name, narrowed } : narrowed !== undefined ? { narrowed } : undefined;
1053
1105
  return Object.keys(ports).map((pn) => ({
1054
1106
  field: goPortFieldName(pn),
1055
- goType: portFieldGoType(ports[pn], comp, plan, typedNodes, `port '${pn}' of node '${comp.name}'`, opts),
1107
+ goType: portFieldGoType(ports[pn], comp, plan, typedNodes, inputPortTypeRef(portSchemas?.[pn], plan), `port '${pn}' of node '${comp.name}'`, opts),
1056
1108
  }));
1057
1109
  }
1058
1110
  /** leafCallArgs — the spread transport-call arguments for a ports-struct var (Go: by value, no borrow). */
@@ -1086,7 +1138,8 @@ function emitMapPortsStructs(comp, node, typedNodes, plan) {
1086
1138
  // struct element). A pure-static/concat port ignores the binding.
1087
1139
  const { elemRef } = mapOverElemInfo(comp, node, typedNodes, plan);
1088
1140
  const asBinding = { name: m.as, ref: elemRef, plan };
1089
- const elemStruct = emitPortsStruct(comp, { id: node.id, component: m.component, ports: m.ports }, asBinding, plan, typedNodes);
1141
+ // #170: a guarded map (`when(ne($e.key,null))`) proves the element key non-null in kept elements — narrow it.
1142
+ const elemStruct = emitPortsStruct(comp, { id: node.id, component: m.component, ports: m.ports, portSchemas: m.portSchemas }, asBinding, plan, typedNodes, nodeNarrowedPaths(comp, node));
1090
1143
  const batchStruct = `${structName}_batch`;
1091
1144
  return `${elemStruct}
1092
1145
 
@@ -1104,7 +1157,7 @@ function emitFanoutPortsStructs(comp, node, typedNodes, plan) {
1104
1157
  const structName = portsStructName(comp.name, node.id);
1105
1158
  const { elemRef } = fanoutOverElemInfo(comp, node, typedNodes, plan);
1106
1159
  const asBinding = { name: f.as, ref: elemRef, plan };
1107
- const elemStruct = emitPortsStruct(comp, { id: node.id, component: f.component, ports: f.ports }, asBinding, plan, typedNodes);
1160
+ const elemStruct = emitPortsStruct(comp, { id: node.id, component: f.component, ports: f.ports, portSchemas: f.portSchemas }, asBinding, plan, typedNodes);
1108
1161
  const batchStruct = `${structName}_batch`;
1109
1162
  return `${elemStruct}
1110
1163
 
@@ -1443,8 +1496,8 @@ function emitInDecoder(comp, plan) {
1443
1496
  * plane — a boxed escape would re-introduce the bc-runtime coupling this module removes). Returns the
1444
1497
  * struct field initializer (`Field: <expr>`). `resolveRef` resolves a ref head for the scalar path.
1445
1498
  */
1446
- function emitPortInit(pn, expr, comp, plan, typedNodes, isPrior, opts) {
1447
- const c = compilePortNode(expr, comp, plan, typedNodes, isPrior, `port '${pn}'`, opts);
1499
+ function emitPortInit(pn, expr, comp, plan, typedNodes, isPrior, expected, opts) {
1500
+ const c = compilePortNode(expr, comp, plan, typedNodes, isPrior, `port '${pn}'`, expected, opts);
1448
1501
  if (c.stmts.length > 0)
1449
1502
  throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `go typed-native (runtime-free): port '${pn}' ${JSON.stringify(expr)} lowers to a FALLIBLE expression (one that can raise INT_OVERFLOW / NAN_OR_INF / MOD_ZERO / PRECISION_LOSS). Such an expression lowers to STATEMENTS carrying an early error-return, and a port is built inline in the ports-struct literal — a position that cannot host them. Use a non-fallible port expression.`);
1450
1503
  return `${goPortFieldName(pn)}: ${c.expr}`;
@@ -1555,8 +1608,9 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1555
1608
  }
1556
1609
  }
1557
1610
  const inits = [];
1611
+ const narrowed = nodeNarrowedPaths(comp, node);
1558
1612
  for (const pn of Object.keys(node.ports)) {
1559
- inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, atPos)));
1613
+ inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, atPos), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed, wireSel: wire.selector }));
1560
1614
  }
1561
1615
  lines.push(`${ind}ps_${s} = ${structName}{${inits.join(", ")}}`);
1562
1616
  lines.push(`${ind}run_${s} = true`);
@@ -1578,7 +1632,7 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1578
1632
  lines.push(`\t\t\t\tdefer func() { <-sem }()`);
1579
1633
  // DIRECT leaf transport call — the node's port fields spread off the preflight-built ports struct. No
1580
1634
  // `bound` (BC's internal produced/skip gate is already applied in preflight — the leaf never sees it).
1581
- const call = `${resolveLeafSymbol(node.component, leaf)}(${leafCallArgs(`ps_${s}`, portFieldSpread(node.ports, comp, plan, typedNodes))})`;
1635
+ const call = `${resolveLeafSymbol(node.component, leaf)}(${leafCallArgs(`ps_${s}`, portFieldSpread(node.ports, node.portSchemas, comp, plan, typedNodes, undefined, nodeNarrowedPaths(comp, node)))})`;
1582
1636
  lines.push(`\t\t\t\twire_${s}, row_${s}Err = ${call}`);
1583
1637
  lines.push(`\t\t\t}()`);
1584
1638
  lines.push(`\t\t}`);
@@ -1777,13 +1831,14 @@ function emitNativeRawRunner(comp, plan, flags, wire, leaf) {
1777
1831
  // static string array / number literal) assigned straight into the ports field — ZERO
1778
1832
  // dslcontracts.Value, ZERO nvVE helper, ZERO `.(T)`. A genuinely-dynamic port FAILS CLOSED.
1779
1833
  const inits = [];
1834
+ const narrowed = nodeNarrowedPaths(comp, node);
1780
1835
  for (const pn of portNames) {
1781
- inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k)));
1836
+ inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed, wireSel: wire.selector }));
1782
1837
  }
1783
1838
  // DIRECT leaf transport call: the resolved op-agnostic symbol, the node's port fields spread. `bound` is
1784
1839
  // NOT passed — it is BC's internal produced/skip gate, already enforced by the surrounding
1785
1840
  // `if bound_<s> != nil` / `if produced_<parent>` guards; the leaf never receives it.
1786
- const call = `${resolveLeafSymbol(node.component, leaf)}(${leafCallArgs(`ports_${s}`, portFieldSpread(node.ports, comp, plan, typedNodes))})`;
1841
+ const call = `${resolveLeafSymbol(node.component, leaf)}(${leafCallArgs(`ports_${s}`, portFieldSpread(node.ports, node.portSchemas, comp, plan, typedNodes, undefined, nodeNarrowedPaths(comp, node)))})`;
1787
1842
  lines.push(`${indent}ports_${s} := ${structName}{${inits.join(", ")}}`);
1788
1843
  // uniform seam: the transport returns a single result WIRE (${wire.value}); the inline de-box
1789
1844
  // (renderResultDeBox) classifies it against the STATICALLY declared result type and produces the
@@ -1871,6 +1926,10 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1871
1926
  const batched = m.batched === true;
1872
1927
  const hasInto = m.into !== undefined;
1873
1928
  const hasGuard = m.when !== undefined;
1929
+ // #177 keep-with-null: a guarded map WITH `into` keeps guard-skipped elements with the (opt) into
1930
+ // field set to nil (coveredMapNode only admits this when the into field is opt). This differs from a
1931
+ // guarded NO-into map, which DROPs skipped elements. Byte-equal to run_behavior's applyInto keep-with-null.
1932
+ const keepWithNull = hasGuard && hasInto;
1874
1933
  const s = sanitize(node.id);
1875
1934
  // #154 cross-package: a BATCHED map's element + batch ports structs live in the shared package (they
1876
1935
  // cross the transport boundary as a whole value), so reference them selector-qualified here. A
@@ -1904,7 +1963,9 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1904
1963
  // loop, `elemVar` the over element loop variable). Returns the lines building `ep_<s>`.
1905
1964
  const buildPorts = (il, elemVar) => {
1906
1965
  const asBinding = { name: asName, ref: overElemRef, plan };
1907
- const inits = portNames.map((pn) => emitPortInit(pn, m.ports[pn], comp, plan, typedNodes, priorHere, { asBinding, asBase: elemVar }));
1966
+ // #170: a guarded map narrows its `when(ne($e.key,null))`-proven element key non-null in kept elements.
1967
+ const narrowed = nodeNarrowedPaths(comp, node);
1968
+ const inits = portNames.map((pn) => emitPortInit(pn, m.ports[pn], comp, plan, typedNodes, priorHere, inputPortTypeRef(m.portSchemas?.[pn], plan), { asBinding, asBase: elemVar, narrowed, wireSel }));
1908
1969
  return [`${il}ep_${s} := ${structName}{${inits.join(", ")}}`];
1909
1970
  };
1910
1971
  const lines = [];
@@ -1919,7 +1980,9 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1919
1980
  }
1920
1981
  // over collection (typed field access to the parent node's arr — no serialize).
1921
1982
  lines.push(`${indent}over_${s} := ${overExpr}`);
1922
- lines.push(`${indent}${typedLocal(node.id)} = make(${elemGo}, 0, len(over_${s}))`);
1983
+ // #177 batched keep-with-null assembles the result BY INDEX (over-order, kept slots filled post-dispatch),
1984
+ // so it needs a full-length backing slice; every other shape appends in kept order.
1985
+ lines.push(`${indent}${typedLocal(node.id)} = make(${elemGo}, ${batched && keepWithNull ? `len(over_${s})` : `0, len(over_${s})`})`);
1923
1986
  // each element is de-boxed strictly INLINE: the handler returns the per-element WIRE and the arm decodes
1924
1987
  // it against the element ref (the `into` field's type for map...into, else the element type). A de-box
1925
1988
  // mismatch fails closed regardless of elementPolicy (matching the interpreter's whole-node outType
@@ -1929,7 +1992,7 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1929
1992
  const renderElemDeBox = (target, src, il) => renderResultDeBox(elemRowRef, target, src, node.id, plan, il, returnZeroFail(zeroOut), nodeWirePassthrough(node));
1930
1993
  // emit the per-element guard keep-gate (#108). `il` = indent, `elemVar` = the over element loop var.
1931
1994
  // On skip: batched → `continue` (element excluded from items + keptOver); non-batched → `continue`.
1932
- const emitGuard = (il, elemVar) => {
1995
+ const emitGuard = (il, elemVar, onSkip = ["continue"]) => {
1933
1996
  const g = mkGuard(elemVar);
1934
1997
  if (g === null)
1935
1998
  return [];
@@ -1937,11 +2000,46 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1937
2000
  for (const st of g.stmts)
1938
2001
  out.push(`${il}${st}`);
1939
2002
  out.push(`${il}if !(${g.expr}) {`);
1940
- out.push(`${il}\tcontinue`);
2003
+ for (const a of onSkip)
2004
+ out.push(`${il}\t${a}`);
1941
2005
  out.push(`${il}}`);
1942
2006
  return out;
1943
2007
  };
1944
- if (batched) {
2008
+ if (batched && keepWithNull) {
2009
+ // #177 BATCHED keep-with-null (guarded map...into, opt into): first pass records, per over element in
2010
+ // ORDER, whether it is kept (guard true → build its ports, remember its over-index) or skipped (guard
2011
+ // false → materialize the augmented element in place with into=nil). ONE batched dispatch over the kept
2012
+ // ports, then the aligned rows are de-boxed and zipped back onto their over-index slots. Byte-equal to
2013
+ // run_behavior: batched keptIdx-aligned collect + applyInto (skipped element unaugmented → opt-into null).
2014
+ const g = mkGuard(elemLocal(s));
2015
+ lines.push(`${indent}items_${s} := make([]${structName}, 0, len(over_${s}))`);
2016
+ lines.push(`${indent}keptIdx_${s} := make([]int, 0, len(over_${s}))`);
2017
+ lines.push(`${indent}for oi_${s} := range over_${s} {`);
2018
+ lines.push(`${indent}\t${elemLocal(s)} := over_${s}[oi_${s}]`);
2019
+ for (const st of g.stmts)
2020
+ lines.push(`${indent}\t${st}`);
2021
+ lines.push(`${indent}\tif ${g.expr} {`);
2022
+ for (const l of buildPorts(indent + "\t\t", elemLocal(s)))
2023
+ lines.push(l);
2024
+ lines.push(`${indent}\t\titems_${s} = append(items_${s}, ep_${s})`);
2025
+ lines.push(`${indent}\t\tkeptIdx_${s} = append(keptIdx_${s}, oi_${s})`);
2026
+ lines.push(`${indent}\t} else {`);
2027
+ lines.push(`${indent}\t\t${typedLocal(node.id)}[oi_${s}] = ${elemMat}(${elemLocal(s)}, nil)`);
2028
+ lines.push(`${indent}\t}`);
2029
+ lines.push(`${indent}}`);
2030
+ lines.push(`${indent}if len(items_${s}) > 0 {`);
2031
+ lines.push(`${indent}\tbp_${s} := ${batchStruct}{Items: items_${s}}`);
2032
+ lines.push(`${indent}\tmo_${s}, mo_${s}Err := ${leafSym}(bp_${s})`);
2033
+ lines.push(`${indent}\tif mo_${s}Err != nil {`, `${indent}\t\treturn ${zeroOut}, opFailed(${JSON.stringify(node.id)}, "fail", mo_${s}Err)`, `${indent}\t}`);
2034
+ lines.push(`${indent}\tif len(mo_${s}) != len(items_${s}) {`, `${indent}\t\treturn ${zeroOut}, ${goErr("MAP_BATCH_RESULT_MISMATCH", `fmt.Sprintf("map '${node.id}': batched handler must return a list aligned to items (want %d)", len(items_${s}))`)}`, `${indent}\t}`);
2035
+ lines.push(`${indent}\tfor mk_${s} := range items_${s} {`);
2036
+ lines.push(`${indent}\t\tvar dec_${s} ${elemRowGo}`);
2037
+ lines.push(renderElemDeBox(`dec_${s}`, `mo_${s}[mk_${s}]`, `${indent}\t\t`));
2038
+ lines.push(`${indent}\t\t${typedLocal(node.id)}[keptIdx_${s}[mk_${s}]] = ${elemMat}(over_${s}[keptIdx_${s}[mk_${s}]], dec_${s})`);
2039
+ lines.push(`${indent}\t}`);
2040
+ lines.push(`${indent}}`);
2041
+ }
2042
+ else if (batched) {
1945
2043
  // BATCHED (#86 pt2 into / #93 shape 3 no-into / #108 guarded no-into): build kept-element ports,
1946
2044
  // dispatch ONCE. The concrete Node_* returns the aligned per-element WIRES ([]WireValue) or an error.
1947
2045
  // With a guard, `items` (and, for into, `keptOver`) hold only kept elements — matching run_behavior's
@@ -1992,7 +2090,12 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1992
2090
  // (no dispatch, excluded from the result). The concrete Node_* returns ONE element WIRE (WireValue).
1993
2091
  lines.push(`${indent}for mk_${s} := range over_${s} {`);
1994
2092
  lines.push(`${indent}\t${elemLocal(s)} := over_${s}[mk_${s}]`);
1995
- for (const l of emitGuard(indent + "\t", elemLocal(s)))
2093
+ // #177 keep-with-null: a guard-skipped element is KEPT with into=nil (elemMat(over,nil)) instead of
2094
+ // dropped — byte-equal to run_behavior's applyInto pass-through + opt-into null.
2095
+ const nonBatchedSkip = keepWithNull
2096
+ ? [`${typedLocal(node.id)} = append(${typedLocal(node.id)}, ${elemMat}(${elemLocal(s)}, nil))`, "continue"]
2097
+ : ["continue"];
2098
+ for (const l of emitGuard(indent + "\t", elemLocal(s), nonBatchedSkip))
1996
2099
  lines.push(l);
1997
2100
  for (const l of buildPorts(indent + "\t", elemLocal(s)))
1998
2101
  lines.push(l);
@@ -2002,7 +2105,7 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
2002
2105
  // Element Error Policy (scp-error.md): `skip` drops the failing element and proceeds (order is
2003
2106
  // preserved; the leaf keeps the Error Value it produced). `error` (default) promotes the element
2004
2107
  // Failure to the map's Component Failure, carrying the leaf's detail through.
2005
- lines.push(`${indent}\tmo_${s}, mo_${s}Err := ${leafSym}(${leafCallArgs(`ep_${s}`, portFieldSpread(m.ports, comp, plan, typedNodes, { name: asName, ref: overElemRef, plan }))})`);
2108
+ lines.push(`${indent}\tmo_${s}, mo_${s}Err := ${leafSym}(${leafCallArgs(`ep_${s}`, portFieldSpread(m.ports, m.portSchemas, comp, plan, typedNodes, { name: asName, ref: overElemRef, plan }, nodeNarrowedPaths(comp, node)))})`);
2006
2109
  if (m.elementPolicy === "skip") {
2007
2110
  lines.push(`${indent}\tif mo_${s}Err != nil {`, `${indent}\t\tcontinue`, `${indent}\t}`);
2008
2111
  }
@@ -2070,7 +2173,7 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut
2070
2173
  // per-id native ports build (same as a batched map's per-element ports). $as → the over id value.
2071
2174
  const buildPorts = (il, elemVar) => {
2072
2175
  const asBinding = { name: asName, ref: overElemRef, plan };
2073
- const inits = portNames.map((pn) => emitPortInit(pn, f.ports[pn], comp, plan, typedNodes, priorHere, { asBinding, asBase: elemVar }));
2176
+ const inits = portNames.map((pn) => emitPortInit(pn, f.ports[pn], comp, plan, typedNodes, priorHere, inputPortTypeRef(f.portSchemas?.[pn], plan), { asBinding, asBase: elemVar, wireSel }));
2074
2177
  return [`${il}ep_${s} := ${structName}{${inits.join(", ")}}`];
2075
2178
  };
2076
2179
  const lines = [];
@@ -2371,26 +2474,32 @@ const goExprUsed = { helpers: false };
2371
2474
  * ctor. A `value[]` bound-value list carries scalar / opaque elements; a nested opt / collection / record
2372
2475
  * element is fail-closed here (C1 — the compound box lands with the batched WireRow contract).
2373
2476
  */
2374
- function renderGoWireBox(plan, srcExpr) {
2477
+ function renderGoWireBox(plan, srcExpr, wireSel) {
2478
+ // #174: cross-package (`--shared-types-import`) the wire CONSTRUCTORS live in the shared package alongside
2479
+ // the wire TYPE, so qualify them with the same selector (`wire.WireFloat(...)`); in-package they are local
2480
+ // (bare). Without this the type is `wire.WireValue` but the ctor is a bare `WireFloat` → does not compile.
2481
+ const q = wireSel !== undefined && wireSel !== "" ? `${wireSel}.` : "";
2375
2482
  if (plan.optDepth === 0) {
2376
2483
  if (plan.k === "value")
2377
2484
  return srcExpr; // identity — already the opaque BC wire.
2378
2485
  if (plan.k === "scalar") {
2379
2486
  switch (plan.scalar) {
2380
2487
  case "string":
2381
- return `WireStr(${srcExpr})`;
2488
+ return `${q}WireStr(${srcExpr})`;
2382
2489
  case "int":
2383
- return `WireInt(${srcExpr})`;
2490
+ return `${q}WireInt(${srcExpr})`;
2384
2491
  case "float":
2385
- return `WireFloat(${srcExpr})`;
2492
+ return `${q}WireFloat(${srcExpr})`;
2386
2493
  case "bool":
2387
- return `WireBool(${srcExpr})`;
2494
+ return `${q}WireBool(${srcExpr})`;
2388
2495
  }
2389
2496
  }
2390
2497
  }
2391
2498
  throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `go 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)`);
2392
2499
  }
2393
- function makeGoExprBackend(zeroOut, resolveHead, plan) {
2500
+ function makeGoExprBackend(zeroOut, resolveHead, plan,
2501
+ // #174: cross-package selector for the shared wire constructors (`wire`); undefined/"" ⇒ in-package (bare).
2502
+ wireSel) {
2394
2503
  const used = goExprUsed;
2395
2504
  return {
2396
2505
  lang: "go",
@@ -2398,7 +2507,7 @@ function makeGoExprBackend(zeroOut, resolveHead, plan) {
2398
2507
  renderType: (ref) => renderTypeRef(ref),
2399
2508
  wireType: () => renderTypeRef({ kind: "value" }),
2400
2509
  // bc#156/#160: box a value[] element into the opaque BC wire via the ONE box SSoT (owned element expr).
2401
- wireBox: (item) => renderGoWireBox(buildWirePlan(item.ref, { from: "top" }, { model: "port", field: "port", plan }, "in"), item.expr),
2510
+ wireBox: (item) => renderGoWireBox(buildWirePlan(item.ref, { from: "top" }, { model: "port", field: "port", plan }, "in"), item.expr, wireSel),
2402
2511
  scalarType: (s) => goScalar(s),
2403
2512
  strLit: (s) => JSON.stringify(s),
2404
2513
  boolLit: (b) => (b ? "true" : "false"),
@@ -2427,12 +2536,15 @@ function makeGoExprBackend(zeroOut, resolveHead, plan) {
2427
2536
  arrLit: (elemTy, items) => `[]${elemTy}{${items.join(", ")}}`,
2428
2537
  // a projection port of static string literals — bare `[]string{"a", "b"}` (Go string literals are
2429
2538
  // already allocation-free; no divergence from the general arr path, so no golden churn).
2430
- staticStrArr: (literals) => ({ expr: `[]string{${literals.map((s) => JSON.stringify(s)).join(", ")}}`, type: "[]string" }),
2431
2539
  // an opt (`*T`) NONE literal is `nil` (the inner type is not needed for the untyped nil in Go).
2432
2540
  optNone: (_innerTy) => "nil",
2433
2541
  // opt (`*T`) null-presence test: present = `(expr != nil)`, absent = `(expr == nil)`.
2434
2542
  optIsSome: (expr) => `(${expr} != nil)`,
2435
2543
  optIsNone: (expr) => `(${expr} == nil)`,
2544
+ // #170: narrow a gate/guard-proven-non-null opt to its inner value — `*T` → `T` via deref. Safe by
2545
+ // construction: the gated child / guarded element only runs when the ref is non-null (the nil case is
2546
+ // statically unreachable in the proven scope). NOT a default — there is no fallback value.
2547
+ narrowUnwrap: (optExpr, _innerRef) => `(*(${optExpr}))`,
2436
2548
  // opt (`*T`) defaulted to a PURE default — an immediately-invoked func literal: bind the pointer ONCE,
2437
2549
  // deref when present, else yield the default (evaluated only when absent — run_behavior's lazy right).
2438
2550
  optUnwrapOr: (optExpr, defaultExpr, innerTy) => `func() ${innerTy} { if v := ${optExpr}; v != nil { return *v }; return ${defaultExpr} }()`,
@@ -2690,7 +2802,8 @@ function emit(ctx) {
2690
2802
  }
2691
2803
  else {
2692
2804
  // #129: pass typedNodes so a leaf array port fed by a prior node's arr outType types as []ElemT.
2693
- structs.push(emitPortsStruct(c, n, undefined, plan, typedNodes));
2805
+ // #170: a gated child narrows its gate-proven opt key (field type must match the narrowed init).
2806
+ structs.push(emitPortsStruct(c, n, undefined, plan, typedNodes, nodeNarrowedPaths(c, n)));
2694
2807
  }
2695
2808
  }
2696
2809
  // augmented-element copiers for covered map...into nodes (over fields + the de-boxed into value).
@@ -2980,7 +3093,7 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
2980
3093
  }
2981
3094
  else {
2982
3095
  const { elemRef: overElemRef } = mapOverElemInfo(c, n, typedNodes, plan);
2983
- const spread = portFieldSpread(m.ports, c, plan, typedNodes, { name: m.as, ref: overElemRef, plan });
3096
+ const spread = portFieldSpread(m.ports, m.portSchemas, c, plan, typedNodes, { name: m.as, ref: overElemRef, plan }, nodeNarrowedPaths(c, n));
2984
3097
  const params = spread.map((pf) => `_${pf.field} ${pf.goType}`).join(", ");
2985
3098
  transportFns.push(`func ${sym}(${params}) (WireValue, error) {
2986
3099
  src, ok := nextScripted(${JSON.stringify(catalog)})
@@ -2997,8 +3110,11 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
2997
3110
  }
2998
3111
  // componentRef (point read): spread port fields; supports echo (#129/#141) reading the port params.
2999
3112
  const node = n;
3113
+ // #170: the observe transport fn's param types must match the covered module's leaf call args, which
3114
+ // narrow a gate-proven opt key — so this reads the SAME node narrowing.
3115
+ const crNarrowed = nodeNarrowedPaths(c, node);
3000
3116
  const ref = typedNodes.get(n.id);
3001
- const spread = portFieldSpread(node.ports, c, plan, typedNodes);
3117
+ const spread = portFieldSpread(node.ports, node.portSchemas, c, plan, typedNodes, undefined, crNarrowed);
3002
3118
  const echoBranches = [];
3003
3119
  if (ref.kind === "named") {
3004
3120
  const decl = findDecl(plan, ref.name);
@@ -3008,7 +3124,7 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
3008
3124
  for (const pn of Object.keys(node.ports)) {
3009
3125
  let portGo = null;
3010
3126
  try {
3011
- portGo = portFieldGoType(node.ports[pn], c, plan, typedNodes, `echo port '${pn}'`);
3127
+ portGo = portFieldGoType(node.ports[pn], c, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[pn], plan), `echo port '${pn}'`, { narrowed: crNarrowed });
3012
3128
  }
3013
3129
  catch {
3014
3130
  portGo = null;