behavior-contracts 0.11.5 → 0.11.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/authoring.d.ts +12 -3
  2. package/dist/authoring.d.ts.map +1 -1
  3. package/dist/authoring.js +6 -2
  4. package/dist/authoring.js.map +1 -1
  5. package/dist/behavior.d.ts +46 -10
  6. package/dist/behavior.d.ts.map +1 -1
  7. package/dist/behavior.js +98 -20
  8. package/dist/behavior.js.map +1 -1
  9. package/dist/builder.d.ts.map +1 -1
  10. package/dist/builder.js +23 -10
  11. package/dist/builder.js.map +1 -1
  12. package/dist/commands/ts-compile.d.ts.map +1 -1
  13. package/dist/commands/ts-compile.js +32 -7
  14. package/dist/commands/ts-compile.js.map +1 -1
  15. package/dist/generator/async-plan.d.ts.map +1 -1
  16. package/dist/generator/async-plan.js +2 -1
  17. package/dist/generator/async-plan.js.map +1 -1
  18. package/dist/generator/emit-shared-go.d.ts.map +1 -1
  19. package/dist/generator/emit-shared-go.js +40 -7
  20. package/dist/generator/emit-shared-go.js.map +1 -1
  21. package/dist/generator/emit-shared-rust.d.ts.map +1 -1
  22. package/dist/generator/emit-shared-rust.js +46 -12
  23. package/dist/generator/emit-shared-rust.js.map +1 -1
  24. package/dist/generator/emit-shared-typescript.d.ts.map +1 -1
  25. package/dist/generator/emit-shared-typescript.js +43 -13
  26. package/dist/generator/emit-shared-typescript.js.map +1 -1
  27. package/dist/generator/emit-typed-native-go.d.ts +4 -4
  28. package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
  29. package/dist/generator/emit-typed-native-go.js +162 -71
  30. package/dist/generator/emit-typed-native-go.js.map +1 -1
  31. package/dist/generator/emit-typed-native-rust.d.ts +1 -1
  32. package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
  33. package/dist/generator/emit-typed-native-rust.js +145 -78
  34. package/dist/generator/emit-typed-native-rust.js.map +1 -1
  35. package/dist/generator/straightline.d.ts +16 -4
  36. package/dist/generator/straightline.d.ts.map +1 -1
  37. package/dist/generator/straightline.js +51 -32
  38. package/dist/generator/straightline.js.map +1 -1
  39. package/dist/guard.js +32 -15
  40. package/dist/guard.js.map +1 -1
  41. package/dist/lowering.d.ts +47 -3
  42. package/dist/lowering.d.ts.map +1 -1
  43. package/dist/lowering.js +121 -24
  44. package/dist/lowering.js.map +1 -1
  45. package/dist/plan.d.ts +9 -2
  46. package/dist/plan.d.ts.map +1 -1
  47. package/dist/plan.js +9 -2
  48. package/dist/plan.js.map +1 -1
  49. package/dist/primitives.d.ts +0 -2
  50. package/dist/primitives.d.ts.map +1 -1
  51. package/dist/primitives.js +0 -4
  52. package/dist/primitives.js.map +1 -1
  53. package/dist/runtime.d.ts +1 -1
  54. package/dist/runtime.d.ts.map +1 -1
  55. package/dist/runtime.js +1 -1
  56. package/dist/runtime.js.map +1 -1
  57. package/dist/type-gate.d.ts.map +1 -1
  58. package/dist/type-gate.js +35 -6
  59. package/dist/type-gate.js.map +1 -1
  60. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  import { entryPortOrder, GeneratorFailure } from "./core.js";
2
- import { isControlGate, mapNodeElemIsOpaqueWire, nodeWirePassthrough } from "../behavior.js";
2
+ import { isControlGate, mapNodeElemIsOpaqueWire, mapTransformExpr, nodeWirePassthrough } from "../behavior.js";
3
3
  import { goStraightlineInternals } from "./emit-shared-go.js";
4
4
  import { goTypedInternals } from "./emit-shared-go-typed.js";
5
5
  import { buildTypePlan, deriveTypeRef, findDecl, guardedMapIntoIsCoverable, inputPortIsOptional, inputPortTypeRef } from "./typed.js";
