behavior-contracts 0.11.9 → 0.11.10

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.
@@ -118,7 +118,7 @@ func deMissingField(model, field, expected string) *BehaviorError {
118
118
  }`;
119
119
  }
120
120
  const { sanitize, emitExpr } = goStraightlineInternals;
121
- const { goFieldName, renderTypeRef, goScalar, serializeTyped, emitTypeDecls, emitSerializers, emitTypedValue, checkOutputFieldType, emitMustHelpers, } = goTypedInternals;
121
+ const { goFieldName, renderTypeRef, goScalar, serializeTyped, emitTypeDecls, emitTypedValue, checkOutputFieldType, } = goTypedInternals;
122
122
  /** typed node-result local — MUST match goTypedInternals.typedLocal (`t_<id>`) so the reused
123
123
  * emitTypedValue (output assembly via struct field access) reads the same locals. */
124
124
  function typedLocal(nodeId) {
@@ -1068,7 +1068,7 @@ function assertTypedCoverage(comp) {
1068
1068
  * resolveLeafSymbol — the op-agnostic transport symbol a covered leaf (= catalog component) is called
1069
1069
  * through at its execution point. A consumer-supplied override (`leafTransport.symbols[component]`) wins;
1070
1070
  * else the in-package DEFAULT convention `Leaf_<sanitizedComponent>`. This is the ONE place leaf→symbol
1071
- * resolution lives (SSoT) — the runner call sites, the import block, and the test observe transport fns all
1071
+ * resolution lives (SSoT) — the runner call sites and the import block all
1072
1072
  * read it. There is no per-node handler indirection: a leaf is ONE transport, not one method per node.
1073
1073
  */
1074
1074
  function goLeafSel(leaf) {
@@ -1077,8 +1077,8 @@ function goLeafSel(leaf) {
1077
1077
  /** leafSymbolBare — the UNQUALIFIED transport symbol name. Resolution order (#176): the SPEC-fixed
1078
1078
  * `node.leafSymbol` (from `defineLeaf` meta.transport, baked per node) FIRST, then the CLI
1079
1079
  * `--leaf-transport` override (`leaf.symbols[component]`), then the default `Leaf_<comp>`. The ONE source
1080
- * for the name: call sites qualify it with the package selector (resolveLeafSymbol); the observe companion
1081
- * DEFINES the fn under this bare name (a definition carries no selector). */
1080
+ * for the name: call sites qualify it with the package selector (resolveLeafSymbol); the consumer DEFINES
1081
+ * the fn under this bare name (a definition carries no selector). */
1082
1082
  function leafSymbolBare(component, leaf, specSymbol) {
1083
1083
  return specSymbol ?? leaf?.symbols[component] ?? `Leaf_${sanitize(component)}`;
1084
1084
  }
@@ -1119,7 +1119,7 @@ function runnerName(compName) {
1119
1119
  }
1120
1120
  /** #192: the Go package name = the namespace (declaring class), lower-cased (`UserQueries` → `userqueries`);
1121
1121
  * default `behaviors` when unset. Physical placement / namespace is set in ONE place (GenerateOptions.namespace).
1122
- * The covered module and its test-only observe companion MUST share this package (same-package transport calls). */
1122
+ * An in-package leaf transport (no --leaf-transport-import) MUST live in this package. */
1123
1123
  function goPackageName(ns) {
1124
1124
  if (ns === undefined)
1125
1125
  return "behaviors";
@@ -1349,115 +1349,6 @@ function inputPortGoType(schema, plan, where = "input port") {
1349
1349
  throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `go typed-native (runtime-free): ${where} is OPTIONAL (declared {opt:…}) but its inner type ${JSON.stringify(schema?.type)} has no native Go lowering, so "absent" has no native representation. Declare an elemType for an array/map, or use a natively-lowerable scalar.`);
1350
1350
  return `${PKG}.Value`;
1351
1351
  }
1352
- /** The scalar kind an input port declares, or undefined if it is not a native scalar. */
1353
- function inputScalarKind(schema) {
1354
- switch (schema?.type) {
1355
- case "string":
1356
- case "literal": // a `"literal"` union is a constrained string (see inputPortGoType).
1357
- return "string";
1358
- case "int":
1359
- return "int64";
1360
- case "float":
1361
- case "number": // a `"number"` port is the FLOAT channel (run_behavior: number → float / float64).
1362
- return "float64";
1363
- case "bool":
1364
- return "bool";
1365
- default:
1366
- return undefined;
1367
- }
1368
- }
1369
- /**
1370
- * emitInDecoder — the TEST-glue decoder `decode_<comp>(input *Obj) (<positional args...>, err error)`. It reads
1371
- * each declared input port from the generic *Obj into the entry's POSITIONAL arg (named return; scalar →
1372
- * typed read on the SDK/wire Value; value-typed → the raw wire). Lives ONLY in the observe companion (test
1373
- * harness), never in the covered module — the entry takes positional params (#192, box removed) and the
1374
- * observe passes these decoded args positionally. A missing key leaves the zero value (every covered input
1375
- * is required + always supplied by the corpus); a present-but-wrong-scalar is a fail-closed decode error.
1376
- */
1377
- function emitInDecoder(comp, plan, declared) {
1378
- const ports = entryPortOrder(comp, declared);
1379
- if (ports.length === 0 || comp.inputPorts === undefined)
1380
- return ""; // no input → observe calls the entry with no args.
1381
- // #192: decode the generic *Obj test input into the entry's POSITIONAL args (named returns = the params,
1382
- // in inputPorts order; a decode mismatch sets `err` and returns). The `In_<comp>` box is gone — this
1383
- // test-glue decoder produces the values the observe companion passes positionally to the entry.
1384
- const rets = ports
1385
- .map((p) => `${goParamName(p)} ${inputPortGoType(comp.inputPorts[p], plan, `input port '${p}' of component '${comp.name}'`)}`)
1386
- .join(", ");
1387
- const lines = [];
1388
- lines.push(`func decode_${sanitize(comp.name)}(input *${PKG}.Obj) (${rets}, err error) {`);
1389
- lines.push(`\tif input == nil {`);
1390
- lines.push(`\t\treturn`);
1391
- lines.push(`\t}`);
1392
- for (const p of ports) {
1393
- const arg = goParamName(p);
1394
- const schema = comp.inputPorts[p];
1395
- const scalar = inputScalarKind(schema);
1396
- const et = schema.elemType;
1397
- lines.push(`\tif v, ok := input.Get(${JSON.stringify(p)}); ok {`);
1398
- if ((schema?.type === "array" || schema?.type === "arr") && et !== undefined) {
1399
- // #108: decode the boxed Value array into the native []ElemT (test glue — materialize each element
1400
- // via the typed materializer; a non-array or non-conforming element is a fail-closed decode error).
1401
- // bc#156: a `value[]` element is BC's opaque wire — decode it with the BC-owned valueToWire (the SAME
1402
- // wire the output de-box uses), NOT the typed materializer (WireValue is not a de-box target).
1403
- const elemRef = deriveTypeRef(et, plan);
1404
- const elemGo = renderTypeRef(elemRef);
1405
- const mat = elemRef.kind === "value" ? "valueToWire(ev)" : goTypedInternals.materializeExpr("ev", elemRef, plan);
1406
- lines.push(`\t\tarr, isArr := v.([]${PKG}.Value)`);
1407
- lines.push(`\t\tif !isArr {`);
1408
- lines.push(`\t\t\terr = ${PKG}.NewExprFailure("TYPE_MISMATCH", "input ${p}: expected array, got "+${PKG}.TypeName(v))`);
1409
- lines.push(`\t\t\treturn`);
1410
- lines.push(`\t\t}`);
1411
- lines.push(`\t\tdec := make([]${elemGo}, 0, len(arr))`);
1412
- lines.push(`\t\tfor _, ev := range arr {`);
1413
- lines.push(`\t\t\tdec = append(dec, ${mat})`);
1414
- lines.push(`\t\t}`);
1415
- // #177 (A): an OPTIONAL array port param is `*[]E` (inputPortTypeRef opt → pointer), so take its address.
1416
- lines.push(`\t\t${arg} = ${inputPortIsOptional(schema) ? "&dec" : "dec"}`);
1417
- lines.push(`\t}`);
1418
- continue;
1419
- }
1420
- if (schema?.type === "value") {
1421
- lines.push(`\t\t${arg} = valueToWire(v)`);
1422
- lines.push(`\t}`);
1423
- continue;
1424
- }
1425
- if (schema?.type === "map" && et !== undefined) {
1426
- const valRef = deriveTypeRef(et, plan);
1427
- // #209: a map port whose VALUE type is the opaque `value` decodes with the BC-owned valueToWire —
1428
- // the SAME rule the `value[]` array branch above and the scalar `value` branch below already apply
1429
- // (`value` is input-only, so the typed materializer stays fail-closed for it).
1430
- if (valRef.kind === "value") {
1431
- lines.push(`\t\tmv := make(map[string]WireValue)`);
1432
- lines.push(`\t\tif mo, isObj := v.(*${PKG}.Obj); isObj && mo != nil {`);
1433
- lines.push(`\t\t\tfor _, mk := range mo.Keys {`);
1434
- lines.push(`\t\t\t\tmvv, _ := mo.Get(mk)`);
1435
- lines.push(`\t\t\t\tmv[mk] = valueToWire(mvv)`);
1436
- lines.push(`\t\t\t}`);
1437
- lines.push(`\t\t}`);
1438
- lines.push(`\t\t${arg} = mv`);
1439
- lines.push(`\t}`);
1440
- continue;
1441
- }
1442
- const mapRef = { kind: "map", value: valRef };
1443
- lines.push(`\t\t${arg} = ${goTypedInternals.materializeExpr("v", mapRef, plan)}`);
1444
- lines.push(`\t}`);
1445
- continue;
1446
- }
1447
- if (scalar === undefined) {
1448
- lines.push(`\t\t${arg} = v`);
1449
- }
1450
- else {
1451
- // #139: materialize via the inputPortTypeRef SSoT so an OPTIONAL scalar reads as *T (present → &v);
1452
- // an absent optional never enters this block (Get !ok), leaving the param nil (not a required zero).
1453
- lines.push(`\t\t${arg} = ${goTypedInternals.materializeExpr("v", inputPortTypeRef(schema, plan), plan)}`);
1454
- }
1455
- lines.push(`\t}`);
1456
- }
1457
- lines.push(`\treturn`);
1458
- lines.push(`}`);
1459
- return lines.join("\n");
1460
- }
1461
1352
  /** A ref resolver for native lowering: given a ref head + remaining field path, return a native scalar
1462
1353
  * Go expression (typed input field / prior-node typed struct scalar / element binding field), or null
1463
1354
  * when the ref does not resolve to a REQUIRED (non-opt) native scalar (then the caller falls back to
@@ -2816,9 +2707,8 @@ func bcExpr_strGe(a, b string) bool { return bcExpr_cmpCP(a, b) >= 0 }`;
2816
2707
  * `<Method>(<positional params>) (T, error)`) ARE the exposed API. The consumer calls the entry directly
