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.
@@ -173,13 +173,34 @@ function pascal(s) {
173
173
  function portsStructName(compName, nodeId) {
174
174
  return `PortsNR${pascal(compName)}${pascal(nodeId)}`;
175
175
  }
176
- /** HandlerNR<Comp> — the per-component concrete handler trait name (one node_* method per node). */
177
- function handlerTraitName(compName) {
178
- return `HandlerNR${pascal(compName)}`;
176
+ /**
177
+ * resolveLeafSymbol — the op-agnostic transport symbol a covered leaf (= catalog component) is called
178
+ * through at its execution point. A consumer-supplied override (`leafTransport.symbols[component]`) wins;
179
+ * else the in-package DEFAULT convention `leaf_<sanitizedComponent>`. This is the ONE place leaf→symbol
180
+ * resolution lives (SSoT) — the runner call sites, the import block, and the test observe transport fns
181
+ * all read it. There is no per-node handler indirection: the leaf is one transport, not one method per node.
182
+ */
183
+ function resolveLeafSymbol(component, leaf) {
184
+ return leaf?.symbols[component] ?? `leaf_${sanitize(component)}`;
185
+ }
186
+ /**
187
+ * portFieldSpread — the covered node's port fields, in declared `Object.keys(ports)` order, each carrying
188
+ * its native ports-struct field name, its Copy-ness (borrow vs move), and its rendered field type. The ONE
189
+ * place the transport-call port spread is derived (SSoT): a runner call site spreads `<var>.<f>` (Copy) /
190
+ * `&<var>.<f>` (non-Copy); the test observe transport fn declares params of the matching type. Types come
191
+ * from the SAME `compilePortNode` lowering `emitPortsStruct` uses, so the spread can never disagree with
192
+ * the field types the ports struct declares.
193
+ */
194
+ function portFieldSpread(ports, comp, plan, typedNodes, asBinding) {
195
+ const opts = asBinding !== undefined ? { asBinding, asBase: asBinding.name } : undefined;
196
+ return Object.keys(ports).map((pn) => {
197
+ const c = compilePortNode(ports[pn], comp, plan, typedNodes, (h) => typedNodes.has(h), `port '${pn}' of node '${comp.name}'`, opts);
198
+ return { field: portFieldName(pn), isCopy: typeRefIsCopy(c.ref), renderedType: c.renderedType ?? renderTypeRef(c.ref) };
199
+ });
179
200
  }
180
- /** node_<id> — the concrete per-node handler method name. */
181
- function nodeMethodName(nodeId) {
182
- return `node_${nodeId.replace(/[^A-Za-z0-9_]/g, "_").toLowerCase()}`;
201
+ /** leafCallArgs — the spread transport-call arguments for a ports-struct var (Copy→move, non-Copy→borrow). */
202
+ function leafCallArgs(varExpr, spread) {
203
+ return spread.map((p) => (p.isCopy ? `${varExpr}.${p.field}` : `&${varExpr}.${p.field}`)).join(", ");
183
204
  }
184
205
  /** InNR<Comp> — the concrete per-component input struct name (fields = inputPorts). */
185
206
  function inStructName(compName) {
@@ -766,65 +787,6 @@ function boundRustType(node, typedNodes, plan) {
766
787
  return `Option<${renderTypeRef(bfRef.inner)}>`;
767
788
  return `Option<${renderTypeRef(bfRef)}>`;
768
789
  }
769
- /**
770
- * emitHandlerTrait — the per-component `HandlerNR<Comp>` trait: one concrete-typed `node_*` method per
771
- * covered node. A componentRef node method takes the node's native ports struct + the typed produced-aware
772
- * `bound` (change #3 — NO boxed Value) and returns Option<RawRowNR…> (None = unknown component,
773
- * fail-closed). A covered map node's method takes the batch ports struct (batched) or the element ports
774
- * struct (per-element). This is the fully-concrete, runtime-free replacement for the NativeRawComponentExec
775
- * seam.
776
- */
777
- function emitHandlerTrait(comp, typedNodes, plan, ap) {
778
- // bc#97 (increment 2): async I/O model is PER-TERMINAL-NODE. A node whose terminal handler is declared
779
- // async gets an `async fn node_*` (the consumer's impl returns a future the runner awaits at the call
780
- // site); a sync terminal stays plain `fn node_*` (called directly, no await). Mixed sync+async in one
781
- // trait is fine. `async fn` needs NO external runtime to compile — the future is `async fn` sugar over
782
- // std, so the covered module stays runtime-free either way. Uniform ioModel:'async' ⇒ every method
783
- // async (byte-identical to increment-1); ioModel unset/'sync' ⇒ every method plain `fn` (pre-#97).
784
- const fnKwFor = (nodeId) => (ap.nodeIsAsync(nodeId) ? "async fn" : "fn");
785
- const lines = [];
786
- lines.push(`// ${handlerTraitName(comp.name)} — the CONCRETE per-component handler seam: one typed method`);
787
- lines.push(`// per covered node (native ports struct IN, WIRE value OUT). No generic boxed-ports / boxed-value`);
788
- lines.push(`// / dynamic accessor crosses the covered boundary — the consumer implements each node_* by`);
789
- lines.push(`// returning its own wire payload as a WireValue; the generated inline de-box turns that into the`);
790
- lines.push(`// node's concrete native result (see INTEGRATION.md §6).`);
791
- lines.push(`pub trait ${handlerTraitName(comp.name)} {`);
792
- // every covered node returns the consumer's WIRE (a single associated `Wire: WireValue`) — the producer's
793
- // datum at the node's result-consumption point; the generated inline de-box classifies it against the
794
- // STATICALLY declared type. A batched map returns one wire per element (Vec); a fanout returns the aligned
795
- // per-id wires (Vec<Option<Wire>> — None = a DANGLING id). The `+ Send` bound lets the wire cross the
796
- // parallel-stage runner's scoped fan-out threads.
797
- const hasHandler = comp.body.some((n) => !("cond" in n));
798
- if (hasHandler)
799
- lines.push(` type Wire: WireValue + Send;`);
800
- for (const n of comp.body) {
801
- if ("cond" in n)
802
- continue; // #108: a cond node has no handler method (pure Expression).
803
- const method = nodeMethodName(n.id);
804
- const fnKw = fnKwFor(n.id);
805
- const bt = boundRustType(n, typedNodes, plan);
806
- if ("fanout" in n) {
807
- // fanout (v3): one batched dispatch of the deduped id list, returning the aligned element WIRES the
808
- // runner de-boxes then dedupe/drops. Each aligned position is Option<Self::Wire> — None = a DANGLING
809
- // id (the runner maps it to the zero elem row).
810
- const portsT = `${portsStructName(comp.name, n.id)}Batch`;
811
- lines.push(` ${fnKw} ${method}(&self, ports: &${portsT}, bound: ${bt}) -> Result<Vec<Option<Self::Wire>>, BehaviorError>;`);
812
- continue;
813
- }
814
- if ("map" in n) {
815
- const m = n.map;
816
- const batched = m.batched === true;
817
- const portsT = batched ? `${portsStructName(comp.name, n.id)}Batch` : portsStructName(comp.name, n.id);
818
- // a map returns the element WIRE(s): batched → Vec<Self::Wire>, non-batched → Self::Wire.
819
- const retT = batched ? "Vec<Self::Wire>" : "Self::Wire";
820
- lines.push(` ${fnKw} ${method}(&self, ports: &${portsT}, bound: ${bt}) -> Result<${retT}, BehaviorError>;`);
821
- continue;
822
- }
823
- lines.push(` ${fnKw} ${method}(&self, ports: &${portsStructName(comp.name, n.id)}, bound: ${bt}) -> Result<Self::Wire, BehaviorError>;`);
824
- }
825
- lines.push(`}`);
826
- return lines.join("\n");
827
- }
828
790
  /** mapElemMaterializerName — the augmented-element copier for a covered map...into node.
829
791
  * QUALIFIED by component name: two components may each carry a map node at the SAME
830
792
  * recorder-scan index (e.g. both `…authorFollows` and `…groupsNested` have a map at `n4`),
@@ -1334,7 +1296,7 @@ function emitPortInit(pn, expr, comp, plan, typedNodes, isPrior, opts) {
1334
1296
  function rustScalar(s) {
1335
1297
  return s === "string" ? "String" : s === "int" ? "i64" : s === "float" ? "f64" : "bool";
1336
1298
  }
1337
- function emitNativeRawRunner(comp, plan, ap) {
1299
+ function emitNativeRawRunner(comp, plan, ap, leaf) {
1338
1300
  const ep = execPlan(comp);
1339
1301
  const order = ep.order;
1340
1302
  const hasConcurrency = ep.parallelStageOf.size > 0;
@@ -1423,28 +1385,22 @@ function emitNativeRawRunner(comp, plan, ap) {
1423
1385
  const inParam = readsInput ? "in_" : "_in_";
1424
1386
  const lines = [];
1425
1387
  lines.push(`// run_native_raw_struct_${fn} — the STRUCT-RETURNING combined read (bc#77/#87/#94): the fully`);
1426
- lines.push(`// de-plumbed CONCRETE path. Generic over the per-component CONCRETE ${handlerTraitName(comp.name)} trait,`);
1427
- lines.push(`// whose node_* methods take the node's native ports struct and return the node's result WIRE`);
1428
- lines.push(`// (Self::Wire: WireValue). The runner builds each ports struct by direct native construction (a`);
1429
- lines.push(`// simple string port lowers to a native Rust expr), dispatches the concrete node_* method, and`);
1430
- lines.push(`// de-boxes the result wire INLINE (match wire.as_*() { … } fully unrolled — no decode helper) into`);
1388
+ lines.push(`// de-plumbed CONCRETE path. At each covered node's execution point it calls the op-agnostic leaf`);
1389
+ lines.push(`// TRANSPORT symbol DIRECTLY (the node's port fields spread — no per-node handler indirection) and`);
1390
+ lines.push(`// de-boxes the returned wire INLINE (match wire.as_*() { … } fully unrolled — no decode helper) into`);
1431
1391
  lines.push(`// the node's outType struct cell — no boxed handler result, no generic enum crossing, no dispatch on a dynamic value on the covered plane. Node`);
1432
1392
  lines.push(`// results are typed struct cells; a relation child reads the parent's REAL struct result via`);
1433
1393
  lines.push(`// direct field access (child-present decision from the real parent value — relationSingle /`);
1434
1394
  lines.push(`// connection converge). A real-concurrency stage (bc#87) is static parallel orchestration —`);
1435
- lines.push(`// scoped worker threads (bounded by the static plan.concurrency) call the concrete node_*`);
1436
- lines.push(`// method; preflight + interpret are committed in ascending index order so the value / op`);
1437
- lines.push(`// multiset / failure precedence byte-match run_behavior. The output is a typed struct/value`);
1438
- lines.push(`// assembled by struct literal + field access — the consumer keeps it native.`);
1439
- const bound = hasConcurrency ? `<H: ${handlerTraitName(comp.name)} + Sync>` : `<H: ${handlerTraitName(comp.name)}>`;
1440
- // bc#97: async propagation (uniform) — if the terminal handlers are async, every handler call awaits,
1395
+ lines.push(`// scoped worker threads (bounded by the static plan.concurrency) call the transport; preflight +`);
1396
+ lines.push(`// interpret are committed in ascending index order so the value / op multiset / failure`);
1397
+ lines.push(`// precedence byte-match run_behavior. The output is a typed struct/value assembled by struct`);
1398
+ lines.push(`// literal + field access — the consumer keeps it native.`);
1399
+ // bc#97: async propagation (uniform) — if the terminal handlers are async, every transport call awaits,
1441
1400
  // so the runner is itself `async fn` and returns a future the (already-async) consumer awaits. Sync
1442
1401
  // default emits `pub fn` exactly as before (byte-identical).
1443
1402
  const fnKw = isAsync ? "pub async fn" : "pub fn";
1444
- // #108: a component whose body is ALL cond nodes dispatches NO handler — bind `_handlers` (clippy-clean).
1445
- const dispatchesHandler = comp.body.some((n) => "map" in n || "fanout" in n || "component" in n);
1446
- lines.push(`${fnKw} run_native_raw_struct_${fn}${bound}(`);
1447
- lines.push(` ${dispatchesHandler ? "handlers" : "_handlers"}: &H,`);
1403
+ lines.push(`${fnKw} run_native_raw_struct_${fn}(`);
1448
1404
  lines.push(` ${inParam}: ${inStructName(comp.name)},`);
1449
1405
  lines.push(`) -> Result<${outTy}, BehaviorError> {`);
1450
1406
  for (const k of order.keys()) {
@@ -1462,16 +1418,16 @@ function emitNativeRawRunner(comp, plan, ap) {
1462
1418
  const i = order[k];
1463
1419
  const stage = ep.parallelStageOf.get(i);
1464
1420
  if (stage !== undefined && stage[0] === i) {
1465
- lines.push(emitParallelStageArm(comp, stage, k, ep.concurrency, metas, typedNodes, plan, priorNodeAt));
1421
+ lines.push(emitParallelStageArm(comp, stage, k, ep.concurrency, metas, typedNodes, plan, priorNodeAt, leaf));
1466
1422
  k += stage.length - 1;
1467
1423
  continue;
1468
1424
  }
1469
1425
  if ("fanout" in comp.body[i]) {
1470
- lines.push(emitFanoutArm(comp, comp.body[i], k, typedNodes, plan, priorNodeAt, ap.nodeIsAsync(comp.body[i].id)));
1426
+ lines.push(emitFanoutArm(comp, comp.body[i], k, typedNodes, plan, priorNodeAt, leaf, ap.nodeIsAsync(comp.body[i].id)));
1471
1427
  continue;
1472
1428
  }
1473
1429
  if ("map" in comp.body[i]) {
1474
- lines.push(emitMapArm(comp, comp.body[i], k, typedNodes, plan, priorNodeAt, ap.nodeIsAsync(comp.body[i].id)));
1430
+ lines.push(emitMapArm(comp, comp.body[i], k, typedNodes, plan, priorNodeAt, leaf, ap.nodeIsAsync(comp.body[i].id)));
1475
1431
  continue;
1476
1432
  }
1477
1433
  // #108: a cond node — pure Expression (no handler). Compile via the runtime-free NativeExprCompiler.
@@ -1494,11 +1450,10 @@ function emitNativeRawRunner(comp, plan, ap) {
1494
1450
  closers.unshift(`${indent}}`);
1495
1451
  indent += " ";
1496
1452
  if (node.bindField !== undefined && parentIsGate) {
1497
- // #125: a when(...) control-gate parent. gate の bindField:"ok" は run_behavior では成立時 `true`
1498
- // / 不成立時 `null`(→ null-binding skip)。native では produced_<gate>(= gate の `if`)が既に
1499
- // その skip を担うので、ここに来た時点で gate は成立。bound は skip の sentinel(データキーでは
1500
- // ない — 子の ports は実データ親を参照する)として、非 None の `Option<String>` を渡す。
1501
- lines.push(`${indent}let bound_${s}: ${boundRustType(node, typedNodes, plan)} = Some("ok".to_string());`);
1453
+ // #125: a when(...) control-gate parent. produced_<gate> (= the gate's `if`) ALREADY carries the
1454
+ // skip, so past it the gate held — there is no further skip to gate here. The bindField:"ok" was
1455
+ // only a sentinel formerly passed to the handler; the leaf transport no longer receives `bound`, so
1456
+ // NO bound local is emitted (the child ports read the real data parent, not the gate).
1502
1457
  }
1503
1458
  else if (node.bindField !== undefined) {
1504
1459
  // bind (change #3 — typed produced-aware bound): read the parent struct field DIRECTLY (typed
@@ -1526,15 +1481,19 @@ function emitNativeRawRunner(comp, plan, ap) {
1526
1481
  for (const pn of portNames) {
1527
1482
  inits.push(emitPortInit(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k)));
1528
1483
  }
1529
- const boundArg = node.bindField !== undefined ? `bound_${s}` : "None";
1530
1484
  // bc#97: derived per-node await — this point-read's future is awaited HERE (its result-consumption
1531
1485
  // point) iff THIS node's terminal handler is async. A sync handler in the same async runner is called
1532
1486
  // directly (no `.await`). The runner being `async fn` does not force every call site to await.
1533
1487
  const awaitSfx = ap.nodeIsAsync(node.id) ? ".await" : "";
1488
+ // DIRECT leaf transport call: the resolved op-agnostic symbol, the node's port fields spread (Copy→move,
1489
+ // non-Copy→borrow). `bound` is NOT passed — it is BC's internal produced/skip gate, already enforced by
1490
+ // the surrounding `if bound_<s>.is_some()` / `if produced_<parent>` guards; the leaf never receives it.
1491
+ const call = `${resolveLeafSymbol(node.component, leaf)}(${leafCallArgs(`ports_${s}`, portFieldSpread(node.ports, comp, plan, typedNodes))})${awaitSfx}`;
1534
1492
  lines.push(`${indent}let ports_${s} = ${structName} { ${inits.join(", ")} };`);
1535
- // uniform seam: every covered node returns a single result WIRE (Self::Wire); the inline de-box
1536
- // (renderResultDeBox) classifies it against the STATICALLY declared result type and produces the
1537
- // structured Error Value on a mismatch (byte-equal codes to run_behavior's outType check, so ≡ holds).
1493
+ // uniform seam: every covered node returns a single result WIRE; the inline de-box (renderResultDeBox)
1494
+ // classifies it against the STATICALLY declared result type and produces the structured Error Value on a
1495
+ // mismatch (byte-equal codes to run_behavior's outType check, so ≡ holds). The wire's concrete type is
1496
+ // inferred from the transport's return type (no annotation) — the wire trait methods resolve.
1538
1497
  if (meta.policy === "continue") {
1539
1498
  // continue: a failed node (leaf failure OR de-box mismatch) produces no Port — the downstream Skip
1540
1499
  // propagation is what `continue` means. The inline de-box's mismatch breaks the labeled block (a
@@ -1542,7 +1501,7 @@ function emitNativeRawRunner(comp, plan, ap) {
1542
1501
  // are always 'fail' policy today — this arm is defensive.)
1543
1502
  const label = `debox_${s}`;
1544
1503
  const contFail = (e) => `break '${label} Err(${e})`;
1545
- lines.push(`${indent}if let Ok(wire_${s}) = handlers.${nodeMethodName(node.id)}(&ports_${s}, ${boundArg})${awaitSfx} {`);
1504
+ lines.push(`${indent}if let Ok(wire_${s}) = ${call} {`);
1546
1505
  lines.push(`${indent} let decoded_${s}: Result<${renderTypeRef(ref)}, BehaviorError> = '${label}: {`);
1547
1506
  lines.push(`${indent} Ok(${renderResultDeBox(ref, `wire_${s}`, node.id, plan, `${indent} `, contFail)})`);
1548
1507
  lines.push(`${indent} };`);
@@ -1554,7 +1513,7 @@ function emitNativeRawRunner(comp, plan, ap) {
1554
1513
  }
1555
1514
  else {
1556
1515
  const policyLit = meta.policy === "retry" ? "retry' policy (exhausted)" : "fail' policy";
1557
- lines.push(`${indent}let wire_${s} = match handlers.${nodeMethodName(node.id)}(&ports_${s}, ${boundArg})${awaitSfx} {`);
1516
+ lines.push(`${indent}let wire_${s} = match ${call} {`);
1558
1517
  lines.push(`${indent} Ok(r) => r,`);
1559
1518
  lines.push(`${indent} Err(e) => return Err(BehaviorError { code: "OP_FAILED".to_string(), message: format!("operation '{}' failed under '${policyLit}: {}", ${rustStrLit(node.id)}, e.message), detail: e.detail }),`);
1560
1519
  lines.push(`${indent}};`);
@@ -1597,7 +1556,7 @@ function emitNativeRawRunner(comp, plan, ap) {
1597
1556
  * 3. COMMIT (ascending index): interpret policy + move the concrete row into the outType cell —
1598
1557
  * lowest-index failure wins.
1599
1558
  */
1600
- function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes, plan, priorNodeAt) {
1559
+ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes, plan, priorNodeAt, leaf) {
1601
1560
  const lines = [];
1602
1561
  const ids = stage.map((i) => comp.body[i].id);
1603
1562
  lines.push(` // ── bc#87 real-concurrency stage {${ids.map((x) => rustStrLit(x)).join(", ")}} — static parallel`);
@@ -1639,27 +1598,23 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1639
1598
  const parentIsGate = node.parent !== undefined && isControlGate(comp.body.find((b) => b.id === node.parent));
1640
1599
  let ind = " ";
1641
1600
  const closers = [];
1642
- if (node.bindField !== undefined) {
1643
- // declared at stage scope so the worker closure captures it; defaults None (skip).
1644
- lines.push(` let mut bound_${s}: ${boundRustType(node, typedNodes, plan)} = None;`);
1645
- }
1601
+ // bound is now purely the preflight skip-gate condition (the leaf transport no longer receives it), so
1602
+ // it is a plain local inside the produced block — NOT a stage-scoped mut (nothing captures it) and no
1603
+ // dead None init. A control-gate parent needs no bound at all (produced_<gate> already carries the skip).
1646
1604
  if (gated) {
1647
1605
  lines.push(` let mut ports_${s}: Option<${structName}> = None;`);
1648
1606
  lines.push(`${ind}if produced_${sanitize(node.parent)}.get() {`);
1649
1607
  closers.unshift(`${ind}}`);
1650
1608
  ind += " ";
1651
- if (node.bindField !== undefined && parentIsGate) {
1652
- lines.push(`${ind}bound_${s} = Some("ok".to_string());`);
1653
- }
1654
- else if (node.bindField !== undefined) {
1609
+ if (node.bindField !== undefined && !parentIsGate) {
1655
1610
  const parentRef = typedNodes.get(node.parent);
1656
1611
  const { expr: bfExpr, ref: bfRef } = typedFieldAccess(`${typedCell(node.parent)}.borrow()`, parentRef, [node.bindField], plan);
1657
1612
  if (bfRef.kind === "opt") {
1658
- lines.push(`${ind}bound_${s} = ${bfExpr}.clone();`);
1613
+ lines.push(`${ind}let bound_${s}: ${boundRustType(node, typedNodes, plan)} = ${bfExpr}.clone();`);
1659
1614
  }
1660
1615
  else {
1661
1616
  const owned = bfRef.kind === "scalar" && bfRef.scalar === "string" ? `(${bfExpr}).clone()` : `*(${bfExpr})`;
1662
- lines.push(`${ind}bound_${s} = Some(${owned});`);
1617
+ lines.push(`${ind}let bound_${s}: ${boundRustType(node, typedNodes, plan)} = Some(${owned});`);
1663
1618
  }
1664
1619
  lines.push(`${ind}if bound_${s}.is_some() {`);
1665
1620
  closers.unshift(`${ind}}`);
@@ -1679,19 +1634,19 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1679
1634
  for (const c of closers)
1680
1635
  lines.push(c);
1681
1636
  }
1682
- // 2) DISPATCH (bounded scoped threads). Share `&H` (concrete trait; H: Sync). Each worker calls the
1683
- // concrete node_* method for its member's CONCRETE ports and stores the concrete row in its slot.
1684
- // #125: the fan-out (slots / jobs / workers) spans the COMPONENTREF members only — a control gate
1685
- // dispatches no handler (committed in preflight above), so it is not a scoped-thread job.
1637
+ // 2) DISPATCH (bounded scoped threads). Each worker calls the leaf TRANSPORT directly for its member's
1638
+ // CONCRETE ports and stores the returned wire in its slot. #125: the fan-out (slots / jobs / workers)
1639
+ // spans the COMPONENTREF members only — a control gate dispatches no handler (committed in preflight
1640
+ // above), so it is not a scoped-thread job. The wire's concrete type is inferred from the transport's
1641
+ // return (Result<_, BehaviorError>); it impls Send so it crosses the scoped threads.
1686
1642
  const nMembers = refMembers.length;
1687
1643
  const boundN = Math.min(concurrency, nMembers);
1688
1644
  const jobsVar = `jobs_${sanitize(comp.name)}`;
1689
- const hWire = `<H as ${handlerTraitName(comp.name)}>::Wire`;
1690
1645
  for (const i of refMembers) {
1691
1646
  const s = sanitize(comp.body[i].id);
1692
- // every member's thread returns the result WIRE (a single Self::Wire); the ascending COMMIT phase
1693
- // de-boxes it (so the wire — not the decode — is what crosses the scoped threads).
1694
- lines.push(` let slot_${s}: std::sync::Mutex<Option<Result<${hWire}, BehaviorError>>> = std::sync::Mutex::new(None);`);
1647
+ // every member's thread returns the result WIRE; the ascending COMMIT phase de-boxes it (so the wire —
1648
+ // not the decode — is what crosses the scoped threads).
1649
+ lines.push(` let slot_${s}: std::sync::Mutex<Option<Result<_, BehaviorError>>> = std::sync::Mutex::new(None);`);
1695
1650
  }
1696
1651
  lines.push(` let mut ${jobsVar}: Vec<usize> = Vec::new();`);
1697
1652
  refMembers.forEach((i, slot) => {
@@ -1710,10 +1665,12 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1710
1665
  refMembers.forEach((i, slot) => {
1711
1666
  const node = comp.body[i];
1712
1667
  const s = sanitize(node.id);
1713
- const boundArg = node.bindField !== undefined ? `bound_${s}.clone()` : "None";
1668
+ // DIRECT leaf transport call — the node's port fields spread off the preflight-built ports struct. No
1669
+ // `bound` (BC's internal produced/skip gate is already applied in preflight — the leaf never sees it).
1670
+ const call = `${resolveLeafSymbol(node.component, leaf)}(${leafCallArgs("ports", portFieldSpread(node.ports, comp, plan, typedNodes))})`;
1714
1671
  lines.push(` ${slot} => {`);
1715
1672
  lines.push(` let ports = ports_${s}.as_ref().expect("runnable member has ports");`);
1716
- lines.push(` let row = handlers.${nodeMethodName(node.id)}(ports, ${boundArg});`);
1673
+ lines.push(` let row = ${call};`);
1717
1674
  lines.push(` *slot_${s}.lock().unwrap() = Some(row);`);
1718
1675
  lines.push(` }`);
1719
1676
  });
@@ -1768,7 +1725,7 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1768
1725
  * - #93 shape 2: NON-batched map...into — dispatch ONCE PER ELEMENT (N physical requests), into per element.
1769
1726
  * - #93 shape 3: BATCHED map NO into — dispatch once, collect each element from the concrete element row.
1770
1727
  */
1771
- function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt,
1728
+ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf,
1772
1729
  // bc#97: whether THIS map node's terminal handler is async (derived per-node) — awaits the batched /
1773
1730
  // per-element handler call at its consumption point iff true. Sync map handlers are called directly.
1774
1731
  isAsync = false) {
@@ -1780,6 +1737,7 @@ isAsync = false) {
1780
1737
  const s = sanitize(node.id);
1781
1738
  const structName = portsStructName(comp.name, node.id);
1782
1739
  const batch = `${structName}Batch`;
1740
+ const leafSym = resolveLeafSymbol(m.component, leaf);
1783
1741
  // #108: over element type + the OWNED over-Vec expression (prior-node arr OR input array w/ elemType).
1784
1742
  const { elemRef: overElemRef, overExpr } = mapOverElemInfo(comp, node, typedNodes, plan);
1785
1743
  const elemMat = mapElemMaterializerName(comp.name, node.id);
@@ -1848,7 +1806,10 @@ isAsync = false) {
1848
1806
  lines.push(`${indent}if !items_${s}.is_empty() {`);
1849
1807
  lines.push(`${indent} let want_${s} = items_${s}.len();`);
1850
1808
  lines.push(`${indent} let bp_${s} = ${batch} { items: items_${s} };`);
1851
- lines.push(`${indent} let row_${s} = match handlers.${nodeMethodName(node.id)}(&bp_${s}, None)${awaitSfx} {`);
1809
+ // DIRECT transport call — the batched dispatch takes the CONCRETE batch ports struct (shape unchanged
1810
+ // from the removed trait method; only the call target changes). Returns the aligned per-element wires
1811
+ // (Vec<Wire>). No `bound` (batched maps carry none).
1812
+ lines.push(`${indent} let row_${s} = match ${leafSym}(&bp_${s})${awaitSfx} {`);
1852
1813
  lines.push(`${indent} Ok(r) => r,`);
1853
1814
  lines.push(`${indent} Err(e) => return Err(op_failed(${rustStrLit(node.id)}, "fail", e)),`);
1854
1815
  lines.push(`${indent} };`);
@@ -1883,8 +1844,9 @@ isAsync = false) {
1883
1844
  lines.push(l);
1884
1845
  // Element Error Policy (scp-error.md): `skip` drops the failing element and proceeds (order is
1885
1846
  // preserved; the leaf keeps the Error Value it produced). `error` (default) promotes the element
1886
- // Failure to the map's Component Failure, carrying the leaf's detail through.
1887
- lines.push(`${indent} let er_${s} = match handlers.${nodeMethodName(node.id)}(&ep_${s}, None)${awaitSfx} {`);
1847
+ // Failure to the map's Component Failure, carrying the leaf's detail through. DIRECT transport call —
1848
+ // the element ports fields spread (resolved with the `$as` binding, exactly the element ports struct).
1849
+ lines.push(`${indent} let er_${s} = match ${leafSym}(${leafCallArgs(`ep_${s}`, portFieldSpread(m.ports, comp, plan, typedNodes, { name: asName, ref: overElemRef, plan }))})${awaitSfx} {`);
1888
1850
  lines.push(`${indent} Ok(r) => r,`);
1889
1851
  if (m.elementPolicy === "skip") {
1890
1852
  lines.push(`${indent} Err(_) => continue,`);
@@ -1917,12 +1879,13 @@ isAsync = false) {
1917
1879
  * dangling (empty dedupeKey ≡ the interpreter's null/absent-key body), implicitSource strip (STRUCTURAL:
1918
1880
  * the elem type already omits it), wrap into the connection struct { items, cursor: None }.
1919
1881
  */
1920
- function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, isAsync = false) {
1882
+ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, leaf, isAsync = false) {
1921
1883
  const f = node.fanout;
1922
1884
  const awaitSfx = isAsync ? ".await" : "";
1923
1885
  const s = sanitize(node.id);
1924
1886
  const structName = portsStructName(comp.name, node.id);
1925
1887
  const batch = `${structName}Batch`;
1888
+ const leafSym = resolveLeafSymbol(f.component, leaf);
1926
1889
  const connRef = typedNodes.get(node.id);
1927
1890
  const elemRef = fanoutItemsElemRef(node, connRef, plan);
1928
1891
  const elemName = renderTypeRef(elemRef);
@@ -1965,7 +1928,10 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, isAsync
1965
1928
  lines.push(`${indent}if !pi_${s}.is_empty() {`);
1966
1929
  lines.push(`${indent} let want_${s} = pi_${s}.len();`);
1967
1930
  lines.push(`${indent} let bp_${s} = ${batch} { items: pi_${s} };`);
1968
- lines.push(`${indent} let row_${s} = match handlers.${nodeMethodName(node.id)}(&bp_${s}, None)${awaitSfx} {`);
1931
+ // DIRECT transport call — the batched fanout dispatch takes the CONCRETE batch ports struct (shape
1932
+ // unchanged; only the call target changes). Returns the aligned per-id element wires
1933
+ // (Vec<Option<Wire>> — None = a DANGLING id). No `bound`.
1934
+ lines.push(`${indent} let row_${s} = match ${leafSym}(&bp_${s})${awaitSfx} {`);
1969
1935
  lines.push(`${indent} Ok(r) => r,`);
1970
1936
  lines.push(`${indent} Err(e) => return Err(op_failed(${rustStrLit(node.id)}, "fail", e)),`);
1971
1937
  lines.push(`${indent} };`);
@@ -2133,8 +2099,8 @@ function valueLeafProduced(expr, ref, expected) {
2133
2099
  function emitStructSurface(native) {
2134
2100
  const names = native.map((c) => rustStrLit(c.name));
2135
2101
  return `// COMPONENT_NAMES_NATIVE_RAW — covered reads exposed on the combined struct-native path. Each is
2136
- // driven via run_native_raw_struct_<comp>(handlers, in_) -> Result<T, BehaviorError>: a STRUCT return
2137
- // (the consumer builds the CONCRETE InNR_<comp> input + implements the CONCRETE HandlerNR<comp> trait).
2102
+ // driven via run_native_raw_struct_<comp>(in_) -> Result<T, BehaviorError>: a STRUCT return (the consumer
2103
+ // builds the CONCRETE InNR_<comp> input + supplies the op-agnostic leaf transport symbols the runner calls).
2138
2104
  // See INTEGRATION.md §6.
2139
2105
  pub const COMPONENT_NAMES_NATIVE_RAW: [&str; ${names.length}] = [${names.join(", ")}];`;
2140
2106
  }
@@ -2193,8 +2159,8 @@ ${emitStructSurface([])}
2193
2159
  const defaults = emitDefaults(plan);
2194
2160
  // #108: reset the native-expr helper-usage accumulator (set by the cond/guard compiler).
2195
2161
  rustExprUsed.helpers = false;
2162
+ const leaf = ctx.leafTransport;
2196
2163
  const structs = [];
2197
- const handlerTraits = [];
2198
2164
  const inStructs = [];
2199
2165
  const elemMaterializers = [];
2200
2166
  // every covered node returns a WireValue the inline de-box classifies — the wire seam (probe enums +
@@ -2217,34 +2183,52 @@ ${emitStructSurface([])}
2217
2183
  else
2218
2184
  structs.push(emitPortsStruct(c, n, undefined, plan, typedNodes)); // #129: typedNodes for prior-node arr leaf ports.
2219
2185
  }
2220
- handlerTraits.push(emitHandlerTrait(c, typedNodes, plan, asyncPlans.get(c.name)));
2221
2186
  inStructs.push(emitInStruct(c, plan));
2222
2187
  const mm = emitMapElemMaterializers(c, typedNodes, plan);
2223
2188
  if (mm)
2224
2189
  elemMaterializers.push(mm);
2225
2190
  }
2226
- const runners = native.map((c) => emitNativeRawRunner(c, plan, asyncPlans.get(c.name))).join("\n\n");
2191
+ const runners = native.map((c) => emitNativeRawRunner(c, plan, asyncPlans.get(c.name), leaf)).join("\n\n");
2227
2192
  const structSurface = emitStructSurface(native);
2193
+ // Leaf transport import (SSoT resolution via resolveLeafSymbol): if the consumer names an import module,
2194
+ // bring the DISTINCT resolved transport symbols into the covered module's scope. Omitted → the symbols
2195
+ // resolve where the module is used (the covered module emits no `use`). cond nodes have no leaf.
2196
+ const importBlock = (() => {
2197
+ if (leaf?.import === undefined)
2198
+ return undefined;
2199
+ const syms = new Set();
2200
+ for (const c of native)
2201
+ for (const n of c.body) {
2202
+ const component = "fanout" in n ? n.fanout.component : "map" in n ? n.map.component : "cond" in n ? undefined : n.component;
2203
+ if (component !== undefined)
2204
+ syms.add(resolveLeafSymbol(component, leaf));
2205
+ }
2206
+ if (syms.size === 0)
2207
+ return undefined;
2208
+ return `// op-agnostic leaf transport symbols (consumer-supplied) — called directly at each covered node.\nuse ${leaf.import}::{${[...syms].sort().join(", ")}};`;
2209
+ })();
2228
2210
  // (nonNative.length === 0 is guaranteed here — the fail-closed guard above threw otherwise.)
2229
2211
  const banner = `#![allow(dead_code, unused_imports, non_snake_case)]
2230
2212
  // GENERATED by behavior-contracts (bc#90, rust-typed-native — the RUNTIME-FREE read de-box; STRUCT-ONLY,
2231
2213
  // FULLY-NATIVE). A covered read is a strictly-sequential typed componentRef chain (point reads +
2232
- // relationKind:single children), emitted ONLY as a STRUCT-returning runner GENERIC over a per-component
2233
- // CONCRETE handler trait (HandlerNR<comp>): native ports struct IN (direct construction — every port is a
2234
- // CONCRETE Rust value: String / bool / Vec<&str> projection / i64 limit — NO boxed Value, NO by-name
2235
- // accessor); the handler takes a typed produced-aware 'bound' Option and returns the node's result WIRE
2236
- // (Self::Wire: WireValue), and the runner de-boxes it INLINE (fully-unrolled probe/match — no decode helper,
2237
- // no output recursion) into the node's outType struct. The covered plane carries NO bc-runtime reference at all — failures use the LOCAL
2238
- // BehaviorError (same codes, byte-equal to run_behavior). INLINE sequential (no plan driver) so a relation
2239
- // child reads the parent's REAL struct result via direct field access and the child-present decision is
2240
- // made from the real parent value — relationSingle / connection converge with run_behavior (fixes
2241
- // #323/#74). The exposed API is run_native_raw_struct_<comp>(handlers, in_) over the CONCRETE InNR_<comp>
2242
- // input struct + the CONCRETE HandlerNR<comp> trait (the consumer builds/implements both, keeping the
2243
- // model native). This module is FULLY NATIVE: a naive grep for boxing primitives OR for the bc-runtime
2244
- // crate finds nothing, by design (bc#90 / runtime-free).
2214
+ // relationKind:single children), emitted ONLY as a STRUCT-returning runner that calls the op-agnostic leaf
2215
+ // TRANSPORT symbol DIRECTLY at each covered node's execution point: native ports struct IN (direct
2216
+ // construction — every port is a CONCRETE Rust value: String / bool / Vec<&str> projection / i64 limit —
2217
+ // NO boxed Value, NO by-name accessor); the transport is called with the node's port fields spread and
2218
+ // returns the node's result WIRE (a value implementing WireValue), and the runner de-boxes it INLINE
2219
+ // (fully-unrolled probe/match — no decode helper, no output recursion) into the node's outType struct.
2220
+ // There is NO per-node handler indirection — a leaf is ONE transport, not one method per authored node.
2221
+ // The covered plane carries NO bc-runtime reference at all — failures use the LOCAL BehaviorError (same
2222
+ // codes, byte-equal to run_behavior). INLINE sequential (no plan driver) so a relation child reads the
2223
+ // parent's REAL struct result via direct field access and the child-present decision is made from the real
2224
+ // parent value — relationSingle / connection converge with run_behavior (fixes #323/#74). The exposed API
2225
+ // is run_native_raw_struct_<comp>(in_) over the CONCRETE InNR_<comp> input struct; the consumer supplies
2226
+ // the leaf transport symbols (default in-scope names leaf_<comp>, or a leafTransport import). This module
2227
+ // is FULLY NATIVE: a naive grep for boxing primitives OR for the bc-runtime crate finds nothing, by design.
2245
2228
  use std::cell::RefCell;`;
2246
2229
  const sections = [
2247
2230
  banner,
2231
+ importBlock,
2248
2232
  `// Local concrete failure type (runtime-free) — a covered runner returns Result<T, BehaviorError> over\n// THIS local type instead of a bc-runtime failure, so the fully-covered module imports ZERO bc runtime.\n${emitBehaviorErrorType()}`,
2249
2233
  decls || undefined,
2250
2234
  defaults || undefined,
@@ -2256,7 +2240,6 @@ use std::cell::RefCell;`;
2256
2240
  ? `// Native ports structs (one per componentRef node; typed per the static port type — CONCRETE).\n${structs.filter((r) => r.trim().length > 0).join("\n\n")}`
2257
2241
  : undefined,
2258
2242
  `// CONCRETE per-component input structs (fields = inputPorts).\n${inStructs.join("\n\n")}`,
2259
- `// CONCRETE per-component handler traits (one node_* method per node — native ports IN, WIRE value OUT).\n${handlerTraits.join("\n\n")}`,
2260
2243
  anyWire
2261
2244
  ? `// strict de-box wire seam — the consumer implements WireValue (+ WireRow/WireList reached via\n// as_row/as_list) over its wire payload (variant classification); the generated INLINE de-box owns\n// strictness (required/optional, present/absent, error assembly, fail-closed). Concrete enums +\n// monomorphized traits — no boxed value, no trait object, no heap allocation crosses the seam.\n${emitRustProbeWireTypes()}`
2262
2245
  : undefined,
@@ -2270,14 +2253,15 @@ use std::cell::RefCell;`;
2270
2253
  }
2271
2254
  /**
2272
2255
  * rustTypedNativeObserve — the TEST-ONLY observe companion (a submodule string the test harness writes
2273
- * alongside the covered module). It carries the typed->Value serializers (ser_*) + a CONCRETE scripted
2274
- * handler (ScriptedNativeRaw) that implements every HandlerNR<comp> trait by decoding a scripted Value
2275
- * into the concrete per-node row, + an observe_native_raw dispatch that decodes the generic input into the
2276
- * concrete InNR_<comp>, drives the module-private struct runner, and serializes its result to a canonical
2277
- * Value for the equivalence pin. Lives OUTSIDE the covered module so the module stays literal whole-file
2278
- * zero (the ser_* / decode helpers are test glue, never on the consumer's read hot path).
2256
+ * alongside the covered module). It carries the typed->Value serializers (ser_*) + the SCRIPTED analog of
2257
+ * the consumer's leaf transport symbols: free \`leaf_<comp>\` fns that drain a shared scripted static and
2258
+ * return the scripted wire (so the covered module's transport calls resolve to real fns), + an
2259
+ * observe_native_raw dispatch that fills the static from the per-case spec, decodes the generic input into
2260
+ * the concrete InNR_<comp>, drives the module-private struct runner, and serializes its result to a
2261
+ * canonical Value for the equivalence pin. Lives OUTSIDE the covered module so the module stays literal
2262
+ * whole-file zero (the ser_* / decode helpers are test glue, never on the consumer's read hot path).
2279
2263
  */
2280
- export function rustTypedNativeObserve(ir, ioModel = "sync") {
2264
+ export function rustTypedNativeObserve(ir, ioModel = "sync", leaf) {
2281
2265
  const components = ir.components;
2282
2266
  const native = components.filter(isNativeRaw);
2283
2267
  const plan = buildTypePlan(ir);
@@ -2465,36 +2449,38 @@ impl WireList for ScriptedWireList {
2465
2449
  }
2466
2450
  }`
2467
2451
  : "";
2468
- // ── concrete scripted handler: implements every HandlerNR<comp> trait by returning the scripted ok
2469
- // Value as a WireValue (the generic scripted-source queue meets the uniform wire seam). ──
2470
- const traitImpls = [];
2452
+ // ── op-agnostic leaf TRANSPORT fns (TEST glue) — the scripted analog of the consumer's transport
2453
+ // symbols. ONE free `leaf_<component>` per DISTINCT covered leaf (catalog component) in the IR (a
2454
+ // per-module leaf has one consistent shape — verified), draining the shared scripted-outcome static and
2455
+ // returning the scripted wire in EXACTLY the shape the removed per-node trait method returned. bc#87
2456
+ // parallel scoped threads share the static (Mutex-guarded); cases run sequentially so a shared static is
2457
+ // fine. Echo (#129/#141) reads the spread port params directly. ──
2458
+ const transportFns = [];
2459
+ const emittedLeaf = new Set();
2460
+ const drainStmt = (catalog, echoBind) => `let (is_err, err, ok, ${echoBind}) = next_scripted(${rustStrLit(catalog)}).ok_or_else(|| unknown_component(${rustStrLit(catalog)}))?;\n if is_err {\n return Err(leaf_failure(err));\n }`;
2461
+ const spreadParams = (spread) => spread.map((p) => `${p.field}: ${p.isCopy ? p.renderedType : `&${p.renderedType}`}`).join(", ");
2471
2462
  for (const c of native) {
2472
2463
  const ap = asyncPlans.get(c.name);
2473
- // the scripted impl's node_* is `async fn` iff the trait's is (same per-node derivation).
2474
- const fnKwFor = (nodeId) => (ap.nodeIsAsync(nodeId) ? "async fn" : "fn");
2475
2464
  const typedNodes = new Map();
2476
2465
  for (const n of c.body)
2477
2466
  if (!isControlGate(n))
2478
2467
  typedNodes.set(n.id, "map" in n ? mapNodeArrRef(n, plan) : deriveTypeRef(n.outType, plan)); // #125: control-gate typeless; map は produced-array ref に正規化
2479
- const methods = [];
2480
2468
  for (const n of c.body) {
2481
2469
  if ("cond" in n)
2482
- continue; // #108: a cond node has no handler method (pure Expression) — no scripted impl.
2483
- const ref = typedNodes.get(n.id);
2484
- const fnKw = fnKwFor(n.id);
2485
- // bc#90 / runtime-free: the scripted impl's `_bound` param mirrors the trait's typed produced-aware
2486
- // Option<K> (NOT a boxed Value) — computed per node so the impl signature matches the trait.
2487
- const bt = boundRustType(n, typedNodes, plan);
2470
+ continue; // #108: a cond node has no leaf (pure Expression) — no transport fn.
2471
+ const catalog = "fanout" in n ? n.fanout.component : "map" in n ? n.map.component : n.component;
2472
+ if (emittedLeaf.has(catalog))
2473
+ continue; // per-module a leaf has ONE consistent shape — emit once.
2474
+ emittedLeaf.add(catalog);
2475
+ const sym = resolveLeafSymbol(catalog, leaf);
2476
+ // async iff this catalog leaf's terminal handler is async (consistent per catalog component).
2477
+ const fnKw = ap.nodeIsAsync(n.id) ? "pub async fn" : "pub fn";
2488
2478
  if ("fanout" in n) {
2489
2479
  // fanout: return the aligned per-id element WIRES (Vec<Option<ScriptedWireValue>>); a null aligned
2490
2480
  // body is a DANGLING id → None (the covered runner maps it to the zero element).
2491
- const f = n.fanout;
2492
2481
  const portsT = `${portsStructName(c.name, n.id)}Batch`;
2493
- methods.push(` ${fnKw} ${nodeMethodName(n.id)}(&self, _ports: &${portsT}, _bound: ${bt}) -> Result<Vec<Option<ScriptedWireValue>>, BehaviorError> {
2494
- let (is_err, err, ok, _echo) = self.next(${rustStrLit(f.component)}).ok_or_else(|| unknown_component(${rustStrLit(f.component)}))?;
2495
- if is_err {
2496
- return Err(leaf_failure(err));
2497
- }
2482
+ transportFns.push(`${fnKw} ${sym}(_batch: &${portsT}) -> Result<Vec<Option<ScriptedWireValue>>, BehaviorError> {
2483
+ ${drainStmt(catalog, "_echo")}
2498
2484
  let arr = match ok { Some(Value::Arr(a)) => a, _ => Vec::new() };
2499
2485
  let wires = arr
2500
2486
  .into_iter()
@@ -2510,35 +2496,28 @@ impl WireList for ScriptedWireList {
2510
2496
  if ("map" in n) {
2511
2497
  // map: batched → one WIRE per element (Vec<ScriptedWireValue>); non-batched → one element WIRE.
2512
2498
  const m = n.map;
2513
- const batched = m.batched === true;
2514
- const portsT = batched ? `${portsStructName(c.name, n.id)}Batch` : portsStructName(c.name, n.id);
2515
- if (batched) {
2516
- methods.push(` ${fnKw} ${nodeMethodName(n.id)}(&self, _ports: &${portsT}, _bound: ${bt}) -> Result<Vec<ScriptedWireValue>, BehaviorError> {
2517
- let (is_err, err, ok, _echo) = self.next(${rustStrLit(m.component)}).ok_or_else(|| unknown_component(${rustStrLit(m.component)}))?;
2518
- if is_err {
2519
- return Err(leaf_failure(err));
2520
- }
2499
+ if (m.batched === true) {
2500
+ const portsT = `${portsStructName(c.name, n.id)}Batch`;
2501
+ transportFns.push(`${fnKw} ${sym}(_batch: &${portsT}) -> Result<Vec<ScriptedWireValue>, BehaviorError> {
2502
+ ${drainStmt(catalog, "_echo")}
2521
2503
  let arr = match ok { Some(Value::Arr(a)) => a, _ => Vec::new() };
2522
2504
  let wires = arr.into_iter().map(ScriptedWireValue::new).collect();
2523
2505
  Ok(wires)
2524
2506
  }`);
2525
2507
  }
2526
2508
  else {
2527
- methods.push(` ${fnKw} ${nodeMethodName(n.id)}(&self, _ports: &${portsT}, _bound: ${bt}) -> Result<ScriptedWireValue, BehaviorError> {
2528
- let (is_err, err, ok, _echo) = self.next(${rustStrLit(m.component)}).ok_or_else(|| unknown_component(${rustStrLit(m.component)}))?;
2529
- if is_err {
2530
- return Err(leaf_failure(err));
2531
- }
2509
+ const { elemRef: overElemRef } = mapOverElemInfo(c, n, typedNodes, plan);
2510
+ const params = spreadParams(portFieldSpread(m.ports, c, plan, typedNodes, { name: m.as, ref: overElemRef, plan }));
2511
+ transportFns.push(`${fnKw} ${sym}(${params}) -> Result<ScriptedWireValue, BehaviorError> {
2512
+ ${drainStmt(catalog, "_echo")}
2532
2513
  Ok(ScriptedWireValue::new(ok.unwrap_or(Value::Null)))
2533
2514
  }`);
2534
2515
  }
2535
2516
  continue;
2536
2517
  }
2537
- // componentRef: return the whole result WIRE (one ScriptedWireValue wrapping the scripted ok Value);
2538
- // the covered runner's INLINE de-box classifies it. A real consumer returns its own wire payload.
2518
+ // componentRef (point read): spread port fields; supports echo (#129/#141) reading the port params.
2539
2519
  const node = n;
2540
- // echo (#129/#141 fixtures): the scripted leaf can ECHO an input PORT back as its result wire, so the
2541
- // input-port value flows into the de-boxed result and the runtime non-vacuity asserts survive.
2520
+ const ref = typedNodes.get(n.id);
2542
2521
  const echoBranches = [];
2543
2522
  if (ref.kind === "named") {
2544
2523
  const decl = findDecl(plan, ref.name);
@@ -2555,12 +2534,12 @@ impl WireList for ScriptedWireList {
2555
2534
  }
2556
2535
  if (portRust === recordRust) {
2557
2536
  // the port IS the whole record → echo it DIRECTLY (matching run_behavior's plain echo:port).
2558
- const own = typeRefIsCopy(ref) ? `ports.${portFieldName(pn)}` : `ports.${portFieldName(pn)}.clone()`;
2537
+ const own = typeRefIsCopy(ref) ? `${portFieldName(pn)}` : `${portFieldName(pn)}.clone()`;
2559
2538
  echoBranches.push(` if echo == ${rustStrLit(pn)} {\n let tv = ${own};\n return Ok(ScriptedWireValue::new(${serializeTyped("tv", ref, plan)}));\n }`);
2560
2539
  }
2561
2540
  else if (fieldRust !== null && field !== undefined && portRust === fieldRust) {
2562
2541
  // a scalar port wraps into the record's single field ({v: ports.X}).
2563
- const own = typeRefIsCopy(field.type) ? `ports.${portFieldName(pn)}` : `ports.${portFieldName(pn)}.clone()`;
2542
+ const own = typeRefIsCopy(field.type) ? `${portFieldName(pn)}` : `${portFieldName(pn)}.clone()`;
2564
2543
  echoBranches.push(` if echo == ${rustStrLit(pn)} {\n let tv = ${own};\n return Ok(ScriptedWireValue::new(Value::Obj(vec![(${rustStrLit(field.name)}.to_string(), ${serializeTyped("tv", field.type, plan)})])));\n }`);
2565
2544
  }
2566
2545
  }
@@ -2569,23 +2548,16 @@ impl WireList for ScriptedWireList {
2569
2548
  // #129: an arr node with an `items` port echoes the NATIVE port array (serialized element-by-element
2570
2549
  // into a Value::Arr) so the node→leaf array dataflow test is non-vacuous.
2571
2550
  const elemRef = ref.elem;
2572
- echoBranches.push(` if echo == "items" {\n let tv = Value::Arr(ports.${portFieldName("items")}.iter().map(|e| { let ev = e.clone(); ${serializeTyped("ev", elemRef, plan)} }).collect());\n return Ok(ScriptedWireValue::new(tv));\n }`);
2551
+ echoBranches.push(` if echo == "items" {\n let tv = Value::Arr(${portFieldName("items")}.iter().map(|e| { let ev = e.clone(); ${serializeTyped("ev", elemRef, plan)} }).collect());\n return Ok(ScriptedWireValue::new(tv));\n }`);
2573
2552
  }
2574
2553
  const canEcho = echoBranches.length > 0;
2575
- const portsParam = canEcho ? "ports" : "_ports";
2576
- const okBind = canEcho ? "(is_err, err, ok, echo)" : "(is_err, err, ok, _echo)";
2554
+ const params = spreadParams(portFieldSpread(node.ports, c, plan, typedNodes));
2577
2555
  const echoBlock = canEcho ? `${echoBranches.join("\n")}\n` : "";
2578
- methods.push(` ${fnKw} ${nodeMethodName(node.id)}(&self, ${portsParam}: &${portsStructName(c.name, node.id)}, _bound: ${bt}) -> Result<ScriptedWireValue, BehaviorError> {
2579
- let ${okBind} = self.next(${rustStrLit(node.component)}).ok_or_else(|| unknown_component(${rustStrLit(node.component)}))?;
2580
- if is_err {
2581
- return Err(leaf_failure(err));
2582
- }
2556
+ transportFns.push(`${fnKw} ${sym}(${params}) -> Result<ScriptedWireValue, BehaviorError> {
2557
+ ${drainStmt(catalog, canEcho ? "echo" : "_echo")}
2583
2558
  ${echoBlock} Ok(ScriptedWireValue::new(ok.unwrap_or(Value::Null)))
2584
2559
  }`);
2585
2560
  }
2586
- const cHasHandler = c.body.some((n) => !("cond" in n));
2587
- const wireAssoc = cHasHandler ? ` type Wire = ScriptedWireValue;\n` : "";
2588
- traitImpls.push(`impl ${handlerTraitName(c.name)} for ScriptedNativeRaw {\n${wireAssoc}${methods.join("\n")}\n}`);
2589
2561
  }
2590
2562
  const arms = native
2591
2563
  .map((c) => {
@@ -2598,80 +2570,80 @@ ${echoBlock} Ok(ScriptedWireValue::new(ok.unwrap_or(Value::Null)))
2598
2570
  // bc#97: an async runner returns a Future — drive it to completion with the std-only block-on
2599
2571
  // (bc_block_on) so observe_native_raw keeps its SYNC external signature (the harness is unchanged).
2600
2572
  // The scripted async node_* return ready values, so the future needs no real executor / no runtime.
2601
- const runnerCall = `super::run_native_raw_struct_${sanitize(c.name)}(handlers, in_)`;
2573
+ const runnerCall = `super::run_native_raw_struct_${sanitize(c.name)}(in_)`;
2602
2574
  const driven = asyncPlans.get(c.name).runnerIsAsync ? `bc_block_on(${runnerCall})` : runnerCall;
2603
2575
  return ` ${rustStrLit(c.name)} => {\n let in_ = decode_${inStructName(c.name)}(input).map_err(to_rt_err)?;\n let tv = ${driven}.map_err(to_rt_err)?;\n Ok(${ser})\n }`;
2604
2576
  })
2605
2577
  .join("\n");
2606
- // the scripted handler is passed as `&ScriptedNativeRaw`; the observe entry takes `&ScriptedNativeRaw`
2607
- // directly (the harness constructs it). Sync is inherent (the queues live behind a Mutex, seen behind
2608
- // an atomic) so a concurrency stage runs it in parallel.
2609
- const adapter = `// ScriptedNativeRaw — the CONCRETE test handler: it satisfies every HandlerNR<comp> trait by draining a
2610
- // per-COMPONENT scripted-outcome queue and decoding the scripted ok Value into the concrete row struct.
2611
- // The decode (decode_row_*) is generated (it knows the concrete row type), so the runner stays fully
2612
- // concrete. Sync (queues behind a Mutex, the probe counter an atomic) so a bc#87 stage parallelizes it.
2613
- pub struct ScriptedNativeRaw {
2614
- queues: std::sync::Mutex<std::collections::HashMap<String, (Vec<serde_json::Value>, bool)>>,
2615
- #[allow(dead_code)]
2616
- seen: std::sync::atomic::AtomicUsize,
2617
- }
2578
+ // the scripted-outcome source is a MODULE-LEVEL static (Mutex<Option<HashMap>> + AtomicUsize), NOT a
2579
+ // per-call handler object: the free transport fns drain it, and observe_native_raw resets+fills it from
2580
+ // the per-case handlers spec before driving the runner. A static (not thread_local) so the bc#87 parallel
2581
+ // scoped threads — which call the transport fns concurrently — share it (Mutex-guarded). Cases run
2582
+ // sequentially in the harness, so one shared static per case is fine.
2583
+ const adapter = `// SCRIPTED_QUEUES — the shared scripted-outcome source the free leaf transport fns drain (TEST glue).
2584
+ // { "<component>": (queue, single) }. reset+filled per case by observe_native_raw. \`Mutex::new(None)\` is
2585
+ // a const initializer (no LazyLock/OnceLock needed). SCRIPTED_SEEN mirrors the old probe counter.
2586
+ static SCRIPTED_QUEUES: std::sync::Mutex<Option<std::collections::HashMap<String, (Vec<serde_json::Value>, bool)>>> =
2587
+ std::sync::Mutex::new(None);
2588
+ #[allow(dead_code)]
2589
+ static SCRIPTED_SEEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2618
2590
 
2619
- impl ScriptedNativeRaw {
2620
- // build from the JSON handlers spec: { "<component>": {ok|error} | [ {ok|error}, … ] }.
2621
- pub fn new(spec: &serde_json::Map<String, serde_json::Value>) -> Self {
2622
- let mut queues = std::collections::HashMap::new();
2623
- for (name, raw) in spec {
2624
- let (items, single) = match raw {
2625
- serde_json::Value::Array(a) => (a.clone(), false),
2626
- other => (vec![other.clone()], true),
2627
- };
2628
- queues.insert(name.clone(), (items, single));
2629
- }
2630
- ScriptedNativeRaw {
2631
- queues: std::sync::Mutex::new(queues),
2632
- seen: std::sync::atomic::AtomicUsize::new(0),
2633
- }
2591
+ // fill_scripted — reset + load the shared static from the JSON handlers spec: { "<component>": {ok|error}
2592
+ // | [ {ok|error}, … ] }.
2593
+ fn fill_scripted(spec: &serde_json::Map<String, serde_json::Value>) {
2594
+ let mut map = std::collections::HashMap::new();
2595
+ for (name, raw) in spec {
2596
+ let (items, single) = match raw {
2597
+ serde_json::Value::Array(a) => (a.clone(), false),
2598
+ other => (vec![other.clone()], true),
2599
+ };
2600
+ map.insert(name.clone(), (items, single));
2634
2601
  }
2602
+ *SCRIPTED_QUEUES.lock().unwrap() = Some(map);
2603
+ SCRIPTED_SEEN.store(0, std::sync::atomic::Ordering::SeqCst);
2604
+ }
2635
2605
 
2636
- // drain one scripted outcome for a component (last entry repeats — mirrors the reference scripted
2637
- // handlers); None when the component has no scripted queue. Returns (is_error, err,
2638
- // ok_value, echo). The bc#87 parallel-stage runner calls node_* from multiple threads, so the drain
2639
- // is Mutex-guarded. #129: \`echo\` carries the reference scriptedHandlers' \`echo\` directive (e.g.
2640
- // "items") so a scripted node can ECHO a named input PORT back — used to make the node→leaf array
2641
- // dataflow test non-vacuous (the leaf returns its \`items\` port; a dropped/boxed array diverges).
2642
- fn next(&self, component: &str) -> Option<(bool, String, Option<Value>, String)> {
2643
- self.seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2644
- let mut queues = self.queues.lock().unwrap();
2645
- let (queue, single) = queues.get_mut(component)?;
2646
- let raw = if *single || queue.len() <= 1 { queue[0].clone() } else { queue.remove(0) };
2647
- // normalize echo:port to the port NAME X so a de-box handler's echo comparison fires;
2648
- // echo:items already names the port directly.
2649
- let echo = {
2650
- let e = raw.get("echo").and_then(|e| e.as_str()).unwrap_or("");
2651
- if e == "port" { raw.get("port").and_then(|p| p.as_str()).unwrap_or("").to_string() } else { e.to_string() }
2652
- };
2653
- if let Some(okv) = raw.get("ok") {
2654
- let v = behavior_contracts::decode_value(okv).expect("decode ok");
2655
- Some((false, String::new(), Some(v), echo))
2656
- } else {
2657
- let e = raw.get("error").and_then(|e| e.as_str()).unwrap_or("").to_string();
2658
- Some((true, e, None, echo))
2659
- }
2606
+ // next_scripted — drain one scripted outcome for a component (last entry repeats — mirrors the reference
2607
+ // scripted handlers); None when the component has no scripted queue. Returns (is_error, err, ok_value,
2608
+ // echo). The bc#87 parallel-stage runner calls the transport fns from multiple threads, so the drain is
2609
+ // Mutex-guarded. #129: \`echo\` carries the reference scriptedHandlers' \`echo\` directive (e.g. "items")
2610
+ // so a scripted node can ECHO a named input PORT back — used to make the node→leaf array dataflow test
2611
+ // non-vacuous (the leaf returns its \`items\` port; a dropped/boxed array diverges).
2612
+ fn next_scripted(component: &str) -> Option<(bool, String, Option<Value>, String)> {
2613
+ SCRIPTED_SEEN.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2614
+ let mut guard = SCRIPTED_QUEUES.lock().unwrap();
2615
+ let map = guard.as_mut()?;
2616
+ let (queue, single) = map.get_mut(component)?;
2617
+ let raw = if *single || queue.len() <= 1 { queue[0].clone() } else { queue.remove(0) };
2618
+ // normalize echo:port to the port NAME X so a de-box handler's echo comparison fires;
2619
+ // echo:items already names the port directly.
2620
+ let echo = {
2621
+ let e = raw.get("echo").and_then(|e| e.as_str()).unwrap_or("");
2622
+ if e == "port" { raw.get("port").and_then(|p| p.as_str()).unwrap_or("").to_string() } else { e.to_string() }
2623
+ };
2624
+ if let Some(okv) = raw.get("ok") {
2625
+ let v = behavior_contracts::decode_value(okv).expect("decode ok");
2626
+ Some((false, String::new(), Some(v), echo))
2627
+ } else {
2628
+ let e = raw.get("error").and_then(|e| e.as_str()).unwrap_or("").to_string();
2629
+ Some((true, e, None, echo))
2660
2630
  }
2661
2631
  }`;
2662
- const observeBound = needSync ? "" : "";
2663
- void observeBound;
2632
+ void needSync;
2664
2633
  return `// GENERATED test-only observe companion (bc#77/#94) — NOT part of the covered module. Serializes the
2665
- // struct-native runner's result to a canonical Value for the equivalence pin, and carries the CONCRETE
2666
- // scripted test handler (ScriptedNativeRaw) that satisfies every HandlerNR<comp> trait by decoding a
2667
- // scripted Value into the concrete per-node row. The consumer never uses this (it keeps the model native
2668
- // + implements HandlerNR<comp> over its own wire payload); it exists only so the test harness can
2669
- // byte-compare the STRUCT-only covered read against run_behavior. A submodule of the covered module
2670
- // (reads its pub run_native_raw_struct_* + the CONCRETE structs/traits — incl. the LOCAL BehaviorError —
2671
- // via super::*). bc#90 / runtime-free: the covered module's BehaviorError is LOCAL, so this test-glue
2672
- // companion refers to it via super::* (as \`BehaviorError\`) and refers to the bc-runtime failure type
2673
- // FULLY-QUALIFIED (\`behavior_contracts::BehaviorError\`) only where it bridges at the observe boundary.
2674
- #![allow(dead_code, unused_imports)]
2634
+ // struct-native runner's result to a canonical Value for the equivalence pin, and carries the SCRIPTED
2635
+ // analog of the consumer's leaf transport symbols: free \`leaf_<comp>\` fns that drain a shared scripted
2636
+ // static and return the scripted wire (exactly the shape the removed per-node trait method returned). The
2637
+ // consumer never uses this (it keeps the model native + supplies its own transport fns over its own wire
2638
+ // payload); it exists only so the test harness can byte-compare the STRUCT-only covered read against
2639
+ // run_behavior. A submodule of the covered module (reads its pub run_native_raw_struct_* + the CONCRETE
2640
+ // structs — incl. the LOCAL BehaviorError — via super::*, and its \`leaf_<comp>\` fns resolve the covered
2641
+ // module's transport calls). bc#90 / runtime-free: the covered module's BehaviorError is LOCAL, so this
2642
+ // test-glue companion refers to it via super::* (as \`BehaviorError\`) and refers to the bc-runtime failure
2643
+ // type FULLY-QUALIFIED (\`behavior_contracts::BehaviorError\`) only where it bridges at the observe boundary.
2644
+ // The transport-fn signatures spread the port fields, so they carry \`&String\`/\`&Vec\` params and (for
2645
+ // point reads) many args — clippy::ptr_arg / too_many_arguments are TEST-glue-only allows here.
2646
+ #![allow(dead_code, unused_imports, unused_variables, non_snake_case, clippy::ptr_arg, clippy::too_many_arguments, clippy::needless_lifetimes, clippy::type_complexity)]
2675
2647
  use behavior_contracts::Value;
2676
2648
  use super::*;
2677
2649
 
@@ -2738,17 +2710,19 @@ ${wireAdapter}
2738
2710
 
2739
2711
  ${adapter}
2740
2712
 
2741
- // scripted handler trait impls (one per covered component — the concrete node_* seam, test glue).
2742
- ${traitImpls.join("\n\n")}
2713
+ // scripted leaf transport fns (one per covered leaf — the free op-agnostic transport the covered runner
2714
+ // calls directly; test glue draining the shared scripted static).
2715
+ ${transportFns.join("\n\n")}
2743
2716
 
2744
- // observe_native_raw drives the CONCRETE struct-native runner and serializes to a canonical Value (test
2745
- // only). Takes the CONCRETE &ScriptedNativeRaw handler so each enclosed run_native_raw_struct_* call is
2746
- // instantiated at the concrete handler type (direct per-node method calls), not at a trait object.
2717
+ // observe_native_raw resets+fills the shared scripted static from the per-case handlers spec, then drives
2718
+ // the covered struct-native runner and serializes to a canonical Value (test only). No handler object is
2719
+ // passed — the runner calls the free \`leaf_<comp>\` transport fns above directly.
2747
2720
  pub fn observe_native_raw(
2748
2721
  name: &str,
2749
- handlers: &ScriptedNativeRaw,
2722
+ spec: &serde_json::Map<String, serde_json::Value>,
2750
2723
  input: &[(String, Value)],
2751
2724
  ) -> Result<Value, behavior_contracts::BehaviorError> {
2725
+ fill_scripted(spec);
2752
2726
  match name {
2753
2727
  ${arms}
2754
2728
  other => Err(behavior_contracts::BehaviorError::new("UNKNOWN_ENTRY", format!("component '{other}' is not a covered read (fail-closed)"))),