behavior-contracts 0.3.0

Language-neutral IR runtime core (expression evaluation, template rendering, execution plan, canonical serialization) shared across DSL implementations. Passes the dsl-contracts conformance vectors byte-for-byte.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
//! behavior — component-graph IR + `run_behavior` unified execution IF.
//!
//! Ports the TS reference `ts/src/behavior.ts` (scp-ir-architecture.md §5-§7).
//!
//! A portable component-graph IR (`components[]{name, inputPorts, body[], output, plan}`)
//! is executed on top of the existing COMMON primitives: `run_plan` (stage exec /
//! Skip propagation / Policy Kind) + `evaluate` (Expression IR). The concrete
//! per-component (leaf) implementation is resolved by name through a [`ComponentExec`]
//! seam — the boundary-injected handler registry (IR + {effects,config,hooks}).
//!
//! Body node kinds:
//!   - componentRef: `{id, component, ports, parent?, bindField?, relationKind?, policy?}`
//!   - map:          `{id, map:{over, as, component, ports, when?, into?, batched?, parent?,
//!                    relationKind?, policy?}}` (`when`/`into`/`batched` are behaviorVersion 2)
//!   - cond:         `{id, cond:{if, then, else, parent?}}` (pure Expression; no handler)
//!
//! behaviorVersion 2 (bc#22):
//!   - `map.when`    — per-element guard, lowered to `{cond:[when,true,false]}` (strict bool;
//!     non-bool fails closed with TYPE_MISMATCH). Falsy elements are skipped (handler not
//!     called, excluded from the result list; order preserved).
//!   - `map.into`    — zip-attach: the node result becomes the `over` list with each
//!     guard-passing element shallow-copied and augmented with `into: <handler result>`
//!     (same length/order as `over`; skipped elements pass through unchanged). Parent
//!     results are never mutated. Non-object kept elements fail closed
//!     (MAP_INTO_ELEMENT_NOT_OBJECT).
//!   - `map.batched` — evaluates the ports of all guard-passing elements first, then calls
//!     the handler ONCE with `{items:[<ports>...]}`; the handler must return a list aligned
//!     to items (violations fail closed with MAP_BATCH_RESULT_MISMATCH). Zero kept elements
//!     means the handler is not called and the result is the empty list.
//!   - handler ctx   — every handler call carries the node identity (nodeId + component)
//!     via the [`ComponentExec::exec_ctx`] seam (additive; default forwards to `exec`).

use crate::expr::{evaluate as evaluate_expression, ExprFailure};
use crate::plan::{run_plan, ExecOutcome, ExecutionPlanSpec, OpSpec, PlanFailure, RelationKind};
use crate::value::Value;
use serde_json::Value as J;

/// Stable behavior-execution failure codes (in addition to plan/expr codes).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BehaviorFailureCode {
    UnknownComponent,
    UnknownNodeKind,
    MapOverNotArray,
    MapIntoElementNotObject,
    MapBatchResultMismatch,
    UnknownEntry,
}

impl BehaviorFailureCode {
    pub fn as_str(self) -> &'static str {
        match self {
            BehaviorFailureCode::UnknownComponent => "UNKNOWN_COMPONENT",
            BehaviorFailureCode::UnknownNodeKind => "UNKNOWN_NODE_KIND",
            BehaviorFailureCode::MapOverNotArray => "MAP_OVER_NOT_ARRAY",
            BehaviorFailureCode::MapIntoElementNotObject => "MAP_INTO_ELEMENT_NOT_OBJECT",
            BehaviorFailureCode::MapBatchResultMismatch => "MAP_BATCH_RESULT_MISMATCH",
            BehaviorFailureCode::UnknownEntry => "UNKNOWN_ENTRY",
        }
    }
}

/// A unified failure for `run_behavior`, carrying a stable string code so the
/// conformance runner can compare against expression / plan / behavior codes alike.
#[derive(Debug, Clone)]
pub struct BehaviorError {
    code: String,
    pub message: String,
}