@@ -91,10 +91,16 @@ func leafFailure(message string) *BehaviorError {
91
91
  // leaf's structured detail through unchanged (the runner transports the Error Value, it does not
92
92
  // synthesize or re-interpret it).
93
93
  func opFailed(node string, policy string, e error) *BehaviorError {
94
+ // The Kind names itself in the message, and 'retry' says it gave up — the runtime owns the attempts
95
+ // (scp-error.md: tuning is Runtime-owned), so what the plan reports is the exhausted retry.
96
+ where := "operation '" + node + "' failed under '" + policy + "' policy"
97
+ if policy == "retry" {
98
+ where += " (exhausted)"
99
+ }
94
100
  if be, ok := e.(*BehaviorError); ok {
95
- return &BehaviorError{Code: "OP_FAILED", Message: "operation '" + node + "' failed under '" + policy + "' policy: " + be.Message, Detail: be.Detail}
101
+ return &BehaviorError{Code: "OP_FAILED", Message: where + ": " + be.Message, Detail: be.Detail}
96
102
  }
97
- return &BehaviorError{Code: "OP_FAILED", Message: "operation '" + node + "' failed under '" + policy + "' policy: " + e.Error()}
103
+ return &BehaviorError{Code: "OP_FAILED", Message: where + ": " + e.Error()}
98
104
  }
99
105
 
100
106
  // deTypeMismatch / deMissingField / deOverflow — the de-box mismatch failures the generated decode
@@ -668,7 +674,7 @@ function staticArrElems(node) {
668
674
  * isNativeRawComponent — a component covered by the combined read emitter. Strictly sequential
669
675
  * (no real concurrency), body is ALL componentRef (no map/cond), default 'fail'/'continue'
670
676
  * policy, relationKind is single/connection or absent, and EVERY node carries outType + the
671
- * component carries outputType. relationKind:single / bindField ARE the point — inline exec makes
677
+ * component carries outputType. the relation bindField ARE the point — inline exec makes
672
678
  * the child-present decision from the real parent result. Ports AND the output are evaluated via
673
679
  * the primitive SSoT over a Value-space portScope (so a dynamic operator in a port or an
674
680
  * obj-assembly output is fine — the SSoT handles fail-closed semantics; only the RESULT plane +
@@ -771,7 +777,7 @@ function outputIsNativeLowerable(comp) {
771
777
  if (e.kind === "str" || e.kind === "bool" || e.kind === "null")
772
778
  return true;
773
779
  // ref OR refOpt to a body node (typed). refOpt is how a produced-aware output reads a skippable
774
- // relationSingle child: the head node's produced flag gates it, yielding opt-nil when unproduced.
780
+ // relation child: the head node's produced flag gates it, yielding opt-nil when unproduced.
775
781
  if (e.kind === "ref")
776
782
  return bodyIds.has(e.path[0]); // must ref a body node (typed), not input
777
783
  if (e.kind === "concat")
@@ -804,7 +810,7 @@ function isNativeRaw(comp) {
804
810
  * - every element port is static (literal / ref into the element binding / concat / static arr),
805
811
  * - element outType is a NAMED struct (the augmented element type — over element + the into field),
806
812
  * - no `when` guard (guard+into => heterogeneous elements, not one []T — stays boxed),
807
- * - default 'fail' policy, relationKind single/connection or absent.
813
+ * - relationKind single/connection or absent (every Error Policy Kind is covered — goPolicyArm).
808
814
  * This is the struct-native de-box of a typed `map...into` element collection: build the per-element
809
815
  * native ports struct, dispatch the batched handler ONCE (RawValue out), and assemble each augmented
810
816
  * element struct by copying the over element's typed fields + materializing the into field from the
@@ -825,9 +831,7 @@ function coveredMapNode(n, bodyIds, comp) {
825
831
  // byte-equal. The skip value below (goZero of the into row type) yields nil / connection-struct-zero.
826
832
  if (m.when !== undefined && m.into !== undefined && !guardedMapIntoIsCoverable(n, comp))
827
833
  return false;
828
- if (m.policy !== undefined && m.policy !== "fail")
829
- return false;
830
- if (m.relationKind !== undefined && m.relationKind !== "single" && m.relationKind !== "connection")
834
+ if (m.relationKind !== undefined && m.relationKind !== "connection")
831
835
  return false;
832
836
  // A map node must carry an outType (its ELEMENT type per the recorder SoT — authoring.ts recordMap
833
837
  // holds `node.outType = mapElem`, the PRE-array-wrap element; the emitter synthesizes the produced
@@ -838,7 +842,13 @@ function coveredMapNode(n, bodyIds, comp) {
838
842
  // per-op re-box), exactly as the componentRef path treats a passthrough result. Any other non-compound
839
843
  // element type stays uncovered (loud), as before.
840
844
  const outT = n.outType;
841
- if (outT === undefined || (typeof outT !== "object" && !mapNodeElemIsOpaqueWire(n)))
845
+ // #225: 純式 map(`transform`)の要素は**式から native に組む**(ワイヤも de-box も無い)ので、要素型が
846
+ // スカラでも被覆される — 宣言型 materializer が組めれば良く、組めなければそこで loud に落ちる。
847
+ // Component map は要素 wire を de-box するので従来どおり compound / opaque wire に限る。
848
+ const isTransformMap = mapTransformExpr(m) !== undefined;
849
+ if (outT === undefined)
850
+ return false;
851
+ if (!isTransformMap && typeof outT !== "object" && !mapNodeElemIsOpaqueWire(n))
842
852
  return false;
843
853
  // `over` element type must be STATICALLY resolvable: a ref to a PRIOR BODY NODE's typed arr field
844
854
  // (mapOverElemType) OR a ref to an INPUT array port that carries `elemType` (#108 — the C3 "BC does
@@ -858,7 +868,9 @@ function coveredMapNode(n, bodyIds, comp) {
858
868
  if (schema === undefined || schema.elemType === undefined)
859
869
  return false;
860
870
  }
861
- const ports = m.ports;
871
+ // 純式 map(#222)は port を持たない: 被覆条件は「要素式が宣言された要素型へ native に materialize
872
+ // できること」で、それは compilePortNode(宣言型 materializer)が失敗したときに loud に落ちる。
873
+ const ports = (m.ports ?? {});
862
874
  const plan = planForComp(comp);
863
875
  const typedNodes = buildTypedNodes(comp, plan);
864
876
  const asBinding = mapAsBinding(comp, n, typedNodes, plan);
@@ -873,7 +885,7 @@ function coveredMapNode(n, bodyIds, comp) {
873
885
  * coveredFanoutNode (v3) — a FANOUT node (first-class `@refs` id-list fan-out) is covered when:
874
886
  * - over is a static ref to a PRIOR BODY NODE's typed arr field OR an INPUT array port with elemType,
875
887
  * - every element port is static (literal / ref into the $as binding / concat / static arr),
876
- * - default 'fail' policy, relationKind connection (guard-checked by the guard/builder).
888
+ * - relationKind connection (guard-checked by the guard/builder); every Error Policy Kind is covered.
877
889
  * The fanout de-boxes to: one deduped batched dispatch → first-seen dedupe (by the elem's dedupeKey
878
890
  * field) + dangling drop + implicitSource strip + connection wrap {items, cursor:nil} — NO boxed Value.
879
891
  */
@@ -881,8 +893,6 @@ function coveredFanoutNode(n, bodyIds, comp) {
881
893
  if (n === null || typeof n !== "object" || !("fanout" in n))
882
894
  return false;
883
895
  const f = n.fanout;
884
- if (f.policy !== undefined && f.policy !== "fail")
885
- return false;
886
896
  if (f.relationKind !== "connection")
887
897
  return false;
888
898
  const overE = classifyExpr(f.over);
@@ -955,8 +965,13 @@ function coverageRejectReason(comp) {
955
965
  // cond (#108, has outType, then/else are data branches — the sibling Φ-join). The cond's own
956
966
  // validity (a value cond REQUIRES outType; a control gate is exempt) is enforced by the per-node
957
967
  // cond check below, so a parallel value cond without outType still loud-rejects there.
968
+ // #225: 純式 map(`map.transform` — Component 呼びなし)も同じ性質を持つ: handler も boxed result も
969
+ // 無い変換なので、昇順 preflight で確定させれば bounded-concurrency の error-precedence 協定
970
+ // (componentRef fan-out メンバを統べる)を乱さない。cond の免除根拠がそのまま当てはまる。
958
971
  if ("cond" in n)
959
972
  continue;
973
+ if ("map" in n && mapTransformExpr(n.map) !== undefined)
974
+ continue;
960
975
  if (!("component" in n))
961
976
  return `node '${n.id}' is a non-componentRef member of a parallel stage (not native-covered)`;
962
977
  }
@@ -996,28 +1011,22 @@ function coverageRejectReason(comp) {
996
1011
  if (!("component" in n))
997
1012
  return `node '${n.id}' is not a componentRef, map, or cond node (not native-covered)`;
998
1013
  const cr = n;
999
- // Only default 'fail' policy on covered reads: 'continue' (and any skip source, incl. bindField)
1000
- // makes a node UNPRODUCED at runtime, whose output ref must yield the unproduced rep — a
1001
- // produced-aware output lowering the struct-only path does not do yet (documented follow-up).
1002
- // Such components fall through to the boxed typed / straight-line path (correct, just not
1003
- // struct-de-plumbed). relationKind:single WITHOUT bindField (the #74/#323 core) IS covered.
1004
- if (cr.policy !== undefined && cr.policy !== "fail")
1005
- return `node '${n.id}' componentRef policy '${cr.policy}' (produced-aware output not yet native-covered)`;
1006
- // #125: a when(...) control-gate child (`parent=gate, bindField:"ok"`). Its bindField is the gate's
1007
- // skip signal, NOT a relation data key — so the relationKind constraint below (which governs a
1008
- // relation bindField into a single|connection parent) does not apply. Its skip is driven by the
1009
- // gate's produced_<gate> flag; the child itself can be a plain point read (or a relation read).
1010
- const childOfGate = cr.parent !== undefined && isControlGate(comp.body.find((b) => b.id === cr.parent));
1011
- // #86 part 1: a relationKind:single child WITH bindField (relationSingle) IS covered. When the
1014
+ // Every Error Policy Kind IS covered on a componentRef: `continue` makes the node unproduced, which the
1015
+ // produced-aware output lowering (emitProducedAwareValue, driven by the same canSkip the bindField skip
1016
+ // uses) already renders, and `retry` shares `fail`'s control flow with the Kind named in the failure
1017
+ // (the attempts themselves are Runtime-owned — scp-error.md §Separating Policy Kind and Tuning, which
1018
+ // in native mode is the per-Component leaf transport). Proven by real go build + run, not by assertion.
1019
+ // #86 part 1: a relation child WITH bindField IS covered. When the
1012
1020
  // bound parent field is null/absent the child is UNPRODUCED — the produced-aware output lowering
1013
1021
  // (emitProducedAwareValue) then yields the unproduced rep (null / opt-nil) for a ref/refOpt into
1014
1022
  // it, matching run_behavior's writeUnproduced. #93 shape 1: a bindField on a relationKind:connection
1015
1023
  // child is ALSO covered — the connection's unproduced rep is the empty connection {items:[],cursor:null}
1016
1024
  // (unproducedValue("connection")), which emitProducedAwareValue emits explicitly for a skipped
1017
1025
  // connection node (a ref into it yields {items:[],cursor:null}, matching run_behavior).
1018
- if (!childOfGate && cr.bindField !== undefined && cr.relationKind !== "single" && cr.relationKind !== "connection")
1019
- return `node '${n.id}' relationKind '${cr.relationKind ?? "point"}' not native-covered (bindField only supports single|connection)`;
1020
- if (cr.relationKind !== undefined && cr.relationKind !== "single" && cr.relationKind !== "connection")
1026
+ // relationKind の閉集合は `connection` の 1 値で、**注記の不在**が「未生成は null」を意味する。ゆえに
1027
+ // bindField 由来 skip は 2 形(connection = 空 connection / 不在 = null)とも produced-aware 出力が
1028
+ // 表現でき、被覆条件は無い(かつての「明示的に single と書け」は既定値の重複綴りの要求だった)。
1029
+ if (cr.relationKind !== undefined && cr.relationKind !== "connection")
1021
1030
  return `relationKind '${cr.relationKind}' not native-covered (node '${n.id}')`;
1022
1031
  // #170: a control-gate child's ports may narrow a gate-proven opt ref to non-null (the (a3) gated read).
1023
1032
  const crNarrowed = nodeNarrowedPaths(comp, cr);
@@ -1496,12 +1505,18 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1496
1505
  // them ascending at the head of the stage block is byte-equal to run_behavior (each cond's `if`
1497
1506
  // evaluated in preflight). A cond never shares a stage with a node that depends on it (an intra-
1498
1507
  // stage parent/child dep is rejected by concurrencyPlan).
1499
- const condMembers = stage.filter((i) => "cond" in comp.body[i]);
1500
- const refMembers = stage.filter((i) => !("cond" in comp.body[i]));
1508
+ // #225: dispatch を持たないメンバ = cond + 純式 map(どちらも handler も boxed result も持たない)。
1509
+ // 昇順に、**逐次パスと同じ arm** で emit する(lowering を分岐させない)。
1510
+ const noDispatch = (i) => "cond" in comp.body[i] || ("map" in comp.body[i] && mapTransformExpr(comp.body[i].map) !== undefined);
1511
+ const condMembers = stage.filter(noDispatch);
1512
+ const refMembers = stage.filter((i) => !noDispatch(i));
1501
1513
  for (const i of condMembers) {
1502
- // emit the cond EXACTLY as #108/#136 does sequentially (reused, not forked) — position in `order`
1503
- // is atPos + slot; emitCondArm dispatches control-gate vs value-cond internally.
1504
- lines.push(emitCondArm(comp, comp.body[i], atPos + stage.indexOf(i), typedNodes, plan, priorNodeAt, zeroOut));
1514
+ // emit it EXACTLY as the sequential path does (reused, not forked) — position in `order` is
1515
+ // atPos + slot; emitCondArm dispatches control-gate vs value-cond internally.
1516
+ const n = comp.body[i];
1517
+ lines.push("cond" in n
1518
+ ? emitCondArm(comp, n, atPos + stage.indexOf(i), typedNodes, plan, priorNodeAt, zeroOut)
1519
+ : emitMapArm(comp, n, atPos + stage.indexOf(i), typedNodes, plan, priorNodeAt, zeroOut, flags, leaf, wire.selector, metas[i].policy));
1505
1520
  }
1506
1521
  // A cond-ONLY stage carries no handler fan-out — the conds above ARE the whole stage (each committed
1507
1522
  // its produced flag / typed cell in ascending order). Skip the parallel orchestration block entirely
@@ -1635,7 +1650,7 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1635
1650
  * OUT (marshalRaw_* straight into the node's outType struct — no boxed Value on the row plane),
1636
1651
  * INLINE sequential (NO RunPlan). Node results are TYPED STRUCT locals; a relation child reads the
1637
1652
  * parent's REAL struct result inline (typed field access — no serialize), and the child-present /
1638
- * bindField / continue-skip decision is made from the real parent value — so relationSingle /
1653
+ * bindField / continue-skip decision is made from the real parent value — so relation /
1639
1654
  * connection converge with run_behavior. The output is assembled as a TYPED STRUCT/value (via the
1640
1655
  * typed output lowering — struct literal + struct-field access, ZERO NewObj/.Set). For a covered
1641
1656
  * read whose ports/output are input-static + cross-node refs, this runner allocates ZERO *Obj: the
@@ -1668,7 +1683,7 @@ function emitNativeRawRunner(comp, plan, flags, wire, leaf, declared) {
1668
1683
  lines.push(`// de-plumbed path. Ports are a native struct (direct field assignment); the handler`);
1669
1684
  lines.push(`// result is materialized straight into the node's outType struct. Node results are typed`);
1670
1685
  lines.push(`// struct locals; a relation child reads the parent's REAL struct result via direct field`);
1671
- lines.push(`// access (child-present decision from the real parent value — relationSingle / connection`);
1686
+ lines.push(`// access (child-present decision from the real parent value — relation / connection`);
1672
1687
  lines.push(`// converge). A strictly-sequential plan is a plain statement list (no plan driver); a`);
1673
1688
  lines.push(`// real-concurrency stage (bc#87) is EXPLICIT static parallel orchestration — one goroutine`);
1674
1689
  lines.push(`// per statically-known parallel op, bounded by the static plan.concurrency via a semaphore`);
@@ -1716,12 +1731,12 @@ function emitNativeRawRunner(comp, plan, flags, wire, leaf, declared) {
1716
1731
  // v3: a covered fanout node — deduped batched dispatch + first-seen dedupe + dangling drop +
1717
1732
  // connection wrap (the SAME definition as run_behavior's fanoutDedupDrop).
1718
1733
  if ("fanout" in comp.body[i]) {
1719
- lines.push(emitFanoutArm(comp, comp.body[i], k, typedNodes, plan, priorNodeAt, zeroOut, leaf, wire.selector));
1734
+ lines.push(emitFanoutArm(comp, comp.body[i], k, typedNodes, plan, priorNodeAt, zeroOut, leaf, wire.selector, metas[i].policy));
1720
1735
  continue;
1721
1736
  }
1722
1737
  // #86 pt2: a covered batched map...into node — struct-native element collection + into enrichment.
1723
1738
  if ("map" in comp.body[i]) {
1724
- lines.push(emitMapArm(comp, comp.body[i], k, typedNodes, plan, priorNodeAt, zeroOut, flags, leaf, wire.selector));
1739
+ lines.push(emitMapArm(comp, comp.body[i], k, typedNodes, plan, priorNodeAt, zeroOut, flags, leaf, wire.selector, metas[i].policy));
1725
1740
  continue;
1726
1741
  }
1727
1742
  // #108: a cond node — pure Expression (no handler). Compile `if` to a native bool + materialize the
@@ -1786,22 +1801,14 @@ function emitNativeRawRunner(comp, plan, flags, wire, leaf, declared) {
1786
1801
  // (renderResultDeBox) classifies it against the STATICALLY declared result type and produces the
1787
1802
  // structured Error Value on a mismatch (byte-equal codes to run_behavior's outType check, so ≡ holds).
1788
1803
  if (meta.policy === "continue") {
1789
- // continue: a failed node (leaf failure OR de-box mismatch) produces no Port — the downstream Skip
1790
- // propagation is what `continue` means. The inline de-box runs in a local closure so a mismatch is a
1791
- // LOCAL skip (not a runner-wide propagate); only a clean decode commits. (Covered componentRef nodes
1792
- // are always 'fail' policy today — this arm is defensive.)
1793
- const nodeGo = renderTypeRef(ref);
1794
- const nodeZeroFail = (e) => `return ${goZero(ref)}, ${e}`;
1804
+ // continue: a node whose COMPONENT failed produces no Port — the downstream Skip propagation is what
1805
+ // `continue` means (scp-error.md §Dependency rules for continue), so the leaf error leaves
1806
+ // produced_<s> false instead of propagating. A de-box mismatch is NOT a component failure: the
1807
+ // interpreter checks the declared outType in wrappedExec, OUTSIDE the policy interpretation, and
1808
+ // throws — so it must propagate here too, or the two surfaces disagree on the same IR.
1795
1809
  lines.push(`${indent}if wire_${s}, wire_${s}Err := ${call}; wire_${s}Err == nil {`);
1796
- lines.push(`${indent}\tdec_${s}, dec_${s}DErr := func() (${nodeGo}, error) {`);
1797
- lines.push(`${indent}\t\tvar out ${nodeGo}`);
1798
- lines.push(renderResultDeBox(ref, "out", `wire_${s}`, node.id, plan, `${indent}\t\t`, nodeZeroFail, nodeWirePassthrough(node), seqCtr));
1799
- lines.push(`${indent}\t\treturn out, nil`);
1800
- lines.push(`${indent}\t}()`);
1801
- lines.push(`${indent}\tif dec_${s}DErr == nil {`);
1802
- lines.push(`${indent}\t\t${typedLocal(node.id)} = dec_${s}`);
1803
- lines.push(`${indent}\t\tproduced_${s} = true`);
1804
- lines.push(`${indent}\t}`);
1810
+ lines.push(renderResultDeBox(ref, typedLocal(node.id), `wire_${s}`, node.id, plan, `${indent}\t`, returnZeroFail(zeroOut), nodeWirePassthrough(node), seqCtr));
1811
+ lines.push(`${indent}\tproduced_${s} = true`);
1805
1812
  lines.push(`${indent}}`);
1806
1813
  }
1807
1814
  else {
@@ -1821,7 +1828,7 @@ function emitNativeRawRunner(comp, plan, flags, wire, leaf, declared) {
1821
1828
  // result stays a struct (the consumer keeps it native). An input-param output ref would need the
1822
1829
  // Value-scope fallback (scopeNR) — the covered read corpus does not hit it.
1823
1830
  //
1824
- // #86 part 1: for a bindField relationSingle child that can SKIP at runtime, a ref/refOpt into it
1831
+ // #86 part 1: for a bindField relation child that can SKIP at runtime, a ref/refOpt into it
1825
1832
  // must yield the UNPRODUCED rep (run_behavior's writeUnproduced: null for a single child) rather
1826
1833
  // than the zero-value struct. So when any covered node canSkip, we use the produced-aware lowering
1827
1834
  // which gates such a ref on the node's produced_<id> flag.
@@ -1863,9 +1870,15 @@ function emitNativeRawRunner(comp, plan, flags, wire, leaf, declared) {
1863
1870
  * (direct field assignment; $as refs read the over element's typed fields), and the result is a
1864
1871
  * native []T with NO boxed Value on any plane. The map is under the parent's produced gate (inline).
1865
1872
  */
1866
- function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, flags, leaf, wireSel) {
1873
+ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, flags, leaf, wireSel, policy) {
1867
1874
  const m = node.map;
1868
1875
  const batched = m.batched === true;
1876
+ // Error Policy Kind of the map's Component (the unit is "a Component failed", and for a map that is this
1877
+ // node). The resolved Kind comes from the sequential analysis (the mirror of plan.ts preflight) — it is
1878
+ // never re-derived from the node here. `continue` → the node is unproduced (goPolicyArm wraps the body);
1879
+ // `fail`/`retry` → propagate, naming the Kind.
1880
+ const contPolicy = policy === "continue";
1881
+ const policyLit = JSON.stringify(policy === "retry" ? "retry" : "fail");
1869
1882
  const hasInto = m.into !== undefined;
1870
1883
  const hasGuard = m.when !== undefined;
1871
1884
  // #177 keep-with-null: a guarded map WITH `into` keeps guard-skipped elements with the (opt) into
@@ -1873,7 +1886,8 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1873
1886
  // guarded NO-into map, which DROPs skipped elements. Byte-equal to run_behavior's applyInto keep-with-null.
1874
1887
  const keepWithNull = hasGuard && hasInto;
1875
1888
  const s = sanitize(node.id);
1876
- const leafSym = resolveLeafSymbol(m.component, leaf, m.leafSymbol);
1889
+ const transform = mapTransformExpr(m);
1890
+ const leafSym = transform === undefined ? resolveLeafSymbol(m.component, leaf, m.leafSymbol) : "";
1877
1891
  const arrRef = typedNodes.get(node.id);
1878
1892
  const elemGo = renderTypeRef(arrRef);
1879
1893
  const asName = m.as;
@@ -1883,7 +1897,7 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1883
1897
  const overElemGo = renderTypeRef(overElemRef);
1884
1898
  const elemMat = mapElemMaterializerName(comp.name, node.id);
1885
1899
  const priorHere = (head) => priorNodeAt(head, atPos);
1886
- const portNames = Object.keys(m.ports);
1900
+ const portNames = Object.keys(m.ports ?? {});
1887
1901
  // #108 guard: compile the `when` expression to a native bool over an element-scoped resolveHead
1888
1902
  // ($as → the over element value `elemVar`; prior node → its typed local; input port → in.<Field>).
1889
1903
  // Returns the compiled {stmts, expr} or null (no guard). Mirrors run_behavior's per-element keep-gate
@@ -1911,7 +1925,7 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1911
1925
  const buildPayloadElem = (il, elemVar) => [`${il}ep_${s} := ${goPayloadRow(portFields(elemVar), wireSel)}`];
1912
1926
  const lines = [];
1913
1927
  const closers = [];
1914
- lines.push(`\t// ── map '${node.id}' (${m.component}, ${batched ? "batched" : "per-element"}, into:${JSON.stringify(m.into ?? null)}${m.relationKind ? ", relationKind:" + m.relationKind : ""}${m.parent ? ", parent:" + m.parent : ""}) ──`);
1928
+ lines.push(`\t// ── map '${node.id}' (${m.component ?? "pure expression"}, ${batched ? "batched" : "per-element"}, into:${JSON.stringify(m.into ?? null)}${m.relationKind ? ", relationKind:" + m.relationKind : ""}${m.parent ? ", parent:" + m.parent : ""}) ──`);
1915
1929
  let indent = "\t";
1916
1930
  // the map is gated on the parent's produced flag (inline, like a relation child).
1917
1931
  if (m.parent !== undefined && priorNodeAt(m.parent, atPos)) {
@@ -1919,6 +1933,11 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1919
1933
  closers.unshift(`${indent}}`);
1920
1934
  indent += "\t";
1921
1935
  }
1936
+ // the node's own statements start here: goPolicyArm wraps THIS range (not the parent gate) when the Kind
1937
+ // is `continue`, so a Component failure skips the rest of the node and leaves it unproduced.
1938
+ const bodyStart = lines.length;
1939
+ /** the map's Component failed (the transport returned an error) — what the Kind does about it. */
1940
+ const onComponentFailure = (errVar) => contPolicy ? [`skipped_${s} = true`, "break"] : [`return ${zeroOut}, opFailed(${JSON.stringify(node.id)}, ${policyLit}, ${errVar})`];
1922
1941
  // over collection (typed field access to the parent node's arr — no serialize; opt-arr → nil-safe deref).
1923
1942
  for (const l of goBindOver(indent, s, overExpr, overOptArr, overElemGo))
1924
1943
  lines.push(l);
@@ -1958,6 +1977,29 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1958
1977
  out.push(`${il}}`);
1959
1978
  return out;
1960
1979
  };
1980
+ if (transform !== undefined) {
1981
+ // 純式 map(#222): transport 呼びもワイヤも de-box も無い。要素式を**宣言された要素型**へ native に
1982
+ // materialize して積むだけ(port 境界と同一の宣言型 materializer `compilePortNode` を通す — 要素種の
1983
+ // 推論は無い)。`when` guard は Component map と同一の keep-gate。
1984
+ lines.push(`${indent}for _, ${elemLocal(s)} := range over_${s} {`);
1985
+ for (const l of emitGuard(indent + "\t", elemLocal(s)))
1986
+ lines.push(l);
1987
+ const tc = compilePortNode(transform, comp, plan, typedNodes, priorHere, `map '${node.id}' transform`, arrRef.elem, {
1988
+ asBinding: { name: asName, ref: overElemRef, plan },
1989
+ asBase: elemLocal(s),
1990
+ narrowed: nodeNarrowedPaths(comp, node),
1991
+ wireSel,
1992
+ });
1993
+ for (const st of tc.stmts)
1994
+ lines.push(`${indent}\t${st}`);
1995
+ lines.push(`${indent}\t${typedLocal(node.id)} = append(${typedLocal(node.id)}, ${tc.expr})`);
1996
+ lines.push(`${indent}}`);
1997
+ lines.push(...goPolicyArm(s, indent, false, lines.splice(bodyStart)));
1998
+ for (const c of closers)
1999
+ lines.push(c);
2000
+ void overElemGo;
2001
+ return lines.join("\n");
2002
+ }
1961
2003
  if (batched && keepWithNull) {
1962
2004
  // #177 BATCHED keep-with-null (guarded map...into, opt into): first pass records, per over element in
1963
2005
  // ORDER, whether it is kept (guard true → build its ports, remember its over-index) or skipped (guard
@@ -1984,7 +2026,7 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
1984
2026
  // ONE op-agnostic transport call: the batch is a WireRow {items:[…]}; the result is a WireList whose
1985
2027
  // aligned elements are read via `.Items` (byte-equal to run_behavior's aligned batch result).
1986
2028
  lines.push(`${indent}\tmo_${s}, mo_${s}Err := ${leafSym}(${goPayloadBatch(`items_${s}`, wireSel)})`);
1987
- lines.push(`${indent}\tif mo_${s}Err != nil {`, `${indent}\t\treturn ${zeroOut}, opFailed(${JSON.stringify(node.id)}, "fail", mo_${s}Err)`, `${indent}\t}`);
2029
+ lines.push(`${indent}\tif mo_${s}Err != nil {`, ...onComponentFailure(`mo_${s}Err`).map((l) => `${indent}\t\t${l}`), `${indent}\t}`);
1988
2030
  lines.push(`${indent}\tmi_${s} := mo_${s}.Items`);
1989
2031
  lines.push(`${indent}\tif len(mi_${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}`);
1990
2032
  lines.push(`${indent}\tfor mk_${s} := range items_${s} {`);
@@ -2015,7 +2057,7 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
2015
2057
  lines.push(`${indent}if len(items_${s}) > 0 {`);
2016
2058
  // ONE op-agnostic transport call: batch payload WireRow {items:[…]}; result WireList read via `.Items`.
2017
2059
  lines.push(`${indent}\tmo_${s}, mo_${s}Err := ${leafSym}(${goPayloadBatch(`items_${s}`, wireSel)})`);
2018
- lines.push(`${indent}\tif mo_${s}Err != nil {`, `${indent}\t\treturn ${zeroOut}, opFailed(${JSON.stringify(node.id)}, "fail", mo_${s}Err)`, `${indent}\t}`);
2060
+ lines.push(`${indent}\tif mo_${s}Err != nil {`, ...onComponentFailure(`mo_${s}Err`).map((l) => `${indent}\t\t${l}`), `${indent}\t}`);
2019
2061
  lines.push(`${indent}\tmi_${s} := mo_${s}.Items`);
2020
2062
  lines.push(`${indent}\tif len(mi_${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}`);
2021
2063
  if (hasInto) {
@@ -2064,7 +2106,7 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
2064
2106
  lines.push(`${indent}\tif mo_${s}Err != nil {`, `${indent}\t\tcontinue`, `${indent}\t}`);
2065
2107
  }
2066
2108
  else {
2067
- lines.push(`${indent}\tif mo_${s}Err != nil {`, `${indent}\t\treturn ${zeroOut}, opFailed(${JSON.stringify(node.id)}, "fail", mo_${s}Err)`, `${indent}\t}`);
2109
+ lines.push(`${indent}\tif mo_${s}Err != nil {`, ...onComponentFailure(`mo_${s}Err`).map((l) => `${indent}\t\t${l}`), `${indent}\t}`);
2068
2110
  }
2069
2111
  // the element's wire is de-boxed strictly INLINE. A de-box mismatch fails closed regardless of
2070
2112
  // elementPolicy (≡ the interpreter's whole-node outType throw); elementPolicy governs the handler's
@@ -2081,12 +2123,38 @@ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, f
2081
2123
  lines.push(`${indent}\t${typedLocal(node.id)} = append(${typedLocal(node.id)}, el_${s})`);
2082
2124
  lines.push(`${indent}}`);
2083
2125
  }
2084
- lines.push(`${indent}produced_${s} = true`);
2126
+ lines.push(...goPolicyArm(s, indent, contPolicy, lines.splice(bodyStart)));
2085
2127
  for (const c of closers)
2086
2128
  lines.push(c);
2087
2129
  void overElemGo;
2088
2130
  return lines.join("\n");
2089
2131
  }
2132
+ /**
2133
+ * goContinuePolicy — Error Policy Kind を 1 つのノード arm へ適用する共通形(map / fanout が共有)。
2134
+ *
2135
+ * `continue` は「Component が失敗 → その Port は未生成 → 下流は Skip」(scp-error.md §Dependency rules
2136
+ * for continue)なので、失敗した時点でそのノードの残りの処理を飛ばし `produced_<s>` を立てない。Go は
2137
+ * 宣言をまたぐ `goto` を禁じるので once-block(`for { … break }`)で囲む。この形なら de-box 不一致 /
2138
+ * 整列違反の `return` はそのまま関数を抜ける — interpreter も outType 検査を policy の外(wrappedExec)で
2139
+ * throw するので、そこが一致する。
2140
+ *
2141
+ * `fail` / `retry` は制御フローが同じで、違いは失敗が名乗る Kind だけ(試行そのものは Runtime 所有 =
2142
+ * native では per-Component の leaf transport)。
2143
+ */
2144
+ function goPolicyArm(s, indent, continuePolicy, body) {
2145
+ if (!continuePolicy)
2146
+ return [...body, `${indent}produced_${s} = true`];
2147
+ return [
2148
+ `${indent}skipped_${s} := false`,
2149
+ `${indent}for {`,
2150
+ ...body.map((l) => `\t${l}`.replace(/\n/g, "\n\t")),
2151
+ `${indent}\tbreak`,
2152
+ `${indent}}`,
2153
+ `${indent}if !skipped_${s} {`,
2154
+ `${indent}\tproduced_${s} = true`,
2155
+ `${indent}}`,
2156
+ ];
2157
+ }
2090
2158
  /** the map element loop variable (the over element, a typed struct). */
2091
2159
  function elemLocal(s) {
2092
2160
  return `oel_${s}`;
@@ -2100,9 +2168,12 @@ function elemLocal(s) {
2100
2168
  * (STRUCTURAL — the connection items elem type already omits the implicitSource field), and wrap into
2101
2169
  * the connection struct {items, cursor:nil}. NO boxed Value on any plane. Byte-equal to run_behavior.
2102
2170
  */
2103
- function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, leaf, wireSel) {
2171
+ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, leaf, wireSel, policy) {
2104
2172
  const f = node.fanout;
2105
2173
  const s = sanitize(node.id);
2174
+ // Error Policy Kind of the fanout's Component (same rule as the map arm — see goPolicyArm).
2175
+ const contPolicy = policy === "continue";
2176
+ const policyLit = JSON.stringify(policy === "retry" ? "retry" : "fail");
2106
2177
  const wvQ = goWireQ(wireSel);
2107
2178
  const leafSym = resolveLeafSymbol(f.component, leaf, f.leafSymbol);
2108
2179
  const connRef = typedNodes.get(node.id);
@@ -2137,6 +2208,8 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut
2137
2208
  closers.unshift(`${indent}}`);
2138
2209
  indent += "\t";
2139
2210
  }
2211
+ // the node's own statements start here (goPolicyArm wraps THIS range when the Kind is `continue`).
2212
+ const bodyStart = lines.length;
2140
2213
  // over id-list (typed field access — no serialize; opt-arr → nil-safe deref) → per-id ports (all ids).
2141
2214
  for (const l of goBindOver(indent, s, overExpr, overOptArr, overElemGo))
2142
2215
  lines.push(l);
@@ -2153,7 +2226,7 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut
2153
2226
  // per-id element wires (read via `.Items`). A DANGLING id is a WireNull element → the zero element (empty
2154
2227
  // dedupeKey), which the dangling drop below excludes. No `bound`.
2155
2228
  lines.push(`${indent}\tfo_${s}, fo_${s}Err := ${leafSym}(${goPayloadBatch(`pi_${s}`, wireSel)})`);
2156
- lines.push(`${indent}\tif fo_${s}Err != nil {`, `${indent}\t\treturn ${zeroOut}, opFailed(${JSON.stringify(node.id)}, "fail", fo_${s}Err)`, `${indent}\t}`);
2229
+ lines.push(`${indent}\tif fo_${s}Err != nil {`, ...(contPolicy ? [`${indent}\t\tskipped_${s} = true`, `${indent}\t\tbreak`] : [`${indent}\t\treturn ${zeroOut}, opFailed(${JSON.stringify(node.id)}, ${policyLit}, fo_${s}Err)`]), `${indent}\t}`);
2157
2230
  lines.push(`${indent}\tfw_${s} := fo_${s}.Items`);
2158
2231
  lines.push(`${indent}\tif len(fw_${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}`);
2159
2232
  // ── THE ONE dedupe/drop (mirrors fanoutDedupDrop verbatim): first-seen dedupe by dedupeKey field;
@@ -2179,7 +2252,7 @@ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut
2179
2252
  // wrap into the connection struct {Items, Cursor:nil}. A nil items slice serializes to [] (the
2180
2253
  // connection serializer normalizes it) — matching {items:[],cursor:null} for an empty fan-out.
2181
2254
  lines.push(`${indent}${typedLocal(node.id)} = ${connRef.name}{${goFieldName("items")}: items_${s}}`);
2182
- lines.push(`${indent}produced_${s} = true`);
2255
+ lines.push(...goPolicyArm(s, indent, contPolicy, lines.splice(bodyStart)));
2183
2256
  for (const c of closers)
2184
2257
  lines.push(c);
2185
2258
  return lines.join("\n");
@@ -2272,7 +2345,7 @@ function emitCondArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut)
2272
2345
  }
2273
2346
  /**
2274
2347
  * emitProducedAwareValue — the #86 part 1 produced-aware output lowering (go). It mirrors the
2275
- * boxed-typed emitTypedValue, but a `ref`/`refOpt` whose HEAD is a skippable relationSingle child is
2348
+ * boxed-typed emitTypedValue, but a `ref`/`refOpt` whose HEAD is a skippable relation child is
2276
2349
  * gated on that node's `produced_<id>` flag: when the child is UNPRODUCED (bound parent field was
2277
2350
  * null/absent), run_behavior's writeUnproduced makes the node null, so a refOpt into it yields null
2278
2351
  * (the output opt field => nil). We emit that exactly: `if produced_<head> { <typed field access> }
@@ -2821,7 +2894,22 @@ function emit(ctx) {
2821
2894
  const structSurface = emitStructSurface(native);
2822
2895
  const behaviorErrorType = emitBehaviorErrorType();
2823
2896
  // bc#87: a covered component with a real-concurrency stage emits sync.WaitGroup + a semaphore.
2824
- const needSync = native.some((c) => concurrencyPlan(c) !== null);
2897
+ // #225: `sync` は goroutine 並行ブロックを実際に emit したときだけ要る。全メンバが dispatch を持たない
2898
+ // stage(cond / 純式 map だけ)は昇順 preflight で確定し orchestration ブロックを出さないので、
2899
+ // その stage しか無い component では sync を import しない(未使用 import は go でコンパイルエラー)。
2900
+ const hasDispatchingStage = (c) => {
2901
+ const ep = execPlan(c);
2902
+ if (ep === null)
2903
+ return false;
2904
+ for (const [, stage] of ep.parallelStageOf)
2905
+ if (stage.some((i) => {
2906
+ const n = c.body[i];
2907
+ return !("cond" in n) && !("map" in n && mapTransformExpr(n.map) !== undefined);
2908
+ }))
2909
+ return true;
2910
+ return false;
2911
+ };
2912
+ const needSync = native.some((c) => concurrencyPlan(c) !== null && hasDispatchingStage(c));
2825
2913
  // bc#90: the ONLY std-lib `fmt.Sprintf` site on the covered plane is the batched-map result-count
2826
2914
  // mismatch error — so `fmt` is imported iff a covered component has a batched map node.
2827
2915
  const needFmt = native.some((c) => c.body.some((n) => ("map" in n && n.map.batched === true) || "fanout" in n));
@@ -2858,7 +2946,7 @@ function emit(ctx) {
2858
2946
  const needSort = runnerCodes.some((c) => c.includes("sort.Strings"));
2859
2947
  const header = emitMinimalHeader(ctx, false, needSync, needFmt, needMath, needStrconv, needWireImport ? wire.import : undefined, leaf?.import, needSort);
2860
2948
  const banner = `// COMBINED READ layer (bc#90 — the RUNTIME-FREE read de-box; STRUCT-ONLY, FULLY-NATIVE surface). A
2861
- // covered read is a strictly-sequential typed componentRef chain (point reads + relationKind:single
2949
+ // covered read is a strictly-sequential typed componentRef chain (point reads + relation children
2862
2950
  // children), emitted ONLY here: each node builds a native ports struct by direct field assignment (every
2863
2951
  // port is a CONCRETE Go value — string / bool / []string projection / int64 limit — NO boxed Value, NO
2864
2952
  // PortReader accessor); the runner calls the op-agnostic leaf TRANSPORT symbol (default Leaf_<comp>)
@@ -2869,7 +2957,7 @@ function emit(ctx) {
2869
2957
  // carries NO bc-runtime reference at all — failures use the LOCAL *BehaviorError (same codes, byte-equal to
2870
2958
  // run_behavior). Exec is INLINE sequential (no plan driver) so a relation child reads the parent's REAL
2871
2959
  // struct result via direct field access and the child-present decision is made from the real parent value —
2872
- // relationSingle / connection converge with run_behavior (fixes #323/#74). The exposed API is the 1:1
2960
+ // relation / connection converge with run_behavior (fixes #323/#74). The exposed API is the 1:1
2873
2961
  // STRUCT-returning entry <Method>(<positional params>) (the In_<comp> box removed); the consumer supplies
2874
2962
  // the leaf transport symbols (default same-package Leaf_<comp>, or a leafTransport import). This module is
2875
2963
  // FULLY NATIVE: a naive grep for
@@ -3032,7 +3120,10 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
3032
3120
  for (const n of c.body) {
3033
3121
  if ("cond" in n)
3034
3122
  continue; // #108: cond has no leaf (pure Expression) — no transport fn.
3035
- const catalog = "fanout" in n ? n.fanout.component : "map" in n ? n.map.component : n.component;
3123
+ // 純式 map(#222)も Component を呼ばないので transport は要らない(cond と同じ扱い)。
3124
+ if ("map" in n && mapTransformExpr(n.map) !== undefined)
3125
+ continue;
3126
+ const catalog = ("fanout" in n ? n.fanout.component : "map" in n ? n.map.component : n.component);
3036
3127
  const specSym = "fanout" in n ? n.fanout.leafSymbol : "map" in n ? n.map.leafSymbol : n.leafSymbol;
3037
3128
  const sym = leafSymbolBare(catalog, leaf, specSym);
3038
3129
  // echo branches (point/componentRef nodes only — a batched/fanout node returns a WireList, not a port).