behavior-contracts 0.8.10 → 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.
@@ -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}}`);
@@ -1627,7 +1622,7 @@ function emitNativeRawRunner(comp, plan, flags, wire) {
1627
1622
  * (direct field assignment; $as refs read the over element's typed fields), and the result is a
1628
1623
  * native []T with NO boxed Value on any plane. The map is under the parent's produced gate (inline).
1629
1624
  */
1630
- function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, flags) {
1625
+ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, flags, leaf) {
1631
1626
  const m = node.map;
1632
1627
  const batched = m.batched === true;
1633
1628
  const hasInto = m.into !== undefined;
@@ -1635,6 +1630,7 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1635
1630
  const s = sanitize(node.id);
1636
1631
  const structName = portsStructName(comp.name, node.id);
1637
1632
  const batchStruct = `${structName}_batch`;
1633
+ const leafSym = resolveLeafSymbol(m.component, leaf);
1638
1634
  const arrRef = typedNodes.get(node.id);
1639
1635
  const elemGo = renderTypeRef(arrRef);
1640
1636
  const asName = m.as;
@@ -1717,7 +1713,9 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1717
1713
  // empty items => empty result (handler not called), matching run_behavior.
1718
1714
  lines.push(`${indent}if len(items_${s}) > 0 {`);
1719
1715
  lines.push(`${indent}\tbp_${s} := ${batchStruct}{Items: items_${s}}`);
1720
- 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})`);
1721
1719
  lines.push(`${indent}\tif mo_${s}Err != nil {`, `${indent}\t\treturn ${zeroOut}, opFailed(${JSON.stringify(node.id)}, "fail", mo_${s}Err)`, `${indent}\t}`);
1722
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}`);
1723
1721
  if (hasInto) {
@@ -1756,7 +1754,7 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1756
1754
  // Element Error Policy (scp-error.md): `skip` drops the failing element and proceeds (order is
1757
1755
  // preserved; the leaf keeps the Error Value it produced). `error` (default) promotes the element
1758
1756
  // Failure to the map's Component Failure, carrying the leaf's detail through.
1759
- 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 }))})`);
1760
1758
  if (m.elementPolicy === "skip") {
1761
1759
  lines.push(`${indent}\tif mo_${s}Err != nil {`, `${indent}\t\tcontinue`, `${indent}\t}`);
1762
1760
  }
@@ -1797,11 +1795,12 @@ function elemLocal(s) {
1797
1795
  * (STRUCTURAL — the connection items elem type already omits the implicitSource field), and wrap into
1798
1796
  * the connection struct {items, cursor:nil}. NO boxed Value on any plane. Byte-equal to run_behavior.
1799
1797
  */
1800
- function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut) {
1798
+ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, leaf) {
1801
1799
  const f = node.fanout;
1802
1800
  const s = sanitize(node.id);
1803
1801
  const structName = portsStructName(comp.name, node.id);
1804
1802
  const batchStruct = `${structName}_batch`;
1803
+ const leafSym = resolveLeafSymbol(f.component, leaf);
1805
1804
  const connRef = typedNodes.get(node.id);
1806
1805
  const elemRef = fanoutItemsElemRef(node, connRef, plan);
1807
1806
  const elemGo = renderTypeRef(elemRef);
@@ -1847,7 +1846,9 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut
1847
1846
  // the handler returns the aligned per-id element WIRES (one nilable WireValue per id); each present
1848
1847
  // body is de-boxed strictly INLINE (a de-box mismatch fails closed). A DANGLING id is a nil wire → the
1849
1848
  // zero element (empty dedupeKey), which the dangling drop below excludes.
1850
- 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})`);
1851
1852
  lines.push(`${indent}\tif fo_${s}Err != nil {`, `${indent}\t\treturn ${zeroOut}, opFailed(${JSON.stringify(node.id)}, "fail", fo_${s}Err)`, `${indent}\t}`);
1852
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}`);
1853
1854
  // ── THE ONE dedupe/drop (mirrors fanoutDedupDrop verbatim): first-seen dedupe by dedupeKey field;