impl BehaviorError {
    /// Construct a coded behavior error. Public so the straight-line codegen surface
    /// (bc#39) can raise the same fail-closed codes/messages as `run_behavior`
    /// (`UNKNOWN_COMPONENT` / `UNKNOWN_ENTRY` / `UNKNOWN_NODE_KIND`) without depending
    /// on the private `BehaviorFailureCode` enum.
    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
        BehaviorError {
            code: code.into(),
            message: message.into(),
        }
    }

    /// The stable string code used for conformance matching.
    pub fn code(&self) -> &str {
        &self.code
    }
}

impl std::fmt::Display for BehaviorError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}", self.code, self.message)
    }
}
impl std::error::Error for BehaviorError {}

impl From<ExprFailure> for BehaviorError {
    fn from(e: ExprFailure) -> Self {
        BehaviorError {
            code: e.code.as_str().to_string(),
            message: e.message,
        }
    }
}
impl From<PlanFailure> for BehaviorError {
    fn from(e: PlanFailure) -> Self {
        BehaviorError {
            code: e.code.as_str().to_string(),
            message: e.message,
        }
    }
}

fn bfail<T>(code: BehaviorFailureCode, message: impl Into<String>) -> Result<T, BehaviorError> {
    Err(BehaviorError {
        code: code.as_str().to_string(),
        message: message.into(),
    })
}

/// The boundary-injected handler registry seam (§7.1). Resolves a catalog name to
/// a leaf implementation and executes it with evaluated ports (+ the map element
/// `bound` value, if any). Returns `None` when the name is unknown so `run_behavior`
/// can fail closed with `UNKNOWN_COMPONENT`.
pub trait ComponentExec {
    fn exec(
        &mut self,
        component: &str,
        ports: &[(String, Value)],
        bound: Option<&Value>,
    ) -> Option<ExecOutcome>;

    /// behaviorVersion 2: like [`ComponentExec::exec`] but carrying the handler ctx
    /// (`node_id` = body node id, `component` = catalog name). `run_behavior` calls
    /// this seam for every handler invocation. The default forwards to `exec`, so
    /// existing implementations keep working unchanged; override it to observe the
    /// node identity (error context / tracing).
    fn exec_ctx(
        &mut self,
        node_id: &str,
        component: &str,
        ports: &[(String, Value)],
        bound: Option<&Value>,
    ) -> Option<ExecOutcome> {
        let _ = node_id;
        self.exec(component, ports, bound)
    }
}

/// Blanket forwarding impl so a **trait object** handler registry
/// (`&mut dyn ComponentExec`) itself satisfies [`ComponentExec`] (bc#68).
///
/// The generic straight-line / typed codegen surface exposes generic-by-value
/// entries (`bind<H: ComponentExec>(handlers: H)` / `run_*<H: ComponentExec>(
/// handlers: &mut H, …)`). A consumer that holds its handler registry behind a
/// trait object (`handlers: &mut dyn ComponentExec` — exactly how [`run_behavior`]
/// takes it) could not name a concrete `H` to hand those entries. This impl makes
/// `H = &mut dyn ComponentExec` a valid instantiation, so the trait-object handler
/// drives the generated straight-line/typed module through the *unchanged* generic
/// path (no `bind_dyn` variant needed, no emitter change). It is purely additive:
/// every existing concrete `H` keeps working exactly as before.
///
/// Both methods forward to the underlying `dyn` (a plain reborrow), so calling a
/// generated module through `&mut dyn` runs the SAME straight-line/typed code as a
/// concrete handler — it never falls back to `run_behavior`.
impl ComponentExec for &mut dyn ComponentExec {
    fn exec(
        &mut self,
        component: &str,
        ports: &[(String, Value)],
        bound: Option<&Value>,
    ) -> Option<ExecOutcome> {
        (**self).exec(component, ports, bound)
    }

    fn exec_ctx(
        &mut self,
        node_id: &str,
        component: &str,
        ports: &[(String, Value)],
        bound: Option<&Value>,
    ) -> Option<ExecOutcome> {
        (**self).exec_ctx(node_id, component, ports, bound)
    }
}

fn scope_get<'a>(scope: &'a [(String, Value)], key: &str) -> Option<&'a Value> {
    scope.iter().find(|(k, _)| k == key).map(|(_, v)| v)
}

