behavior-contracts 0.8.11 → 0.8.12

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 (36) hide show
  1. package/README.md +22 -16
  2. package/cli-contract.yaml +46 -44
  3. package/dist/cli.js +16 -14
  4. package/dist/cli.js.map +1 -1
  5. package/dist/commands/codegen.d.ts +4 -3
  6. package/dist/commands/codegen.d.ts.map +1 -1
  7. package/dist/commands/codegen.js +8 -5
  8. package/dist/commands/codegen.js.map +1 -1
  9. package/dist/generated/commands.d.ts.map +1 -1
  10. package/dist/generated/commands.js +12 -16
  11. package/dist/generated/commands.js.map +1 -1
  12. package/dist/generated/contract.d.ts.map +1 -1
  13. package/dist/generated/contract.js +2 -2
  14. package/dist/generated/contract.js.map +1 -1
  15. package/dist/generated/program.d.ts +6 -8
  16. package/dist/generated/program.d.ts.map +1 -1
  17. package/dist/generated/program.js +6 -8
  18. package/dist/generated/program.js.map +1 -1
  19. package/dist/generated/types.d.ts +6 -8
  20. package/dist/generated/types.d.ts.map +1 -1
  21. package/dist/generator/core.d.ts +9 -24
  22. package/dist/generator/core.d.ts.map +1 -1
  23. package/dist/generator/core.js +1 -1
  24. package/dist/generator/core.js.map +1 -1
  25. package/dist/generator/emit-typed-native-go.d.ts +10 -0
  26. package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
  27. package/dist/generator/emit-typed-native-go.js +340 -202
  28. package/dist/generator/emit-typed-native-go.js.map +1 -1
  29. package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
  30. package/dist/generator/emit-typed-native-rust.js +195 -221
  31. package/dist/generator/emit-typed-native-rust.js.map +1 -1
  32. package/dist/generator/index.d.ts +1 -1
  33. package/dist/generator/index.d.ts.map +1 -1
  34. package/dist/generator/index.js +1 -1
  35. package/dist/generator/index.js.map +1 -1
  36. package/package.json +1 -1