@@ -2306,9 +2307,9 @@ func bcExpr_strGe(a, b string) bool { return bcExpr_cmpCP(a, b) >= 0 }`;
2306
2307
  * which lives OUTSIDE this module so the covered module stays literal whole-file zero. */
2307
2308
  function emitStructSurface(native) {
2308
2309
  return `// ComponentNamesNativeRaw — covered reads exposed on the combined struct-native path (declaration
2309
- // order). Each is driven via RunNativeRawStruct_<comp>(handlers, input) -> (T, error): a STRUCT
2310
- // return; the consumer keeps the model native (no Value serialization on the read hot path — the
2311
- // 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.
2312
2313
  var ComponentNamesNativeRaw = []string{${native.map((c) => JSON.stringify(c.name)).join(", ")}}`;
2313
2314
  }
2314
2315
  /** Minimal module header for a FULLY-covered module (bc#90 / runtime-free). A fully-covered module
@@ -2316,7 +2317,7 @@ var ComponentNamesNativeRaw = []string{${native.map((c) => JSON.stringify(c.name
2316
2317
  * mismatch Sprintf, `strings` for a concat builder, `sync` for a parallel stage). ExpectedSpecVersions
2317
2318
  * stays as a local `var` for provenance, but the old `dslcontracts.SpecVersions` skew `init()` is GONE
2318
2319
  * (change #5 — there is no runtime to skew against once the module is runtime-free). */
2319
- function emitMinimalHeader(ctx, needStrings, needSync, needFmt, needMath, needStrconv = false, wireImport) {
2320
+ function emitMinimalHeader(ctx, needStrings, needSync, needFmt, needMath, needStrconv = false, wireImport, leafImport) {
2320
2321
  const sv = ctx.specVersions;
2321
2322
  const imports = [];
2322
2323
  if (needFmt)
@@ -2333,6 +2334,10 @@ function emitMinimalHeader(ctx, needStrings, needSync, needFmt, needMath, needSt
2333
2334
  // WireValue/WireRow/WireList types (default: in-package, no import).
2334
2335
  if (wireImport !== undefined)
2335
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)}`);
2336
2341
  const importBlock = imports.length > 0 ? `\nimport (\n${imports.join("\n")}\n)\n` : "";
2337
2342
  return `// GENERATED by behavior-contracts (bc#90, go-typed-native — the RUNTIME-FREE covered read de-box) — DO NOT EDIT.
2338
2343
  // Input: portable component-graph IR only. Every component here is a COVERED READ (sequential typed
@@ -2359,6 +2364,7 @@ function emit(ctx) {
2359
2364
  // a fallible checked-arith helper call — determines whether the helper library + `math` import ship).
2360
2365
  goExprUsed.helpers = false;
2361
2366
  const wire = resolveGoWire(ctx);
2367
+ const leaf = ctx.leafTransport;
2362
2368
  // Emit the runners first so the nv* helper usage flags are known.
2363
2369
  const flags = { bind: false, field: false, cat: false, arr: false };
2364
2370
  const structs = [];
@@ -2397,7 +2403,7 @@ function emit(ctx) {
2397
2403
  const mm = emitMapElemMaterializers(c, typedNodes, plan);
2398
2404
  if (mm)
2399
2405
  elemCopiers.push(mm);
2400
- const r = emitNativeRawRunner(c, plan, flags, wire);
2406
+ const r = emitNativeRawRunner(c, plan, flags, wire, leaf);
2401
2407
  runnerCodes.push(r.code);
2402
2408
  }
2403
2409
  const structSurface = emitStructSurface(native);
@@ -2428,21 +2434,22 @@ function emit(ctx) {
2428
2434
  const needMath = goExprUsed.helpers;
2429
2435
  // `strconv` is imported iff a generated inline de-box parses a numeric field (int/float range check).
2430
2436
  const needStrconv = runnerCodes.some((c) => c.includes("strconv."));
2431
- 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);
2432
2438
  const banner = `// COMBINED READ layer (bc#90 — the RUNTIME-FREE read de-box; STRUCT-ONLY, FULLY-NATIVE surface). A
2433
2439
  // covered read is a strictly-sequential typed componentRef chain (point reads + relationKind:single
