behavior-contracts 0.8.9 → 0.8.11

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 (49) hide show
  1. package/README.md +49 -1
  2. package/cli-contract.yaml +76 -0
  3. package/dist/cli.js +14 -1
  4. package/dist/cli.js.map +1 -1
  5. package/dist/commands/codegen.d.ts +5 -3
  6. package/dist/commands/codegen.d.ts.map +1 -1
  7. package/dist/commands/codegen.js +10 -3
  8. package/dist/commands/codegen.js.map +1 -1
  9. package/dist/generated/commands.d.ts.map +1 -1
  10. package/dist/generated/commands.js +16 -0
  11. package/dist/generated/commands.js.map +1 -1
  12. package/dist/generated/contract.d.ts.map +1 -1
  13. package/dist/generated/contract.js +2 -2
  14. package/dist/generated/contract.js.map +1 -1
  15. package/dist/generated/program.d.ts +8 -0
  16. package/dist/generated/program.d.ts.map +1 -1
  17. package/dist/generated/program.js +8 -0
  18. package/dist/generated/program.js.map +1 -1
  19. package/dist/generated/types.d.ts +8 -0
  20. package/dist/generated/types.d.ts.map +1 -1
  21. package/dist/generator/core.d.ts +33 -1
  22. package/dist/generator/core.d.ts.map +1 -1
  23. package/dist/generator/core.js +1 -0
  24. package/dist/generator/core.js.map +1 -1
  25. package/dist/generator/emit-shared-go-typed.d.ts +11 -1
  26. package/dist/generator/emit-shared-go-typed.d.ts.map +1 -1
  27. package/dist/generator/emit-shared-go-typed.js +26 -3
  28. package/dist/generator/emit-shared-go-typed.js.map +1 -1
  29. package/dist/generator/emit-shared-rust-typed.d.ts +11 -1
  30. package/dist/generator/emit-shared-rust-typed.d.ts.map +1 -1
  31. package/dist/generator/emit-shared-rust-typed.js +26 -3
  32. package/dist/generator/emit-shared-rust-typed.js.map +1 -1
  33. package/dist/generator/emit-straightline-typed-typescript.d.ts.map +1 -1
  34. package/dist/generator/emit-straightline-typed-typescript.js +55 -7
  35. package/dist/generator/emit-straightline-typed-typescript.js.map +1 -1
  36. package/dist/generator/emit-typed-native-go.d.ts +9 -7
  37. package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
  38. package/dist/generator/emit-typed-native-go.js +247 -221
  39. package/dist/generator/emit-typed-native-go.js.map +1 -1
  40. package/dist/generator/emit-typed-native-rust.d.ts +27 -22
  41. package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
  42. package/dist/generator/emit-typed-native-rust.js +261 -272
  43. package/dist/generator/emit-typed-native-rust.js.map +1 -1
  44. package/dist/generator/index.d.ts +1 -1
  45. package/dist/generator/index.d.ts.map +1 -1
  46. package/dist/generator/index.js.map +1 -1
  47. package/dist/index.d.ts +1 -1
  48. package/dist/index.d.ts.map +1 -1
  49. package/package.json +3 -2
@@ -107,7 +107,7 @@ func deOverflow(model, field, expected, actualWire, raw string) *BehaviorError {
107
107
  }`;
108
108
  }
109
109
  const { sanitize, emitExpr } = goStraightlineInternals;
110
- const { goFieldName, renderTypeRef, goScalar, serializeTyped, emitTypeDecls, emitSerializers, emitTypedValue, emitMustHelpers, } = goTypedInternals;
110
+ const { goFieldName, renderTypeRef, goScalar, serializeTyped, emitTypeDecls, emitSerializers, emitTypedValue, checkOutputFieldType, emitMustHelpers, } = goTypedInternals;
111
111
  /** typed node-result local — MUST match goTypedInternals.typedLocal (`t_<id>`) so the reused
112
112
  * emitTypedValue (output assembly via struct field access) reads the same locals. */
113
113
  function typedLocal(nodeId) {
@@ -354,8 +354,8 @@ function goPortFieldName(wire) {
354
354
  return /[a-z]/.test(head) ? head.toUpperCase() + safe.slice(1) : "F_" + safe;
355
355
  }
356
356
  function portsStructName(compName, nodeId) {
357
- // EXPORTED so a consumer (and the test bench, both in a DIFFERENT Go package) can name the ports
358
- // type to implement the per-component Handler_<comp> interface's concrete Node_* method signatures.
357
+ // EXPORTED so a consumer (and the test bench, both in a DIFFERENT Go package) can name the ports type
358
+ // in their leaf transport symbols (the batched/fanout transport takes the batch ports struct).
359
359
  return `PortsNR_${sanitize(compName)}_${nodeId.replace(/[^A-Za-z0-9_]/g, "_")}`;
360
360
  }
361
361
  /** scalar TypeRef → PortFieldType (native go scalar kind). */
@@ -794,12 +794,42 @@ type ${structName} struct {
794
794
  ${fields}
795
795
  }`;
796
796
  }
