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 { goStraightlineInternals } from "./emit-shared-go.js";
4
4
  import { goTypedInternals } from "./emit-shared-go-typed.js";
5
5
  import { buildTypePlan, deriveTypeRef, findDecl, inputPortIsOptional, inputPortTypeRef } from "./typed.js";
6
- import { concurrencyPlan, execPlan, analyzeSequentialOps, classifyExpr, buildComponentPlan, } from "./straightline.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";
@@ -16,10 +16,18 @@ function resolveGoWire(ctx) {
16
16
  const imp = ctx.sharedTypesImport;
17
17
  if (imp === undefined)
18
18
  return { value: "WireValue", row: "WireRow", list: "WireList" };
19
- const bare = imp.split("/").pop().replace(/[^A-Za-z0-9_]/g, "_");
19
+ const bare = goSharedTypesPackageName(imp);
20
20
  const sel = `${bare}.`;
21
21
  return { value: `${sel}WireValue`, row: `${sel}WireRow`, list: `${sel}WireList`, import: imp, selector: bare };
22
22
  }
23
+ /** goSharedTypesPackageName — the SSoT for deriving the shared wire types package's Go identifier from a
24
+ * `--shared-types-import` path: the last path segment, sanitized to a legal Go identifier. Used by BOTH
25
+ * resolveGoWire (to selector-qualify the hoisted wire types in the covered module) and the CLI's
26
+ * `--shared-types-out` codegen wrapper (to name the emitted shared package) — so the covered module's
27
+ * import selector and the shared package's `package` declaration are derived identically (they must agree). */
28
+ export function goSharedTypesPackageName(sharedTypesImport) {
29
+ return sharedTypesImport.split("/").pop().replace(/[^A-Za-z0-9_]/g, "_");
30
+ }
23
31
  /** goErr — build the LOCAL concrete error value for a behavior/plan failure on the covered read
24
32
  * plane (runtime-free). The covered module declares `type BehaviorError struct { Code, Message string }`
25
33
  * (see emitBehaviorErrorType); a `*BehaviorError` satisfies the runner's `error` return. This REPLACES
@@ -605,16 +613,33 @@ function goNativeResolveHead(comp, plan, typedNodes, isPrior, opts) {
605
613
  * field), a concat, a static array, an optional-input read — all resolve here. A port that cannot lower
606
614
  * FAILS CLOSED. A FALLIBLE lowering (hoists statements) is returned as-is; only emitPortInit rejects it.
607
615
  */
608
- 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`);
609
622
  const resolveHead = goNativeResolveHead(comp, plan, typedNodes, isPrior, opts);
623
+ const resolveDecl = (name) => findDecl(plan, name).fields;
624
+ let c;
610
625
  try {
611
- 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);
612
630
  }
613
631
  catch (e) {
614
632
  if (!(e instanceof GeneratorFailure))
615
633
  throw e;
616
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}`);
617
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;
618
643
  }
619
644
  /**
620
645
  * portFieldGoType — the NATIVE Go type for a covered port field (bc#90 / runtime-free). The covered
@@ -626,9 +651,9 @@ function compilePortNode(node, comp, plan, typedNodes, isPrior, where, opts) {
626
651
  * Value-typed input) FAILS CLOSED — the covered read plane admits NO boxed escape (there is no
627
652
  * `dslcontracts.Value` fallback on the native module). `where` names the emission site for the error.
628
653
  */
629
- function portFieldGoType(node, comp, plan, typedNodes, where = "port", opts) {
630
- const c = compilePortNode(node, comp, plan, typedNodes, (h) => typedNodes.has(h), where, opts);
631
- 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);
632
657
  }