2434
2440
  // children), emitted ONLY here: each node builds a native ports struct by direct field assignment (every
2435
2441
  // port is a CONCRETE Go value — string / bool / []string projection / int64 limit — NO boxed Value, NO
2436
- // PortReader accessor); the runner takes the consumer's CONCRETE Handler_<comp> handler by
2437
- // value and calls h.Node_*(...) DIRECTLY (no interface, no generics — zero dynamic dispatch). Each Node_*
2438
- // takes a typed produced-aware 'bound' pointer and returns the node's result WIRE (a single ${wire.value});
2439
- // the runner de-boxes it INLINE (fully-unrolled probe/match — no decode helper, no output recursion) into
2440
- // the node's outType struct. The covered plane carries NO bc-runtime reference at all — failures use the
2441
- // LOCAL *BehaviorError (same codes, byte-equal to run_behavior). Exec is INLINE sequential (no plan driver)
2442
- // so a relation child reads the parent's REAL struct result via direct field access and the child-present
2443
- // decision is made from the real parent value — relationSingle / connection converge with run_behavior
2444
- // (fixes #323/#74). The exposed API is the STRUCT-returning RunNativeRawStruct_<comp> (the consumer keeps
2445
- // 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
2446
2453
  // boxing primitives OR for the bc-runtime package finds nothing, by design (bc#90/runtime-free).`;