fn node_kind(n: &J) -> Result<&'static str, BehaviorError> {
    if n.get("map").is_some() {
        Ok("map")
    } else if n.get("cond").is_some() {
        Ok("cond")
    } else if n.get("component").is_some() {
        Ok("componentRef")
    } else {
        bfail(
            BehaviorFailureCode::UnknownNodeKind,
            format!(
                "body node '{}' is not componentRef/map/cond",
                n.get("id").and_then(|v| v.as_str()).unwrap_or("?")
            ),
        )
    }
}

fn node_parent(n: &J) -> Option<&str> {
    let sub = if let Some(m) = n.get("map") {
        m
    } else if let Some(c) = n.get("cond") {
        c
    } else {
        n
    };
    sub.get("parent").and_then(|v| v.as_str())
}

fn node_bind_field(n: &J) -> Option<String> {
    if n.get("map").is_some() || n.get("cond").is_some() {
        return None;
    }
    n.get("bindField")
        .and_then(|v| v.as_str())
        .map(str::to_string)
}

fn node_relation_kind(n: &J) -> Option<RelationKind> {
    let sub = if let Some(m) = n.get("map") { m } else { n };
    if n.get("cond").is_some() {
        return None;
    }
    match sub.get("relationKind").and_then(|v| v.as_str()) {
        Some("connection") => Some(RelationKind::Connection),
        Some(_) => Some(RelationKind::Single),
        None => None,
    }
}

fn node_relation_kind_str(n: &J) -> Option<&str> {
    let sub = if let Some(m) = n.get("map") { m } else { n };
    if n.get("cond").is_some() {
        return None;
    }
    sub.get("relationKind").and_then(|v| v.as_str())
}

fn node_policy(n: &J) -> Option<String> {
    if n.get("cond").is_some() {
        return None;
    }
    let sub = if let Some(m) = n.get("map") { m } else { n };
    sub.get("policy")
        .and_then(|v| v.as_str())
        .map(str::to_string)
}

fn eval_ports(ports: &J, scope: &[(String, Value)]) -> Result<Vec<(String, Value)>, BehaviorError> {
    let obj = ports.as_object().ok_or_else(|| BehaviorError {
        code: BehaviorFailureCode::UnknownNodeKind.as_str().to_string(),
        message: "ports must be an object".into(),
    })?;
    let mut out = Vec::with_capacity(obj.len());
    for (k, v) in obj {
        out.push((k.clone(), evaluate_expression(v, scope)?));
    }
    Ok(out)
}

/// Parse an `ExecutionPlanSpec` from a component's `plan` field (`null`/absent → None).
fn parse_plan(plan: Option<&J>) -> Option<ExecutionPlanSpec> {
    let p = plan?;
    if p.is_null() {
        return None;
    }
    let groups = p
        .get("groups")?
        .as_array()?
        .iter()
        .map(|g| {
            g.as_array()
                .map(|row| {
                    row.iter()
                        .filter_map(|i| i.as_u64().map(|x| x as usize))
                        .collect()
                })
                .unwrap_or_default()
        })
        .collect();
    let concurrency = p.get("concurrency").and_then(|c| c.as_i64()).unwrap_or(1);
    Some(ExecutionPlanSpec {
        groups,
        concurrency,
    })
}