797
- /** handlerTypeName — the per-component CONCRETE handler type name the runner takes by value (one Node_*
798
- * method per node). It is NOT a bc-declared interface (a Go interface is vtable dynamic dispatch): the
799
- * consumer supplies a concrete type of this name (default `Handler_<comp>`) and the runner calls
800
- * `h.Node_*(...)` directly (zero dynamic dispatch, zero dictionary). */
801
- function handlerTypeName(compName) {
802
- return `Handler_${sanitize(compName)}`;
797
+ /**
798
+ * resolveLeafSymbol — the op-agnostic transport symbol a covered leaf (= catalog component) is called
799
+ * through at its execution point. A consumer-supplied override (`leafTransport.symbols[component]`) wins;
800
+ * else the in-package DEFAULT convention `Leaf_<sanitizedComponent>`. This is the ONE place leaf→symbol
801
+ * resolution lives (SSoT) — the runner call sites, the import block, and the test observe transport fns all
802
+ * read it. There is no per-node handler indirection: a leaf is ONE transport, not one method per node.
803
+ */
804
+ function goLeafSel(leaf) {
805
+ return leaf?.import !== undefined ? `${leaf.import.split("/").pop().replace(/[^A-Za-z0-9_]/g, "_")}.` : "";
806
+ }
807
+ /** leafSymbolBare — the UNQUALIFIED transport symbol name (consumer override or the default Leaf_<comp>).
808
+ * The ONE source for the name: call sites qualify it with the package selector (resolveLeafSymbol); the
809
+ * observe companion DEFINES the fn under this bare name (a definition carries no selector). */
810
+ function leafSymbolBare(component, leaf) {
811
+ return leaf?.symbols[component] ?? `Leaf_${sanitize(component)}`;
812
+ }
813
+ function resolveLeafSymbol(component, leaf) {
814
+ return `${goLeafSel(leaf)}${leafSymbolBare(component, leaf)}`;
815
+ }
816
+ /**
817
+ * portFieldSpread — the covered node's port fields, in declared `Object.keys(ports)` order, each carrying
818
+ * its native ports-struct field name + Go type. The ONE place the transport-call port spread is derived
819
+ * (SSoT): a runner call site spreads `<var>.<F>`; the test observe transport fn declares matching params.
820
+ * Types come from the SAME `portFieldGoType` lowering `emitPortsStruct` uses, so the spread can never
821
+ * disagree with the ports struct field types. (Go has no borrow — every field is passed by value.)
822
+ */
823
+ function portFieldSpread(ports, comp, plan, typedNodes, asBinding) {
824
+ const opts = asBinding !== undefined ? { asBinding, asBase: asBinding.name } : undefined;
825
+ return Object.keys(ports).map((pn) => ({
826
+ field: goPortFieldName(pn),
827
+ goType: portFieldGoType(ports[pn], comp, plan, typedNodes, `port '${pn}' of node '${comp.name}'`, opts),
828
+ }));
829
+ }
830
+ /** leafCallArgs — the spread transport-call arguments for a ports-struct var (Go: by value, no borrow). */
831
+ function leafCallArgs(varExpr, spread) {
832
+ return spread.map((p) => `${varExpr}.${p.field}`).join(", ");
803
833
  }
804
834
  /** RunNativeRawStruct_<comp> — the EXPORTED name of the per-component struct-returning combined runner
805
835
  * (bc#102). It MUST be an exported Go identifier so a consumer in a DIFFERENT package can call it (a
@@ -809,39 +839,6 @@ function handlerTypeName(compName) {
809
839
  function runnerName(compName) {
810
840
  return `RunNativeRawStruct_${sanitize(compName)}`;
811
841
  }
812
- /** Node_<comp>_<nodeId> — the concrete per-node handler method name. */
813
- function nodeMethodName(compName, nodeId) {
814
- return `Node_${sanitize(compName)}_${nodeId.replace(/[^A-Za-z0-9_]/g, "_")}`;
815
- }
816
- /**
817
- * boundGoType (change #3 — typed `bound`) — the CONCRETE Go type of a covered node's `bound` handler
818
- * param (bc#90 / runtime-free). `bound` is the parent-produced key (the bindField value); it replaces
819
- * the old boxed `dslcontracts.Value`. We represent PRODUCED-vs-UNPRODUCED with a POINTER: a non-nil
820
- * `*T` means the parent value was produced/present (an empty string is a VALID produced value — a
821
- * non-nil `*string` to ""); a nil pointer means UNPRODUCED/skip (exactly the old `!= nil` guard ≡
822
- * run_behavior). The pointed-to type is the bindField's concrete Go type (a string key here). A node
823
- * WITHOUT a bindField never receives a bound value — its param is a `*string` placeholder always
824
- * passed `nil` (a typed nil, so the ABI stays uniform and carries NO dslcontracts.Value).
825
- */
826
- function boundGoType(node, comp, typedNodes, plan) {
827
- if (node.bindField === undefined || node.parent === undefined)
828
- return "*string";
829
- const parentRef = typedNodes.get(node.parent);
830
- if (parentRef === undefined)
831
- return "*string";
832
- let bfRef;
833
- try {
834
- bfRef = goTypedInternals.typedFieldAccess(typedLocal(node.parent), parentRef, [node.bindField], plan).ref;
835
- }
836
- catch {
837
- return "*string";
838
- }
839
- // opt bindField: the field is already a *T — the bound pointed-to type is the inner. A required
840
- // scalar bindField: the bound pointed-to type is that scalar's Go type.
841
- if (bfRef.kind === "opt")
842
- return `*${renderTypeRef(bfRef.inner)}`;
843
- return `*${renderTypeRef(bfRef)}`;
844
- }
845
842
  /** mapElemMaterializerName — the augmented-element copier for a covered map...into node. */
846
843
  function mapElemMaterializerName(compName, nodeId) {
847
844
  return `materializeMapElemNR_${sanitize(compName)}_${nodeId.replace(/[^A-Za-z0-9_]/g, "_")}`;
@@ -1235,7 +1232,7 @@ function emitPortInit(pn, expr, comp, plan, typedNodes, isPrior, opts) {
1235
1232
  *
1236
1233
  * NO RunPlan / []OpSpec / planSpec walk: the staging, the bound, and which ops are parallel are baked.
1237
1234
  */
1238
- function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes, plan, priorNodeAt, zeroOut, flags, wire) {
1235
+ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes, plan, priorNodeAt, zeroOut, flags, wire, leaf) {
1239
1236
  const lines = [];
1240
1237
  const ids = stage.map((i) => comp.body[i].id);
1241
1238
  lines.push(`\t// ── bc#87 real-concurrency stage {${ids.map((x) => JSON.stringify(x)).join(", ")}} — static parallel`);
@@ -1279,12 +1276,6 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1279
1276
  lines.push(`\t\trun_${s} := false`);
1280
1277
  lines.push(`\t\tvar ps_${s} ${structName}`);
1281
1278
  lines.push(`\t\t_ = ps_${s}`);
1282
- // #114: a bindField relation child member carries its produced-aware bound key (a typed pointer,
1283
- // nil => UNPRODUCED/skip) into the goroutine — declared at stage scope, assigned in preflight.
1284
- if (node.bindField !== undefined) {
1285
- lines.push(`\t\tvar bound_${s} ${boundGoType(node, comp, typedNodes, plan)}`);
1286
- lines.push(`\t\t_ = bound_${s}`);
1287
- }
1288
1279
  }
1289
1280
  // 1) PREFLIGHT (ascending): parent-produced gate (+ #114 bindField bound-key gate) + ports build,
1290
1281
  // per member (BEFORE dispatch). For a bindField relation child the bound key is read from the SETTLED
@@ -1306,18 +1297,19 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1306
1297
  closers.unshift(`${ind}}`);
1307
1298
  ind += "\t";
1308
1299
  if (node.bindField !== undefined && parentIsGate) {
1309
- lines.push(`${ind}gateOK_${s} := "ok"`);
1310
- lines.push(`${ind}bound_${s} = &gateOK_${s}`);
1300
+ // #125: a control-gate parent — produced_<gate> already carries the skip; no bound needed here
1301
+ // (the leaf transport no longer receives it, the child ports read the real data parent).
1311
1302
  }
1312
1303
  else if (node.bindField !== undefined) {
1304
+ // bound is the preflight skip-gate condition only (a local — the goroutine no longer captures it).
1313
1305
  const parentRef = typedNodes.get(node.parent);
1314
1306
  const { expr: bfExpr, ref: bfRef } = goTypedInternals.typedFieldAccess(typedLocal(node.parent), parentRef, [node.bindField], plan);
1315
1307
  if (bfRef.kind === "opt") {
1316
- lines.push(`${ind}bound_${s} = ${bfExpr}`);
1308
+ lines.push(`${ind}bound_${s} := ${bfExpr}`);
1317
1309
  }
1318
1310
  else {
1319
1311
  lines.push(`${ind}boundV_${s} := ${bfExpr}`);
1320
- lines.push(`${ind}bound_${s} = &boundV_${s}`);
1312
+ lines.push(`${ind}bound_${s} := &boundV_${s}`);
1321
1313
  }
1322
1314
  lines.push(`${ind}if bound_${s} != nil {`);
1323
1315
  closers.unshift(`${ind}}`);
@@ -1346,8 +1338,10 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1346
1338
  lines.push(`\t\t\tgo func() {`);
1347
1339
  lines.push(`\t\t\t\tdefer wg.Done()`);
1348
1340
  lines.push(`\t\t\t\tdefer func() { <-sem }()`);
1349
- const boundArg = node.bindField !== undefined ? `bound_${s}` : "nil";
1350
- lines.push(`\t\t\t\twire_${s}, row_${s}Err = handlers.${nodeMethodName(comp.name, node.id)}(ps_${s}, ${boundArg})`);
1341
+ // DIRECT leaf transport call — the node's port fields spread off the preflight-built ports struct. No
1342
+ // `bound` (BC's internal produced/skip gate is already applied in preflight — the leaf never sees it).
1343
+ const call = `${resolveLeafSymbol(node.component, leaf)}(${leafCallArgs(`ps_${s}`, portFieldSpread(node.ports, comp, plan, typedNodes))})`;
1344
+ lines.push(`\t\t\t\twire_${s}, row_${s}Err = ${call}`);
1351
1345
  lines.push(`\t\t\t}()`);
1352
1346
  lines.push(`\t\t}`);
1353
1347
  }
@@ -1404,7 +1398,7 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1404
1398
  * consumer (graphddb) drives it and keeps the struct native. A Value observation is produced ONLY
1405
1399
  * by the separate serialize wrapper (run_native_raw_<comp>, below), the single outer Value boundary.
1406
1400
  */
1407
- function emitNativeRawRunner(comp, plan, flags, wire) {
1401
+ function emitNativeRawRunner(comp, plan, flags, wire, leaf) {
1408
1402
  const ep = execPlan(comp);
1409
1403
  const order = ep.order;
1410
1404
  const cplan = buildComponentPlan(comp, goStraightlineInternals.dialect, "scope");
@@ -1441,12 +1435,12 @@ function emitNativeRawRunner(comp, plan, flags, wire) {
1441
1435
  lines.push(`// index order so the observed value / op multiset / failure precedence byte-match run_behavior`);
1442
1436
  lines.push(`// (the goroutine spawn is the ONLY runtime element — the WHAT is baked). The output is a typed`);
1443
1437
  lines.push(`// struct/value assembled by struct literal + field access — the consumer keeps it native.`);
1444
- // FULLY CONCRETE + NON-GENERIC: the runner takes the consumer's CONCRETE ${handlerTypeName(comp.name)}
1445
- // handler by value and calls h.Node_*(...) DIRECTLY (a Go generic method call goes through a dictionary,
1446
- // a Go interface through a vtable — BOTH are dynamic dispatch, so the covered plane uses neither). Each
1447
- // Node_* returns the node's result WIRE (a single ${wire.value}); the runner de-boxes it INLINE
1448
- // (fully-unrolled probe/match — no decode helper, no output recursion) into the node's outType struct.
1449
- lines.push(`func ${runnerName(comp.name)}(handlers ${handlerTypeName(comp.name)}, in ${inStructName(comp.name)}) (${outStructType}, error) {`);
1438
+ // At each covered node's execution point the runner calls the op-agnostic leaf TRANSPORT symbol
1439
+ // (default Leaf_<comp>) DIRECTLY with the node's port fields spread — no per-node handler indirection, no
1440
+ // interface, no generics (both are dynamic dispatch). Each transport returns the node's result WIRE (a
1441
+ // single ${wire.value}); the runner de-boxes it INLINE (fully-unrolled probe/match — no decode helper, no
1442
+ // output recursion) into the node's outType struct.
1443
+ lines.push(`func ${runnerName(comp.name)}(in ${inStructName(comp.name)}) (${outStructType}, error) {`);
1450
1444
  lines.push(`\t_ = in`);
1451
1445
  for (const k of order.keys()) {
1452
1446
  const node = comp.body[order[k]];
@@ -1470,19 +1464,19 @@ function emitNativeRawRunner(comp, plan, flags, wire) {
1470
1464
  // ascending-sorted stages), so we emit the block at the first member and skip the rest.
1471
1465
  const stage = ep.parallelStageOf.get(i);
1472
1466
  if (stage !== undefined && stage[0] === i) {
1473
- lines.push(emitParallelStageArm(comp, stage, k, ep.concurrency, metas, typedNodes, plan, priorNodeAt, zeroOut, flags, wire));
1467
+ lines.push(emitParallelStageArm(comp, stage, k, ep.concurrency, metas, typedNodes, plan, priorNodeAt, zeroOut, flags, wire, leaf));
1474
1468
  k += stage.length - 1;
1475
1469
  continue;
1476
1470
  }
1477
1471
  // v3: a covered fanout node — deduped batched dispatch + first-seen dedupe + dangling drop +
1478
1472
  // connection wrap (the SAME definition as run_behavior's fanoutDedupDrop).
1479
1473
  if ("fanout" in comp.body[i]) {
1480
- lines.push(emitFanoutArm(comp, comp.body[i], k, typedNodes, plan, priorNodeAt, zeroOut));
1474
+ lines.push(emitFanoutArm(comp, comp.body[i], k, typedNodes, plan, priorNodeAt, zeroOut, leaf));
1481
1475
  continue;
1482
1476
  }
1483
1477
  // #86 pt2: a covered batched map...into node — struct-native element collection + into enrichment.
1484
1478
  if ("map" in comp.body[i]) {
1485
- lines.push(emitMapArm(comp, comp.body[i], k, typedNodes, plan, priorNodeAt, zeroOut, flags));
1479
+ lines.push(emitMapArm(comp, comp.body[i], k, typedNodes, plan, priorNodeAt, zeroOut, flags, leaf));
1486
1480
  continue;
1487
1481
  }
1488
1482
  // #108: a cond node — pure Expression (no handler). Compile `if` to a native bool + materialize the
@@ -1507,12 +1501,10 @@ function emitNativeRawRunner(comp, plan, flags, wire) {
1507
1501
  closers.unshift(`${indent}}`);
1508
1502
  indent += "\t";
1509
1503
  if (node.bindField !== undefined && parentIsGate) {
1510
- // #125: a when(...) control-gate parent. gate の bindField:"ok" は run_behavior では成立時
1511
- // `true` / 不成立時 `null`(→ null-binding skip)。native では produced_<gate>(= gate の `if`)
1512
- // が既にその skip を担うので、ここに来た時点で gate は成立。bound は skip の sentinel(データ
1513
- // キーではない — 子の ports は実データ親を参照する)として、非 nil の `*string` を渡す。
1514
- lines.push(`${indent}gateOK_${s} := "ok"`);
1515
- lines.push(`${indent}bound_${s} := &gateOK_${s}`);
1504
+ // #125: a when(...) control-gate parent. produced_<gate> (= the gate's `if`) ALREADY carries the
1505
+ // skip, so past it the gate held — there is no further skip to gate here. The bindField:"ok" was
1506
+ // only a sentinel formerly passed to the handler; the leaf transport no longer receives `bound`, so
1507
+ // NO bound local is emitted (the child ports read the real data parent, not the gate).
1516
1508
  }
1517
1509
  else if (node.bindField !== undefined) {
1518
1510
  // bind (change #3 — typed produced-aware bound): read the parent struct field DIRECTLY (typed
@@ -1541,12 +1533,15 @@ function emitNativeRawRunner(comp, plan, flags, wire) {
1541
1533
  // static string array / number literal) assigned straight into the ports field — ZERO
1542
1534
  // dslcontracts.Value, ZERO nvVE helper, ZERO `.(T)`. A genuinely-dynamic port FAILS CLOSED.
1543
1535
  const inits = [];
1544
- const boundArg = node.bindField !== undefined ? `bound_${s}` : "nil";
1545
1536
  for (const pn of portNames) {
1546
1537
  inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k)));
1547
1538
  }
1539
+ // DIRECT leaf transport call: the resolved op-agnostic symbol, the node's port fields spread. `bound` is
1540
+ // NOT passed — it is BC's internal produced/skip gate, already enforced by the surrounding
1541
+ // `if bound_<s> != nil` / `if produced_<parent>` guards; the leaf never receives it.
1542
+ const call = `${resolveLeafSymbol(node.component, leaf)}(${leafCallArgs(`ports_${s}`, portFieldSpread(node.ports, comp, plan, typedNodes))})`;
1548
1543
  lines.push(`${indent}ports_${s} := ${structName}{${inits.join(", ")}}`);
1549
- // uniform seam: the handler returns a single result WIRE (${wire.value}); the inline de-box
1544
+ // uniform seam: the transport returns a single result WIRE (${wire.value}); the inline de-box
1550
1545
  // (renderResultDeBox) classifies it against the STATICALLY declared result type and produces the
1551
1546
  // structured Error Value on a mismatch (byte-equal codes to run_behavior's outType check, so ≡ holds).
1552
1547
  if (meta.policy === "continue") {
@@ -1556,7 +1551,7 @@ function emitNativeRawRunner(comp, plan, flags, wire) {
1556
1551
  // are always 'fail' policy today — this arm is defensive.)
1557
1552
  const nodeGo = renderTypeRef(ref);
1558
1553
  const nodeZeroFail = (e) => `return ${goZero(ref)}, ${e}`;
1559
- lines.push(`${indent}if wire_${s}, wire_${s}Err := handlers.${nodeMethodName(comp.name, node.id)}(ports_${s}, ${boundArg}); wire_${s}Err == nil {`);
1554
+ lines.push(`${indent}if wire_${s}, wire_${s}Err := ${call}; wire_${s}Err == nil {`);
1560
1555
  lines.push(`${indent}\tdec_${s}, dec_${s}DErr := func() (${nodeGo}, error) {`);
1561
1556
  lines.push(`${indent}\t\tvar out ${nodeGo}`);
1562
1557
  lines.push(renderResultDeBox(ref, "out", `wire_${s}`, node.id, plan, `${indent}\t\t`, nodeZeroFail, seqCtr));
@@ -1570,7 +1565,7 @@ function emitNativeRawRunner(comp, plan, flags, wire) {
1570
1565
  }
1571
1566
  else {
1572
1567
  const policyLit = JSON.stringify(meta.policy === "retry" ? "retry" : "fail");
1573
- lines.push(`${indent}wire_${s}, wire_${s}Err := handlers.${nodeMethodName(comp.name, node.id)}(ports_${s}, ${boundArg})`);
1568
+ lines.push(`${indent}wire_${s}, wire_${s}Err := ${call}`);
1574
1569
  lines.push(`${indent}if wire_${s}Err != nil {`);
1575
1570
  lines.push(`${indent}\treturn ${zeroOut}, opFailed(${JSON.stringify(node.id)}, ${policyLit}, wire_${s}Err)`);
1576
1571
  lines.push(`${indent}}`);
@@ -1603,8 +1598,11 @@ function emitNativeRawRunner(comp, plan, flags, wire) {
1603
1598
  }
1604
1599
  }
1605
1600
  const out = skippable.size > 0
1606
- ? emitProducedAwareValue(comp.output, outRef, typedNodes, plan, skippable, skippableKind)
1607
- : emitTypedValue(comp.output, outRef, typedNodes, plan);
1601
+ ? emitProducedAwareValue(comp.output, outRef, typedNodes, plan, skippable, skippableKind, comp.name, "<output>")
1602
+ : emitTypedValue(comp.output, outRef, typedNodes, plan, comp.name, "<output>");
1603
+ // top-level output that is a bare node-result (not an obj/arr assembly): its honest `ref` must equal the
1604
+ // declared component output type, or the emitted `return <out>, nil` does not compile.
1605
+ checkOutputFieldType(comp.name, "<output>", outRef, out.ref, plan);
1608
1606
  lines.push(`\treturn ${out.expr}, nil`);
1609
1607
  lines.push(`}`);
1610
1608
  return { code: lines.join("\n"), outRef: out.ref ?? outRef };
@@ -1624,7 +1622,7 @@ function emitNativeRawRunner(comp, plan, flags, wire) {
1624
1622
  * (direct field assignment; $as refs read the over element's typed fields), and the result is a
1625
1623
  * native []T with NO boxed Value on any plane. The map is under the parent's produced gate (inline).
1626
1624
  */
1627
- function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, flags) {
1625
+ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, flags, leaf) {
1628
1626
  const m = node.map;
1629
1627
  const batched = m.batched === true;
1630
1628
  const hasInto = m.into !== undefined;
@@ -1632,6 +1630,7 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1632
1630
  const s = sanitize(node.id);
1633
1631
  const structName = portsStructName(comp.name, node.id);
1634
1632
  const batchStruct = `${structName}_batch`;
1633
+ const leafSym = resolveLeafSymbol(m.component, leaf);
1635
1634
  const arrRef = typedNodes.get(node.id);
1636
1635
  const elemGo = renderTypeRef(arrRef);
1637
1636
  const asName = m.as;
@@ -1714,7 +1713,9 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1714
1713
  // empty items => empty result (handler not called), matching run_behavior.
1715
1714
  lines.push(`${indent}if len(items_${s}) > 0 {`);
1716
1715
  lines.push(`${indent}\tbp_${s} := ${batchStruct}{Items: items_${s}}`);
1717
- lines.push(`${indent}\tmo_${s}, mo_${s}Err := handlers.${nodeMethodName(comp.name, node.id)}(bp_${s}, nil)`);
1716
+ // DIRECT transport call — the batched dispatch takes the CONCRETE batch ports struct (shape unchanged;
1717
+ // only the call target changes). Returns the aligned per-element wires ([]WireValue). No `bound`.
1718
+ lines.push(`${indent}\tmo_${s}, mo_${s}Err := ${leafSym}(bp_${s})`);
1718
1719
  lines.push(`${indent}\tif mo_${s}Err != nil {`, `${indent}\t\treturn ${zeroOut}, opFailed(${JSON.stringify(node.id)}, "fail", mo_${s}Err)`, `${indent}\t}`);
1719
1720
  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}`);
1720
1721
  if (hasInto) {
@@ -1753,7 +1754,7 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1753
1754
  // Element Error Policy (scp-error.md): `skip` drops the failing element and proceeds (order is
1754
1755
  // preserved; the leaf keeps the Error Value it produced). `error` (default) promotes the element
1755
1756
  // Failure to the map's Component Failure, carrying the leaf's detail through.
1756
- lines.push(`${indent}\tmo_${s}, mo_${s}Err := handlers.${nodeMethodName(comp.name, node.id)}(ep_${s}, nil)`);
1757
+ lines.push(`${indent}\tmo_${s}, mo_${s}Err := ${leafSym}(${leafCallArgs(`ep_${s}`, portFieldSpread(m.ports, comp, plan, typedNodes, { name: asName, ref: overElemRef, plan }))})`);
1757
1758
  if (m.elementPolicy === "skip") {
1758
1759
  lines.push(`${indent}\tif mo_${s}Err != nil {`, `${indent}\t\tcontinue`, `${indent}\t}`);
1759
1760
  }
@@ -1794,11 +1795,12 @@ function elemLocal(s) {
1794
1795
  * (STRUCTURAL — the connection items elem type already omits the implicitSource field), and wrap into
1795
1796
  * the connection struct {items, cursor:nil}. NO boxed Value on any plane. Byte-equal to run_behavior.
1796
1797
  */
1797
- function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut) {
1798
+ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, leaf) {
1798
1799
  const f = node.fanout;
1799
1800
  const s = sanitize(node.id);
1800
1801
  const structName = portsStructName(comp.name, node.id);
1801
1802
  const batchStruct = `${structName}_batch`;
1803
+ const leafSym = resolveLeafSymbol(f.component, leaf);
1802
1804
  const connRef = typedNodes.get(node.id);
1803
1805
  const elemRef = fanoutItemsElemRef(node, connRef, plan);
1804
1806
  const elemGo = renderTypeRef(elemRef);
@@ -1844,7 +1846,9 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut
1844
1846
  // the handler returns the aligned per-id element WIRES (one nilable WireValue per id); each present
1845
1847
  // body is de-boxed strictly INLINE (a de-box mismatch fails closed). A DANGLING id is a nil wire → the
1846
1848
  // zero element (empty dedupeKey), which the dangling drop below excludes.
1847
- lines.push(`${indent}\tfo_${s}, fo_${s}Err := handlers.${nodeMethodName(comp.name, node.id)}(bp_${s}, nil)`);
1849
+ // DIRECT transport call — the batched fanout dispatch takes the CONCRETE batch ports struct (shape
1850
+ // unchanged; only the call target changes). Returns the aligned per-id element wires. No `bound`.
1851
+ lines.push(`${indent}\tfo_${s}, fo_${s}Err := ${leafSym}(bp_${s})`);
1848
1852
  lines.push(`${indent}\tif fo_${s}Err != nil {`, `${indent}\t\treturn ${zeroOut}, opFailed(${JSON.stringify(node.id)}, "fail", fo_${s}Err)`, `${indent}\t}`);
1849
1853
  lines.push(`${indent}\tif len(fo_${s}) != len(pi_${s}) {`, `${indent}\t\treturn ${zeroOut}, ${goErr("FANOUT_BATCH_RESULT_MISMATCH", `fmt.Sprintf("fanout '${node.id}': batched handler must return a list aligned to the deduped id list (want %d)", len(pi_${s}))`)}`, `${indent}\t}`);
1850
1854
  // ── THE ONE dedupe/drop (mirrors fanoutDedupDrop verbatim): first-seen dedupe by dedupeKey field;
@@ -1969,7 +1973,7 @@ function emitCondArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut)
1969
1973
  * else { <unproduced-rep for the expected type> }`. Obj/arr/concat/literal recurse; a ref into a
1970
1974
  * NON-skippable node delegates to the plain typed field access (identical to emitTypedValue).
1971
1975
  */
1972
- function emitProducedAwareValue(node, expected, typedNodes, plan, skippable, skippableKind) {
1976
+ function emitProducedAwareValue(node, expected, typedNodes, plan, skippable, skippableKind, compName, fieldPath) {
1973
1977
  // ref / refOpt (classifyExpr encodes both as kind:"ref" with .opt).
1974
1978
  const e = classifyExpr(node);
1975
1979
  if (e.kind === "ref" && e.path.length >= 1 && typedNodes.has(e.path[0])) {
@@ -1985,6 +1989,12 @@ function emitProducedAwareValue(node, expected, typedNodes, plan, skippable, ski
1985
1989
  // nil cursor to null) — matching unproducedValue("connection") byte-for-byte.
1986
1990
  const { expr, ref } = goTypedInternals.typedFieldAccess(typedLocal(head), baseRef, e.path.slice(1), plan);
1987
1991
  const producedFlag = `produced_${sanitize(head)}`;
1992
+ // The value placed into this output field is `producedExpr` — valueLeafTyped returns a *T (opt-wrap)
1993
+ // iff the field is opt and the value is not; otherwise the bare `ref` value. Its rendered type must
1994
+ // equal the func()'s declared return type = renderTypeRef(expected). That is exactly what the Go
1995
+ // compiler checks, so this fires IFF the emitted module would not compile (type mismatch).
1996
+ const placed = expected && expected.kind === "opt" && ref.kind !== "opt" ? { kind: "opt", inner: ref } : ref;
1997
+ checkOutputFieldType(compName, fieldPath, expected, placed, plan);
1988
1998
  const producedExpr = valueLeafTyped(expr, ref, e.opt, expected);
1989
1999
  const outTy = expected ? renderTypeRef(expected) : renderTypeRef(ref);
1990
2000
  const isConn = skippableKind.get(head) === "connection" && e.path.length === 1;
@@ -1997,7 +2007,9 @@ function emitProducedAwareValue(node, expected, typedNodes, plan, skippable, ski
1997
2007
  ref: expected ?? ref,
1998
2008
  };
1999
2009
  }
2000
- // non-skippable node ref — identical to emitTypedValue's typed field access.
2010
+ // non-skippable node ref — identical to emitTypedValue's typed field access. Its `ref` is returned
2011
+ // honestly (not laundered), so the placing site — the obj-field assembly below, or the top-level call —
2012
+ // runs checkOutputFieldType against the field type.
2001
2013
  const { expr, ref } = goTypedInternals.typedFieldAccess(typedLocal(head), baseRef, e.path.slice(1), plan);
2002
2014
  return { expr, ref };
2003
2015
  }
@@ -2009,7 +2021,11 @@ function emitProducedAwareValue(node, expected, typedNodes, plan, skippable, ski
2009
2021
  const decl = findDecl(plan, expected.name);
2010
2022
  const fields = node.obj;
2011
2023
  const inits = decl.fields.map((f) => {
2012
- const sub = emitProducedAwareValue(fields[f.name], f.type, typedNodes, plan, skippable, skippableKind);
2024
+ const childPath = fieldPath === "" ? f.name : `${fieldPath}.${f.name}`;
2025
+ const sub = emitProducedAwareValue(fields[f.name], f.type, typedNodes, plan, skippable, skippableKind, compName, childPath);
2026
+ // Non-skippable field: sub.ref is the honest value type → catches a mismatch here. A skippable field
2027
+ // launders sub.ref to expected, but its own produced-arm check (above) already fired.
2028
+ checkOutputFieldType(compName, childPath, f.type, sub.ref, plan);
2013
2029
  return `${goFieldName(f.name)}: ${sub.expr}`;
2014
2030
  });
2015
2031
  return { expr: `${expected.name}{${inits.join(", ")}}`, ref: expected };
@@ -2017,7 +2033,7 @@ function emitProducedAwareValue(node, expected, typedNodes, plan, skippable, ski
2017
2033
  }
2018
2034
  // everything else (literal / non-skippable ref / obj-of-non-named / arr / concat) — delegate to
2019
2035
  // the plain typed lowering (no skippable head reachable there in the covered corpus).
2020
- return emitTypedValue(node, expected, typedNodes, plan);
2036
+ return emitTypedValue(node, expected, typedNodes, plan, compName, fieldPath);
2021
2037
  }
2022
2038
  /** Lower a typed field-access expr to the EXPECTED output type (used in the produced branch). When
2023
2039
  * the expected type is `opt` and the accessed value is already a *T pointer (the field itself is
@@ -2291,9 +2307,9 @@ func bcExpr_strGe(a, b string) bool { return bcExpr_cmpCP(a, b) >= 0 }`;
2291
2307
  * which lives OUTSIDE this module so the covered module stays literal whole-file zero. */
2292
2308
  function emitStructSurface(native) {
2293
2309
  return `// ComponentNamesNativeRaw — covered reads exposed on the combined struct-native path (declaration
2294
- // order). Each is driven via RunNativeRawStruct_<comp>(handlers, input) -> (T, error): a STRUCT
2295
- // return; the consumer keeps the model native (no Value serialization on the read hot path — the
2296
- // boxing residue bc#77 removes). See INTEGRATION.md §6.
2310
+ // order). Each is driven via RunNativeRawStruct_<comp>(input) -> (T, error): a STRUCT return; the consumer
2311
+ // keeps the model native (no Value serialization on the read hot path — the boxing residue bc#77 removes)
2312
+ // and supplies the op-agnostic leaf transport symbols the runner calls. See INTEGRATION.md §6.
2297
2313
  var ComponentNamesNativeRaw = []string{${native.map((c) => JSON.stringify(c.name)).join(", ")}}`;
2298
2314
  }
2299
2315
  /** Minimal module header for a FULLY-covered module (bc#90 / runtime-free). A fully-covered module
@@ -2301,7 +2317,7 @@ var ComponentNamesNativeRaw = []string{${native.map((c) => JSON.stringify(c.name
2301
2317
  * mismatch Sprintf, `strings` for a concat builder, `sync` for a parallel stage). ExpectedSpecVersions
2302
2318
  * stays as a local `var` for provenance, but the old `dslcontracts.SpecVersions` skew `init()` is GONE
2303
2319
  * (change #5 — there is no runtime to skew against once the module is runtime-free). */
2304
- function emitMinimalHeader(ctx, needStrings, needSync, needFmt, needMath, needStrconv = false, wireImport) {
2320
+ function emitMinimalHeader(ctx, needStrings, needSync, needFmt, needMath, needStrconv = false, wireImport, leafImport) {
2305
2321
  const sv = ctx.specVersions;
2306
2322
  const imports = [];
2307
2323
  if (needFmt)
@@ -2318,6 +2334,10 @@ function emitMinimalHeader(ctx, needStrings, needSync, needFmt, needMath, needSt
2318
2334
  // WireValue/WireRow/WireList types (default: in-package, no import).
2319
2335
  if (wireImport !== undefined)
2320
2336
  imports.push(`\t${JSON.stringify(wireImport)}`);
2337
+ // a configured leaf-transport package (leafTransport.import) — the covered module calls the op-agnostic
2338
+ // transport symbols qualified by its selector (default: in-package / same package, no import).
2339
+ if (leafImport !== undefined && leafImport !== wireImport)
2340
+ imports.push(`\t${JSON.stringify(leafImport)}`);
2321
2341
  const importBlock = imports.length > 0 ? `\nimport (\n${imports.join("\n")}\n)\n` : "";
2322
2342
  return `// GENERATED by behavior-contracts (bc#90, go-typed-native — the RUNTIME-FREE covered read de-box) — DO NOT EDIT.
2323
2343
  // Input: portable component-graph IR only. Every component here is a COVERED READ (sequential typed
@@ -2344,6 +2364,7 @@ function emit(ctx) {
2344
2364
  // a fallible checked-arith helper call — determines whether the helper library + `math` import ship).
2345
2365
  goExprUsed.helpers = false;
2346
2366
  const wire = resolveGoWire(ctx);
2367
+ const leaf = ctx.leafTransport;
2347
2368
  // Emit the runners first so the nv* helper usage flags are known.
2348
2369
  const flags = { bind: false, field: false, cat: false, arr: false };
2349
2370
  const structs = [];
@@ -2382,7 +2403,7 @@ function emit(ctx) {
2382
2403
  const mm = emitMapElemMaterializers(c, typedNodes, plan);
2383
2404
  if (mm)
2384
2405
  elemCopiers.push(mm);
2385
- const r = emitNativeRawRunner(c, plan, flags, wire);
2406
+ const r = emitNativeRawRunner(c, plan, flags, wire, leaf);
2386
2407
  runnerCodes.push(r.code);
2387
2408
  }
2388
2409
  const structSurface = emitStructSurface(native);
@@ -2413,21 +2434,22 @@ function emit(ctx) {
2413
2434
  const needMath = goExprUsed.helpers;
2414
2435
  // `strconv` is imported iff a generated inline de-box parses a numeric field (int/float range check).
2415
2436
  const needStrconv = runnerCodes.some((c) => c.includes("strconv."));
2416
- const header = emitMinimalHeader(ctx, false, needSync, needFmt, needMath, needStrconv, wire.import);
2437
+ const header = emitMinimalHeader(ctx, false, needSync, needFmt, needMath, needStrconv, wire.import, leaf?.import);
2417
2438
  const banner = `// COMBINED READ layer (bc#90 — the RUNTIME-FREE read de-box; STRUCT-ONLY, FULLY-NATIVE surface). A
2418
2439
  // covered read is a strictly-sequential typed componentRef chain (point reads + relationKind:single
2419
2440
  // children), emitted ONLY here: each node builds a native ports struct by direct field assignment (every
2420
2441
  // port is a CONCRETE Go value — string / bool / []string projection / int64 limit — NO boxed Value, NO
2421
- // PortReader accessor); the runner takes the consumer's CONCRETE Handler_<comp> handler by
2422
- // value and calls h.Node_*(...) DIRECTLY (no interface, no generics — zero dynamic dispatch). Each Node_*
2423
- // takes a typed produced-aware 'bound' pointer and returns the node's result WIRE (a single ${wire.value});
2424
- // the runner de-boxes it INLINE (fully-unrolled probe/match — no decode helper, no output recursion) into
2425
- // the node's outType struct. The covered plane carries NO bc-runtime reference at all — failures use the
2426
- // LOCAL *BehaviorError (same codes, byte-equal to run_behavior). Exec is INLINE sequential (no plan driver)
2427
- // so a relation child reads the parent's REAL struct result via direct field access and the child-present
2428
- // decision is made from the real parent value — relationSingle / connection converge with run_behavior
2429
- // (fixes #323/#74). The exposed API is the STRUCT-returning RunNativeRawStruct_<comp> (the consumer keeps
2430
- // the model native — no serialization on the read hot path). This module is FULLY NATIVE: a naive grep for
2442
+ // PortReader accessor); the runner calls the op-agnostic leaf TRANSPORT symbol (default Leaf_<comp>)
2443
+ // DIRECTLY with the node's port fields spread (no per-node handler indirection, no interface, no generics —
2444
+ // zero dynamic dispatch). A leaf is ONE transport, not one method per authored node. The transport returns
2445
+ // the node's result WIRE (a single ${wire.value}); the runner de-boxes it INLINE (fully-unrolled
2446
+ // probe/match — no decode helper, no output recursion) into the node's outType struct. The covered plane
2447
+ // carries NO bc-runtime reference at all — failures use the LOCAL *BehaviorError (same codes, byte-equal to
2448
+ // run_behavior). Exec is INLINE sequential (no plan driver) so a relation child reads the parent's REAL
2449
+ // struct result via direct field access and the child-present decision is made from the real parent value —
2450
+ // relationSingle / connection converge with run_behavior (fixes #323/#74). The exposed API is the
2451
+ // STRUCT-returning RunNativeRawStruct_<comp>; the consumer supplies the leaf transport symbols (default
2452
+ // same-package Leaf_<comp>, or a leafTransport import). This module is FULLY NATIVE: a naive grep for
2431
2453
  // boxing primitives OR for the bc-runtime package finds nothing, by design (bc#90/runtime-free).`;
2432
2454
  const sections = [
2433
2455
  banner,
@@ -2453,13 +2475,15 @@ function emit(ctx) {
2453
2475
  }
2454
2476
  /**
2455
2477
  * goTypedNativeObserve — the TEST-ONLY observe companion (a SEPARATE file in the SAME package as the
2456
- * covered module). It carries the typed->Value serializers (ser_*) + an ObserveNativeRaw dispatch
2457
- * that drives the module-private struct runner and serializes its result to a canonical Value for
2458
- * the equivalence pin. This lives OUTSIDE the covered module so the module stays literal whole-file
2459
- * zero (the ser_* NewObj is test glue, never on the consumer's read hot path). Emitted only for the
2460
- * fully-covered case (the equivalence harness); production consumers never use it.
2478
+ * covered module). It carries the typed->Value serializers (ser_*) + the SCRIPTED analog of the consumer's
2479
+ * leaf transport symbols: free Leaf_<comp> funcs (same package, so the covered module's transport calls
2480
+ * resolve) that drain a shared package-level scripted queue, + an ObserveNativeRaw dispatch that fills the
2481
+ * queue from the per-case spec, drives the module-private struct runner, and serializes its result to a
2482
+ * canonical Value for the equivalence pin. This lives OUTSIDE the covered module so the module stays literal
2483
+ * whole-file zero (the ser_* NewObj is test glue, never on the consumer's read hot path). Emitted only for
2484
+ * the fully-covered case (the equivalence harness); production consumers never use it.
2461
2485
  */
2462
- export function goTypedNativeObserve(ir, runtimeImport) {
2486
+ export function goTypedNativeObserve(ir, runtimeImport, leaf) {
2463
2487
  const components = ir.components;
2464
2488
  const native = components.filter(isNativeRaw);
2465
2489
  const plan = buildTypePlan(ir);
@@ -2476,7 +2500,7 @@ export function goTypedNativeObserve(ir, runtimeImport) {
2476
2500
  // decode the generic *Obj input into the CONCRETE In_<comp> struct (test glue — ONE decode at the
2477
2501
  // top, OUTSIDE the covered hot path; a REQUIRED declared input is present so an absent key is a
2478
2502
  // fail-closed decode error surfaced here, never on the native runner path).
2479
- return `\tif name == ${JSON.stringify(c.name)} {\n\t\tin, ierr := decode_${inStructName(c.name)}(input)\n\t\tif ierr != nil {\n\t\t\treturn nil, ierr\n\t\t}\n\t\ttv, err := ${runnerName(c.name)}(${handlerTypeName(c.name)}{handlers}, in)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn ${ser}, nil\n\t}`;
2503
+ return `\tif name == ${JSON.stringify(c.name)} {\n\t\tin, ierr := decode_${inStructName(c.name)}(input)\n\t\tif ierr != nil {\n\t\t\treturn nil, ierr\n\t\t}\n\t\ttv, err := ${runnerName(c.name)}(in)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn ${ser}, nil\n\t}`;
2480
2504
  })
2481
2505
  .join("\n");
2482
2506
  // input decoders (TEST glue): generic *Obj -> concrete In_<comp>. Scalar fields read the typed value
@@ -2674,17 +2698,14 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
2674
2698
  return d.Kind, d.Model, d.Field, d.ExpectedType, d.ActualWireType, d.RawValue, true
2675
2699
  }`
2676
2700
  : "";
2677
- // Handler_<comp> wrapper types: the covered runner takes the CONCRETE per-component handler by value
2678
- // (non-generic). One scripted queue backs every component, so each Handler_<comp> embeds the shared
2679
- // *ScriptedNativeRaw — the Node_* methods (on *ScriptedNativeRaw) are promoted, so the runner's direct
2680
- // h.Node_*(...) call resolves to a concrete method (no interface, no dictionary). Test glue only.
2681
- const handlerWrappers = native
2682
- .map((c) => `// ${handlerTypeName(c.name)} — the CONCRETE handler the '${c.name}' runner takes by value (embeds the\n// shared scripted queue; the Node_* methods are promoted).\ntype ${handlerTypeName(c.name)} struct {\n\t*ScriptedNativeRaw\n}`)
2683
- .join("\n\n");
2684
- // ── concrete scripted adapter (TEST glue): implements every Node_* method by draining a per-COMPONENT
2685
- // scripted-outcome queue and returning the scripted ok Value wrapped as a WireValue (the generic
2686
- // scripted source — a Value queue — meets the uniform CONCRETE wire seam). ──
2687
- const methodImpls = [];
2701
+ // ── op-agnostic leaf TRANSPORT funcs (TEST glue) — the scripted analog of the consumer's transport
2702
+ // symbols. ONE free `Leaf_<component>` per DISTINCT covered leaf (catalog component) in the IR (a
2703
+ // per-module leaf has one consistent shape — verified), draining the shared package-level scripted queue
2704
+ // and returning the scripted wire in EXACTLY the shape the removed per-node method returned. bc#87
2705
+ // parallel goroutines share the queue (mutex-guarded); cases run sequentially so a shared package var is
2706
+ // fine. Echo (#129/#141) reads the spread port params directly. ──
2707
+ const transportFns = [];
2708
+ const emittedLeaf = new Set();
2688
2709
  for (const c of native) {
2689
2710
  const typedNodes = new Map();
2690
2711
  for (const n of c.body)
@@ -2692,18 +2713,20 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
2692
2713
  typedNodes.set(n.id, "map" in n ? mapNodeArrRef(n, plan) : deriveTypeRef(n.outType, plan)); // #125: control-gate typeless; map は produced-array ref に正規化
2693
2714
  for (const n of c.body) {
2694
2715
  if ("cond" in n)
2695
- continue; // #108: cond has no handler method (pure Expression) — no scripted impl.
2696
- const ref = typedNodes.get(n.id);
2716
+ continue; // #108: cond has no leaf (pure Expression) — no transport fn.
2717
+ const catalog = "fanout" in n ? n.fanout.component : "map" in n ? n.map.component : n.component;
2718
+ if (emittedLeaf.has(catalog))
2719
+ continue; // per-module a leaf has ONE consistent shape — emit once.
2720
+ emittedLeaf.add(catalog);
2721
+ const sym = leafSymbolBare(catalog, leaf);
2697
2722
  if ("fanout" in n) {
2698
2723
  // fanout: return the aligned per-id element WIRES ([]*WireValue); a null aligned body is a
2699
2724
  // DANGLING id → nil (the covered runner maps it to the zero element).
2700
- const f = n.fanout;
2701
2725
  const portsT = `${portsStructName(c.name, n.id)}_batch`;
2702
- const foBoundT = boundGoType(n, c, typedNodes, plan);
2703
- methodImpls.push(`func (s *ScriptedNativeRaw) ${nodeMethodName(c.name, n.id)}(_ ${portsT}, _ ${foBoundT}) ([]*WireValue, error) {
2704
- src, ok := s.next(${JSON.stringify(f.component)})
2726
+ transportFns.push(`func ${sym}(_ ${portsT}) ([]*WireValue, error) {
2727
+ src, ok := nextScripted(${JSON.stringify(catalog)})
2705
2728
  if !ok {
2706
- return nil, unknownComponent(${JSON.stringify(f.component)})
2729
+ return nil, unknownComponent(${JSON.stringify(catalog)})
2707
2730
  }
2708
2731
  if src.isErr {
2709
2732
  return nil, leafFailure(src.err)
@@ -2725,14 +2748,12 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
2725
2748
  if ("map" in n) {
2726
2749
  // map: batched → one WIRE per element ([]WireValue); non-batched → one element WIRE (WireValue).
2727
2750
  const m = n.map;
2728
- const batched = m.batched === true;
2729
- const portsT = batched ? `${portsStructName(c.name, n.id)}_batch` : portsStructName(c.name, n.id);
2730
- const mapBoundT = boundGoType(n, c, typedNodes, plan);
2731
- if (batched) {
2732
- methodImpls.push(`func (s *ScriptedNativeRaw) ${nodeMethodName(c.name, n.id)}(_ ${portsT}, _ ${mapBoundT}) ([]WireValue, error) {
2733
- src, ok := s.next(${JSON.stringify(m.component)})
2751
+ if (m.batched === true) {
2752
+ const portsT = `${portsStructName(c.name, n.id)}_batch`;
2753
+ transportFns.push(`func ${sym}(_ ${portsT}) ([]WireValue, error) {
2754
+ src, ok := nextScripted(${JSON.stringify(catalog)})
2734
2755
  if !ok {
2735
- return nil, unknownComponent(${JSON.stringify(m.component)})
2756
+ return nil, unknownComponent(${JSON.stringify(catalog)})
2736
2757
  }
2737
2758
  if src.isErr {
2738
2759
  return nil, leafFailure(src.err)
@@ -2746,10 +2767,13 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
2746
2767
  }`);
2747
2768
  }
2748
2769
  else {
2749
- methodImpls.push(`func (s *ScriptedNativeRaw) ${nodeMethodName(c.name, n.id)}(_ ${portsT}, _ ${mapBoundT}) (WireValue, error) {
2750
- src, ok := s.next(${JSON.stringify(m.component)})
2770
+ const { elemRef: overElemRef } = mapOverElemInfo(c, n, typedNodes, plan);
2771
+ const spread = portFieldSpread(m.ports, c, plan, typedNodes, { name: m.as, ref: overElemRef, plan });
2772
+ const params = spread.map((pf) => `_${pf.field} ${pf.goType}`).join(", ");
2773
+ transportFns.push(`func ${sym}(${params}) (WireValue, error) {
2774
+ src, ok := nextScripted(${JSON.stringify(catalog)})
2751
2775
  if !ok {
2752
- return WireValue{}, unknownComponent(${JSON.stringify(m.component)})
2776
+ return WireValue{}, unknownComponent(${JSON.stringify(catalog)})
2753
2777
  }
2754
2778
  if src.isErr {
2755
2779
  return WireValue{}, leafFailure(src.err)
@@ -2759,12 +2783,10 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
2759
2783
  }
2760
2784
  continue;
2761
2785
  }
2762
- // componentRef: return the whole result WIRE (one WireValue wrapping the scripted ok Value); the
2763
- // covered runner's INLINE de-box classifies it. A real consumer returns its own wire payload.
2786
+ // componentRef (point read): spread port fields; supports echo (#129/#141) reading the port params.
2764
2787
  const node = n;
2765
- const nodeBoundT = boundGoType(node, c, typedNodes, plan);
2766
- // echo (#129/#141 fixtures): the scripted leaf can ECHO an input PORT back as its result wire, so the
2767
- // input-port value flows into the de-boxed result and the runtime non-vacuity asserts survive.
2788
+ const ref = typedNodes.get(n.id);
2789
+ const spread = portFieldSpread(node.ports, c, plan, typedNodes);
2768
2790
  const echoBranches = [];
2769
2791
  if (ref.kind === "named") {
2770
2792
  const decl = findDecl(plan, ref.name);
@@ -2781,26 +2803,27 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
2781
2803
  }
2782
2804
  if (portGo === recordGo) {
2783
2805
  // the port IS the whole record → echo it DIRECTLY (matching run_behavior's plain echo:port).
2784
- echoBranches.push(`\tif src.echo == ${JSON.stringify(pn)} {\n\t\treturn WireValue{v: ${serializeTyped(`ports.${goPortFieldName(pn)}`, ref, plan)}}, nil\n\t}`);
2806
+ echoBranches.push(`\tif src.echo == ${JSON.stringify(pn)} {\n\t\treturn WireValue{v: ${serializeTyped(goPortFieldName(pn), ref, plan)}}, nil\n\t}`);
2785
2807
  }
2786
2808
  else if (fieldGo !== null && field !== undefined && portGo === fieldGo) {
2787
2809
  // a scalar port wraps into the record's single field ({v: ports.X}).
2788
- echoBranches.push(`\tif src.echo == ${JSON.stringify(pn)} {\n\t\treturn WireValue{v: ${serializeTyped(`${recordGo}{${goFieldName(field.name)}: ports.${goPortFieldName(pn)}}`, ref, plan)}}, nil\n\t}`);
2810
+ echoBranches.push(`\tif src.echo == ${JSON.stringify(pn)} {\n\t\treturn WireValue{v: ${serializeTyped(`${recordGo}{${goFieldName(field.name)}: ${goPortFieldName(pn)}}`, ref, plan)}}, nil\n\t}`);
2789
2811
  }
2790
2812
  }
2791
2813
  }
2792
2814
  else if (ref.kind === "arr" && Object.prototype.hasOwnProperty.call(node.ports, "items")) {
2793
2815
  // #129: an arr node with an `items` port echoes the NATIVE port array (serialized to a Value array)
2794
2816
  // so the node→leaf array dataflow test is non-vacuous.
2795
- echoBranches.push(`\tif src.echo == "items" {\n\t\treturn WireValue{v: ${serializeTyped(`ports.${goPortFieldName("items")}`, ref, plan)}}, nil\n\t}`);
2817
+ echoBranches.push(`\tif src.echo == "items" {\n\t\treturn WireValue{v: ${serializeTyped(goPortFieldName("items"), ref, plan)}}, nil\n\t}`);
2796
2818
  }
2797
2819
  const canEcho = echoBranches.length > 0;
2798
- const portsParam = canEcho ? "ports" : "_";
2820
+ // params keep their field names (echo reads them); Go allows unused params, so no underscore needed.
2821
+ const params = spread.map((pf) => `${pf.field} ${pf.goType}`).join(", ");
2799
2822
  const echoBlock = canEcho ? `${echoBranches.join("\n")}\n` : "";
2800
- methodImpls.push(`func (s *ScriptedNativeRaw) ${nodeMethodName(c.name, node.id)}(${portsParam} ${portsStructName(c.name, node.id)}, _ ${nodeBoundT}) (WireValue, error) {
2801
- src, ok := s.next(${JSON.stringify(node.component)})
2823
+ transportFns.push(`func ${sym}(${params}) (WireValue, error) {
2824
+ src, ok := nextScripted(${JSON.stringify(catalog)})
2802
2825
  if !ok {
2803
- return WireValue{}, unknownComponent(${JSON.stringify(node.component)})
2826
+ return WireValue{}, unknownComponent(${JSON.stringify(catalog)})
2804
2827
  }
2805
2828
  if src.isErr {
2806
2829
  return WireValue{}, leafFailure(src.err)
@@ -2820,87 +2843,90 @@ type scriptSrc struct {
2820
2843
  ok ${PKG}.Value
2821
2844
  }
2822
2845
 
2823
- // ScriptedNativeRaw — the CONCRETE test handler: its Node_* methods drain a per-COMPONENT scripted queue
2824
- // and return the ok Value wrapped as a WireValue (the covered runner de-boxes it inline). Each runner
2825
- // takes a Handler_<comp> value that embeds this, so the Node_* calls stay fully concrete (no interface).
2826
- // EXPORTED so the runner glue (a separate package) can name it.
2827
- type ScriptedNativeRaw struct {
2828
- mu sync.Mutex
2829
- queues map[string][]scriptSrc
2830
- seen int
2831
- }
2846
+ // the shared scripted-outcome source the free Leaf_<comp> transport funcs drain (TEST glue). A package var
2847
+ // (not a per-call handler object) so the bc#87 parallel goroutines share it (mutex-guarded); reset+filled
2848
+ // per case by ObserveNativeRaw. Cases run sequentially in the harness, so one shared queue per case is fine.
2849
+ var (
2850
+ scriptedMu sync.Mutex
2851
+ scriptedQueues = map[string][]scriptSrc{}
2852
+ scriptedSeen int
2853
+ )
2832
2854
 
2833
- // NewScriptedNativeRaw builds the concrete test handler from the JSON handlers spec (the SAME shape
2834
- // the reference scriptedHandlers reads): { "<component>": {ok|error} | [ {ok|error}, … ] }. Each
2835
- // component's ok Value is DecodeValue'd once here (test glue); the per-node method decodes it into the
2836
- // concrete row. Returns the handler + any decode error (surfaced by the runner as a fatal).
2837
- func NewScriptedNativeRaw(spec *${PKG}.JObj) (*ScriptedNativeRaw, error) {
2838
- queues := map[string][]scriptSrc{}
2839
- if spec != nil {
2840
- for _, comp := range spec.Keys {
2841
- var entries []${PKG}.JNode
2842
- switch t := spec.Vals[comp].(type) {
2843
- case []${PKG}.JNode:
2844
- entries = t
2845
- default:
2846
- entries = []${PKG}.JNode{t}
2847
- }
2848
- for _, e := range entries {
2849
- eo, _ := e.(*${PKG}.JObj)
2850
- // #129: an \`echo\` directive names an input port to echo back (mirrors the reference
2851
- // scriptedHandlers' \`echo === "items"\`). It is drained together with the ok payload.
2852
- echo := ""
2853
- if echoNode, has := eo.Get("echo"); has {
2854
- echo, _ = echoNode.(string)
2855
- // normalize echo:port to the port NAME X so a de-box handler's echo comparison fires;
2856
- // echo:items already names the port directly.
2857
- if echo == "port" {
2858
- if portNode, hasPort := eo.Get("port"); hasPort {
2859
- echo, _ = portNode.(string)
2860
- }
2855
+ // fillScripted resets + loads the shared queue from the JSON handlers spec (the SAME shape the reference
2856
+ // scriptedHandlers reads): { "<component>": {ok|error} | [ {ok|error}, … ] }. Each ok Value is
2857
+ // DecodeValue'd once here (test glue). Returns any decode error (surfaced by the runner as a fatal).
2858
+ func fillScripted(spec *${PKG}.JObj) error {
2859
+ scriptedMu.Lock()
2860
+ defer scriptedMu.Unlock()
2861
+ scriptedQueues = map[string][]scriptSrc{}
2862
+ scriptedSeen = 0
2863
+ if spec == nil {
2864
+ return nil
2865
+ }
2866
+ for _, comp := range spec.Keys {
2867
+ var entries []${PKG}.JNode
2868
+ switch t := spec.Vals[comp].(type) {
2869
+ case []${PKG}.JNode:
2870
+ entries = t
2871
+ default:
2872
+ entries = []${PKG}.JNode{t}
2873
+ }
2874
+ for _, e := range entries {
2875
+ eo, _ := e.(*${PKG}.JObj)
2876
+ // #129: an \`echo\` directive names an input port to echo back (mirrors the reference
2877
+ // scriptedHandlers' \`echo === "items"\`). It is drained together with the ok payload.
2878
+ echo := ""
2879
+ if echoNode, has := eo.Get("echo"); has {
2880
+ echo, _ = echoNode.(string)
2881
+ // normalize echo:port to the port NAME X so a de-box handler's echo comparison fires;
2882
+ // echo:items already names the port directly.
2883
+ if echo == "port" {
2884
+ if portNode, hasPort := eo.Get("port"); hasPort {
2885
+ echo, _ = portNode.(string)
2861
2886
  }
2862
2887
  }
2863
- if okNode, has := eo.Get("ok"); has {
2864
- val, derr := ${PKG}.DecodeValue(okNode)
2865
- if derr != nil {
2866
- return nil, derr
2867
- }
2868
- queues[comp] = append(queues[comp], scriptSrc{ok: val, echo: echo})
2869
- continue
2888
+ }
2889
+ if okNode, has := eo.Get("ok"); has {
2890
+ val, derr := ${PKG}.DecodeValue(okNode)
2891
+ if derr != nil {
2892
+ return derr
2870
2893
  }
2871
- ev, _ := eo.Get("error")
2872
- es, _ := ev.(string)
2873
- queues[comp] = append(queues[comp], scriptSrc{isErr: true, err: es})
2894
+ scriptedQueues[comp] = append(scriptedQueues[comp], scriptSrc{ok: val, echo: echo})
2895
+ continue
2874
2896
  }
2897
+ ev, _ := eo.Get("error")
2898
+ es, _ := ev.(string)
2899
+ scriptedQueues[comp] = append(scriptedQueues[comp], scriptSrc{isErr: true, err: es})
2875
2900
  }
2876
2901
  }
2877
- return &ScriptedNativeRaw{queues: queues}, nil
2902
+ return nil
2878
2903
  }
2879
2904
 
2880
- // next drains one scripted outcome for a component (last entry repeats — mirrors the reference
2881
- // scriptedHandlers), returns ok=false when the component has no scripted queue (fail-closed). The
2882
- // bc#87 parallel-stage runner calls Node_* from multiple goroutines, so the drain is mutex-guarded.
2883
- func (s *ScriptedNativeRaw) next(component string) (scriptSrc, bool) {
2884
- s.mu.Lock()
2885
- defer s.mu.Unlock()
2886
- s.seen++
2887
- q, ok := s.queues[component]
2905
+ // nextScripted drains one scripted outcome for a component (last entry repeats — mirrors the reference
2906
+ // scriptedHandlers), returns ok=false when the component has no scripted queue (fail-closed). The bc#87
2907
+ // parallel-stage runner calls the transport funcs from multiple goroutines, so the drain is mutex-guarded.
2908
+ func nextScripted(component string) (scriptSrc, bool) {
2909
+ scriptedMu.Lock()
2910
+ defer scriptedMu.Unlock()
2911
+ scriptedSeen++
2912
+ q, ok := scriptedQueues[component]
2888
2913
  if !ok || len(q) == 0 {
2889
2914
  return scriptSrc{}, false
2890
2915
  }
2891
2916
  if len(q) > 1 {
2892
2917
  v := q[0]
2893
- s.queues[component] = q[1:]
2918
+ scriptedQueues[component] = q[1:]
2894
2919
  return v, true
2895
2920
  }
2896
2921
  return q[0], true
2897
2922
  }`;
2898
2923
  return `// GENERATED test-only observe companion (bc#77) — NOT part of the covered module. Serializes the
2899
- // struct-native runner's result to a canonical Value for the equivalence pin, and carries the CONCRETE
2900
- // scripted test handler (ScriptedNativeRaw) + the CONCRETE WireValue/WireRow/WireList seam types +
2901
- // per-component Handler_<comp> wrappers the runner takes. The consumer never uses this (it keeps the
2902
- // model native + supplies its own concrete WireValue + Handler_<comp>); it exists only so the test
2903
- // harness can byte-compare the STRUCT-only covered read against run_behavior. Same package as the module.
2924
+ // struct-native runner's result to a canonical Value for the equivalence pin, and carries the SCRIPTED
2925
+ // analog of the consumer's leaf transport symbols: free Leaf_<comp> funcs (same package as the covered
2926
+ // module, so its transport calls resolve) that drain a shared package-level scripted queue + the CONCRETE
2927
+ // WireValue/WireRow/WireList seam types. The consumer never uses this (it keeps the model native + supplies
2928
+ // its own concrete WireValue + transport funcs); it exists only so the test harness can byte-compare the
2929
+ // STRUCT-only covered read against run_behavior. Same package as the module.
2904
2930
  package behaviors
2905
2931
 
2906
2932
  import (
@@ -2927,17 +2953,17 @@ ${inDecoders}
2927
2953
 
2928
2954
  ${adapter}
2929
2955
 
2930
- // per-component CONCRETE handler wrappers (the runner takes one by value — embeds the shared queue).
2931
- ${handlerWrappers}
2932
-
2933
- // ScriptedNativeRaw method impls (one per covered node — the concrete Node_* seam returning WireValue).
2934
- ${methodImpls.join("\n\n")}
2956
+ // scripted leaf transport funcs (one per covered leaf — the free op-agnostic transport the covered runner
2957
+ // calls directly; test glue draining the shared package queue).
2958
+ ${transportFns.join("\n\n")}
2935
2959
 
2936
- // ObserveNativeRaw drives the struct-native runner and serializes to a canonical Value (test only). It
2937
- // takes the CONCRETE *ScriptedNativeRaw and wraps it per component in the runner's Handler_<comp> value —
2938
- // each enclosed RunNativeRawStruct_* call is a NON-generic call over a concrete handler (direct,
2939
- // devirtualized per-node method calls), never an interface or a generic dictionary.
2940
- func ObserveNativeRaw(name string, handlers *ScriptedNativeRaw, input *${PKG}.Obj) (${PKG}.Value, error) {
2960
+ // ObserveNativeRaw resets+fills the shared scripted queue from the per-case spec, then drives the covered
2961
+ // struct-native runner and serializes to a canonical Value (test only). No handler object is passed — the
2962
+ // runner calls the free Leaf_<comp> transport funcs above directly (same package).
2963
+ func ObserveNativeRaw(name string, spec *${PKG}.JObj, input *${PKG}.Obj) (${PKG}.Value, error) {
2964
+ if ferr := fillScripted(spec); ferr != nil {
2965
+ return nil, ferr
2966
+ }
2941
2967
  ${arms}
2942
2968
  return nil, ${PKG}.NewBehaviorFailure("UNKNOWN_ENTRY", "component '"+name+"' is not a covered read (fail-closed)")
2943
2969
  }