@@ -7,17 +7,18 @@ import { concurrencyPlan, execPlan, analyzeSequentialOps, classifyExpr, buildCom
7
7
  import { NativeExprCompiler } from "./native-expr.js";
8
8
  import { buildDeBoxPlan, notationOfRef } from "./emit-shared-debox.js";
9
9
  const PKG = "dslcontracts";
10
- /** resolveGoWire — the CONCRETE consumer wire type names the de-box classifies a node result against
11
- * (bc#141). Default (no option) → the in-package convention names, unqualified. A configured `import`
12
- * qualifies the names with the imported package's selector so a consumer can keep its wire types in its
13
- * own package. `value`/`row`/`list` name the WireValue / WireRow / WireList concrete types; the covered
14
- * runner + the generated Probe result structs reference them by these names. */
10
+ /** resolveGoWire — the BC-OWNED wire type names the de-box classifies a node result against. bc OWNS +
11
+ * GENERATES `WireValue`/`WireRow`/`WireList` (emitGoWireTypes); the consumer supplies none. A configured
12
+ * `sharedTypesImport` (Task A cross-package) qualifies the names with the shared BC-generated package's
13
+ * selector and moves the type definitions there (so a separate transport package can return them without an
14
+ * import cycle); absent → in-package (the covered module defines + references them unqualified). */
15
15
  function resolveGoWire(ctx) {
16
- const w = ctx.goWire;
17
- if (w === undefined)
16
+ const imp = ctx.sharedTypesImport;
17
+ if (imp === undefined)
18
18
  return { value: "WireValue", row: "WireRow", list: "WireList" };
19
- const sel = w.import !== undefined ? `${w.import.split("/").pop().replace(/[^A-Za-z0-9_]/g, "_")}.` : "";
20
- return { value: `${sel}${w.value}`, row: `${sel}${w.row}`, list: `${sel}${w.list}`, import: w.import };
19
+ const bare = imp.split("/").pop().replace(/[^A-Za-z0-9_]/g, "_");
20
+ const sel = `${bare}.`;
21
+ return { value: `${sel}WireValue`, row: `${sel}WireRow`, list: `${sel}WireList`, import: imp, selector: bare };
21
22
  }
22
23
  /** goErr — build the LOCAL concrete error value for a behavior/plan failure on the covered read
23
24
  * plane (runtime-free). The covered module declares `type BehaviorError struct { Code, Message string }`
@@ -290,14 +291,22 @@ function renderResultDeBox(ref, target, srcExpr, nodeId, plan, indent, fail, ctr
290
291
  * WireList seam types (that would own the wire format, and a Go interface is vtable dynamic dispatch); it
291
292
  * REFERENCES the consumer's CONCRETE types by name (RowProbe.Got is a `${wire.row}`, ListProbe.Got a
292
293
  * `${wire.list}`) and the runner calls their methods directly (zero dynamic dispatch, zero dictionary). */
293
- function emitProbeWireTypes(wire) {
294
+ /** emitGoProbeKinds — the probe kind consts. Emitted in the COVERED module ALWAYS (the inline de-box
295
+ * compares against them) AND in the shared wire package (its classifiers set them). Both packages carry an
296
+ * identical copy (values 0..3), so a probe struct built in one package compares equal in the other — no
297
+ * cross-package const reference, no export needed. */
298
+ function emitGoProbeKinds() {
294
299
  return `// Probe kinds — the outcome of classifying one wire attribute against a declared field type.
295
300
  const (
296
301
  probeGot uint8 = 0 // present; the wire variant matches the declared type
297
302
  probeWrong uint8 = 1 // present but a different wire variant (carries ActualWireType + Raw)
298
303
  probeAbsent uint8 = 2 // no attribute for this field
299
304
  probeNull uint8 = 3 // present as the producer's null variant (opt → None; required → mismatch)
300
- )
305
+ )`;
306
+ }
307
+ function emitProbeWireTypes(wire) {
308
+ return `// Probe RESULT structs — concrete data the WireValue classifiers hand back; the de-box reads .Kind /
309
+ // .Got / .ActualWireType / .Raw (exported fields).
301
310
 
302
311
  // StringProbe / NumberProbe / BoolProbe — a scalar probe result. Got holds the matched value (a
303
312
  // NumberProbe's Got is the raw numeric text; the de-box parses + range-checks it). ActualWireType is the
@@ -341,6 +350,198 @@ type ListProbe struct {
341
350
  Raw string
342
351
  }`;
343
352
  }
353
+ /** emitGoWireTypes — the BC-OWNED, BC-GENERATED, self-contained (runtime-free) concrete wire types + their
354
+ * classification. bc GENERATES the whole seam: `WireValue` is the generic result the consumer's SINGLE
355
+ * op-agnostic transport builds + returns (implementing NOTHING over it); numbers ride as raw text so BC
356
+ * owns overflow. The generated inline de-box reads it via the As.../Probe.../Elem... methods — static
357
+ * extraction lowers it to the covered plane's typed values immediately (no dynamic value crosses the covered
358
+ * plane). WireRow/WireList probes hand out a value wrapper over a SHARED slice backing (no deep copy). NO
359
+ * consumer classification. */
360
+ function emitGoWireTypes() {
361
+ return `// WireValue — the BC-OWNED generic result the consumer's single op-agnostic transport builds + returns
362
+ // (WireStr/WireNum/WireInt/WireFloat/WireBool/WireNull/WireRowOf/WireListOf) and implements NOTHING over.
363
+ // A self-contained tagged union (no untyped box, no bc-runtime Value); numbers carry raw text (BC parses +
364
+ // range-checks → overflow is BC's to detect). Composite = nested Entries (row) / Items (list).
365
+ type WireValue struct {
366
+ kind uint8
367
+ str string
368
+ num string
369
+ bl bool
370
+ Entries []WireField
371
+ Items []WireValue
372
+ }
373
+
374
+ type WireField struct {
375
+ Key string
376
+ Val WireValue
377
+ }
378
+
379
+ // WireRow / WireList — a wire map / array handle over a SHARED slice backing (value type; probes return the
380
+ // bc probe RESULT structs). The generated de-box probes them by declared field / element.
381
+ type WireRow struct {
382
+ entries []WireField
383
+ }
384
+
385
+ type WireList struct {
386
+ items []WireValue
387
+ }
388
+
389
+ const (
390
+ wireNull uint8 = 0
391
+ wireStr uint8 = 1
392
+ wireNum uint8 = 2
393
+ wireBool uint8 = 3
394
+ wireRow uint8 = 4
395
+ wireList uint8 = 5
396
+ )
397
+
398
+ // constructors the consumer's transport uses to build the result (numbers ride as raw text).
399
+ func WireStr(s string) WireValue { return WireValue{kind: wireStr, str: s} }
400
+ func WireNum(s string) WireValue { return WireValue{kind: wireNum, num: s} }
401
+ func WireInt(n int64) WireValue { return WireValue{kind: wireNum, num: strconv.FormatInt(n, 10)} }
402
+ func WireFloat(f float64) WireValue { return WireValue{kind: wireNum, num: strconv.FormatFloat(f, 'g', -1, 64)} }
403
+ func WireBool(b bool) WireValue { return WireValue{kind: wireBool, bl: b} }
404
+ func WireNull() WireValue { return WireValue{kind: wireNull} }
405
+ func WireRowOf(fields []WireField) WireValue { return WireValue{kind: wireRow, Entries: fields} }
406
+ func WireListOf(items []WireValue) WireValue { return WireValue{kind: wireList, Items: items} }
407
+
408
+ func (w *WireValue) wireTag() string {
409
+ switch w.kind {
410
+ case wireStr:
411
+ return "S"
412
+ case wireNum:
413
+ return "N"
414
+ case wireBool:
415
+ return "BOOL"
416
+ case wireRow:
417
+ return "M"
418
+ case wireList:
419
+ return "L"
420
+ default:
421
+ return "NULL"
422
+ }
423
+ }
424
+ func (w *WireValue) wireRaw() string {
425
+ switch w.kind {
426
+ case wireStr:
427
+ return w.str
428
+ case wireNum:
429
+ return w.num
430
+ case wireBool:
431
+ if w.bl {
432
+ return "true"
433
+ }
434
+ return "false"
435
+ case wireNull:
436
+ return "null"
437
+ default:
438
+ return "[composite]"
439
+ }
440
+ }
441
+
442
+ // the top result is always present; field/elem probes share the same classifiers over *WireValue (nil = absent).
443
+ func (w WireValue) AsString() StringProbe { return probeStringOf(&w) }
444
+ func (w WireValue) AsNumber() NumberProbe { return probeNumberOf(&w) }
445
+ func (w WireValue) AsBool() BoolProbe { return probeBoolOf(&w) }
446
+ func (w WireValue) AsRow() RowProbe { return probeRowOf(&w) }
447
+ func (w WireValue) AsList() ListProbe { return probeListOf(&w) }
448
+
449
+ func (r WireRow) get(field string) *WireValue {
450
+ for i := range r.entries {
451
+ if r.entries[i].Key == field {
452
+ return &r.entries[i].Val
453
+ }
454
+ }
455
+ return nil
456
+ }
457
+ func (r WireRow) Keys() []string {
458
+ ks := make([]string, len(r.entries))
459
+ for i := range r.entries {
460
+ ks[i] = r.entries[i].Key
461
+ }
462
+ return ks
463
+ }
464
+ func (r WireRow) ProbeString(field string) StringProbe { return probeStringOf(r.get(field)) }
465
+ func (r WireRow) ProbeNumber(field string) NumberProbe { return probeNumberOf(r.get(field)) }
466
+ func (r WireRow) ProbeBool(field string) BoolProbe { return probeBoolOf(r.get(field)) }
467
+ func (r WireRow) ProbeRow(field string) RowProbe { return probeRowOf(r.get(field)) }
468
+ func (r WireRow) ProbeList(field string) ListProbe { return probeListOf(r.get(field)) }
469
+
470
+ func (l WireList) Len() int { return len(l.items) }
471
+ func (l WireList) ElemString(i int) StringProbe { return probeStringOf(&l.items[i]) }
472
+ func (l WireList) ElemNumber(i int) NumberProbe { return probeNumberOf(&l.items[i]) }
473
+ func (l WireList) ElemBool(i int) BoolProbe { return probeBoolOf(&l.items[i]) }
474
+ func (l WireList) ElemRow(i int) RowProbe { return probeRowOf(&l.items[i]) }
475
+ func (l WireList) ElemList(i int) ListProbe { return probeListOf(&l.items[i]) }
476
+
477
+ // the ONE classifier per kind, over *WireValue (nil = absent attribute/element). The BC-owned variant IS
478
+ // the wire tag — no consumer classification.
479
+ func probeStringOf(w *WireValue) StringProbe {
480
+ if w == nil {
481
+ return StringProbe{Kind: probeAbsent}
482
+ }
483
+ switch w.kind {
484
+ case wireStr:
485
+ return StringProbe{Kind: probeGot, Got: w.str, ActualWireType: "S", Raw: w.str}
486
+ case wireNull:
487
+ return StringProbe{Kind: probeNull, ActualWireType: "NULL", Raw: "null"}
488
+ default:
489
+ return StringProbe{Kind: probeWrong, ActualWireType: w.wireTag(), Raw: w.wireRaw()}
490
+ }
491
+ }
492
+ func probeNumberOf(w *WireValue) NumberProbe {
493
+ if w == nil {
494
+ return NumberProbe{Kind: probeAbsent}
495
+ }
496
+ switch w.kind {
497
+ case wireNum:
498
+ return NumberProbe{Kind: probeGot, Got: w.num, ActualWireType: "N", Raw: w.num}
499
+ case wireNull:
500
+ return NumberProbe{Kind: probeNull, ActualWireType: "NULL", Raw: "null"}
501
+ default:
502
+ return NumberProbe{Kind: probeWrong, ActualWireType: w.wireTag(), Raw: w.wireRaw()}
503
+ }
504
+ }
505
+ func probeBoolOf(w *WireValue) BoolProbe {
506
+ if w == nil {
507
+ return BoolProbe{Kind: probeAbsent}
508
+ }
509
+ switch w.kind {
510
+ case wireBool:
511
+ return BoolProbe{Kind: probeGot, Got: w.bl, ActualWireType: "BOOL", Raw: w.wireRaw()}
512
+ case wireNull:
513
+ return BoolProbe{Kind: probeNull, ActualWireType: "NULL", Raw: "null"}
514
+ default:
515
+ return BoolProbe{Kind: probeWrong, ActualWireType: w.wireTag(), Raw: w.wireRaw()}
516
+ }
517
+ }
518
+ func probeRowOf(w *WireValue) RowProbe {
519
+ if w == nil {
520
+ return RowProbe{Kind: probeAbsent}
521
+ }
522
+ switch w.kind {
523
+ case wireRow:
524
+ return RowProbe{Kind: probeGot, Got: WireRow{entries: w.Entries}, ActualWireType: "M"}
525
+ case wireNull:
526
+ return RowProbe{Kind: probeNull, ActualWireType: "NULL", Raw: "null"}
527
+ default:
528
+ return RowProbe{Kind: probeWrong, ActualWireType: w.wireTag(), Raw: w.wireRaw()}
529
+ }
530
+ }
531
+ func probeListOf(w *WireValue) ListProbe {
532
+ if w == nil {
533
+ return ListProbe{Kind: probeAbsent}
534
+ }
535
+ switch w.kind {
536
+ case wireList:
537
+ return ListProbe{Kind: probeGot, Got: WireList{items: w.Items}, ActualWireType: "L"}
538
+ case wireNull:
539
+ return ListProbe{Kind: probeNull, ActualWireType: "NULL", Raw: "null"}
540
+ default:
541
+ return ListProbe{Kind: probeWrong, ActualWireType: w.wireTag(), Raw: w.wireRaw()}
542
+ }
543
+ }`;
544
+ }
344
545
  /** mapFanoutElemRef — the element ROW TypeRef a map/fanout node decodes (the per-element record). */
345
546
  function mapFanoutElemRef(node, typedNodes, plan) {
346
547
  const ref = typedNodes.get(node.id);
@@ -1398,18 +1599,24 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1398
1599
  * consumer (graphddb) drives it and keeps the struct native. A Value observation is produced ONLY
1399
1600
  * by the separate serialize wrapper (run_native_raw_<comp>, below), the single outer Value boundary.
1400
1601
  */
1602
+ /** isCrossPackageSharedNode — a node whose ports struct CROSSES the leaf-transport boundary as a whole
1603
+ * value (the batch ports struct passed to the transport), so under --shared-types-import it must live in
1604
+ * the shared package (else the transport package → covered package import cycle). Batched maps + fanouts
1605
+ * pass `${struct}_batch{Items: []${struct}}`; every other node passes only primitive port fields, so its
1606
+ * ports struct stays local. The SINGLE predicate emit() (skip-local) and the shared package (emit-there)
1607
+ * both use — they never disagree. */
1608
+ function isCrossPackageSharedNode(n) {
1609
+ return "fanout" in n || ("map" in n && n.map.batched === true);
1610
+ }
1401
1611
  function emitNativeRawRunner(comp, plan, flags, wire, leaf) {
1402
1612
  const ep = execPlan(comp);
1403
1613
  const order = ep.order;
1404
1614
  const cplan = buildComponentPlan(comp, goStraightlineInternals.dialect, "scope");
1405
1615
  const metas = analyzeSequentialOps(cplan.opsLiteral, order);
1406
1616
  const fn = sanitize(comp.name);
1407
- const typedNodes = new Map();
1408
1617
  // #125: a control-gate cond has NO outType (skip marker) — it never yields a typed data cell, so it
1409
1618
  // carries no typedNodes entry. Its skip is expressed purely via produced_<gate> (children gate on it).
1410
- for (const n of comp.body)
1411
- if (!isControlGate(n))
1412
- typedNodes.set(n.id, "map" in n ? mapNodeArrRef(n, plan) : deriveTypeRef(n.outType, plan));
1619
+ const typedNodes = buildTypedNodes(comp, plan);
1413
1620
  const idToPos = new Map();
1414
1621
  order.forEach((opIdx, k) => idToPos.set(comp.body[opIdx].id, k));
1415
1622
  const priorNodeAt = (head, atPos) => {
@@ -1471,12 +1678,12 @@ function emitNativeRawRunner(comp, plan, flags, wire, leaf) {
1471
1678
  // v3: a covered fanout node — deduped batched dispatch + first-seen dedupe + dangling drop +
1472
1679
  // connection wrap (the SAME definition as run_behavior's fanoutDedupDrop).
1473
1680
  if ("fanout" in comp.body[i]) {
1474
- lines.push(emitFanoutArm(comp, comp.body[i], k, typedNodes, plan, priorNodeAt, zeroOut, leaf));
1681
+ lines.push(emitFanoutArm(comp, comp.body[i], k, typedNodes, plan, priorNodeAt, zeroOut, leaf, wire.selector));
1475
1682
  continue;
1476
1683
  }
1477
1684
  // #86 pt2: a covered batched map...into node — struct-native element collection + into enrichment.
1478
1685
  if ("map" in comp.body[i]) {
1479
- lines.push(emitMapArm(comp, comp.body[i], k, typedNodes, plan, priorNodeAt, zeroOut, flags, leaf));
1686
+ lines.push(emitMapArm(comp, comp.body[i], k, typedNodes, plan, priorNodeAt, zeroOut, flags, leaf, wire.selector));
1480
1687
  continue;
1481
1688
  }
1482
1689
  // #108: a cond node — pure Expression (no handler). Compile `if` to a native bool + materialize the
@@ -1622,13 +1829,17 @@ function emitNativeRawRunner(comp, plan, flags, wire, leaf) {
1622
1829
  * (direct field assignment; $as refs read the over element's typed fields), and the result is a
1623
1830
  * native []T with NO boxed Value on any plane. The map is under the parent's produced gate (inline).
1624
1831
  */
1625
- function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, flags, leaf) {
1832
+ function emitMapArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, flags, leaf, wireSel) {
1626
1833
  const m = node.map;
1627
1834
  const batched = m.batched === true;
1628
1835
  const hasInto = m.into !== undefined;
1629
1836
  const hasGuard = m.when !== undefined;
1630
1837
  const s = sanitize(node.id);
1631
- const structName = portsStructName(comp.name, node.id);
1838
+ // #154 cross-package: a BATCHED map's element + batch ports structs live in the shared package (they
1839
+ // cross the transport boundary as a whole value), so reference them selector-qualified here. A
1840
+ // non-batched map passes only primitive fields, so its ports struct stays local (unqualified).
1841
+ const q = wireSel !== undefined && batched ? `${wireSel}.` : "";
1842
+ const structName = `${q}${portsStructName(comp.name, node.id)}`;
1632
1843
  const batchStruct = `${structName}_batch`;
1633
1844
  const leafSym = resolveLeafSymbol(m.component, leaf);
1634
1845
  const arrRef = typedNodes.get(node.id);
@@ -1795,10 +2006,13 @@ function elemLocal(s) {
1795
2006
  * (STRUCTURAL — the connection items elem type already omits the implicitSource field), and wrap into
1796
2007
  * the connection struct {items, cursor:nil}. NO boxed Value on any plane. Byte-equal to run_behavior.
1797
2008
  */
1798
- function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, leaf) {
2009
+ function emitFanoutArm(comp, node, atPos, typedNodes, plan, priorNodeAt, zeroOut, leaf, wireSel) {
1799
2010
  const f = node.fanout;
1800
2011
  const s = sanitize(node.id);
1801
- const structName = portsStructName(comp.name, node.id);
2012
+ // #154 cross-package: a fanout's element + batch ports structs cross the transport boundary as a whole
2013
+ // value, so they live in the shared package — reference them selector-qualified here (else in-package).
2014
+ const q = wireSel !== undefined ? `${wireSel}.` : "";
2015
+ const structName = `${q}${portsStructName(comp.name, node.id)}`;
1802
2016
  const batchStruct = `${structName}_batch`;
1803
2017
  const leafSym = resolveLeafSymbol(f.component, leaf);
1804
2018
  const connRef = typedNodes.get(node.id);
@@ -2330,8 +2544,9 @@ function emitMinimalHeader(ctx, needStrings, needSync, needFmt, needMath, needSt
2330
2544
  imports.push(`\t"strings"`);
2331
2545
  if (needSync)
2332
2546
  imports.push(`\t"sync"`);
2333
- // a configured consumer wire package (goWire.import) — the covered module references its CONCRETE
2334
- // WireValue/WireRow/WireList types (default: in-package, no import).
2547
+ // the BC-generated shared wire package (sharedTypesImport) — the covered module references its
2548
+ // BC-OWNED WireValue/WireRow/WireList (+ batched/fanout batch ports structs) qualified by the
2549
+ // package selector (default: in-package, no import).
2335
2550
  if (wireImport !== undefined)
2336
2551
  imports.push(`\t${JSON.stringify(wireImport)}`);
2337
2552
  // a configured leaf-transport package (leafTransport.import) — the covered module calls the op-agnostic
@@ -2374,15 +2589,20 @@ function emit(ctx) {
2374
2589
  // every covered node returns a WireValue the inline de-box classifies — the wire seam (probe kind
2375
2590
  // consts + probe RESULT structs) is emitted once whenever any handler node exists.
2376
2591
  const anyWire = native.some((c) => c.body.some((n) => !("cond" in n)));
2592
+ // #154 cross-package (--shared-types-import): a batched-map / fanout batch ports struct crosses the
2593
+ // transport boundary as a whole value, so it lives in the SHARED package (goSharedWireTypesPackage),
2594
+ // NOT the covered module — else the transport package would import the covered package (cycle). Every
2595
+ // other ports struct passes only primitive fields and stays local.
2596
+ const crossPackage = wire.import !== undefined;
2377
2597
  for (const c of native) {
2378
2598
  inStructs.push(emitInStruct(c, plan));
2379
- const typedNodes = new Map();
2380
2599
  // build the full typed-node map FIRST so a map's over-element resolution can see every node.
2381
- for (const n of c.body)
2382
- if (!isControlGate(n))
2383
- typedNodes.set(n.id, "map" in n ? mapNodeArrRef(n, plan) : deriveTypeRef(n.outType, plan)); // #125: control-gate typeless; map は produced-array ref に正規化
2600
+ const typedNodes = buildTypedNodes(c, plan);
2384
2601
  for (const n of c.body) {
2385
- if ("fanout" in n) {
2602
+ if (crossPackage && isCrossPackageSharedNode(n)) {
2603
+ // emitted in the shared package instead (goSharedWireTypesPackage), referenced here as <sel>.<T>.
2604
+ }
2605
+ else if ("fanout" in n) {
2386
2606
  // v3: a fanout node emits a per-id element ports struct + a batch struct (like a batched map).
2387
2607
  structs.push(emitFanoutPortsStructs(c, n, typedNodes, plan));
2388
2608
  }
@@ -2432,9 +2652,17 @@ function emit(ctx) {
2432
2652
  // #108: `math` is imported iff the native-expr compiler emitted a fallible helper (bcExpr_modF uses
2433
2653
  // math.Mod). The helper library itself is baked into the module only when used (goExprUsed.helpers).
2434
2654
  const needMath = goExprUsed.helpers;
2435
- // `strconv` is imported iff a generated inline de-box parses a numeric field (int/float range check).
2436
- const needStrconv = runnerCodes.some((c) => c.includes("strconv."));
2437
- const header = emitMinimalHeader(ctx, false, needSync, needFmt, needMath, needStrconv, wire.import, leaf?.import);
2655
+ // `strconv` is imported iff a generated inline de-box parses a numeric field (int/float range check) OR
2656
+ // the BC-owned wire types are emitted in-package (their WireInt/WireFloat constructors use strconv).
2657
+ const emitsWireTypes = anyWire && wire.import === undefined;
2658
+ const needStrconv = runnerCodes.some((c) => c.includes("strconv.")) || emitsWireTypes;
2659
+ // the covered module imports the shared wire package ONLY when it NAMES a qualified shared symbol — a
2660
+ // `var wire_s <pkg>.WireValue` (bc#87 parallel stage) OR a `<pkg>.PortsNR_*` batched/fanout ports struct
2661
+ // (#154 cross-package). A point/relation read holds the transport's return by inference + uses its LOCAL
2662
+ // probe consts, so it references nothing from the shared package and must NOT import it (an unused import
2663
+ // is a Go compile error). The `<sel>.` prefix covers both (wire.value is `<sel>.WireValue`).
2664
+ const needWireImport = wire.import !== undefined && wire.selector !== undefined && runnerCodes.some((c) => c.includes(`${wire.selector}.`));
2665
+ const header = emitMinimalHeader(ctx, false, needSync, needFmt, needMath, needStrconv, needWireImport ? wire.import : undefined, leaf?.import);
2438
2666
  const banner = `// COMBINED READ layer (bc#90 — the RUNTIME-FREE read de-box; STRUCT-ONLY, FULLY-NATIVE surface). A
2439
2667
  // covered read is a strictly-sequential typed componentRef chain (point reads + relationKind:single
2440
2668
  // children), emitted ONLY here: each node builds a native ports struct by direct field assignment (every
@@ -2456,8 +2684,11 @@ function emit(ctx) {
2456
2684
  `// Local concrete failure type (runtime-free) — a covered runner returns *BehaviorError (satisfies\n// error) instead of a bc-runtime failure, so the fully-covered module imports ZERO bc runtime.\n${behaviorErrorType}`,
2457
2685
  decls ? `// Typed struct declarations (outType-derived; hash-dedup — shared type plan).\n${decls}` : undefined,
2458
2686
  `// Per-component CONCRETE input structs (fields = inputPorts; the consumer builds them natively —\n// no generic *Obj crosses the covered read boundary).\n${inStructs.join("\n\n")}`,
2459
- anyWire
2460
- ? `// strict de-box wire seam — the consumer supplies CONCRETE ${wire.value} / ${wire.row} / ${wire.list}\n// types (variant classification) and the runner classifies each node result against the STATICALLY\n// declared type via their methods; the generated INLINE de-box owns strictness (required/optional,\n// present/absent, error assembly, fail-closed). bc emits only the probe RESULT structs — concrete data,\n// no boxed Value, no interface, no dictionary crosses the seam.\n${emitProbeWireTypes(wire)}`
2687
+ // the probe kind consts live in the covered module ALWAYS (the inline de-box compares against them); the
2688
+ // shared wire package carries its own identical copy when the types are hoisted there (cross-package).
2689
+ anyWire ? `// Probe kind consts (the inline de-box compares against these).\n${emitGoProbeKinds()}` : undefined,
2690
+ emitsWireTypes
2691
+ ? `// strict de-box wire seam — the BC-OWNED, BC-GENERATED concrete WireValue (+ WireRow/WireList) the\n// consumer's single transport builds + returns (implementing NOTHING over it), plus the probe RESULT\n// structs. The generated INLINE de-box classifies it against the STATICALLY declared type and owns\n// strictness (required/optional, present/absent, error assembly, fail-closed). Self-contained concrete\n// types — no interface, no boxed runtime value.\n${emitProbeWireTypes(wire)}\n\n${emitGoWireTypes()}`
2461
2692
  : undefined,
2462
2693
  elemCopiers.length
2463
2694
  ? `// Augmented map-element copiers (over element fields + the concrete into row — pure assignment).\n${elemCopiers.join("\n\n")}`
@@ -2473,6 +2704,48 @@ function emit(ctx) {
2473
2704
  ].filter((s) => !!s);
2474
2705
  return `${header}\n\n${sections.join("\n\n")}\n`;
2475
2706
  }
2707
+ /**
2708
+ * goSharedWireTypesPackage — the BC-GENERATED shared package (Task A cross-package). Emits the SAME seam the
2709
+ * covered module emits in-package (emitGoProbeKinds + emitProbeWireTypes + emitGoWireTypes) into a standalone
2710
+ * package, so a separate leaf-transport package can return `WireValue` (and the covered module reference it)
2711
+ * without an import cycle. When `ir` is given, ALSO emits the batched-map / fanout batch ports structs (the
2712
+ * ONLY covered-module types that cross the transport boundary as a whole value) — same `emitMapPortsStructs`
2713
+ * / `emitFanoutPortsStructs` + same `isCrossPackageSharedNode` predicate `emit()` uses to skip them locally,
2714
+ * so the two never disagree (SSoT). Self-contained (only `strconv` for the numeric constructors). `pkgName`
2715
+ * is the package's Go identifier (the last path segment of `sharedTypesImport`). */
2716
+ export function goSharedWireTypesPackage(pkgName, ir) {
2717
+ const portsStructs = [];
2718
+ if (ir !== undefined) {
2719
+ const components = ir.components;
2720
+ const plan = buildTypePlan(ir);
2721
+ for (const c of components.filter(isNativeRaw)) {
2722
+ const typedNodes = buildTypedNodes(c, plan);
2723
+ for (const n of c.body) {
2724
+ if (!isCrossPackageSharedNode(n))
2725
+ continue;
2726
+ portsStructs.push("fanout" in n
2727
+ ? emitFanoutPortsStructs(c, n, typedNodes, plan)
2728
+ : emitMapPortsStructs(c, n, typedNodes, plan));
2729
+ }
2730
+ }
2731
+ }
2732
+ const portsSection = portsStructs.length
2733
+ ? `\n\n// #154 cross-package batched/fanout ports structs — the batch ports the covered module's runner\n// passes to the leaf transport as a whole value. Here (not the covered module) so the transport package\n// can name them without importing the covered package (cycle-free). Native fields — no boxed Value.\n${portsStructs.join("\n\n")}`
2734
+ : "";
2735
+ return `// GENERATED by behavior-contracts (go-typed-native) — the BC-OWNED shared wire types. A covered module
2736
+ // generated with --shared-types-import imports this; a separate leaf-transport package returns its
2737
+ // WireValue. Self-contained + runtime-free.
2738
+ package ${pkgName}
2739
+
2740
+ import "strconv"
2741
+
2742
+ ${emitGoProbeKinds()}
2743
+
2744
+ ${emitProbeWireTypes({ row: "WireRow", list: "WireList" })}
2745
+
2746
+ ${emitGoWireTypes()}${portsSection}
2747
+ `;
2748
+ }
2476
2749
  /**
2477
2750
  * goTypedNativeObserve — the TEST-ONLY observe companion (a SEPARATE file in the SAME package as the
2478
2751
  * covered module). It carries the typed->Value serializers (ser_*) + the SCRIPTED analog of the consumer's
@@ -2516,177 +2789,42 @@ export function goTypedNativeObserve(ir, runtimeImport, leaf) {
2516
2789
  // generated inline de-box from the same scripted vectors run_behavior uses — so actualWireType observed
2517
2790
  // in a mismatch is the PRODUCER tag (e.g. "N"), not the collapsed native type.
2518
2791
  const wireAdapter = anyDeBox
2519
- ? `// ── scripted wire adapter (TEST glue) ──
2520
- func scriptedWireTag(v ${PKG}.Value) string {
2521
- switch v.(type) {
2522
- case nil:
2523
- return "NULL"
2524
- case bool:
2525
- return "BOOL"
2526
- case int64, float64:
2527
- return "N"
2528
- case string:
2529
- return "S"
2530
- case []${PKG}.Value:
2531
- return "L"
2532
- case *${PKG}.Obj:
2533
- return "M"
2534
- default:
2535
- return "UNKNOWN"
2536
- }
2537
- }
2538
-
2539
- func scriptedWireRaw(v ${PKG}.Value) string {
2792
+ ? `// valueToWire (TEST glue): builds the covered module's BC-OWNED concrete WireValue from a scripted bc
2793
+ // Value — the harness analog of the consumer's real transport (which builds WireValue as it reads the
2794
+ // producer). Numbers ride as raw text (WireNum); floats use the SAME repr as run_behavior (PyFloatRepr) so
2795
+ // the raw text is byte-identical. The wire tags + classification live ONCE in the covered module's
2796
+ // WireValue (probeStringOf etc.), so this only CONSTRUCTS.
2797
+ func valueToWire(v ${PKG}.Value) WireValue {
2540
2798
  switch t := v.(type) {
2541
2799
  case nil:
2542
- return "null"
2800
+ return WireNull()
2543
2801
  case bool:
2544
- if t {
2545
- return "true"
2546
- }
2547
- return "false"
2802
+ return WireBool(t)
2548
2803
  case int64:
2549
- return strconv.FormatInt(t, 10)
2804
+ return WireInt(t)
2550
2805
  case float64:
2551
2806
  s, _ := ${PKG}.PyFloatRepr(t)
2552
- return s
2807
+ return WireNum(s)
2553
2808
  case string:
2554
- return t
2809
+ return WireStr(t)
2810
+ case []${PKG}.Value:
2811
+ items := make([]WireValue, len(t))
2812
+ for i := range t {
2813
+ items[i] = valueToWire(t[i])
2814
+ }
2815
+ return WireListOf(items)
2816
+ case *${PKG}.Obj:
2817
+ fields := make([]WireField, len(t.Keys))
2818
+ for i, k := range t.Keys {
2819
+ vv, _ := t.Get(k)
2820
+ fields[i] = WireField{Key: k, Val: valueToWire(vv)}
2821
+ }
2822
+ return WireRowOf(fields)
2555
2823
  default:
2556
- return ${PKG}.EncodeValue(v)
2557
- }
2558
- }
2559
-
2560
- func probeStringVal(v ${PKG}.Value) StringProbe {
2561
- if v == nil {
2562
- return StringProbe{Kind: probeNull, ActualWireType: "NULL", Raw: "null"}
2563
- }
2564
- if s, ok := v.(string); ok {
2565
- return StringProbe{Kind: probeGot, Got: s, ActualWireType: "S", Raw: s}
2566
- }
2567
- return StringProbe{Kind: probeWrong, ActualWireType: scriptedWireTag(v), Raw: scriptedWireRaw(v)}
2568
- }
2569
-
2570
- func probeNumberVal(v ${PKG}.Value) NumberProbe {
2571
- if v == nil {
2572
- return NumberProbe{Kind: probeNull, ActualWireType: "NULL", Raw: "null"}
2573
- }
2574
- switch v.(type) {
2575
- case int64, float64:
2576
- return NumberProbe{Kind: probeGot, Got: scriptedWireRaw(v), ActualWireType: "N", Raw: scriptedWireRaw(v)}
2577
- }
2578
- return NumberProbe{Kind: probeWrong, ActualWireType: scriptedWireTag(v), Raw: scriptedWireRaw(v)}
2579
- }
2580
-
2581
- func probeBoolVal(v ${PKG}.Value) BoolProbe {
2582
- if v == nil {
2583
- return BoolProbe{Kind: probeNull, ActualWireType: "NULL", Raw: "null"}
2584
- }
2585
- if b, ok := v.(bool); ok {
2586
- return BoolProbe{Kind: probeGot, Got: b, ActualWireType: "BOOL", Raw: scriptedWireRaw(v)}
2824
+ return WireNull()
2587
2825
  }
2588
- return BoolProbe{Kind: probeWrong, ActualWireType: scriptedWireTag(v), Raw: scriptedWireRaw(v)}
2589
2826
  }
2590
2827
 
2591
- func probeRowVal(v ${PKG}.Value) RowProbe {
2592
- if v == nil {
2593
- return RowProbe{Kind: probeNull, ActualWireType: "NULL", Raw: "null"}
2594
- }
2595
- if o, ok := v.(*${PKG}.Obj); ok {
2596
- return RowProbe{Kind: probeGot, Got: WireRow{obj: o}, ActualWireType: "M"}
2597
- }
2598
- return RowProbe{Kind: probeWrong, ActualWireType: scriptedWireTag(v), Raw: scriptedWireRaw(v)}
2599
- }
2600
-
2601
- func probeListVal(v ${PKG}.Value) ListProbe {
2602
- if v == nil {
2603
- return ListProbe{Kind: probeNull, ActualWireType: "NULL", Raw: "null"}
2604
- }
2605
- if a, ok := v.([]${PKG}.Value); ok {
2606
- return ListProbe{Kind: probeGot, Got: WireList{items: a}, ActualWireType: "L"}
2607
- }
2608
- return ListProbe{Kind: probeWrong, ActualWireType: scriptedWireTag(v), Raw: scriptedWireRaw(v)}
2609
- }
2610
-
2611
- // WireValue — the CONCRETE scripted node-result wire (the in-package default seam type the covered runner
2612
- // classifies via As*). A top value is always present, so As* never observes Absent; a scripted null is a
2613
- // nil Value → Null. A real consumer supplies its own concrete WireValue over its AttributeValue payload.
2614
- type WireValue struct {
2615
- v ${PKG}.Value
2616
- }
2617
-
2618
- func (w WireValue) AsString() StringProbe { return probeStringVal(w.v) }
2619
- func (w WireValue) AsNumber() NumberProbe { return probeNumberVal(w.v) }
2620
- func (w WireValue) AsBool() BoolProbe { return probeBoolVal(w.v) }
2621
- func (w WireValue) AsRow() RowProbe { return probeRowVal(w.v) }
2622
- func (w WireValue) AsList() ListProbe { return probeListVal(w.v) }
2623
-
2624
- // WireRow / WireList — the CONCRETE scripted wire map / array (the in-package default seam types), probed
2625
- // per declared field / element by the generated inline de-box (their methods return bc's probe structs).
2626
- type WireRow struct {
2627
- obj *${PKG}.Obj
2628
- }
2629
-
2630
- func (w WireRow) field(name string) (${PKG}.Value, bool) {
2631
- if w.obj == nil {
2632
- return nil, false
2633
- }
2634
- return w.obj.Get(name)
2635
- }
2636
-
2637
- func (w WireRow) Keys() []string {
2638
- if w.obj == nil {
2639
- return nil
2640
- }
2641
- return w.obj.Keys
2642
- }
2643
-
2644
- func (w WireRow) ProbeString(field string) StringProbe {
2645
- if v, ok := w.field(field); ok {
2646
- return probeStringVal(v)
2647
- }
2648
- return StringProbe{Kind: probeAbsent}
2649
- }
2650
-
2651
- func (w WireRow) ProbeNumber(field string) NumberProbe {
2652
- if v, ok := w.field(field); ok {
2653
- return probeNumberVal(v)
2654
- }
2655
- return NumberProbe{Kind: probeAbsent}
2656
- }
2657
-
2658
- func (w WireRow) ProbeBool(field string) BoolProbe {
2659
- if v, ok := w.field(field); ok {
2660
- return probeBoolVal(v)
2661
- }
2662
- return BoolProbe{Kind: probeAbsent}
2663
- }
2664
-
2665
- func (w WireRow) ProbeRow(field string) RowProbe {
2666
- if v, ok := w.field(field); ok {
2667
- return probeRowVal(v)
2668
- }
2669
- return RowProbe{Kind: probeAbsent}
2670
- }
2671
-
2672
- func (w WireRow) ProbeList(field string) ListProbe {
2673
- if v, ok := w.field(field); ok {
2674
- return probeListVal(v)
2675
- }
2676
- return ListProbe{Kind: probeAbsent}
2677
- }
2678
-
2679
- type WireList struct {
2680
- items []${PKG}.Value
2681
- }
2682
-
2683
- func (l WireList) Len() int { return len(l.items) }
2684
- func (l WireList) ElemString(i int) StringProbe { return probeStringVal(l.items[i]) }
2685
- func (l WireList) ElemNumber(i int) NumberProbe { return probeNumberVal(l.items[i]) }
2686
- func (l WireList) ElemBool(i int) BoolProbe { return probeBoolVal(l.items[i]) }
2687
- func (l WireList) ElemRow(i int) RowProbe { return probeRowVal(l.items[i]) }
2688
- func (l WireList) ElemList(i int) ListProbe { return probeListVal(l.items[i]) }
2689
-
2690
2828
  // FailureDetail exposes the structured Error Value fields WITHOUT naming the local ErrorDetail type, so
2691
2829
  // the harness can assert the de-box's kind / field / expectedType / actualWireType / rawValue (TEST
2692
2830
  // glue — same package as the covered module, so it may read the fields directly).
@@ -2738,7 +2876,7 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
2738
2876
  wires = append(wires, nil)
2739
2877
  continue
2740
2878
  }
2741
- wv := WireValue{v: ev}
2879
+ wv := valueToWire(ev)
2742
2880
  wires = append(wires, &wv)
2743
2881
  }
2744
2882
  return wires, nil
@@ -2761,7 +2899,7 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
2761
2899
  arr, _ := src.ok.([]${PKG}.Value)
2762
2900
  wires := make([]WireValue, 0, len(arr))
2763
2901
  for _, ev := range arr {
2764
- wires = append(wires, WireValue{v: ev})
2902
+ wires = append(wires, valueToWire(ev))
2765
2903
  }
2766
2904
  return wires, nil
2767
2905
  }`);
@@ -2778,7 +2916,7 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
2778
2916
  if src.isErr {
2779
2917
  return WireValue{}, leafFailure(src.err)
2780
2918
  }
2781
- return WireValue{v: src.ok}, nil
2919
+ return valueToWire(src.ok), nil
2782
2920
  }`);
2783
2921
  }
2784
2922
  continue;
@@ -2803,18 +2941,18 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
2803
2941
  }
2804
2942
  if (portGo === recordGo) {
2805
2943
  // the port IS the whole record → echo it DIRECTLY (matching run_behavior's plain echo:port).
2806
- echoBranches.push(`\tif src.echo == ${JSON.stringify(pn)} {\n\t\treturn WireValue{v: ${serializeTyped(goPortFieldName(pn), ref, plan)}}, nil\n\t}`);
2944
+ echoBranches.push(`\tif src.echo == ${JSON.stringify(pn)} {\n\t\treturn valueToWire(${serializeTyped(goPortFieldName(pn), ref, plan)}), nil\n\t}`);
2807
2945
  }
2808
2946
  else if (fieldGo !== null && field !== undefined && portGo === fieldGo) {
2809
2947
  // a scalar port wraps into the record's single field ({v: ports.X}).
2810
- echoBranches.push(`\tif src.echo == ${JSON.stringify(pn)} {\n\t\treturn WireValue{v: ${serializeTyped(`${recordGo}{${goFieldName(field.name)}: ${goPortFieldName(pn)}}`, ref, plan)}}, nil\n\t}`);
2948
+ echoBranches.push(`\tif src.echo == ${JSON.stringify(pn)} {\n\t\treturn valueToWire(${serializeTyped(`${recordGo}{${goFieldName(field.name)}: ${goPortFieldName(pn)}}`, ref, plan)}), nil\n\t}`);
2811
2949
  }
2812
2950
  }
2813
2951
  }
2814
2952
  else if (ref.kind === "arr" && Object.prototype.hasOwnProperty.call(node.ports, "items")) {
2815
2953
  // #129: an arr node with an `items` port echoes the NATIVE port array (serialized to a Value array)
2816
2954
  // so the node→leaf array dataflow test is non-vacuous.
2817
- echoBranches.push(`\tif src.echo == "items" {\n\t\treturn WireValue{v: ${serializeTyped(goPortFieldName("items"), ref, plan)}}, nil\n\t}`);
2955
+ echoBranches.push(`\tif src.echo == "items" {\n\t\treturn valueToWire(${serializeTyped(goPortFieldName("items"), ref, plan)}), nil\n\t}`);
2818
2956
  }
2819
2957
  const canEcho = echoBranches.length > 0;
2820
2958
  // params keep their field names (echo reads them); Go allows unused params, so no underscore needed.
@@ -2828,7 +2966,7 @@ func (e *BehaviorError) FailureDetail() (kind, model, field, expectedType, actua
2828
2966
  if src.isErr {
2829
2967
  return WireValue{}, leafFailure(src.err)
2830
2968
  }
2831
- ${echoBlock} return WireValue{v: src.ok}, nil
2969
+ ${echoBlock} return valueToWire(src.ok), nil
2832
2970
  }`);
2833
2971
  }
2834
2972
  }
@@ -2930,12 +3068,12 @@ func nextScripted(component string) (scriptSrc, bool) {
2930
3068
  package behaviors
2931
3069
 
2932
3070
  import (
2933
- ${anyDeBox ? '\t"strconv"\n\n' : ""} "sync"
3071
+ "sync"
2934
3072
 
2935
3073
  ${PKG} "${runtimeImport ?? "github.com/foo-ogawa/behavior-contracts/go"}"
2936
3074
  )
2937
3075
 
2938
- // scripted wire adapter (TEST glue) — the CONCRETE WireValue/WireRow/WireList the covered module references.
3076
+ // valueToWire (TEST glue) — builds the covered module's BC-owned WireValue from a scripted bc Value.
2939
3077
  ${wireAdapter}
2940
3078
 
2941
3079
  // typed -> Value serializers (TEST glue only — the covered module has none).