2447
2454
  const sections = [
2448
2455
  banner,
@@ -2468,13 +2475,15 @@ function emit(ctx) {
2468
2475
  }
2469
2476
  /**
2470
2477
  * goTypedNativeObserve — the TEST-ONLY observe companion (a SEPARATE file in the SAME package as the
2471
- * covered module). It carries the typed->Value serializers (ser_*) + an ObserveNativeRaw dispatch
2472
- * that drives the module-private struct runner and serializes its result to a canonical Value for
2473
- * the equivalence pin. This lives OUTSIDE the covered module so the module stays literal whole-file
2474
- * zero (the ser_* NewObj is test glue, never on the consumer's read hot path). Emitted only for the
2475
- * 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.
2476
2485
  */
2477
- export function goTypedNativeObserve(ir, runtimeImport) {
2486
+ export function goTypedNativeObserve(ir, runtimeImport, leaf) {
2478
2487
  const components = ir.components;
2479
2488
  const native = components.filter(isNativeRaw);
2480
2489
  const plan = buildTypePlan(ir);
@@ -2491,7 +2500,7 @@ export function goTypedNativeObserve(ir, runtimeImport) {
2491
2500
  // decode the generic *Obj input into the CONCRETE In_<comp> struct (test glue — ONE decode at the
2492
2501
  // top, OUTSIDE the covered hot path; a REQUIRED declared input is present so an absent key is a
2493
2502
  // fail-closed decode error surfaced here, never on the native runner path).
2494
- 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}`;
2495
2504
  })
2496
2505
  .join("\n");
2497
2506
  // input decoders (TEST glue): generic *Obj -> concrete In_<comp>. Scalar fields read the typed value
@@ -2689,17 +2698,14 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
2689
2698
  return d.Kind, d.Model, d.Field, d.ExpectedType, d.ActualWireType, d.RawValue, true
2690
2699
  }`
2691
2700
  : "";
2692
- // Handler_<comp> wrapper types: the covered runner takes the CONCRETE per-component handler by value
2693
- // (non-generic). One scripted queue backs every component, so each Handler_<comp> embeds the shared
2694
- // *ScriptedNativeRaw — the Node_* methods (on *ScriptedNativeRaw) are promoted, so the runner's direct
2695
- // h.Node_*(...) call resolves to a concrete method (no interface, no dictionary). Test glue only.
2696
- const handlerWrappers = native
2697
- .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}`)
2698
- .join("\n\n");
2699
- // ── concrete scripted adapter (TEST glue): implements every Node_* method by draining a per-COMPONENT
2700
- // scripted-outcome queue and returning the scripted ok Value wrapped as a WireValue (the generic
2701
- // scripted source — a Value queue — meets the uniform CONCRETE wire seam). ──
2702
- 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();
2703
2709
  for (const c of native) {
2704
2710
  const typedNodes = new Map();
2705
2711
  for (const n of c.body)
@@ -2707,18 +2713,20 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
2707
2713
  typedNodes.set(n.id, "map" in n ? mapNodeArrRef(n, plan) : deriveTypeRef(n.outType, plan)); // #125: control-gate typeless; map は produced-array ref に正規化
2708
2714
  for (const n of c.body) {
2709
2715
  if ("cond" in n)
2710
- continue; // #108: cond has no handler method (pure Expression) — no scripted impl.
2711
- 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);
2712
2722
  if ("fanout" in n) {
2713
2723
  // fanout: return the aligned per-id element WIRES ([]*WireValue); a null aligned body is a
2714
2724
  // DANGLING id → nil (the covered runner maps it to the zero element).
2715
- const f = n.fanout;
2716
2725
  const portsT = `${portsStructName(c.name, n.id)}_batch`;
2717
- const foBoundT = boundGoType(n, c, typedNodes, plan);
2718
- methodImpls.push(`func (s *ScriptedNativeRaw) ${nodeMethodName(c.name, n.id)}(_ ${portsT}, _ ${foBoundT}) ([]*WireValue, error) {
2719
- src, ok := s.next(${JSON.stringify(f.component)})
2726
+ transportFns.push(`func ${sym}(_ ${portsT}) ([]*WireValue, error) {
2727
+ src, ok := nextScripted(${JSON.stringify(catalog)})
2720
2728
  if !ok {
2721
- return nil, unknownComponent(${JSON.stringify(f.component)})
2729
+ return nil, unknownComponent(${JSON.stringify(catalog)})
2722
2730
  }
2723
2731
  if src.isErr {
2724
2732
  return nil, leafFailure(src.err)
@@ -2740,14 +2748,12 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
2740
2748
  if ("map" in n) {
2741
2749
  // map: batched → one WIRE per element ([]WireValue); non-batched → one element WIRE (WireValue).
2742
2750
  const m = n.map;
2743
- const batched = m.batched === true;
2744
- const portsT = batched ? `${portsStructName(c.name, n.id)}_batch` : portsStructName(c.name, n.id);
2745
- const mapBoundT = boundGoType(n, c, typedNodes, plan);
2746
- if (batched) {
2747
- methodImpls.push(`func (s *ScriptedNativeRaw) ${nodeMethodName(c.name, n.id)}(_ ${portsT}, _ ${mapBoundT}) ([]WireValue, error) {
2748
- 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)})
2749
2755
  if !ok {
2750
- return nil, unknownComponent(${JSON.stringify(m.component)})
2756
+ return nil, unknownComponent(${JSON.stringify(catalog)})
2751
2757
  }
2752
2758
  if src.isErr {
2753
2759
  return nil, leafFailure(src.err)
@@ -2761,10 +2767,13 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
2761
2767
  }`);
2762
2768
  }
2763
2769
  else {
2764
- methodImpls.push(`func (s *ScriptedNativeRaw) ${nodeMethodName(c.name, n.id)}(_ ${portsT}, _ ${mapBoundT}) (WireValue, error) {
2765
- 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)})
2766
2775
  if !ok {
2767
- return WireValue{}, unknownComponent(${JSON.stringify(m.component)})
2776
+ return WireValue{}, unknownComponent(${JSON.stringify(catalog)})
2768
2777
  }
2769
2778
  if src.isErr {
2770
2779
  return WireValue{}, leafFailure(src.err)
@@ -2774,12 +2783,10 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
2774
2783
  }
2775
2784
  continue;
2776
2785
  }
2777
- // componentRef: return the whole result WIRE (one WireValue wrapping the scripted ok Value); the
2778
- // 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.
2779
2787
  const node = n;
2780
- const nodeBoundT = boundGoType(node, c, typedNodes, plan);
2781
- // echo (#129/#141 fixtures): the scripted leaf can ECHO an input PORT back as its result wire, so the
2782
- // 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);
2783
2790
  const echoBranches = [];
2784
2791
  if (ref.kind === "named") {
2785
2792
  const decl = findDecl(plan, ref.name);
@@ -2796,26 +2803,27 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
2796
2803
  }