/// Run a component-graph IR (scp-ir-architecture.md §7).
///
/// * `ir`      — the portable component-graph IR (`{components:[...]}`).
/// * `handlers`— the boundary-injected [`ComponentExec`] seam (catalog name → leaf impl).
/// * `input`   — the entry component's inputPorts bindings (param values).
/// * `entry`   — the component name to run (`None` = first component).
///
/// Returns the evaluated `output` (Φ merge) or a coded [`BehaviorError`].
pub fn run_behavior(
    ir: &J,
    handlers: &mut dyn ComponentExec,
    input: &[(String, Value)],
    entry: Option<&str>,
) -> Result<Value, BehaviorError> {
    let components = ir
        .get("components")
        .and_then(|c| c.as_array())
        .ok_or_else(|| BehaviorError {
            code: BehaviorFailureCode::UnknownEntry.as_str().to_string(),
            message: "IR.components must be an array".into(),
        })?;
    let comp = match entry {
        Some(name) => components
            .iter()
            .find(|c| c.get("name").and_then(|n| n.as_str()) == Some(name)),
        None => components.first(),
    };
    let comp = match comp {
        Some(c) => c,
        None => {
            return bfail(
                BehaviorFailureCode::UnknownEntry,
                format!("component '{}' not found in IR", entry.unwrap_or("<first>")),
            )
        }
    };

    let body: Vec<J> = comp
        .get("body")
        .and_then(|b| b.as_array())
        .cloned()
        .unwrap_or_default();

    let index_of = |id: &str| {
        body.iter()
            .position(|n| n.get("id").and_then(|v| v.as_str()) == Some(id))
    };

    // Build OpSpecs for run_plan staging (parent id → index via Wire).
    let mut ops: Vec<OpSpec> = Vec::with_capacity(body.len());
    for n in &body {
        let parent = node_parent(n).and_then(index_of);
        ops.push(OpSpec {
            id: n
                .get("id")
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string(),
            parent,
            bind_field: node_bind_field(n),
            relation_kind: node_relation_kind(n),
            policy: node_policy(n),
        });
    }

    run_behavior_inner(
        &body,
        &ops,
        parse_plan(comp.get("plan")),
        comp.get("output").cloned().unwrap_or(J::Null),
        input,
        handlers,
    )
}