2817
2708
  * (it returns the typed model — NO Value serialization on the read hot path, matching how graphddb reads:
2818
2709
  * a model, never a boxed Value). There is deliberately NO Value dispatch map — that would require a Value
2819
- * serializer (the boxing residue bc#77 eliminates). A canonical Value observation (equivalence pin) is
2820
- * produced by the SEPARATE test-only observe companion (goTypedNativeObserve), which lives OUTSIDE this
2821
- * module so the covered module stays literal whole-file zero. */
2710
+ * serializer (the boxing residue bc#77 eliminates), which is what keeps the covered module literal
2711
+ * whole-file zero. */
2822
2712
  function emitStructSurface(native) {
2823
2713
  return `// ComponentNamesNativeRaw — covered reads exposed on the combined native path (declaration order).
2824
2714
  // Each is a 1:1 entry <Method>(<positional params>) -> (T, error): a native return; the consumer keeps the
@@ -3024,329 +2914,6 @@ ${emitProbeWireTypes({ row: "WireRow", list: "WireList" })}
3024
2914
  ${emitGoWireTypes()}
3025
2915
  `;
3026
2916
  }
3027
- /**
3028
- * goTypedNativeObserve — the TEST-ONLY observe companion (a SEPARATE file in the SAME package as the
3029
- * covered module). It carries the typed->Value serializers (ser_*) + the SCRIPTED analog of the consumer's
3030
- * leaf transport symbols: free Leaf_<comp> funcs (same package, so the covered module's transport calls
3031
- * resolve) that drain a shared package-level scripted queue, + an ObserveNativeRaw dispatch that fills the
3032
- * queue from the per-case spec, drives the module-private struct runner, and serializes its result to a
3033
- * canonical Value for the equivalence pin. This lives OUTSIDE the covered module so the module stays literal
3034
- * whole-file zero (the ser_* NewObj is test glue, never on the consumer's read hot path). Emitted only for
3035
- * the fully-covered case (the equivalence harness); production consumers never use it.
3036
- */
3037
- export function goTypedNativeObserve(ir, runtimeImport, leaf, namespace, declared) {
3038
- const components = ir.components;
3039
- const native = components.filter(isNativeRaw);
3040
- const plan = buildTypePlan(ir);
3041
- const serializers = emitSerializers(plan);
3042
- const marshallers = goTypedInternals.emitMarshallers(plan);
3043
- const mustHelpers = emitMustHelpers(plan);
3044
- // arr/opt node materialize helpers (mustArr_*/mustOpt_*) for the concrete-row decode of a node whose
3045
- // whole outType is a bare arr/opt (materializeExpr emits mustArr_/mustOpt_ for those).
3046
- const arrOptHelpers = goTypedInternals.emitArrOptNodeHelpers({ ir }, plan);
3047
- const arms = native
3048
- .map((c) => {
3049
- const outRef = c.outputType !== undefined ? deriveTypeRef(c.outputType, plan) : undefined;
3050
- const ser = outRef ? serializeTyped("tv", outRef, plan) : "tv";
3051
- // #192: decode the generic *Obj test input into the entry's POSITIONAL args (test glue — ONE decode at
3052
- // the top; a REQUIRED declared input absent is a fail-closed decode error here, never on the entry path),
3053
- // then call the 1:1 entry positionally. A no-input entry is called with no args (no decoder).
3054
- const args = entryPortOrder(c, declared).map((p) => goParamName(p));
3055
- const decode = args.length === 0
3056
- ? ""
3057
- : `\t\t${args.join(", ")}, ierr := decode_${sanitize(c.name)}(input)\n\t\tif ierr != nil {\n\t\t\treturn nil, ierr\n\t\t}\n`;
3058
- const unusedInput = args.length === 0 ? "\t\t_ = input\n" : "";
3059
- return `\tif name == ${JSON.stringify(c.name)} {\n${decode}${unusedInput}\t\ttv, err := ${runnerName(c.name)}(${args.join(", ")})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn ${ser}, nil\n\t}`;
3060
- })
3061
- .join("\n");
3062
- // input decoders (TEST glue): generic *Obj -> concrete In_<comp>. Scalar fields read the typed value
3063
- // (a `.(T)` here is on the SDK/wire Value in the OBSERVE companion, never in the covered module).
3064
- const inDecoders = native.map((c) => emitInDecoder(c, plan, declared)).join("\n\n");
3065
- // every covered node returns a WireValue the inline de-box classifies — so the scripted wire adapter is
3066
- // needed whenever any component has a handler node.
3067
- const anyDeBox = native.some((c) => c.body.some((n) => !("cond" in n)));
3068
- // scripted wire adapter (TEST glue): wraps a scripted bc Value as the CONCRETE WireValue / WireRow /
3069
- // WireList (the in-package default seam types the covered module references) and classifies each datum's
3070
- // native type into a DynamoDB-flavored wire tag (S/N/BOOL/L/M/NULL). A real consumer supplies its OWN
3071
- // concrete WireValue over its AttributeValue payload; this exists only so the harness drives the
3072
- // generated inline de-box from the same scripted vectors run_behavior uses — so actualWireType observed
3073
- // in a mismatch is the PRODUCER tag (e.g. "N"), not the collapsed native type.
3074
- const wireAdapter = anyDeBox
3075
- ? `// valueToWire (TEST glue): builds the covered module's BC-OWNED concrete WireValue from a scripted bc
3076
- // Value — the harness analog of the consumer's real transport (which builds WireValue as it reads the
3077
- // producer). Numbers ride NATIVE (WireInt / WireFloat), so the scripted value reaches the de-box as the
3078
- // same int64 / float64 run_behavior holds. The wire tags + classification live ONCE in the covered module's
3079
- // WireValue (probeStringOf etc.), so this only CONSTRUCTS.
3080
- func valueToWire(v ${PKG}.Value) WireValue {
3081
- switch t := v.(type) {
3082
- case nil:
3083
- return WireNull()
3084
- case bool:
3085
- return WireBool(t)
3086
- case int64:
3087
- return WireInt(t)
3088
- case float64:
3089
- return WireFloat(t)
3090
- case string:
3091
- return WireStr(t)
3092
- case []${PKG}.Value:
3093
- items := make([]WireValue, len(t))
3094
- for i := range t {
3095
- items[i] = valueToWire(t[i])
3096
- }
3097
- return WireListOf(items)
3098
- case *${PKG}.Obj:
3099
- fields := make([]WireField, len(t.Keys))
3100
- for i, k := range t.Keys {
3101
- vv, _ := t.Get(k)
3102
- fields[i] = WireField{Key: k, Val: valueToWire(vv)}
3103
- }
3104
- return WireRowOf(fields)
3105
- default:
3106
- return WireNull()
3107
- }
3108
- }
3109
-
3110
- // FailureDetail exposes the structured Error Value fields WITHOUT naming the local ErrorDetail type, so
3111
- // the harness can assert the de-box's kind / field / expectedType / actualWireType / rawValue (TEST
3112
- // glue — same package as the covered module, so it may read the fields directly).
3113
- func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actualWireType, rawValue string, ok bool) {
3114
- if e.Detail == nil {
3115
- return "", "", "", "", "", "", false
3116
- }
3117
- d := e.Detail
3118
- return d.Kind, d.Model, d.Field, d.ExpectedType, d.ActualWireType, d.RawValue, true
3119
- }`
3120
- : "";
3121
- // ── op-agnostic leaf TRANSPORT funcs (TEST glue) — the scripted analog of the consumer's transport
3122
- // symbols. ONE free transport per DISTINCT SPEC-fixed SYMBOL (#176/#183), UNIFORM signature
3123
- // `<sym>(payload WireRow) (WireValue, error)`: it drains the shared scripted queue (keyed by the catalog
3124
- // component) and returns the scripted wire — a WireList for a batched/fanout result (`src.ok` = `[]Value`,
3125
- // a nil element → WireNull, the dangling marker), else a single WireValue. Echo (#129/#141) reads the port
3126
- // back FROM THE PAYLOAD BY NAME (payload.get("<port>")) — proving the WireRow field-name↔port-name contract.
3127
- // A single spec-named leaf used in MULTIPLE roles/cardinalities is emitted ONCE (the #183 fix); two nodes
3128
- // resolving to the SAME symbol but DIFFERENT catalog components is a LOUD collision (never a silent
3129
- // collapse). bc#87 parallel goroutines share the queue (mutex-guarded). ──
3130
- const transportFns = [];
3131
- const bySym = new Map();
3132
- for (const c of native) {
3133
- const typedNodes = new Map();
3134
- for (const n of c.body)
3135
- if (!isControlGate(n))
3136
- typedNodes.set(n.id, "map" in n ? mapNodeArrRef(n, plan) : deriveTypeRef(n.outType, plan)); // #125: control-gate typeless; map は produced-array ref に正規化
3137
- for (const n of c.body) {
3138
- if ("cond" in n)
3139
- continue; // #108: cond has no leaf (pure Expression) — no transport fn.
3140
- // 純式 map(#222)も Component を呼ばないので transport は要らない(cond と同じ扱い)。
3141
- if ("map" in n && mapTransformExpr(n.map) !== undefined)
3142
- continue;
3143
- const catalog = ("fanout" in n ? n.fanout.component : "map" in n ? n.map.component : n.component);
3144
- const specSym = "fanout" in n ? n.fanout.leafSymbol : "map" in n ? n.map.leafSymbol : n.leafSymbol;
3145
- const sym = leafSymbolBare(catalog, leaf, specSym);
3146
- // echo branches (point/componentRef nodes only — a batched/fanout node returns a WireList, not a port).
3147
- const echo = [];
3148
- if (!("fanout" in n) && !("map" in n)) {
3149
- const node = n;
3150
- const crNarrowed = nodeNarrowedPaths(c, node);
3151
- const ref = typedNodes.get(n.id);
3152
- if (ref.kind === "named") {
3153
- const decl = findDecl(plan, ref.name);
3154
- const field = decl !== undefined && decl.fields.length === 1 ? decl.fields[0] : undefined;
3155
- const fieldGo = field !== undefined ? renderTypeRef(field.type) : null;
3156
- const recordGo = renderTypeRef(ref);
3157
- for (const pn of Object.keys(node.ports)) {
3158
- let portGo = null;
3159
- try {
3160
- portGo = portFieldGoType(node.ports[pn], c, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[pn], plan), `echo port '${pn}'`, { narrowed: crNarrowed });
3161
- }
3162
- catch {
3163
- portGo = null;
3164
- }
3165
- if (portGo === recordGo) {
3166
- // the port IS the whole record → echo its payload wire DIRECTLY (matching run_behavior's echo:port).
3167
- echo.push(`\tif src.echo == ${JSON.stringify(pn)} {\n\t\tif v := payload.get(${JSON.stringify(pn)}); v != nil {\n\t\t\treturn *v, nil\n\t\t}\n\t}`);
3168
- }
3169
- else if (fieldGo !== null && field !== undefined && portGo === fieldGo) {
3170
- // a scalar port wraps into the record's single field ({v: <port wire>}) — mirrors the scripted `wrap`.
3171
- echo.push(`\tif src.echo == ${JSON.stringify(pn)} {\n\t\tif v := payload.get(${JSON.stringify(pn)}); v != nil {\n\t\t\treturn WireRowOf([]WireField{{Key: ${JSON.stringify(field.name)}, Val: *v}}), nil\n\t\t}\n\t}`);
3172
- }
3173
- }
3174
- }
3175
- else if (ref.kind === "arr" && Object.prototype.hasOwnProperty.call(node.ports, "items")) {
3176
- // #129: an arr node with an `items` port echoes the payload's items wire (a WireList) so the
3177
- // node→leaf array dataflow test is non-vacuous.
3178
- echo.push(`\tif src.echo == "items" {\n\t\tif v := payload.get("items"); v != nil {\n\t\t\treturn *v, nil\n\t\t}\n\t}`);
3179
- }
3180
- }
3181
- const prev = bySym.get(sym);
3182
- if (prev !== undefined) {
3183
- // #176/#183: a spec-fixed symbol MUST map to exactly ONE leaf (catalog component). The same leaf in
3184
- // multiple roles shares ONE transport (byte-uniform signature) — accumulate its echo branches. Two
3185
- // DIFFERENT catalog components colliding to the same symbol is a codegen error (never silent).
3186
- if (prev.catalog !== catalog)
3187
- throw new GeneratorFailure("DUPLICATE_COMPONENT", `go typed-native observe: leaf transport symbol '${sym}' resolves to TWO different catalog components ('${prev.catalog}' and '${catalog}') — a spec-fixed leaf symbol must map to ONE leaf (collision, fail-closed).`);
3188
- for (const e of echo)
3189
- if (!prev.echo.includes(e))
3190
- prev.echo.push(e);
3191
- continue;
3192
- }
3193
- bySym.set(sym, { catalog, echo });
3194
- }
3195
- }
3196
- for (const [sym, le] of bySym) {
3197
- const echoBlock = le.echo.length > 0 ? `${le.echo.join("\n")}\n` : "";
3198
- transportFns.push(`func ${sym}(payload WireRow) (WireValue, error) {
3199
- _ = payload
3200
- src, ok := nextScripted(${JSON.stringify(le.catalog)})
3201
- if !ok {
3202
- return WireValue{}, unknownComponent(${JSON.stringify(le.catalog)})
3203
- }
3204
- if src.isErr {
3205
- return WireValue{}, leafFailure(src.err)
3206
- }
3207
- ${echoBlock} // valueToWire is recursive: a batched/fanout []Value result becomes a WireList (a nil element ->
3208
- // WireNull, the dangling marker), a single result a scalar/row wire -- ONE signature serves every
3209
- // cardinality (the covered runner reads .Items for batched/fanout, the single wire for a point read).
3210
- return valueToWire(src.ok), nil
3211
- }`);
3212
- }
3213
- const adapter = `// scriptSrc — a scripted per-component outcome (an ok Value or an error), drained in order.
3214
- // #129: \`echo\` carries the reference scriptedHandlers' \`echo\` directive (e.g. "items") so a scripted
3215
- // node can ECHO a named input PORT back as its result — used to make the node→leaf array dataflow test
3216
- // non-vacuous (the leaf handler returns its \`items\` port, so a dropped/boxed native array diverges).
3217
- type scriptSrc struct {
3218
- isErr bool
3219
- err string
3220
- echo string
3221
- ok ${PKG}.Value
3222
- }
3223
-
3224
- // the shared scripted-outcome source the free Leaf_<comp> transport funcs drain (TEST glue). A package var
3225
- // (not a per-call handler object) so the bc#87 parallel goroutines share it (mutex-guarded); reset+filled
3226
- // per case by ObserveNativeRaw. Cases run sequentially in the harness, so one shared queue per case is fine.
3227
- var (
3228
- scriptedMu sync.Mutex
3229
- scriptedQueues = map[string][]scriptSrc{}
3230
- scriptedSeen int
3231
- )
3232
-
3233
- // fillScripted resets + loads the shared queue from the JSON handlers spec (the SAME shape the reference
3234
- // scriptedHandlers reads): { "<component>": {ok|error} | [ {ok|error}, … ] }. Each ok Value is
3235
- // DecodeValue'd once here (test glue). Returns any decode error (surfaced by the runner as a fatal).
3236
- func fillScripted(spec *${PKG}.JObj) error {
3237
- scriptedMu.Lock()
3238
- defer scriptedMu.Unlock()
3239
- scriptedQueues = map[string][]scriptSrc{}
3240
- scriptedSeen = 0
3241
- if spec == nil {
3242
- return nil
3243
- }
3244
- for _, comp := range spec.Keys {
3245
- var entries []${PKG}.JNode
3246
- switch t := spec.Vals[comp].(type) {
3247
- case []${PKG}.JNode:
3248
- entries = t
3249
- default:
3250
- entries = []${PKG}.JNode{t}
3251
- }
3252
- for _, e := range entries {
3253
- eo, _ := e.(*${PKG}.JObj)
3254
- // #129: an \`echo\` directive names an input port to echo back (mirrors the reference
3255
- // scriptedHandlers' \`echo === "items"\`). It is drained together with the ok payload.
3256
- echo := ""
3257
- if echoNode, has := eo.Get("echo"); has {
3258
- echo, _ = echoNode.(string)
3259
- // normalize echo:port to the port NAME X so a de-box handler's echo comparison fires;
3260
- // echo:items already names the port directly.
3261
- if echo == "port" {
3262
- if portNode, hasPort := eo.Get("port"); hasPort {
3263
- echo, _ = portNode.(string)
3264
- }
3265
- }
3266
- }
3267
- if okNode, has := eo.Get("ok"); has {
3268
- val, derr := ${PKG}.DecodeValue(okNode)
3269
- if derr != nil {
3270
- return derr
3271
- }
3272
- scriptedQueues[comp] = append(scriptedQueues[comp], scriptSrc{ok: val, echo: echo})
3273
- continue
3274
- }
3275
- ev, _ := eo.Get("error")
3276
- es, _ := ev.(string)
3277
- scriptedQueues[comp] = append(scriptedQueues[comp], scriptSrc{isErr: true, err: es})
3278
- }
3279
- }
3280
- return nil
3281
- }
3282
-
3283
- // nextScripted drains one scripted outcome for a component (last entry repeats — mirrors the reference
3284
- // scriptedHandlers), returns ok=false when the component has no scripted queue (fail-closed). The bc#87
3285
- // parallel-stage runner calls the transport funcs from multiple goroutines, so the drain is mutex-guarded.
3286
- func nextScripted(component string) (scriptSrc, bool) {
3287
- scriptedMu.Lock()
3288
- defer scriptedMu.Unlock()
3289
- scriptedSeen++
3290
- q, ok := scriptedQueues[component]
3291
- if !ok || len(q) == 0 {
3292
- return scriptSrc{}, false
3293
- }
3294
- if len(q) > 1 {
3295
- v := q[0]
3296
- scriptedQueues[component] = q[1:]
3297
- return v, true
3298
- }
3299
- return q[0], true
3300
- }`;
3301
- return `// GENERATED test-only observe companion (bc#77) — NOT part of the covered module. Serializes the
3302
- // struct-native runner's result to a canonical Value for the equivalence pin, and carries the SCRIPTED
3303
- // analog of the consumer's leaf transport symbols: free Leaf_<comp> funcs (same package as the covered
3304
- // module, so its transport calls resolve) that drain a shared package-level scripted queue + the CONCRETE
3305
- // WireValue/WireRow/WireList seam types. The consumer never uses this (it keeps the model native + supplies
3306
- // its own concrete WireValue + transport funcs); it exists only so the test harness can byte-compare the
3307
- // STRUCT-only covered read against run_behavior. Same package as the module (#192: shared namespace).
3308
- package ${goPackageName(namespace)}
3309
-
3310
- import (
3311
- "sync"
3312
-
3313
- ${PKG} "${runtimeImport ?? "github.com/foo-ogawa/behavior-contracts/go"}"
3314
- )
3315
-
3316
- // valueToWire (TEST glue) — builds the covered module's BC-owned WireValue from a scripted bc Value.
3317
- ${wireAdapter}
3318
-
3319
- // typed -> Value serializers (TEST glue only — the covered module has none).
3320
- ${serializers}
3321
-
3322
- // Value -> typed struct marshallers (+ must* helpers) for the input decoders (TEST glue only).
3323
- ${marshallers}
3324
-
3325
- ${mustHelpers}
3326
-
3327
- ${arrOptHelpers}
3328
-
3329
- // input decoders (generic *Obj -> concrete In_<comp>; TEST glue, one decode at the observe boundary).
3330
- ${inDecoders}
3331
-
3332
- ${adapter}
3333
-
3334
- // scripted leaf transport funcs (one per covered leaf — the free op-agnostic transport the covered runner
3335
- // calls directly; test glue draining the shared package queue).
3336
- ${transportFns.join("\n\n")}
3337
-
3338
- // ObserveNativeRaw resets+fills the shared scripted queue from the per-case spec, then drives the covered
3339
- // struct-native runner and serializes to a canonical Value (test only). No handler object is passed — the
3340
- // runner calls the free Leaf_<comp> transport funcs above directly (same package).
3341
- func ObserveNativeRaw(name string, spec *${PKG}.JObj, input *${PKG}.Obj) (${PKG}.Value, error) {
3342
- if ferr := fillScripted(spec); ferr != nil {
3343
- return nil, ferr
3344
- }
3345
- ${arms}
3346
- return nil, ${PKG}.NewBehaviorFailure("UNKNOWN_ENTRY", "component '"+name+"' is not a covered read (fail-closed)")
3347
- }
3348
- `;
3349
- }
3350
2917
  /**
3351
2918
  * goTypedNativeEmitter — language id `go-typed-native` (bc#77). Emits the generic straight-line
3352
2919
  * body (for non-covered components / helpers) plus the COMBINED READ layer (native ports struct