2797
2804
  if (portGo === recordGo) {
2798
2805
  // the port IS the whole record → echo it DIRECTLY (matching run_behavior's plain echo:port).
2799
- 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}`);
2800
2807
  }
2801
2808
  else if (fieldGo !== null && field !== undefined && portGo === fieldGo) {
2802
2809
  // a scalar port wraps into the record's single field ({v: ports.X}).
2803
- 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}`);
2804
2811
  }
2805
2812
  }
2806
2813
  }
2807
2814
  else if (ref.kind === "arr" && Object.prototype.hasOwnProperty.call(node.ports, "items")) {
2808
2815
  // #129: an arr node with an `items` port echoes the NATIVE port array (serialized to a Value array)
2809
2816
  // so the node→leaf array dataflow test is non-vacuous.
2810
- 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}`);
2811
2818
  }
2812
2819
  const canEcho = echoBranches.length > 0;
2813
- 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(", ");
2814
2822
  const echoBlock = canEcho ? `${echoBranches.join("\n")}\n` : "";
2815
- methodImpls.push(`func (s *ScriptedNativeRaw) ${nodeMethodName(c.name, node.id)}(${portsParam} ${portsStructName(c.name, node.id)}, _ ${nodeBoundT}) (WireValue, error) {
2816
- src, ok := s.next(${JSON.stringify(node.component)})
2823
+ transportFns.push(`func ${sym}(${params}) (WireValue, error) {
2824
+ src, ok := nextScripted(${JSON.stringify(catalog)})
2817
2825
  if !ok {
2818
- return WireValue{}, unknownComponent(${JSON.stringify(node.component)})
2826
+ return WireValue{}, unknownComponent(${JSON.stringify(catalog)})
2819
2827
  }
2820
2828
  if src.isErr {
2821
2829
  return WireValue{}, leafFailure(src.err)
@@ -2835,87 +2843,90 @@ type scriptSrc struct {
2835
2843
  ok ${PKG}.Value
2836
2844
  }
2837
2845
 
2838
- // ScriptedNativeRaw — the CONCRETE test handler: its Node_* methods drain a per-COMPONENT scripted queue
2839
- // and return the ok Value wrapped as a WireValue (the covered runner de-boxes it inline). Each runner
2840
- // takes a Handler_<comp> value that embeds this, so the Node_* calls stay fully concrete (no interface).
2841
- // EXPORTED so the runner glue (a separate package) can name it.
2842
- type ScriptedNativeRaw struct {
2843
- mu sync.Mutex
2844
- queues map[string][]scriptSrc
2845
- seen int
2846
- }
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
+ )
2847
2854
 
2848
- // NewScriptedNativeRaw builds the concrete test handler from the JSON handlers spec (the SAME shape
2849
- // the reference scriptedHandlers reads): { "<component>": {ok|error} | [ {ok|error}, … ] }. Each
2850
- // component's ok Value is DecodeValue'd once here (test glue); the per-node method decodes it into the
2851
- // concrete row. Returns the handler + any decode error (surfaced by the runner as a fatal).
2852
- func NewScriptedNativeRaw(spec *${PKG}.JObj) (*ScriptedNativeRaw, error) {
2853
- queues := map[string][]scriptSrc{}
2854
- if spec != nil {
2855
- for _, comp := range spec.Keys {
2856
- var entries []${PKG}.JNode
2857
- switch t := spec.Vals[comp].(type) {
2858
- case []${PKG}.JNode:
2859
- entries = t
2860
- default:
2861
- entries = []${PKG}.JNode{t}
2862
- }
2863
- for _, e := range entries {
2864
- eo, _ := e.(*${PKG}.JObj)
2865
- // #129: an \`echo\` directive names an input port to echo back (mirrors the reference
2866
- // scriptedHandlers' \`echo === "items"\`). It is drained together with the ok payload.
2867
- echo := ""
2868
- if echoNode, has := eo.Get("echo"); has {
2869
- echo, _ = echoNode.(string)
2870
- // normalize echo:port to the port NAME X so a de-box handler's echo comparison fires;
2871
- // echo:items already names the port directly.
2872
- if echo == "port" {
2873
- if portNode, hasPort := eo.Get("port"); hasPort {
2874
- echo, _ = portNode.(string)
2875
- }
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)
2876
2886
  }
2877
2887
  }
2878
- if okNode, has := eo.Get("ok"); has {
2879
- val, derr := ${PKG}.DecodeValue(okNode)
2880
- if derr != nil {
2881
- return nil, derr
2882
- }
2883
- queues[comp] = append(queues[comp], scriptSrc{ok: val, echo: echo})
2884
- continue
2888
+ }
2889
+ if okNode, has := eo.Get("ok"); has {
2890
+ val, derr := ${PKG}.DecodeValue(okNode)
2891
+ if derr != nil {
2892
+ return derr
2885
2893
  }
2886
- ev, _ := eo.Get("error")
2887
- es, _ := ev.(string)
2888
- queues[comp] = append(queues[comp], scriptSrc{isErr: true, err: es})
2894
+ scriptedQueues[comp] = append(scriptedQueues[comp], scriptSrc{ok: val, echo: echo})
2895
+ continue
2889
2896
  }
2897
+ ev, _ := eo.Get("error")
2898
+ es, _ := ev.(string)
2899
+ scriptedQueues[comp] = append(scriptedQueues[comp], scriptSrc{isErr: true, err: es})
2890
2900
  }
2891
2901
  }
2892
- return &ScriptedNativeRaw{queues: queues}, nil
2902
+ return nil
2893
2903
  }
2894
2904
 
2895
- // next drains one scripted outcome for a component (last entry repeats — mirrors the reference
2896
- // scriptedHandlers), returns ok=false when the component has no scripted queue (fail-closed). The
2897
- // bc#87 parallel-stage runner calls Node_* from multiple goroutines, so the drain is mutex-guarded.
2898
- func (s *ScriptedNativeRaw) next(component string) (scriptSrc, bool) {
2899
- s.mu.Lock()
2900
- defer s.mu.Unlock()
2901
- s.seen++
2902
- 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]
2903
2913
  if !ok || len(q) == 0 {
2904
2914
  return scriptSrc{}, false
2905
2915
  }
2906
2916
  if len(q) > 1 {
2907
2917
  v := q[0]
2908
- s.queues[component] = q[1:]
2918
+ scriptedQueues[component] = q[1:]
2909
2919
  return v, true
2910
2920
  }
2911
2921
  return q[0], true
2912
2922
  }`;
2913
2923
  return `// GENERATED test-only observe companion (bc#77) — NOT part of the covered module. Serializes the
2914
- // struct-native runner's result to a canonical Value for the equivalence pin, and carries the CONCRETE
2915
- // scripted test handler (ScriptedNativeRaw) + the CONCRETE WireValue/WireRow/WireList seam types +
2916
- // per-component Handler_<comp> wrappers the runner takes. The consumer never uses this (it keeps the
2917
- // model native + supplies its own concrete WireValue + Handler_<comp>); it exists only so the test
2918
- // 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.
2919
2930
  package behaviors
2920
2931
 
2921
2932
  import (
@@ -2942,17 +2953,17 @@ ${inDecoders}
2942
2953
 
2943
2954
  ${adapter}
2944
2955
 
2945
- // per-component CONCRETE handler wrappers (the runner takes one by value — embeds the shared queue).
2946
- ${handlerWrappers}
2947
-
2948
- // ScriptedNativeRaw method impls (one per covered node — the concrete Node_* seam returning WireValue).
2949
- ${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")}
2950
2959
 
2951
- // ObserveNativeRaw drives the struct-native runner and serializes to a canonical Value (test only). It
2952
- // takes the CONCRETE *ScriptedNativeRaw and wraps it per component in the runner's Handler_<comp> value —
2953
- // each enclosed RunNativeRawStruct_* call is a NON-generic call over a concrete handler (direct,
2954
- // devirtualized per-node method calls), never an interface or a generic dictionary.
2955
- 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
+ }
2956
2967
  ${arms}
2957
2968
  return nil, ${PKG}.NewBehaviorFailure("UNKNOWN_ENTRY", "component '"+name+"' is not a covered read (fail-closed)")
2958
2969
  }