/// Single-closure implementation: builds the exec closure that owns `handlers`,
/// `results`, and `pending_err`, delegates staging to `run_plan`, then evaluates
/// the component `output`. Kept separate to sidestep split-borrow layering.
fn run_behavior_inner(
    body: &[J],
    ops: &[OpSpec],
    plan: Option<ExecutionPlanSpec>,
    output: J,
    input: &[(String, Value)],
    handlers: &mut dyn ComponentExec,
) -> Result<Value, BehaviorError> {
    let index_of = |id: &str| {
        body.iter()
            .position(|n| n.get("id").and_then(|v| v.as_str()) == Some(id))
    };

    let mut results: Vec<(String, Value)> = Vec::new();
    let mut pending_err: Option<BehaviorError> = None;

    let run = {
        let results_cell = &mut results;
        let err_cell = &mut pending_err;
        let exec = |op: &OpSpec, _bound: Option<&Value>| -> ExecOutcome {
            if err_cell.is_some() {
                return ExecOutcome::Error("aborted".into());
            }
            let idx = match index_of(&op.id) {
                Some(i) => i,
                None => {
                    *err_cell = Some(BehaviorError {
                        code: BehaviorFailureCode::UnknownNodeKind.as_str().to_string(),
                        message: format!("no body node for op '{}'", op.id),
                    });
                    return ExecOutcome::Error("aborted".into());
                }
            };
            let node = &body[idx];

            let base_scope = |extra: Option<(&str, &Value)>| -> Vec<(String, Value)> {
                let mut s: Vec<(String, Value)> = input.to_vec();
                for (k, v) in results_cell.iter() {
                    s.push((k.clone(), v.clone()));
                }
                if let Some((k, v)) = extra {
                    s.push((k.to_string(), v.clone()));
                }
                s
            };

            let outcome = match node_kind(node) {
                Err(e) => {
                    *err_cell = Some(e);
                    return ExecOutcome::Error("aborted".into());
                }
                Ok("cond") => {
                    let c = node.get("cond").unwrap();
                    let cond_expr = serde_json::json!({
                        "cond": [c.get("if"), c.get("then"), c.get("else")]
                    });
                    match evaluate_expression(&cond_expr, &base_scope(None)) {
                        Ok(v) => ExecOutcome::Ok(v),
                        Err(e) => {
                            *err_cell = Some(e.into());
                            return ExecOutcome::Error("aborted".into());
                        }
                    }
                }
                Ok("map") => {
                    let m = node.get("map").unwrap();
                    let over = match evaluate_expression(
                        m.get("over").unwrap_or(&J::Null),
                        &base_scope(None),
                    ) {
                        Ok(v) => v,
                        Err(e) => {
                            *err_cell = Some(e.into());
                            return ExecOutcome::Error("aborted".into());
                        }
                    };
                    let arr = match &over {
                        Value::Arr(a) => a.clone(),
                        _ => {
                            *err_cell = Some(BehaviorError {
                                code: BehaviorFailureCode::MapOverNotArray.as_str().to_string(),
                                message: format!("map '{}': 'over' is not an array", op.id),
                            });
                            return ExecOutcome::Error("aborted".into());
                        }
                    };
                    let component = m.get("component").and_then(|v| v.as_str()).unwrap_or("");
                    let as_name = m.get("as").and_then(|v| v.as_str()).unwrap_or("$");
                    let ports_j = m
                        .get("ports")
                        .cloned()
                        .unwrap_or(J::Object(Default::default()));
                    let when = m.get("when");
                    let batched = m.get("batched").and_then(|v| v.as_bool()).unwrap_or(false);
                    let into = m.get("into").and_then(|v| v.as_str());

                    // per-element guard (v2): lowered to `{cond:[when,true,false]}`
                    // (strict bool — a non-bool guard fails closed via the cond operator).
                    let keep = |scope: &[(String, Value)]| -> Result<bool, BehaviorError> {
                        match when {
                            None => Ok(true),
                            Some(w) => {
                                let cond_expr = serde_json::json!({ "cond": [w, true, false] });
                                Ok(matches!(
                                    evaluate_expression(&cond_expr, scope)?,
                                    Value::Bool(true)
                                ))
                            }
                        }
                    };

                    let mut kept_idx: Vec<usize> = Vec::new(); // guard-passing over indices (for into)
                    let collected: Vec<Value>;
                    if batched {
                        // batched (v2): evaluate all guard-passing ports first, call handler ONCE.
                        let mut items: Vec<Value> = Vec::new();
                        for (i, el) in arr.iter().enumerate() {
                            let scope = base_scope(Some((as_name, el)));
                            match keep(&scope) {
                                Ok(false) => continue,
                                Ok(true) => {}
                                Err(e) => {
                                    *err_cell = Some(e);
                                    return ExecOutcome::Error("aborted".into());
                                }
                            }
                            match eval_ports(&ports_j, &scope) {
                                Ok(p) => items.push(Value::Obj(p)),
                                Err(e) => {
                                    *err_cell = Some(e);
                                    return ExecOutcome::Error("aborted".into());
                                }
                            }
                            kept_idx.push(i);
                        }
                        if items.is_empty() {
                            collected = Vec::new(); // all filtered: handler is not called
                        } else {
                            let want = items.len();
                            let batch_ports = vec![("items".to_string(), Value::Arr(items))];
                            match handlers.exec_ctx(&op.id, component, &batch_ports, None) {
                                None => {
                                    *err_cell = Some(BehaviorError {
                                        code: BehaviorFailureCode::UnknownComponent
                                            .as_str()
                                            .to_string(),
                                        message: format!(
                                            "component '{component}' has no handler (fail-closed)"
                                        ),
                                    });
                                    return ExecOutcome::Error("aborted".into());
                                }
                                Some(ExecOutcome::Error(e)) => return ExecOutcome::Error(e),
                                Some(ExecOutcome::Ok(Value::Arr(r))) if r.len() == want => {
                                    collected = r;
                                }
                                Some(ExecOutcome::Ok(_)) => {
                                    *err_cell = Some(BehaviorError {
                                        code: BehaviorFailureCode::MapBatchResultMismatch
                                            .as_str()
                                            .to_string(),
                                        message: format!(
                                            "map '{}': batched handler must return a list aligned to items (want {want})",
                                            op.id
                                        ),
                                    });
                                    return ExecOutcome::Error("aborted".into());
                                }
                            }
                        }
                    } else {
                        let mut out: Vec<Value> = Vec::with_capacity(arr.len());
                        for (i, el) in arr.iter().enumerate() {
                            let scope = base_scope(Some((as_name, el)));
                            match keep(&scope) {
                                Ok(false) => continue,
                                Ok(true) => {}
                                Err(e) => {
                                    *err_cell = Some(e);
                                    return ExecOutcome::Error("aborted".into());
                                }
                            }
                            let ports = match eval_ports(&ports_j, &scope) {
                                Ok(p) => p,
                                Err(e) => {
                                    *err_cell = Some(e);
                                    return ExecOutcome::Error("aborted".into());
                                }
                            };
                            match handlers.exec_ctx(&op.id, component, &ports, Some(el)) {
                                None => {
                                    *err_cell = Some(BehaviorError {
                                        code: BehaviorFailureCode::UnknownComponent
                                            .as_str()
                                            .to_string(),
                                        message: format!(
                                            "component '{component}' has no handler (fail-closed)"
                                        ),
                                    });
                                    return ExecOutcome::Error("aborted".into());
                                }
                                Some(ExecOutcome::Error(e)) => return ExecOutcome::Error(e),
                                Some(ExecOutcome::Ok(v)) => out.push(v),
                            }
                            kept_idx.push(i);
                        }
                        collected = out;
                    }

                    match into {
                        None => ExecOutcome::Ok(Value::Arr(collected)),
                        Some(key) => {
                            // into (v2): result = over list with kept elements shallow-copied
                            // + `into` key attached; skipped elements pass through unchanged.
                            let mut augmented: Vec<Value> = Vec::with_capacity(arr.len());
                            let mut k = 0usize;
                            for (i, el) in arr.iter().enumerate() {
                                if k < kept_idx.len() && kept_idx[k] == i {
                                    let fields = match el {
                                        Value::Obj(f) => f.clone(),
                                        _ => {
                                            *err_cell = Some(BehaviorError {
                                                code: BehaviorFailureCode::MapIntoElementNotObject
                                                    .as_str()
                                                    .to_string(),
                                                message: format!(
                                                    "map '{}': 'into' requires object elements (element {i} is not an object)",
                                                    op.id
                                                ),
                                            });
                                            return ExecOutcome::Error("aborted".into());
                                        }
                                    };
                                    let mut fields = fields;
                                    let val = collected[k].clone();
                                    match fields.iter_mut().find(|(fk, _)| fk == key) {
                                        Some(slot) => slot.1 = val,
                                        None => fields.push((key.to_string(), val)),
                                    }
                                    augmented.push(Value::Obj(fields));
                                    k += 1;
                                } else {
                                    augmented.push(el.clone());
                                }
                            }
                            ExecOutcome::Ok(Value::Arr(augmented))
                        }
                    }
                }
                Ok(_) => {
                    let component = node.get("component").and_then(|v| v.as_str()).unwrap_or("");
                    let ports_j = node
                        .get("ports")
                        .cloned()
                        .unwrap_or(J::Object(Default::default()));
                    let ports = match eval_ports(&ports_j, &base_scope(None)) {
                        Ok(p) => p,
                        Err(e) => {
                            *err_cell = Some(e);
                            return ExecOutcome::Error("aborted".into());
                        }
                    };
                    match handlers.exec_ctx(&op.id, component, &ports, None) {
                        None => {
                            *err_cell = Some(BehaviorError {
                                code: BehaviorFailureCode::UnknownComponent.as_str().to_string(),
                                message: format!(
                                    "component '{component}' has no handler (fail-closed)"
                                ),
                            });
                            return ExecOutcome::Error("aborted".into());
                        }
                        Some(o) => o,
                    }
                }
            };

            if let ExecOutcome::Ok(v) = &outcome {
                results_cell.push((op.id.clone(), v.clone()));
            }
            outcome
        };

        run_plan(plan.as_ref(), ops, exec)
    };

    // A BehaviorError raised inside exec takes precedence over the synthetic plan
    // OP_FAILED it produced (we injected an "aborted" error to unwind run_plan).
    if let Some(e) = pending_err {
        return Err(e);
    }
    let run = run?;

    // Skipped nodes contribute their unproduced representation to the scope so the
    // component `output` can `ref`/`coalesce` over them.
    for (i, id_val) in run.skipped.iter().enumerate() {
        let _ = i;
        if let Some(idx) = index_of(id_val) {
            let rk = node_relation_kind_str(&body[idx]);
            let unproduced = if rk == Some("connection") {
                Value::Obj(vec![
                    ("items".into(), Value::Arr(vec![])),
                    ("cursor".into(), Value::Null),
                ])
            } else {
                Value::Null
            };
            if scope_get(&results, id_val).is_none() {
                results.push((id_val.clone(), unproduced));
            }
        }
    }

    let scope: Vec<(String, Value)> = {
        let mut s: Vec<(String, Value)> = input.to_vec();
        s.extend(results.iter().cloned());
        s
    };
    Ok(evaluate_expression(&output, &scope)?)
}