behavior-contracts 0.12.0 → 0.13.0

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 (47) hide show
  1. package/README.md +20 -0
  2. package/dist/authoring.d.ts +4 -4
  3. package/dist/authoring.d.ts.map +1 -1
  4. package/dist/authoring.js +11 -23
  5. package/dist/authoring.js.map +1 -1
  6. package/dist/behavior.d.ts +3 -3
  7. package/dist/behavior.d.ts.map +1 -1
  8. package/dist/behavior.js +7 -10
  9. package/dist/behavior.js.map +1 -1
  10. package/dist/generator/emit-native-dynamic.d.ts.map +1 -1
  11. package/dist/generator/emit-native-dynamic.js +7 -4
  12. package/dist/generator/emit-native-dynamic.js.map +1 -1
  13. package/dist/generator/emit-shared-typescript.d.ts.map +1 -1
  14. package/dist/generator/emit-shared-typescript.js +15 -20
  15. package/dist/generator/emit-shared-typescript.js.map +1 -1
  16. package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
  17. package/dist/generator/emit-typed-native-go.js +19 -11
  18. package/dist/generator/emit-typed-native-go.js.map +1 -1
  19. package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
  20. package/dist/generator/emit-typed-native-rust.js +10 -10
  21. package/dist/generator/emit-typed-native-rust.js.map +1 -1
  22. package/go/api_test.go +675 -0
  23. package/go/behavior.go +1202 -0
  24. package/go/cmd/conformance/main.go +40 -0
  25. package/go/codec.go +170 -0
  26. package/go/coderuntime/behaviorcore.go +93 -0
  27. package/go/coderuntime/canonical.go +287 -0
  28. package/go/coderuntime/exprcore.go +334 -0
  29. package/go/coderuntime/plan.go +422 -0
  30. package/go/coderuntime/primitives.go +383 -0
  31. package/go/coderuntime/rawabi.go +281 -0
  32. package/go/coderuntime/spec.go +17 -0
  33. package/go/coderuntime/template.go +139 -0
  34. package/go/coderuntime/value.go +138 -0
  35. package/go/coderuntime/version.go +9 -0
  36. package/go/compat.go +289 -0
  37. package/go/conformance.go +1046 -0
  38. package/go/envelope.go +77 -0
  39. package/go/expr.go +347 -0
  40. package/go/fingerprint.go +147 -0
  41. package/go/fingerprint_test.go +94 -0
  42. package/go/go.mod +3 -0
  43. package/go/guard.go +538 -0
  44. package/go/jsonord.go +151 -0
  45. package/go/plan_parallel_test.go +279 -0
  46. package/go/primitives_test.go +227 -0
  47. package/package.json +5 -2