633
658
  function staticArrElems(node) {
634
659
  if (node === null || typeof node !== "object" || Array.isArray(node))
@@ -679,7 +704,7 @@ function numLiteralGoExpr(node) {
679
704
  /** planForComp — a TypePlan for a single component (its named types are component-scoped, so a
680
705
  * one-component IR yields the same plan the full-IR build would for this component). */
681
706
  function planForComp(comp) {
682
- return buildTypePlan({ irVersion: 1, exprVersion: 2, components: [comp] });
707
+ return buildTypePlan({ irVersion: 2, exprVersion: 2, components: [comp] });
683
708
  }
684
709
  /** buildTypedNodes — the prior-node typed-local TypeRef map for a component (control-gate nodes are
685
710
  * typeless; a map node carries its produced-array ref). An untyped node is omitted (not an error here). */
@@ -710,9 +735,14 @@ function mapAsBinding(comp, node, typedNodes, plan) {
710
735
  /** portIsStatic — the ELIGIBILITY gate ASKS the one port lowering (compilePortNode / native-expr)
711
736
  * whether it can lower this port, rather than re-deriving the shape rules — so the gate and the emitter
712
737
  * can never disagree. A port that does not lower (or lowers fallibly) fails closed. */
713
- function portIsStatic(node, comp, plan, typedNodes, asBinding) {
738
+ function portIsStatic(node, comp, plan, typedNodes, expected, asBinding, narrowed) {
714
739
  try {
715
- 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);
716
746
  return true;
717
747
  }
718
748
  catch {
@@ -820,8 +850,10 @@ function coveredMapNode(n, bodyIds, comp) {
820
850
  const plan = planForComp(comp);
821
851
  const typedNodes = buildTypedNodes(comp, plan);
822
852
  const asBinding = mapAsBinding(comp, n, typedNodes, plan);
853
+ const narrowed = nodeNarrowedPaths(comp, n);
854
+ const mSchemas = m.portSchemas;
823
855
  for (const p of Object.keys(ports))
824
- if (!portIsStatic(ports[p], comp, plan, typedNodes, asBinding))
856
+ if (!portIsStatic(ports[p], comp, plan, typedNodes, inputPortTypeRef(mSchemas?.[p], plan), asBinding, narrowed))
825
857
  return false;
826
858
  return true;
827
859
  }
@@ -862,8 +894,9 @@ function coveredFanoutNode(n, bodyIds, comp) {
862
894
  catch {
863
895
  asBinding = undefined;
864
896
  }
897
+ const fSchemas = f.portSchemas;
865
898
  for (const p of Object.keys(ports))
866
- if (!portIsStatic(ports[p], comp, plan, typedNodes, asBinding))
899
+ if (!portIsStatic(ports[p], comp, plan, typedNodes, inputPortTypeRef(fSchemas?.[p], plan), asBinding))
867
900
  return false;
868
901
  return true;
869
902
  }
@@ -971,8 +1004,10 @@ function coverageRejectReason(comp) {
971
1004
  return `node '${n.id}' relationKind '${cr.relationKind ?? "point"}' not native-covered (bindField only supports single|connection)`;
972
1005
  if (cr.relationKind !== undefined && cr.relationKind !== "single" && cr.relationKind !== "connection")
973
1006
  return `relationKind '${cr.relationKind}' not native-covered (node '${n.id}')`;
1007
+ // #170: a control-gate child's ports may narrow a gate-proven opt ref to non-null (the (a3) gated read).
1008
+ const crNarrowed = nodeNarrowedPaths(comp, cr);
974
1009
  for (const p of Object.keys(cr.ports))
975
- if (portIsStatic(cr.ports[p], comp, crPlan, crTypedNodes) === false)
1010
+ if (portIsStatic(cr.ports[p], comp, crPlan, crTypedNodes, inputPortTypeRef(cr.portSchemas?.[p], crPlan), undefined, crNarrowed) === false)
976
1011
  return `node '${n.id}' port '${p}' is not statically resolvable`;
977
1012
  }
978
1013
  if (!outputIsNativeLowerable(comp))
@@ -988,7 +1023,7 @@ function assertTypedCoverage(comp) {
988
1023
  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).`);
989
1024
  }
990
1025
  // ── native ports struct + PortReader ──────────────────────────────────────────────────
991
- function emitPortsStruct(comp, node, asBinding, plan, typedNodes) {
1026
+ function emitPortsStruct(comp, node, asBinding, plan, typedNodes, narrowed) {
992
1027
  const structName = portsStructName(comp.name, node.id);
993
1028
  const portNames = Object.keys(node.ports);
994
1029
  if (portNames.length === 0) {
@@ -999,7 +1034,10 @@ function emitPortsStruct(comp, node, asBinding, plan, typedNodes) {
999
1034
  if (plan === undefined || typedNodes === undefined) {
1000
1035
  throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `go typed-native: ports struct for node '${node.id}' needs a type plan + prior-node map`);
1001
1036
  }
1002
- 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));
1037
+ // #170: the field TYPE reads the SAME lowering (incl. gate/guard narrowing) the init does, so a narrowed
1038
+ // opt-in-required port is a non-opt field AND a non-opt initializer — they can never disagree.
1039
+ const portOpts = asBinding !== undefined ? { asBinding, asBase: asBinding.name, narrowed } : narrowed !== undefined ? { narrowed } : undefined;
1040
+ const fieldTypes = portNames.map((p) => portFieldGoType(node.ports[p], comp, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[p], plan), `port '${p}' of node '${node.id}'`, portOpts));
1003
1041
  const fieldNames = portNames.map(goPortFieldName);
1004
1042
  const fields = portNames
1005
1043
  .map((p, i) => `\t${fieldNames[i]} ${fieldTypes[i]} // ${JSON.stringify(p)}`)
@@ -1040,11 +1078,15 @@ function resolveLeafSymbol(component, leaf) {
1040
1078
  * Types come from the SAME `portFieldGoType` lowering `emitPortsStruct` uses, so the spread can never
1041
1079
  * disagree with the ports struct field types. (Go has no borrow — every field is passed by value.)
1042
1080
  */
1043
- function portFieldSpread(ports, comp, plan, typedNodes, asBinding) {
1044
- const opts = asBinding !== undefined ? { asBinding, asBase: asBinding.name } : undefined;
1081
+ function portFieldSpread(ports, portSchemas, comp, plan, typedNodes, asBinding, narrowed) {
1082
+ // #170: the transport-call spread reads the SAME lowering (incl. gate/guard narrowing) as the ports
1083
+ // struct fields — a narrowed opt-in-required port is a non-opt arg, matching the non-opt struct field.
1084
+ // #173: `expected` (declared port type from portSchemas) drives the SAME materialization the struct
1085
+ // field type uses, so the spread arg type can never disagree with the field type.
1086
+ const opts = asBinding !== undefined ? { asBinding, asBase: asBinding.name, narrowed } : narrowed !== undefined ? { narrowed } : undefined;
1045
1087
  return Object.keys(ports).map((pn) => ({
1046
1088
  field: goPortFieldName(pn),
1047
- goType: portFieldGoType(ports[pn], comp, plan, typedNodes, `port '${pn}' of node '${comp.name}'`, opts),
1089
+ goType: portFieldGoType(ports[pn], comp, plan, typedNodes, inputPortTypeRef(portSchemas?.[pn], plan), `port '${pn}' of node '${comp.name}'`, opts),
1048
1090
  }));
1049
1091
  }
1050
1092
  /** leafCallArgs — the spread transport-call arguments for a ports-struct var (Go: by value, no borrow). */
@@ -1078,7 +1120,8 @@ function emitMapPortsStructs(comp, node, typedNodes, plan) {
1078
1120
  // struct element). A pure-static/concat port ignores the binding.
1079
1121
  const { elemRef } = mapOverElemInfo(comp, node, typedNodes, plan);
1080
1122
  const asBinding = { name: m.as, ref: elemRef, plan };
1081
- const elemStruct = emitPortsStruct(comp, { id: node.id, component: m.component, ports: m.ports }, asBinding, plan, typedNodes);
1123
+ // #170: a guarded map (`when(ne($e.key,null))`) proves the element key non-null in kept elements — narrow it.
1124
+ const elemStruct = emitPortsStruct(comp, { id: node.id, component: m.component, ports: m.ports, portSchemas: m.portSchemas }, asBinding, plan, typedNodes, nodeNarrowedPaths(comp, node));
1082
1125
  const batchStruct = `${structName}_batch`;
1083
1126
  return `${elemStruct}
1084
1127
 
@@ -1096,7 +1139,7 @@ function emitFanoutPortsStructs(comp, node, typedNodes, plan) {
1096
1139
  const structName = portsStructName(comp.name, node.id);
1097
1140
  const { elemRef } = fanoutOverElemInfo(comp, node, typedNodes, plan);
1098
1141
  const asBinding = { name: f.as, ref: elemRef, plan };
1099
- const elemStruct = emitPortsStruct(comp, { id: node.id, component: f.component, ports: f.ports }, asBinding, plan, typedNodes);
1142
+ const elemStruct = emitPortsStruct(comp, { id: node.id, component: f.component, ports: f.ports, portSchemas: f.portSchemas }, asBinding, plan, typedNodes);
1100
1143
  const batchStruct = `${structName}_batch`;
1101
1144
  return `${elemStruct}
1102
1145
 
@@ -1435,8 +1478,8 @@ function emitInDecoder(comp, plan) {
1435
1478
  * plane — a boxed escape would re-introduce the bc-runtime coupling this module removes). Returns the
1436
1479
  * struct field initializer (`Field: <expr>`). `resolveRef` resolves a ref head for the scalar path.
1437
1480
  */
1438
- function emitPortInit(pn, expr, comp, plan, typedNodes, isPrior, opts) {
1439
- const c = compilePortNode(expr, comp, plan, typedNodes, isPrior, `port '${pn}'`, opts);
1481
+ function emitPortInit(pn, expr, comp, plan, typedNodes, isPrior, expected, opts) {
1482
+ const c = compilePortNode(expr, comp, plan, typedNodes, isPrior, `port '${pn}'`, expected, opts);
1440
1483
  if (c.stmts.length > 0)
1441
1484
  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.`);
1442
1485
  return `${goPortFieldName(pn)}: ${c.expr}`;
@@ -1547,8 +1590,9 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1547
1590
  }
1548
1591
  }
1549
1592
  const inits = [];
1593
+ const narrowed = nodeNarrowedPaths(comp, node);
1550
1594
  for (const pn of Object.keys(node.ports)) {
1551
- inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, atPos)));
1595
+ inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, atPos), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed, wireSel: wire.selector }));
1552
1596
  }
1553
1597
  lines.push(`${ind}ps_${s} = ${structName}{${inits.join(", ")}}`);
1554
1598
  lines.push(`${ind}run_${s} = true`);
@@ -1570,7 +1614,7 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1570
1614
  lines.push(`\t\t\t\tdefer func() { <-sem }()`);
1571
1615
  // DIRECT leaf transport call — the node's port fields spread off the preflight-built ports struct. No
1572
1616
  // `bound` (BC's internal produced/skip gate is already applied in preflight — the leaf never sees it).
1573
- const call = `${resolveLeafSymbol(node.component, leaf)}(${leafCallArgs(`ps_${s}`, portFieldSpread(node.ports, comp, plan, typedNodes))})`;
1617
+ const call = `${resolveLeafSymbol(node.component, leaf)}(${leafCallArgs(`ps_${s}`, portFieldSpread(node.ports, node.portSchemas, comp, plan, typedNodes, undefined, nodeNarrowedPaths(comp, node)))})`;
1574
1618
  lines.push(`\t\t\t\twire_${s}, row_${s}Err = ${call}`);
1575
1619
  lines.push(`\t\t\t}()`);
1576
1620
  lines.push(`\t\t}`);
@@ -1769,13 +1813,14 @@ function emitNativeRawRunner(comp, plan, flags, wire, leaf) {
1769
1813
  // static string array / number literal) assigned straight into the ports field — ZERO
1770
1814
  // dslcontracts.Value, ZERO nvVE helper, ZERO `.(T)`. A genuinely-dynamic port FAILS CLOSED.
1771
1815
  const inits = [];
1816
+ const narrowed = nodeNarrowedPaths(comp, node);
1772
1817
  for (const pn of portNames) {
1773
- inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k)));
1818
+ inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed, wireSel: wire.selector }));
1774
1819
  }
1775
1820
  // DIRECT leaf transport call: the resolved op-agnostic symbol, the node's port fields spread. `bound` is
1776
1821
  // NOT passed — it is BC's internal produced/skip gate, already enforced by the surrounding
1777
1822
  // `if bound_<s> != nil` / `if produced_<parent>` guards; the leaf never receives it.
1778
- const call = `${resolveLeafSymbol(node.component, leaf)}(${leafCallArgs(`ports_${s}`, portFieldSpread(node.ports, comp, plan, typedNodes))})`;
1823
+ const call = `${resolveLeafSymbol(node.component, leaf)}(${leafCallArgs(`ports_${s}`, portFieldSpread(node.ports, node.portSchemas, comp, plan, typedNodes, undefined, nodeNarrowedPaths(comp, node)))})`;
1779
1824
  lines.push(`${indent}ports_${s} := ${structName}{${inits.join(", ")}}`);
1780
1825
  // uniform seam: the transport returns a single result WIRE (${wire.value}); the inline de-box
1781
1826
  // (renderResultDeBox) classifies it against the STATICALLY declared result type and produces the
@@ -1896,7 +1941,9 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1896
1941
  // loop, `elemVar` the over element loop variable). Returns the lines building `ep_<s>`.
1897
1942
  const buildPorts = (il, elemVar) => {
1898
1943
  const asBinding = { name: asName, ref: overElemRef, plan };
1899
- const inits = portNames.map((pn) => emitPortInit(pn, m.ports[pn], comp, plan, typedNodes, priorHere, { asBinding, asBase: elemVar }));
1944
+ // #170: a guarded map narrows its `when(ne($e.key,null))`-proven element key non-null in kept elements.
1945
+ const narrowed = nodeNarrowedPaths(comp, node);
1946
+ const inits = portNames.map((pn) => emitPortInit(pn, m.ports[pn], comp, plan, typedNodes, priorHere, inputPortTypeRef(m.portSchemas?.[pn], plan), { asBinding, asBase: elemVar, narrowed, wireSel }));
1900
1947
  return [`${il}ep_${s} := ${structName}{${inits.join(", ")}}`];
1901
1948
  };
1902
1949
  const lines = [];
@@ -1994,7 +2041,7 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1994
2041
  // Element Error Policy (scp-error.md): `skip` drops the failing element and proceeds (order is
1995
2042
  // preserved; the leaf keeps the Error Value it produced). `error` (default) promotes the element
1996
2043
  // Failure to the map's Component Failure, carrying the leaf's detail through.
1997
- lines.push(`${indent}\tmo_${s}, mo_${s}Err := ${leafSym}(${leafCallArgs(`ep_${s}`, portFieldSpread(m.ports, comp, plan, typedNodes, { name: asName, ref: overElemRef, plan }))})`);
2044
+ 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)))})`);
1998
2045
  if (m.elementPolicy === "skip") {
1999
2046
  lines.push(`${indent}\tif mo_${s}Err != nil {`, `${indent}\t\tcontinue`, `${indent}\t}`);
2000
2047
  }
@@ -2062,7 +2109,7 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut
2062
2109
  // per-id native ports build (same as a batched map's per-element ports). $as → the over id value.
2063
2110
  const buildPorts = (il, elemVar) => {
2064
2111
  const asBinding = { name: asName, ref: overElemRef, plan };
2065
- const inits = portNames.map((pn) => emitPortInit(pn, f.ports[pn], comp, plan, typedNodes, priorHere, { asBinding, asBase: elemVar }));
2112
+ const inits = portNames.map((pn) => emitPortInit(pn, f.ports[pn], comp, plan, typedNodes, priorHere, inputPortTypeRef(f.portSchemas?.[pn], plan), { asBinding, asBase: elemVar, wireSel }));
2066
2113
  return [`${il}ep_${s} := ${structName}{${inits.join(", ")}}`];
2067
2114
  };
2068
2115
  const lines = [];
@@ -2363,26 +2410,32 @@ const goExprUsed = { helpers: false };
2363
2410
  * ctor. A `value[]` bound-value list carries scalar / opaque elements; a nested opt / collection / record
2364
2411
  * element is fail-closed here (C1 — the compound box lands with the batched WireRow contract).
2365
2412
  */
2366
- function renderGoWireBox(plan, srcExpr) {
2413
+ function renderGoWireBox(plan, srcExpr, wireSel) {
2414
+ // #174: cross-package (`--shared-types-import`) the wire CONSTRUCTORS live in the shared package alongside
2415
+ // the wire TYPE, so qualify them with the same selector (`wire.WireFloat(...)`); in-package they are local
2416
+ // (bare). Without this the type is `wire.WireValue` but the ctor is a bare `WireFloat` → does not compile.
2417
+ const q = wireSel !== undefined && wireSel !== "" ? `${wireSel}.` : "";
2367
2418
  if (plan.optDepth === 0) {
2368
2419
  if (plan.k === "value")
2369
2420
  return srcExpr; // identity — already the opaque BC wire.
2370
2421
  if (plan.k === "scalar") {
2371
2422
  switch (plan.scalar) {
2372
2423
  case "string":
2373
- return `WireStr(${srcExpr})`;
2424
+ return `${q}WireStr(${srcExpr})`;
2374
2425
  case "int":
2375
- return `WireInt(${srcExpr})`;
2426
+ return `${q}WireInt(${srcExpr})`;
2376
2427
  case "float":
2377
- return `WireFloat(${srcExpr})`;
2428
+ return `${q}WireFloat(${srcExpr})`;
2378
2429
  case "bool":
2379
- return `WireBool(${srcExpr})`;
2430
+ return `${q}WireBool(${srcExpr})`;
2380
2431
  }
2381
2432
  }
2382
2433
  }
2383
2434
  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)`);
2384
2435
  }
2385
- function makeGoExprBackend(zeroOut, resolveHead, plan) {
2436
+ function makeGoExprBackend(zeroOut, resolveHead, plan,
2437
+ // #174: cross-package selector for the shared wire constructors (`wire`); undefined/"" ⇒ in-package (bare).
2438
+ wireSel) {
2386
2439
  const used = goExprUsed;
2387
2440
  return {
2388
2441
  lang: "go",
@@ -2390,7 +2443,7 @@ function makeGoExprBackend(zeroOut, resolveHead, plan) {
2390
2443
  renderType: (ref) => renderTypeRef(ref),
2391
2444
  wireType: () => renderTypeRef({ kind: "value" }),
2392
2445
  // bc#156/#160: box a value[] element into the opaque BC wire via the ONE box SSoT (owned element expr).
2393
- wireBox: (item) => renderGoWireBox(buildWirePlan(item.ref, { from: "top" }, { model: "port", field: "port", plan }, "in"), item.expr),
2446
+ wireBox: (item) => renderGoWireBox(buildWirePlan(item.ref, { from: "top" }, { model: "port", field: "port", plan }, "in"), item.expr, wireSel),
2394
2447
  scalarType: (s) => goScalar(s),
2395
2448
  strLit: (s) => JSON.stringify(s),
2396
2449
  boolLit: (b) => (b ? "true" : "false"),
@@ -2419,12 +2472,15 @@ function makeGoExprBackend(zeroOut, resolveHead, plan) {
2419
2472
  arrLit: (elemTy, items) => `[]${elemTy}{${items.join(", ")}}`,
2420
2473
  // a projection port of static string literals — bare `[]string{"a", "b"}` (Go string literals are
2421
2474
  // already allocation-free; no divergence from the general arr path, so no golden churn).
2422
- staticStrArr: (literals) => ({ expr: `[]string{${literals.map((s) => JSON.stringify(s)).join(", ")}}`, type: "[]string" }),
2423
2475
  // an opt (`*T`) NONE literal is `nil` (the inner type is not needed for the untyped nil in Go).
2424
2476
  optNone: (_innerTy) => "nil",
2425
2477
  // opt (`*T`) null-presence test: present = `(expr != nil)`, absent = `(expr == nil)`.
2426
2478
  optIsSome: (expr) => `(${expr} != nil)`,
2427
2479
  optIsNone: (expr) => `(${expr} == nil)`,
2480
+ // #170: narrow a gate/guard-proven-non-null opt to its inner value — `*T` → `T` via deref. Safe by
2481
+ // construction: the gated child / guarded element only runs when the ref is non-null (the nil case is
2482
+ // statically unreachable in the proven scope). NOT a default — there is no fallback value.
2483
+ narrowUnwrap: (optExpr, _innerRef) => `(*(${optExpr}))`,
2428
2484
  // opt (`*T`) defaulted to a PURE default — an immediately-invoked func literal: bind the pointer ONCE,
2429
2485
  // deref when present, else yield the default (evaluated only when absent — run_behavior's lazy right).
2430
2486
  optUnwrapOr: (optExpr, defaultExpr, innerTy) => `func() ${innerTy} { if v := ${optExpr}; v != nil { return *v }; return ${defaultExpr} }()`,
@@ -2682,7 +2738,8 @@ function emit(ctx) {
2682
2738
  }
2683
2739
  else {
2684
2740
  // #129: pass typedNodes so a leaf array port fed by a prior node's arr outType types as []ElemT.
2685
- structs.push(emitPortsStruct(c, n, undefined, plan, typedNodes));
2741
+ // #170: a gated child narrows its gate-proven opt key (field type must match the narrowed init).
2742
+ structs.push(emitPortsStruct(c, n, undefined, plan, typedNodes, nodeNarrowedPaths(c, n)));
2686
2743
  }
2687
2744
  }
2688
2745
  // augmented-element copiers for covered map...into nodes (over fields + the de-boxed into value).
@@ -2972,7 +3029,7 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
2972
3029
  }
2973
3030
  else {
2974
3031
  const { elemRef: overElemRef } = mapOverElemInfo(c, n, typedNodes, plan);
2975
- const spread = portFieldSpread(m.ports, c, plan, typedNodes, { name: m.as, ref: overElemRef, plan });
3032
+ const spread = portFieldSpread(m.ports, m.portSchemas, c, plan, typedNodes, { name: m.as, ref: overElemRef, plan }, nodeNarrowedPaths(c, n));
2976
3033
  const params = spread.map((pf) => `_${pf.field} ${pf.goType}`).join(", ");
2977
3034
  transportFns.push(`func ${sym}(${params}) (WireValue, error) {
2978
3035
  src, ok := nextScripted(${JSON.stringify(catalog)})
@@ -2989,8 +3046,11 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
2989
3046
  }
2990
3047
  // componentRef (point read): spread port fields; supports echo (#129/#141) reading the port params.
2991
3048
  const node = n;
3049
+ // #170: the observe transport fn's param types must match the covered module's leaf call args, which
3050
+ // narrow a gate-proven opt key — so this reads the SAME node narrowing.
3051
+ const crNarrowed = nodeNarrowedPaths(c, node);
2992
3052
  const ref = typedNodes.get(n.id);
2993
- const spread = portFieldSpread(node.ports, c, plan, typedNodes);
3053
+ const spread = portFieldSpread(node.ports, node.portSchemas, c, plan, typedNodes, undefined, crNarrowed);
2994
3054
  const echoBranches = [];
2995
3055
  if (ref.kind === "named") {
2996
3056
  const decl = findDecl(plan, ref.name);
@@ -3000,7 +3060,7 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
3000
3060
  for (const pn of Object.keys(node.ports)) {
3001
3061
  let portGo = null;
3002
3062
  try {
3003
- portGo = portFieldGoType(node.ports[pn], c, plan, typedNodes, `echo port '${pn}'`);
3063
+ portGo = portFieldGoType(node.ports[pn], c, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[pn], plan), `echo port '${pn}'`, { narrowed: crNarrowed });
3004
3064
  }
3005
3065
  catch {
3006
3066
  portGo = null;