package/go/behavior.go ADDED
@@ -0,0 +1,1202 @@
1
+ package dslcontracts
2
+
3
+ import (
4
+ "fmt"
5
+ "sync"
6
+ )
7
+
8
+ // behavior.go — component-graph IR + RunBehavior unified execution IF (Go port).
9
+ //
10
+ // Ports the TS reference ts/src/behavior.ts (scp-ir-architecture.md §5-§7). A
11
+ // portable component-graph IR (components[]{name, inputPorts, body[], output, plan})
12
+ // is executed on top of the existing COMMON primitives: RunPlan (stage exec / Skip
13
+ // propagation / Policy Kind) + EvaluateExpression (Expression IR). The per-component
14
+ // (leaf) implementation is resolved by name through a ComponentExec seam — the
15
+ // boundary-injected handler registry (IR + {effects,config,hooks}).
16
+ //
17
+ // body node kinds:
18
+ // - componentRef: {id, component, ports, parent?, bindField?, relationKind?, policy?}
19
+ // - map: {id, map:{over, as, component, ports, when?, into?, batched?, parent?,
20
+ // relationKind?, policy?}} (when/into/batched are behaviorVersion 2)
21
+ // - cond: {id, cond:{if, then, else, parent?}} (pure Expression; no handler)
22
+ //
23
+ // behaviorVersion 2 (bc#22):
24
+ // - map.when — per-element guard, lowered to {cond:[when,true,false]} (strict bool;
25
+ // non-bool fails closed with TYPE_MISMATCH). Falsy elements are skipped (handler not
26
+ // called, excluded from the result list; order preserved).
27
+ // - map.into — zip-attach: the node result becomes the over list with each
28
+ // guard-passing element shallow-copied and augmented with into:<handler result>
29
+ // (same length/order as over; a skipped element holds the unproduced value). Parent results
30
+ // are never mutated. Non-object kept elements fail closed (MAP_INTO_ELEMENT_NOT_OBJECT).
31
+ // - map.batched — evaluates the ports of all guard-passing elements first, then calls the
32
+ // handler ONCE with {items:[<ports>...]}; the handler must return a list aligned to items
33
+ // (violations fail closed with MAP_BATCH_RESULT_MISMATCH). Zero kept elements means the
34
+ // handler is not called and the result is the empty list.
35
+ // - handler ctx — every handler call carries the node identity (nodeID + component) via the
36
+ // optional ComponentCtxExec interface (additive; plain ComponentExec keeps working).
37
+
38
+ // The coded BehaviorFailure, the ComponentExec / ComponentCtxExec handler seams,
39
+ // the execHandler dispatch discipline, and firstExecErrInVisitOrder moved to the
40
+ // JSON-free codegen runtime (coderuntime/behaviorcore.go — shared with generated
41
+ // straight-line code); they are re-exported from this package in compat.go.
42
+
43
+ func behaviorNodeKind(n *JObj) (string, error) {
44
+ if _, ok := n.Get("fanout"); ok {
45
+ return "fanout", nil
46
+ }
47
+ if _, ok := n.Get("map"); ok {
48
+ return "map", nil
49
+ }
50
+ if _, ok := n.Get("cond"); ok {
51
+ return "cond", nil
52
+ }
53
+ if _, ok := n.Get("component"); ok {
54
+ return "componentRef", nil
55
+ }
56
+ id := ""
57
+ if v, ok := n.Get("id"); ok {
58
+ id, _ = v.(string)
59
+ }
60
+ return "", behaviorFail("UNKNOWN_NODE_KIND", fmt.Sprintf("body node '%s' is not componentRef/map/cond/fanout", id))
61
+ }
62
+
63
+ func behaviorSub(n *JObj) *JObj {
64
+ if f, ok := n.Get("fanout"); ok {
65
+ if fo, ok2 := f.(*JObj); ok2 {
66
+ return fo
67
+ }
68
+ }
69
+ if m, ok := n.Get("map"); ok {
70
+ if mo, ok2 := m.(*JObj); ok2 {
71
+ return mo
72
+ }
73
+ }
74
+ if c, ok := n.Get("cond"); ok {
75
+ if co, ok2 := c.(*JObj); ok2 {
76
+ return co
77
+ }
78
+ }
79
+ return n
80
+ }
81
+
82
+ func behaviorNodeParent(n *JObj) (string, bool) {
83
+ sub := behaviorSub(n)
84
+ if p, ok := sub.Get("parent"); ok {
85
+ if s, ok2 := p.(string); ok2 {
86
+ return s, true
87
+ }
88
+ }
89
+ return "", false
90
+ }
91
+
92
+ func behaviorNodeBindField(n *JObj) (string, bool) {
93
+ if _, ok := n.Get("map"); ok {
94
+ return "", false
95
+ }
96
+ if _, ok := n.Get("cond"); ok {
97
+ return "", false
98
+ }
99
+ if _, ok := n.Get("fanout"); ok {
100
+ return "", false
101
+ }
102
+ if bf, ok := n.Get("bindField"); ok {
103
+ if s, ok2 := bf.(string); ok2 {
104
+ return s, true
105
+ }
106
+ }
107
+ return "", false
108
+ }
109
+
110
+ func behaviorNodeRelationKind(n *JObj) string {
111
+ if _, ok := n.Get("cond"); ok {
112
+ return ""
113
+ }
114
+ sub := n
115
+ if _, ok := n.Get("map"); ok {
116
+ sub = behaviorSub(n)
117
+ } else if _, ok := n.Get("fanout"); ok {
118
+ sub = behaviorSub(n)
119
+ }
120
+ if rk, ok := sub.Get("relationKind"); ok {
121
+ if s, ok2 := rk.(string); ok2 {
122
+ return s
123
+ }
124
+ }
125
+ return ""
126
+ }
127
+
128
+ func behaviorNodePolicy(n *JObj) (string, bool) {
129
+ if _, ok := n.Get("cond"); ok {
130
+ return "", false
131
+ }
132
+ sub := n
133
+ if _, ok := n.Get("map"); ok {
134
+ sub = behaviorSub(n)
135
+ } else if _, ok := n.Get("fanout"); ok {
136
+ sub = behaviorSub(n)
137
+ }
138
+ if pol, ok := sub.Get("policy"); ok {
139
+ if s, ok2 := pol.(string); ok2 {
140
+ return s, true
141
+ }
142
+ }
143
+ return "", false
144
+ }
145
+
146
+ // evalPorts evaluates each port value as an Expression IR node against scope.
147
+ func evalPorts(ports *JObj, scope *Obj) (*Obj, error) {
148
+ out := NewObj()
149
+ if ports == nil {
150
+ return out, nil
151
+ }
152
+ for _, k := range ports.Keys {
153
+ v, err := EvaluateExpression(ports.Vals[k], scope)
154
+ if err != nil {
155
+ return nil, err
156
+ }
157
+ out.Set(k, v)
158
+ }
159
+ return out, nil
160
+ }
161
+
162
+ // fanoutDedupDrop — THE ONE dedup/drop definition (behaviorVersion 3) — Go twin of behavior.ts
163
+ // fanoutDedupDrop. Applies first-seen dedupe (by the body's dedupeKey field) + dangling drop
164
+ // (nil / non-object / absent-key body when drop=="dangling") + implicitSource strip to the aligned
165
+ // raw list; returns the connection items (the caller wraps into {items,cursor:nil}). Byte-equal to
166
+ // the TS/Python/PHP/native definitions. Bodies are *Obj; a nil / non-*Obj body is dangling.
167
+ // A non-string dedupe key that has no canonical form (NaN/Inf, forbidden key) fails closed.
168
+ func fanoutDedupDrop(alignedBodies []Value, dedupeKey, drop string, implicitSource *string) ([]Value, error) {
169
+ items := make([]Value, 0, len(alignedBodies))
170
+ seen := map[string]struct{}{}
171
+ for _, body := range alignedBodies {
172
+ rec, isObj := body.(*Obj)
173
+ var keyVal Value
174
+ hasKey := false
175
+ if isObj {
176
+ if kv, ok := rec.Get(dedupeKey); ok && kv != nil {
177
+ keyVal, hasKey = kv, true
178
+ }
179
+ }
180
+ if !hasKey {
181
+ if drop == "dangling" {
182
+ continue
183
+ }
184
+ items = append(items, body) // drop:none keeps a dangling body
185
+ continue
186
+ }
187
+ // Non-string key identity = the canonical-identity SSoT (CanonicalJSON: injective over the value
188
+ // model, int != float, keys sorted at every depth) — not fmt %v, which leaves strings inside a
189
+ // composite unquoted and prints int64(1) and float64(1) alike (#318).
190
+ var seenKey string
191
+ if s, ok := keyVal.(string); ok {
192
+ seenKey = "s:" + s
193
+ } else {
194
+ ck, err := CanonicalJSON(keyVal)
195
+ if err != nil {
196
+ return nil, err
197
+ }
198
+ seenKey = "j:" + ck
199
+ }
200
+ if _, dup := seen[seenKey]; dup {
201
+ continue
202
+ }
203
+ seen[seenKey] = struct{}{}
204
+ if implicitSource != nil {
205
+ if _, has := rec.Get(*implicitSource); has {
206
+ cp := NewObj()
207
+ for _, fk := range rec.Keys {
208
+ if fk == *implicitSource {
209
+ continue
210
+ }
211
+ cp.Set(fk, rec.Vals[fk])
212
+ }
213
+ items = append(items, cp)
214
+ continue
215
+ }
216
+ }
217
+ items = append(items, body)
218
+ }
219
+ return items, nil
220
+ }
221
+
222
+ // parseBehaviorPlan parses a component's plan field into *ExecutionPlanSpec (nil if absent/null).
223
+ func parseBehaviorPlan(n JNode) *ExecutionPlanSpec {
224
+ o, ok := n.(*JObj)
225
+ if !ok {
226
+ return nil
227
+ }
228
+ groupsN, _ := o.Get("groups")
229
+ groupsArr, _ := groupsN.([]JNode)
230
+ groups := make([][]int, len(groupsArr))
231
+ for i, g := range groupsArr {
232
+ ga, _ := g.([]JNode)
233
+ row := make([]int, len(ga))
234
+ for j, idx := range ga {
235
+ row[j] = int(jnumToInt(idx))
236
+ }
237
+ groups[i] = row
238
+ }
239
+ conc := int64(1)
240
+ if c, ok := o.Get("concurrency"); ok {
241
+ conc = jnumToInt(c)
242
+ }
243
+ return &ExecutionPlanSpec{Groups: groups, Concurrency: conc}
244
+ }
245
+
246
+ // ── structural declared-type resolution (#177 (A) opt-over empty iteration) ──────────────
247
+ // Go twin of behavior.ts portableTypeOfInputPort / descend / overIsDeclaredOptArr — resolves whether
248
+ // a fanout/map `over` is a bare ref to a declared {opt:{arr}} so a null over iterates EMPTY.
249
+
250
+ // portableTypeOfInputPort — an input port schema (*JObj) → determined PortableType (JNode), else nil.
251
+ func portableTypeOfInputPort(schema *JObj) JNode {
252
+ ptypeN, _ := schema.Get("type")
253
+ ptype, _ := ptypeN.(string)
254
+ var base JNode
255
+ switch ptype {
256
+ case "string", "int", "float", "bool", "null":
257
+ base = ptype
258
+ case "array":
259
+ if et, ok := schema.Get("elemType"); ok {
260
+ base = JObjOf("arr", et)
261
+ }
262
+ case "map":
263
+ if et, ok := schema.Get("elemType"); ok {
264
+ base = JObjOf("map", et)
265
+ }
266
+ }
267
+ if base == nil {
268
+ return nil
269
+ }
270
+ if req, ok := schema.Get("required"); ok {
271
+ if b, isBool := req.(bool); isBool && !b {
272
+ return JObjOf("opt", base)
273
+ }
274
+ }
275
+ return base
276
+ }
277
+
278
+ // descendType — the type of `field` one level into a determined type ({obj} field / {opt} re-wrap), else nil.
279
+ func descendType(t JNode, field string) JNode {
280
+ obj, ok := t.(*JObj)
281
+ if !ok {
282
+ return nil // scalar string
283
+ }
284
+ if o, has := obj.Get("obj"); has {
285
+ if oo, ok2 := o.(*JObj); ok2 {
286
+ if v, has2 := oo.Get(field); has2 {
287
+ return v
288
+ }
289
+ }
290
+ return nil
291
+ }
292
+ if inner, has := obj.Get("opt"); has {
293
+ d := descendType(inner, field)
294
+ if d == nil {
295
+ return nil
296
+ }
297
+ return JObjOf("opt", d)
298
+ }
299
+ return nil
300
+ }
301
+
302
+ // nodeResultType — the type a result-reference reads (map → {arr: elemType}, else outType); nil if unannotated.
303
+ func nodeResultType(n *JObj) JNode {
304
+ ot, has := n.Get("outType")
305
+ if !has {
306
+ return nil
307
+ }
308
+ if _, isMap := n.Get("map"); isMap {
309
+ return JObjOf("arr", ot)
310
+ }
311
+ return ot
312
+ }
313
+
314
+ // bareRefPath — the static string path of a bare {ref:[…]}/{refOpt:[…]}, else nil.
315
+ func bareRefPath(over JNode) []string {
316
+ obj, ok := over.(*JObj)
317
+ if !ok || obj.Len() != 1 {
318
+ return nil
319
+ }
320
+ key := obj.Keys[0]
321
+ if key != "ref" && key != "refOpt" {
322
+ return nil
323
+ }
324
+ pN, _ := obj.Get(key)
325
+ arr, ok := pN.([]JNode)
326
+ if !ok || len(arr) == 0 {
327
+ return nil
328
+ }
329
+ segs := make([]string, len(arr))
330
+ for i, p := range arr {
331
+ s, ok2 := p.(string)
332
+ if !ok2 {
333
+ return nil
334
+ }
335
+ segs[i] = s
336
+ }
337
+ return segs
338
+ }
339
+
340
+ // isOptArrType — whether t is the {opt:{arr:…}} shape (a declared optional collection).
341
+ func isOptArrType(t JNode) bool {
342
+ obj, ok := t.(*JObj)
343
+ if !ok {
344
+ return false
345
+ }
346
+ inner, has := obj.Get("opt")
347
+ if !has {
348
+ return false
349
+ }
350
+ io, ok := inner.(*JObj)
351
+ if !ok {
352
+ return false
353
+ }
354
+ _, hasArr := io.Get("arr")
355
+ return hasArr
356
+ }
357
+
358
+ // overIsDeclaredOptArr — whether a fanout/map `over` (bare ref only) is a declared {opt:{arr}} (#177 (A)).
359
+ func overIsDeclaredOptArr(over JNode, body []*JObj, inputPorts *JObj) bool {
360
+ path := bareRefPath(over)
361
+ if path == nil {
362
+ return false
363
+ }
364
+ head, rest := path[0], path[1:]
365
+ var node *JObj
366
+ for _, n := range body {
367
+ if idN, ok := n.Get("id"); ok {
368
+ if s, ok2 := idN.(string); ok2 && s == head {
369
+ node = n
370
+ break
371
+ }
372
+ }
373
+ }
374
+ var cur JNode
375
+ if node != nil {
376
+ cur = nodeResultType(node)
377
+ } else {
378
+ if inputPorts == nil {
379
+ return false
380
+ }
381
+ schemaN, ok := inputPorts.Get(head)
382
+ if !ok {
383
+ return false
384
+ }
385
+ schema, ok := schemaN.(*JObj)
386
+ if !ok {
387
+ return false
388
+ }
389
+ if len(rest) == 0 {
390
+ // an optional array input port IS a declared opt-arr regardless of the (native-only) elemType.
391
+ req, hasReq := schema.Get("required")
392
+ typN, _ := schema.Get("type")
393
+ isArr := typN == "array"
394
+ isFalse := false
395
+ if hasReq {
396
+ if b, isB := req.(bool); isB {
397
+ isFalse = !b
398
+ }
399
+ }
400
+ return isFalse && isArr
401
+ }
402
+ cur = portableTypeOfInputPort(schema)
403
+ }
404
+ if cur == nil {
405
+ return false
406
+ }
407
+ for _, f := range rest {
408
+ cur = descendType(cur, f)
409
+ if cur == nil {
410
+ return false
411
+ }
412
+ }
413
+ return isOptArrType(cur)
414
+ }
415
+
416
+ // resolveOverArray — the SOLE gate resolving a fanout/map `over` to its iterated array: an array passes;
417
+ // a null over whose declared type is {opt:{arr}} iterates EMPTY (#177 (A)); any other non-array fails
418
+ // closed with (FANOUT|MAP)_OVER_NOT_ARRAY (strict typing preserved).
419
+ func resolveOverArray(over Value, overExpr JNode, body []*JObj, inputPorts *JObj, opID, code, label string) ([]Value, error) {
420
+ if arr, ok := over.([]Value); ok {
421
+ return arr, nil
422
+ }
423
+ if over == nil && overIsDeclaredOptArr(overExpr, body, inputPorts) {
424
+ return []Value{}, nil
425
+ }
426
+ return nil, behaviorFail(code, fmt.Sprintf("%s '%s': 'over' is not an array", label, opID))
427
+ }
428
+
429
+ // RunBehavior runs a component-graph IR (scp-ir-architecture.md §7).
430
+ //
431
+ // ir — the portable component-graph IR ({components:[...]}), as parsed JNode.
432
+ // handlers — the boundary-injected ComponentExec seam (catalog name → leaf impl).
433
+ // input — the entry component's inputPorts bindings (param Values), or nil.
434
+ // entry — the component name to run ("" = first component).
435
+ //
436
+ // It returns the evaluated output (Φ merge) or a coded failure (BehaviorFailure /
437
+ // PlanFailure / ExprFailure).
438
+ // bindInputScope — the entry component's input bindings, read against its declaration (inputPorts).
439
+ //
440
+ // An input port declared {opt:T} (PortSchema required:false) is OMITTABLE and its value domain is
441
+ // T | null. "Key omitted" and "key present as null" are two spellings of the same "no value", so an
442
+ // omitted key binds to null. This only reads a declaration the portable IR already carries — no new
443
+ // information, no new operator.
444
+ //
445
+ // Required ports and undeclared names are NOT bound: referencing one unbound is still UNKNOWN_BINDING
446
+ // (the fail-closed for a typo / an unwired param stands — only a port DECLARED omittable is relaxed).
447
+ //
448
+ // Only DECLARED ports are bound: binding the caller's undeclared keys would let one shadow a node id in
449
+ // the flat scope (the builder rejects port/id collisions for exactly that reason), so a ref to a node not
450
+ // yet in the results (e.g. skipped) would resolve to the caller's value and reach a leaf port (#322).
451
+ func bindInputScope(comp *JObj, input *Obj) *Obj {
452
+ out := NewObj()
453
+ portsN, ok := comp.Get("inputPorts")
454
+ if !ok {
455
+ return out
456
+ }
457
+ ports, ok := portsN.(*JObj)
458
+ if !ok {
459
+ return out
460
+ }
461
+ for _, name := range ports.Keys {
462
+ if v, given := input.Get(name); given {
463
+ out.Set(name, v)
464
+ }
465
+ }
466
+ for _, name := range ports.Keys {
467
+ schema, ok := ports.Vals[name].(*JObj)
468
+ if !ok {
469
+ continue
470
+ }
471
+ req, has := schema.Get("required")
472
+ if !has {
473
+ continue
474
+ }
475
+ if b, ok := req.(bool); !ok || b {
476
+ continue
477
+ }
478
+ if _, bound := out.Get(name); !bound {
479
+ out.Set(name, nil)
480
+ }
481
+ }
482
+ return out
483
+ }
484
+
485
+ func RunBehavior(ir JNode, handlers ComponentExec, input *Obj, entry string) (Value, error) {
486
+ irObj, ok := ir.(*JObj)
487
+ if !ok {
488
+ return nil, behaviorFail("UNKNOWN_ENTRY", "IR must be an object")
489
+ }
490
+ compsN, _ := irObj.Get("components")
491
+ comps, _ := compsN.([]JNode)
492
+
493
+ var comp *JObj
494
+ if entry != "" {
495
+ for _, cN := range comps {
496
+ if c, ok := cN.(*JObj); ok {
497
+ if nm, ok2 := c.Get("name"); ok2 {
498
+ if s, ok3 := nm.(string); ok3 && s == entry {
499
+ comp = c
500
+ break
501
+ }
502
+ }
503
+ }
504
+ }
505
+ } else if len(comps) > 0 {
506
+ comp, _ = comps[0].(*JObj)
507
+ }
508
+ if comp == nil {
509
+ name := entry
510
+ if name == "" {
511
+ name = "<first>"
512
+ }
513
+ return nil, behaviorFail("UNKNOWN_ENTRY", fmt.Sprintf("component '%s' not found in IR", name))
514
+ }
515
+
516
+ bodyN, _ := comp.Get("body")
517
+ bodyArr, _ := bodyN.([]JNode)
518
+ body := make([]*JObj, len(bodyArr))
519
+ for i, bN := range bodyArr {
520
+ body[i], _ = bN.(*JObj)
521
+ }
522
+ compInputPortsN, _ := comp.Get("inputPorts")
523
+ compInputPorts, _ := compInputPortsN.(*JObj) // for opt-over declared-type resolution (#177 (A))
524
+
525
+ idToIndex := map[string]int{}
526
+ for i, n := range body {
527
+ if idN, ok := n.Get("id"); ok {
528
+ if s, ok2 := idN.(string); ok2 {
529
+ idToIndex[s] = i
530
+ }
531
+ }
532
+ }
533
+
534
+ // Build OpSpecs for RunPlan staging.
535
+ ops := make([]OpSpec, len(body))
536
+ for i, n := range body {
537
+ id := ""
538
+ if idN, ok := n.Get("id"); ok {
539
+ id, _ = idN.(string)
540
+ }
541
+ op := OpSpec{ID: id, Parent: -1}
542
+ if pid, ok := behaviorNodeParent(n); ok {
543
+ if idx, ok2 := idToIndex[pid]; ok2 {
544
+ op.Parent = idx
545
+ }
546
+ }
547
+ if bf, ok := behaviorNodeBindField(n); ok {
548
+ op.BindField = bf
549
+ op.HasBindField = true
550
+ }
551
+ op.RelationKind = behaviorNodeRelationKind(n)
552
+ if pol, ok := behaviorNodePolicy(n); ok {
553
+ op.Policy = pol
554
+ op.HasPolicy = true
555
+ }
556
+ ops[i] = op
557
+ }
558
+
559
+ if input == nil {
560
+ input = NewObj()
561
+ }
562
+ input = bindInputScope(comp, input)
563
+ results := NewObj()
564
+
565
+ // RunPlan calls exec concurrently for stage members when plan.Concurrency > 1
566
+ // (bc#23). results writes land in disjoint slots (each op's own id) and siblings
567
+ // never read each other's slot (§1: stage members are mutually independent), but
568
+ // the ordered-map internals (Keys slice + Vals map) need serialization.
569
+ var scopeMu sync.Mutex
570
+
571
+ // baseScope = input params + accumulated results (+ optional map element binding).
572
+ baseScope := func(extraKey string, extraVal Value, hasExtra bool) *Obj {
573
+ s := NewObj()
574
+ for _, k := range input.Keys {
575
+ s.Set(k, input.Vals[k])
576
+ }
577
+ scopeMu.Lock()
578
+ for _, k := range results.Keys {
579
+ s.Set(k, results.Vals[k])
580
+ }
581
+ scopeMu.Unlock()
582
+ if hasExtra {
583
+ s.Set(extraKey, extraVal)
584
+ }
585
+ return s
586
+ }
587
+
588
+ // Failures raised INSIDE the exec closure (BehaviorFailure / ExprFailure) cannot
589
+ // unwind through RunPlan's ExecOutcome seam, so each op records its own error in
590
+ // a disjoint slot and returns a synthetic ErrOutcome("aborted") that unwinds the
591
+ // plan. Sequential precedence is restored after RunPlan: the first exec-internal
592
+ // error in plan visit order — at or before the op where the plan unwound — wins
593
+ // over the synthetic plan failure (exactly what the old scalar pendingErr
594
+ // short-circuit produced under sequential execution).
595
+ execErrs := make([]error, len(ops))
596
+ abort := func(idx int, err error) ExecOutcome {
597
+ execErrs[idx] = err
598
+ return ErrOutcome("aborted")
599
+ }
600
+
601
+ execNode := func(op OpSpec, _ Value) ExecOutcome {
602
+ idx := idToIndex[op.ID]
603
+ node := body[idx]
604
+ kind, err := behaviorNodeKind(node)
605
+ if err != nil {
606
+ return abort(idx, err)
607
+ }
608
+
609
+ switch kind {
610
+ case "cond":
611
+ cN, _ := node.Get("cond")
612
+ c, _ := cN.(*JObj)
613
+ ifN, _ := c.Get("if")
614
+ thenN, _ := c.Get("then")
615
+ elseN, _ := c.Get("else")
616
+ condExpr := newJObj()
617
+ condExpr.set("cond", []JNode{ifN, thenN, elseN})
618
+ v, e := EvaluateExpression(condExpr, baseScope("", nil, false))
619
+ if e != nil {
620
+ return abort(idx, e)
621
+ }
622
+ return OkOutcome(v)
623
+
624
+ case "map":
625
+ mN, _ := node.Get("map")
626
+ m, _ := mN.(*JObj)
627
+ overN, _ := m.Get("over")
628
+ over, e := EvaluateExpression(overN, baseScope("", nil, false))
629
+ if e != nil {
630
+ return abort(idx, e)
631
+ }
632
+ arr, e := resolveOverArray(over, overN, body, compInputPorts, op.ID, "MAP_OVER_NOT_ARRAY", "map")
633
+ if e != nil {
634
+ return abort(idx, e)
635
+ }
636
+ compName := ""
637
+ if cn, ok := m.Get("component"); ok {
638
+ compName, _ = cn.(string)
639
+ }
640
+ asName := "$"
641
+ if an, ok := m.Get("as"); ok {
642
+ if s, ok2 := an.(string); ok2 {
643
+ asName = s
644
+ }
645
+ }
646
+ // A pure-expression map (#222): no Component is called, so evaluate the element expression per
647
+ // element in the `as`-bound scope. There is no per-element outcome (elementPolicy / batched /
648
+ // into / policy are rejected by the guard).
649
+ if _, hasComp := m.Get("component"); !hasComp {
650
+ if transformN, hasT := m.Get("transform"); hasT {
651
+ whenT, hasWhenT := m.Get("when")
652
+ out := make([]Value, 0, len(arr))
653
+ for _, el := range arr {
654
+ scope := baseScope(asName, el, true)
655
+ if hasWhenT {
656
+ condExpr := newJObj()
657
+ condExpr.set("cond", []JNode{whenT, true, false})
658
+ kv, e := EvaluateExpression(condExpr, scope)
659
+ if e != nil {
660
+ return abort(idx, e)
661
+ }
662
+ if b, _ := kv.(bool); !b {
663
+ continue
664
+ }
665
+ }
666
+ v, e := EvaluateExpression(transformN, scope)
667
+ if e != nil {
668
+ return abort(idx, e)
669
+ }
670
+ out = append(out, v)
671
+ }
672
+ return OkOutcome(out)
673
+ }
674
+ }
675
+ var portsJ *JObj
676
+ if pn, ok := m.Get("ports"); ok {
677
+ portsJ, _ = pn.(*JObj)
678
+ }
679
+ whenN, hasWhen := m.Get("when")
680
+ batched := false
681
+ if bN, ok := m.Get("batched"); ok {
682
+ batched, _ = bN.(bool)
683
+ }
684
+ intoKey, hasInto := "", false
685
+ if iN, ok := m.Get("into"); ok {
686
+ if s, ok2 := iN.(string); ok2 {
687
+ intoKey, hasInto = s, true
688
+ }
689
+ }
690
+
691
+ // per-element guard (v2): lowered to {cond:[when,true,false]} (strict bool —
692
+ // a non-bool guard fails closed via the cond operator).
693
+ keep := func(scope *Obj) (bool, error) {
694
+ if !hasWhen {
695
+ return true, nil
696
+ }
697
+ condExpr := newJObj()
698
+ condExpr.set("cond", []JNode{whenN, true, false})
699
+ v, e := EvaluateExpression(condExpr, scope)
700
+ if e != nil {
701
+ return false, e
702
+ }
703
+ b, _ := v.(bool)
704
+ return b, nil
705
+ }
706
+
707
+ // Element Error Policy Kind (scp-error.md). Default "error"; an unknown kind fails
708
+ // closed. "skip" needs a per-element Failure, so a batched map (one outcome for the
709
+ // whole batch) rejects it.
710
+ elementPolicy := "error"
711
+ if epN, ok := m.Get("elementPolicy"); ok {
712
+ if s, ok2 := epN.(string); ok2 {
713
+ elementPolicy = s
714
+ } else {
715
+ elementPolicy = ""
716
+ }
717
+ }
718
+ if elementPolicy != "error" && elementPolicy != "skip" {
719
+ return abort(idx, behaviorFail("UNKNOWN_ELEMENT_POLICY", fmt.Sprintf("map '%s': unknown element policy '%s' (fail-closed)", op.ID, elementPolicy)))
720
+ }
721
+ if elementPolicy == "skip" && batched {
722
+ return abort(idx, behaviorFail("ELEMENT_POLICY_NOT_APPLICABLE", fmt.Sprintf("map '%s': elementPolicy 'skip' needs a per-element Failure, but a batched map takes ONE outcome for the whole batch (fail-closed)", op.ID)))
723
+ }
724
+
725
+ var keptIdx []int // guard-passing over indices (for into alignment)
726
+ var collected []Value
727
+ if batched {
728
+ // batched (v2): evaluate all guard-passing ports first, call handler ONCE.
729
+ items := make([]Value, 0, len(arr))
730
+ for i, el := range arr {
731
+ scope := baseScope(asName, el, true)
732
+ kp, e := keep(scope)
733
+ if e != nil {
734
+ return abort(idx, e)
735
+ }
736
+ if !kp {
737
+ continue
738
+ }
739
+ ports, e2 := evalPorts(portsJ, scope)
740
+ if e2 != nil {
741
+ return abort(idx, e2)
742
+ }
743
+ items = append(items, ports)
744
+ keptIdx = append(keptIdx, i)
745
+ }
746
+ if len(items) == 0 {
747
+ collected = []Value{} // all filtered: handler is not called
748
+ } else {
749
+ batchPorts := NewObj()
750
+ batchPorts.Set("items", items)
751
+ outcome, resolved := execHandler(handlers, op.ID, compName, batchPorts, nil)
752
+ if !resolved {
753
+ return abort(idx, behaviorFail("UNKNOWN_COMPONENT", fmt.Sprintf("component '%s' has no handler (fail-closed)", compName)))
754
+ }
755
+ if outcome.IsError {
756
+ return outcome
757
+ }
758
+ r, isArr := outcome.Ok.([]Value)
759
+ if !isArr || len(r) != len(items) {
760
+ return abort(idx, behaviorFail("MAP_BATCH_RESULT_MISMATCH", fmt.Sprintf("map '%s': batched handler must return a list aligned to items (want %d)", op.ID, len(items))))
761
+ }
762
+ collected = r
763
+ }
764
+ } else {
765
+ collected = make([]Value, 0, len(arr))
766
+ for i, el := range arr {
767
+ scope := baseScope(asName, el, true)
768
+ kp, e := keep(scope)
769
+ if e != nil {
770
+ return abort(idx, e)
771
+ }
772
+ if !kp {
773
+ continue
774
+ }
775
+ ports, e2 := evalPorts(portsJ, scope)
776
+ if e2 != nil {
777
+ return abort(idx, e2)
778
+ }
779
+ outcome, resolved := execHandler(handlers, op.ID, compName, ports, el)
780
+ if !resolved {
781
+ return abort(idx, behaviorFail("UNKNOWN_COMPONENT", fmt.Sprintf("component '%s' has no handler (fail-closed)", compName)))
782
+ }
783
+ if outcome.IsError {
784
+ // Element Error Policy (scp-error.md): "skip" drops the failing element and
785
+ // proceeds (order preserved; the leaf keeps its Error Value); "error" promotes
786
+ // it to the map's Component Failure.
787
+ if elementPolicy == "skip" {
788
+ continue
789
+ }
790
+ return outcome
791
+ }
792
+ collected = append(collected, outcome.Ok)
793
+ keptIdx = append(keptIdx, i)
794
+ }
795
+ }
796
+
797
+ if !hasInto {
798
+ return OkOutcome(collected)
799
+ }
800
+
801
+ // into (v2): result = over list with kept elements shallow-copied + into key
802
+ // attached. A skipped element (guard / elementPolicy) gets the unproduced value under
803
+ // its into key (unproducedValue: nil by default, the empty connection for a
804
+ // connection-typed into — #182), the SAME SSoT as bindUnproduced's whole-node skip; a
805
+ // same-named key the element carried in is not kept.
806
+ augmented := make([]Value, 0, len(arr))
807
+ k := 0
808
+ nodeRK := behaviorNodeRelationKind(node)
809
+ for i, el := range arr {
810
+ var intoVal Value
811
+ if k < len(keptIdx) && keptIdx[k] == i {
812
+ intoVal = collected[k]
813
+ k++
814
+ } else {
815
+ intoVal = unproducedValue(nodeRK)
816
+ }
817
+ elObj, isObj := el.(*Obj)
818
+ if !isObj {
819
+ return abort(idx, behaviorFail("MAP_INTO_ELEMENT_NOT_OBJECT", fmt.Sprintf("map '%s': 'into' requires object elements (element %d is not an object)", op.ID, i)))
820
+ }
821
+ cp := NewObj()
822
+ for _, fk := range elObj.Keys {
823
+ cp.Set(fk, elObj.Vals[fk])
824
+ }
825
+ cp.Set(intoKey, intoVal)
826
+ augmented = append(augmented, cp)
827
+ }
828
+ return OkOutcome(augmented)
829
+
830
+ case "fanout":
831
+ // fanout (v3): over (id-list) → deduped ONE batched handler → dedupe/drop/strip →
832
+ // connection {items, cursor:null}. The alignment constraint (MAP_BATCH_RESULT_MISMATCH)
833
+ // does NOT apply — the result is a connection, not an aligned list.
834
+ fN, _ := node.Get("fanout")
835
+ f, _ := fN.(*JObj)
836
+ overN, _ := f.Get("over")
837
+ over, e := EvaluateExpression(overN, baseScope("", nil, false))
838
+ if e != nil {
839
+ return abort(idx, e)
840
+ }
841
+ arr, e := resolveOverArray(over, overN, body, compInputPorts, op.ID, "FANOUT_OVER_NOT_ARRAY", "fanout")
842
+ if e != nil {
843
+ return abort(idx, e)
844
+ }
845
+ compName := ""
846
+ if cn, ok := f.Get("component"); ok {
847
+ compName, _ = cn.(string)
848
+ }
849
+ asName := "$"
850
+ if an, ok := f.Get("as"); ok {
851
+ if s, ok2 := an.(string); ok2 {
852
+ asName = s
853
+ }
854
+ }
855
+ var portsJ *JObj
856
+ if pn, ok := f.Get("ports"); ok {
857
+ portsJ, _ = pn.(*JObj)
858
+ }
859
+ dedupeKey := ""
860
+ if dk, ok := f.Get("dedupeKey"); ok {
861
+ dedupeKey, _ = dk.(string)
862
+ }
863
+ drop := ""
864
+ if dr, ok := f.Get("drop"); ok {
865
+ drop, _ = dr.(string)
866
+ }
867
+ implicitSource := ""
868
+ hasImplicit := false
869
+ if is, ok := f.Get("implicitSource"); ok {
870
+ if s, ok2 := is.(string); ok2 {
871
+ implicitSource, hasImplicit = s, true
872
+ }
873
+ }
874
+ items := make([]Value, 0, len(arr))
875
+ for _, el := range arr {
876
+ scope := baseScope(asName, el, true)
877
+ ports, e2 := evalPorts(portsJ, scope)
878
+ if e2 != nil {
879
+ return abort(idx, e2)
880
+ }
881
+ items = append(items, ports)
882
+ }
883
+ conn := NewObj()
884
+ if len(items) == 0 {
885
+ conn.Set("items", []Value{})
886
+ conn.Set("cursor", nil)
887
+ return OkOutcome(conn)
888
+ }
889
+ batchPorts := NewObj()
890
+ batchPorts.Set("items", items)
891
+ outcome, resolved := execHandler(handlers, op.ID, compName, batchPorts, nil)
892
+ if !resolved {
893
+ return abort(idx, behaviorFail("UNKNOWN_COMPONENT", fmt.Sprintf("component '%s' has no handler (fail-closed)", compName)))
894
+ }
895
+ if outcome.IsError {
896
+ return outcome
897
+ }
898
+ r, isArr2 := outcome.Ok.([]Value)
899
+ if !isArr2 || len(r) != len(items) {
900
+ return abort(idx, behaviorFail("FANOUT_BATCH_RESULT_MISMATCH", fmt.Sprintf("fanout '%s': batched handler must return a list aligned to the deduped id list (want %d)", op.ID, len(items))))
901
+ }
902
+ var implicitPtr *string
903
+ if hasImplicit {
904
+ implicitPtr = &implicitSource
905
+ }
906
+ deduped, e := fanoutDedupDrop(r, dedupeKey, drop, implicitPtr)
907
+ if e != nil {
908
+ return abort(idx, e)
909
+ }
910
+ conn.Set("items", deduped)
911
+ conn.Set("cursor", nil)
912
+ return OkOutcome(conn)
913
+
914
+ default: // componentRef
915
+ compName := ""
916
+ if cn, ok := node.Get("component"); ok {
917
+ compName, _ = cn.(string)
918
+ }
919
+ var portsJ *JObj
920
+ if pn, ok := node.Get("ports"); ok {
921
+ portsJ, _ = pn.(*JObj)
922
+ }
923
+ ports, e := evalPorts(portsJ, baseScope("", nil, false))
924
+ if e != nil {
925
+ return abort(idx, e)
926
+ }
927
+ outcome, resolved := execHandler(handlers, op.ID, compName, ports, nil)
928
+ if !resolved {
929
+ return abort(idx, behaviorFail("UNKNOWN_COMPONENT", fmt.Sprintf("component '%s' has no handler (fail-closed)", compName)))
930
+ }
931
+ return outcome
932
+ }
933
+ }
934
+
935
+ wrapped := func(op OpSpec, bound Value) ExecOutcome {
936
+ outcome := execNode(op, bound)
937
+ if !outcome.IsError {
938
+ idx := idToIndex[op.ID]
939
+ node := body[idx]
940
+ // outType conformance (scp-error.md): a declared node result type is a claim; check it
941
+ // here (the runtime holds both the declared type and the returned value), fail closed with
942
+ // the structured Error Value on a mismatch, and NORMALIZE the value to the declared type
943
+ // (int→float widen / absent opt→null) so results match the de-box.
944
+ value := outcome.Ok
945
+ if outType, has := node.Get("outType"); has {
946
+ normalized, e := assertConformsToOutType(op.ID, value, resultTypeOf(node, outType), "result")
947
+ if e != nil {
948
+ return abort(idx, e)
949
+ }
950
+ value = normalized
951
+ }
952
+ scopeMu.Lock()
953
+ results.Set(op.ID, value)
954
+ scopeMu.Unlock()
955
+ }
956
+ return outcome
957
+ }
958
+
959
+ plan := parseBehaviorPlan(func() JNode { p, _ := comp.Get("plan"); return p }())
960
+ // Skipped nodes contribute their unproduced representation to the scope AT THE MOMENT
961
+ // they are skipped, so a later node reading one as a non-parent dependency and the
962
+ // component output both read it (scp-error.md "Dependency rules for continue").
963
+ bindUnproduced := func(op OpSpec) {
964
+ scopeMu.Lock()
965
+ results.Set(op.ID, unproducedValue(op.RelationKind))
966
+ scopeMu.Unlock()
967
+ }
968
+ _, err := RunPlan(plan, ops, wrapped, bindUnproduced)
969
+ // A BehaviorFailure/ExprFailure raised inside exec takes precedence over the
970
+ // synthetic OP_FAILED we injected to unwind RunPlan — but only if it occurred at
971
+ // or before the op where the plan unwound, in plan visit order (stages in order,
972
+ // ascending index within a stage). Under parallel dispatch (bc#23) a LATER
973
+ // sibling may have recorded an exec-internal error speculatively; sequential
974
+ // execution would never have reached it, so it must not win.
975
+ if firstErr := firstExecErrInVisitOrder(execErrs, plan, len(ops), err); firstErr != nil {
976
+ return nil, firstErr
977
+ }
978
+ if err != nil {
979
+ return nil, err
980
+ }
981
+
982
+ outputN, _ := comp.Get("output")
983
+ return EvaluateExpression(outputN, baseScope("", nil, false))
984
+ }
985
+
986
+ // ── outType conformance (scp-error.md "The outType conformance check") ──────────────────────
987
+
988
+ // wireTypeName is the wire type name of an observed value (ErrorDetail.ActualWireType vocabulary).
989
+ func wireTypeName(v Value) string { return TypeName(v) }
990
+
991
+ // rawValueOf is the offending value stringified (never re-parsed to recover a type).
992
+ func rawValueOf(v Value) string {
993
+ switch x := v.(type) {
994
+ case string:
995
+ return x
996
+ case bool:
997
+ if x {
998
+ return "true"
999
+ }
1000
+ return "false"
1001
+ case nil:
1002
+ return "null"
1003
+ case int64:
1004
+ return fmt.Sprintf("%d", x)
1005
+ case float64:
1006
+ if s, err := PyFloatRepr(x); err == nil {
1007
+ return s
1008
+ }
1009
+ return fmt.Sprintf("%v", x)
1010
+ default:
1011
+ if s, err := CanonicalJSON(v); err == nil {
1012
+ return s
1013
+ }
1014
+ return TypeName(v)
1015
+ }
1016
+ }
1017
+
1018
+ // portableTypeNotation renders a declared type node (IR JNode) in Portable Type Notation.
1019
+ func portableTypeNotation(t JNode) string {
1020
+ if s, ok := t.(string); ok {
1021
+ return s
1022
+ }
1023
+ o, ok := t.(*JObj)
1024
+ if !ok {
1025
+ return "?"
1026
+ }
1027
+ for _, key := range []string{"opt", "arr", "map"} {
1028
+ if inner, has := o.Get(key); has {
1029
+ return key + "(" + portableTypeNotation(inner) + ")"
1030
+ }
1031
+ }
1032
+ if objN, has := o.Get("obj"); has {
1033
+ if fields, ok2 := objN.(*JObj); ok2 {
1034
+ parts := make([]string, 0, len(fields.Keys))
1035
+ for _, k := range fields.Keys {
1036
+ parts = append(parts, k+":"+portableTypeNotation(fields.Vals[k]))
1037
+ }
1038
+ out := "obj{"
1039
+ for i, p := range parts {
1040
+ if i > 0 {
1041
+ out += ","
1042
+ }
1043
+ out += p
1044
+ }
1045
+ return out + "}"
1046
+ }
1047
+ }
1048
+ return "?"
1049
+ }
1050
+
1051
+ // resultTypeOf normalizes a node's declared outType to its RESULT type: a map node's outType is its
1052
+ // ELEMENT type, so its result is an array of that element (the compiler's reading). Others: as-is.
1053
+ func resultTypeOf(node JNode, outType JNode) JNode {
1054
+ if o, ok := node.(*JObj); ok {
1055
+ if _, isMap := o.Get("map"); isMap {
1056
+ wrap := newJObj()
1057
+ wrap.set("arr", outType)
1058
+ return wrap
1059
+ }
1060
+ }
1061
+ return outType
1062
+ }
1063
+
1064
+ func conformFail(code, message, kind, nodeID, field string, expected JNode, actual Value, hasActual bool) *ExprFailure {
1065
+ d := &ErrorDetail{
1066
+ Kind: kind,
1067
+ Model: nodeID,
1068
+ Field: field,
1069
+ ExpectedType: portableTypeNotation(expected),
1070
+ }
1071
+ if hasActual {
1072
+ d.ActualWireType = wireTypeName(actual)
1073
+ d.RawValue = rawValueOf(actual)
1074
+ }
1075
+ return &ExprFailure{Code: code, Msg: message, Detail: d}
1076
+ }
1077
+
1078
+ // jnodeIsOpt reports whether a declared field type (IR JNode) is an {opt:...} wrapper.
1079
+ func jnodeIsOpt(t JNode) bool {
1080
+ if o, ok := t.(*JObj); ok {
1081
+ if _, has := o.Get("opt"); has {
1082
+ return true
1083
+ }
1084
+ }
1085
+ return false
1086
+ }
1087
+
1088
+ // assertConformsToOutType checks a value against a declared outType (IR JNode), failing closed with
1089
+ // TYPE_MISMATCH / MISSING_PROP carrying the structured Error Value, and returns the value NORMALIZED
1090
+ // to the declared type. Semantics match the emitters' de-box and the TS/Rust/Python runtimes: float
1091
+ // widens from int AND coerces the value to float64; an absent declared opt field materializes as null
1092
+ // (de-box's absent→None); a required field's absence is MISSING_PROP; a key the declaration does
1093
+ // not name is DROPPED (#233 — de-box is total against the declared type).
1094
+ func assertConformsToOutType(nodeID string, v Value, t JNode, field string) (Value, *ExprFailure) {
1095
+ if scalar, ok := t.(string); ok {
1096
+ conforms := true
1097
+ switch scalar {
1098
+ case "string":
1099
+ _, conforms = v.(string)
1100
+ case "int":
1101
+ // #261: an INTEGRAL float is the same value in another spelling and narrows EXACTLY (the
1102
+ // mirror of the int → float widen below). Non-integral, or beyond int64, stays LOUD.
1103
+ if f, isF := v.(float64); isF {
1104
+ if f >= -9223372036854775808.0 && f < 9223372036854775808.0 && float64(int64(f)) == f {
1105
+ return int64(f), nil
1106
+ }
1107
+ }
1108
+ _, conforms = v.(int64)
1109
+ case "float":
1110
+ if _, isF := v.(float64); !isF {
1111
+ if i, isI := v.(int64); isI {
1112
+ return float64(i), nil // int → float widen (de-box: strconv.ParseFloat と同一)
1113
+ }
1114
+ conforms = false
1115
+ }
1116
+ case "bool":
1117
+ _, conforms = v.(bool)
1118
+ case "null":
1119
+ conforms = v == nil
1120
+ }
1121
+ if !conforms {
1122
+ return nil, conformFail("TYPE_MISMATCH", fmt.Sprintf("node '%s': %s: expected %s, got %s", nodeID, field, scalar, wireTypeName(v)), "typeMismatch", nodeID, field, t, v, true)
1123
+ }
1124
+ return v, nil
1125
+ }
1126
+ o, ok := t.(*JObj)
1127
+ if !ok {
1128
+ return v, nil
1129
+ }
1130
+ if inner, has := o.Get("opt"); has {
1131
+ if v == nil {
1132
+ return nil, nil
1133
+ }
1134
+ return assertConformsToOutType(nodeID, v, inner, field)
1135
+ }
1136
+ if inner, has := o.Get("arr"); has {
1137
+ arr, isArr := v.([]Value)
1138
+ if !isArr {
1139
+ return nil, conformFail("TYPE_MISMATCH", fmt.Sprintf("node '%s': %s: expected arr, got %s", nodeID, field, wireTypeName(v)), "typeMismatch", nodeID, field, t, v, true)
1140
+ }
1141
+ out := make([]Value, len(arr))
1142
+ for i, el := range arr {
1143
+ nv, e := assertConformsToOutType(nodeID, el, inner, fmt.Sprintf("%s[%d]", field, i))
1144
+ if e != nil {
1145
+ return nil, e
1146
+ }
1147
+ out[i] = nv
1148
+ }
1149
+ return out, nil
1150
+ }
1151
+ if inner, has := o.Get("map"); has {
1152
+ obj, isObj := v.(*Obj)
1153
+ if !isObj {
1154
+ return nil, conformFail("TYPE_MISMATCH", fmt.Sprintf("node '%s': %s: expected map, got %s", nodeID, field, wireTypeName(v)), "typeMismatch", nodeID, field, t, v, true)
1155
+ }
1156
+ out := NewObj()
1157
+ for _, k := range obj.Keys {
1158
+ // map keys are arbitrary leaf strings: "__proto__" fails closed exactly as on every other
1159
+ // object-building path, in every language (#319).
1160
+ if k == ForbiddenObjectKey {
1161
+ return nil, &ExprFailure{Code: "FORBIDDEN_KEY", Msg: fmt.Sprintf("node '%s': %s: object key %q is forbidden (fail-closed)", nodeID, field, ForbiddenObjectKey)}
1162
+ }
1163
+ nv, e := assertConformsToOutType(nodeID, obj.Vals[k], inner, field+"."+k)
1164
+ if e != nil {
1165
+ return nil, e
1166
+ }
1167
+ out.Set(k, nv)
1168
+ }
1169
+ return out, nil
1170
+ }
1171
+ if objN, has := o.Get("obj"); has {
1172
+ fields, _ := objN.(*JObj)
1173
+ obj, isObj := v.(*Obj)
1174
+ if !isObj {
1175
+ return nil, conformFail("TYPE_MISMATCH", fmt.Sprintf("node '%s': %s: expected obj, got %s", nodeID, field, wireTypeName(v)), "typeMismatch", nodeID, field, t, v, true)
1176
+ }
1177
+ // #233: build ONLY the declared fields, in declared order — de-box is TOTAL against the declared
1178
+ // type, and a key the declaration does not name is not a position (typed-native has nowhere to
1179
+ // put it, so keeping it here would split the observable key set by language family).
1180
+ out := NewObj()
1181
+ if fields != nil {
1182
+ for _, k := range fields.Keys {
1183
+ ft := fields.Vals[k]
1184
+ fv, present := obj.Get(k)
1185
+ if !present {
1186
+ if jnodeIsOpt(ft) {
1187
+ out.Set(k, nil) // absent opt → null (de-box: absent→None)
1188
+ continue
1189
+ }
1190
+ return nil, conformFail("MISSING_PROP", fmt.Sprintf("node '%s': %s: missing property .%s", nodeID, field, k), "missingField", nodeID, field+"."+k, ft, nil, false)
1191
+ }
1192
+ nv, e := assertConformsToOutType(nodeID, fv, ft, field+"."+k)
1193
+ if e != nil {
1194
+ return nil, e
1195
+ }
1196
+ out.Set(k, nv)
1197
+ }
1198
+ }
1199
+ return out, nil
1200
+ }
1201
+ return v, nil
1202
+ }