behavior-contracts 0.8.15

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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
//! conformance.rs — dsl-contracts conformance kit Rust runner.
//!
//!   cargo run --bin conformance
//!
//! Loads ../conformance/vectors/*.json, runs each vector through the reference
//! primitives, compares to expect, and tallies pass/fail. exit 0 if all pass,
//! exit 1 on any fail, exit 2 on a spec-version mismatch (pre-flight fail-closed).

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::exit;

use behavior_contracts::behavior::{run_behavior, ComponentExec};
use behavior_contracts::canonical::{
    canonical_json, canonical_value, py_float_repr, CanonicalFailure, CanonicalFailureCode,
};
use behavior_contracts::codec::{decode_value, encode_value};
use behavior_contracts::expr::{evaluate as evaluate_expression, ExprFailure};
use behavior_contracts::fingerprint::fingerprint_component_graph;
use behavior_contracts::guard::assert_portable_component_graph;
use behavior_contracts::plan::{
    run_plan, run_plan_parallel, ErrorDetail, ErrorKind, ExecOutcome, ExecutionPlanSpec, OpSpec,
    PlanFailure, RelationKind,
};
use behavior_contracts::template::{render_template, TemplateFailure};
use behavior_contracts::value::{deep_equals, Value};
use behavior_contracts::SpecVersions;

use serde_json::Value as J;

fn vectors_dir() -> PathBuf {
    if let Ok(env) = std::env::var("DSL_CONTRACTS_VECTORS") {
        return PathBuf::from(env);
    }
    // this file: <crate>/src/bin/conformance.rs ; CARGO_MANIFEST_DIR = <crate> = dsl-contracts/rust
    let manifest = env!("CARGO_MANIFEST_DIR");
    Path::new(manifest)
        .parent()
        .unwrap()
        .join("conformance")
        .join("vectors")
}

fn load_json(dir: &Path, file: &str) -> J {
    let raw = std::fs::read_to_string(dir.join(file))
        .unwrap_or_else(|e| panic!("cannot read {file}: {e}"));
    serde_json::from_str(&raw).unwrap_or_else(|e| panic!("cannot parse {file}: {e}"))
}

struct Tally {
    passed: u32,
    failed: u32,
}

fn line(ok: bool, name: &str, detail: &str) {
    if ok {
        println!("  \u{2713} {name}");
    } else {
        println!("  \u{2717} {name}");
        if !detail.is_empty() {
            println!("      {detail}");
        }
    }
}

fn bump(t: &mut Tally, ok: bool) {
    if ok {
        t.passed += 1;
    } else {
        t.failed += 1;
    }
}

// ── pre-flight version sweep (PROTOCOL §5) ───────────────────────────────────
fn preflight(dir: &Path) -> std::collections::HashMap<&'static str, J> {
    let specs: [(&str, &str, &str, i64); 8] = [
        (
            "expression.json",
            "expression",
            "exprVersion",
            SpecVersions::EXPRESSION,
        ),
        (
            "template.json",
            "template",
            "templateVersion",
            SpecVersions::TEMPLATE,
        ),
        ("plan.json", "plan", "planVersion", SpecVersions::PLAN),
        (
            "canonical.json",
            "canonical",
            "canonicalVersion",
            SpecVersions::CANONICAL,
        ),
        (
            "behavior.json",
            "behavior",
            "behaviorVersion",
            SpecVersions::BEHAVIOR,
        ),
        ("guard.json", "guard", "guardVersion", SpecVersions::GUARD),
        ("c2-catalog-swap.json", "c2", "c2Version", SpecVersions::C2),
        (
            "provenance.json",
            "provenance",
            "provenanceVersion",
            SpecVersions::PROVENANCE,
        ),
    ];
    let loaded: Vec<(&str, &str, i64, J)> = specs
        .iter()
        .map(|(f, suite, vk, want)| (*suite, *vk, *want, load_json(dir, f)))
        .collect();
    let mismatches: Vec<(&str, i64, i64)> = loaded
        .iter()
        .filter_map(|(suite, vk, want, doc)| {
            let got = doc.get(*vk).and_then(|v| v.as_i64()).unwrap_or(-1);
            if got != *want {
                Some((*suite, got, *want))
            } else {
                None
            }
        })
        .collect();
    if !mismatches.is_empty() {
        for (suite, got, want) in &mismatches {
            eprintln!("FAIL-CLOSED: {suite} suite version {got} != supported {want}.");
        }
        eprintln!(
            "Refusing to run: {} suite version mismatch(es). No vectors executed.",
            mismatches.len()
        );
        exit(2);
    }
    loaded
        .into_iter()
        .map(|(suite, _, _, doc)| (suite, doc))
        .collect()
}

/// Decode a vector's `detail` into the structured Error Value (scp-error.md "The Error Value").
///
/// This is the leaf side of the contract: a scripted handler produces the detail exactly as a real
/// leaf at a wire boundary would, so the runtime's transport of it is what the vector observes. An
/// unrecognized `kind` decodes to `None` — the closed set does not degrade to a default.
fn decode_error_detail(raw: Option<&J>) -> Option<Box<ErrorDetail>> {
    let d = raw?;
    let s = |k: &str| d.get(k).and_then(|v| v.as_str()).map(|v| v.to_string());
    let mut context = std::collections::BTreeMap::new();
    if let Some(J::Object(m)) = d.get("context") {
        for (k, v) in m {
            if let Some(sv) = v.as_str() {
                context.insert(k.clone(), sv.to_string());
            }
        }
    }
    Some(Box::new(ErrorDetail {
        kind: d
            .get("kind")
            .and_then(|v| v.as_str())
            .and_then(ErrorKind::parse),
        model: s("model"),
        field: s("field"),
        expected_type: s("expectedType"),
        actual_wire_type: s("actualWireType"),
        raw_value: s("rawValue"),
        context,
    }))
}

fn as_scope(v: Option<&J>) -> Vec<(String, Value)> {
    match v {
        Some(J::Object(o)) => o
            .iter()
            .map(|(k, val)| (k.clone(), decode_value(val).expect("decode scope")))
            .collect(),
        _ => Vec::new(),
    }
}

// ── expression ───────────────────────────────────────────────────────────────
fn run_expression(t: &mut Tally, doc: &J) {
    let vectors = doc["vectors"].as_array().unwrap();
    println!(
        "\nexpression.json (v{}) — {} vectors",
        doc["exprVersion"],
        vectors.len()
    );
    for v in vectors {
        let name = v["name"].as_str().unwrap_or("?");
        let scope = as_scope(v.get("scope"));
        let expect = &v["expect"];
        let (mut ok, mut detail) = (false, String::new());
        match evaluate_expression(&v["expr"], &scope) {
            Ok(result) => {
                if let Some(exp) = expect.get("value") {
                    let want = decode_value(exp).expect("decode expect.value");
                    ok = deep_equals(&result, &want);
                    if !ok {
                        detail = format!("expected value {}, got {}", exp, encode_value(&result));
                    }
                } else {
                    detail = format!("expected Failure({}), got a value", expect["failure"]);
                }
            }
            Err(e) => {
                let e: ExprFailure = e;
                if let Some(f) = expect.get("failure").and_then(|f| f.as_str()) {
                    ok = e.code.as_str() == f;
                    if !ok {
                        detail = format!("expected Failure({f}), got Failure({})", e.code.as_str());
                    }
                } else {
                    detail = format!("expected a value, got Failure({})", e.code.as_str());
                }
            }
        }
        line(ok, name, &detail);
        bump(t, ok);
    }
}

// ── template ─────────────────────────────────────────────────────────────────
fn run_template(t: &mut Tally, doc: &J) {
    let vectors = doc["vectors"].as_array().unwrap();
    println!(
        "\ntemplate.json (v{}) — {} vectors",
        doc["templateVersion"],
        vectors.len()
    );
    for v in vectors {
        let name = v["name"].as_str().unwrap_or("?");
        let tmpl = v["template"].as_str().unwrap();
        let params: Vec<(String, Value)> = v["params"]
            .as_object()
            .unwrap()
            .iter()
            .map(|(k, val)| (k.clone(), decode_value(val).expect("decode param")))
            .collect();
        let expect = &v["expect"];
        let (mut ok, mut detail) = (false, String::new());
        match render_template(tmpl, &params) {
            Ok(out) => {
                if let Some(exp) = expect.get("ok").and_then(|x| x.as_str()) {
                    ok = out == exp;
                    if !ok {
                        detail = format!("expected {exp:?}, got {out:?}");
                    }
                } else {
                    detail = format!("expected Failure({}), got {out:?}", expect["failure"]);
                }
            }
            Err(e) => {
                let e: TemplateFailure = e;
                if let Some(f) = expect.get("failure").and_then(|f| f.as_str()) {
                    ok = e.code.as_str() == f;
                    if !ok {
                        detail = format!("expected Failure({f}), got Failure({})", e.code.as_str());
                    }
                } else {
                    detail = format!("expected value, got Failure({})", e.code.as_str());
                }
            }
        }
        line(ok, name, &detail);
        bump(t, ok);
    }
}

// ── canonical ────────────────────────────────────────────────────────────────
fn run_canonical(t: &mut Tally, doc: &J) {
    let vectors = doc["vectors"].as_array().unwrap();
    println!(
        "\ncanonical.json (v{}) — {} vectors",
        doc["canonicalVersion"],
        vectors.len()
    );
    for v in vectors {
        let name = v["name"].as_str().unwrap_or("?");
        let kind = v["kind"].as_str().unwrap();
        let expect = &v["expect"];
        let (mut ok, mut detail) = (false, String::new());
        // decode_value may itself fail-closed (e.g. FORBIDDEN_KEY for a "__proto__"
        // own key). Map a coded decode error into the canonical Failure path so it
        // is compared like any other Failure code (PROTOCOL §3.4); an uncoded
        // decode error is a genuine malformed-vector bug and still panics.
        let result: Result<String, CanonicalFailure> = match decode_value(&v["value"]) {
            Ok(val) => match kind {
                "canonicalValue" => canonical_value(&val),
                "canonicalJson" => canonical_json(&val),
                "floatRepr" => match &val {
                    Value::Float(f) => py_float_repr(*f),
                    other => panic!("floatRepr expects a float, got {}", other.type_name()),
                },
                other => panic!("unknown kind: {other}"),
            },
            Err(e) => match e.code {
                Some(code) => Err(CanonicalFailure {
                    code: match code {
                        "FORBIDDEN_KEY" => CanonicalFailureCode::ForbiddenKey,
                        _ => CanonicalFailureCode::InvalidValue,
                    },
                    message: e.msg,
                }),
                None => panic!("decode value: {}", e.msg),
            },
        };
        match result {
            Ok(out) => {
                if let Some(exp) = expect.get("ok").and_then(|x| x.as_str()) {
                    ok = out == exp;
                    if !ok {
                        detail = format!("expected {exp:?}, got {out:?}");
                    }
                } else {
                    detail = format!("expected Failure({}), got {out:?}", expect["failure"]);
                }
            }
            Err(e) => {
                if let Some(f) = expect.get("failure").and_then(|f| f.as_str()) {
                    ok = e.code.as_str() == f;
                    if !ok {
                        detail = format!("expected Failure({f}), got Failure({})", e.code.as_str());
                    }
                } else {
                    detail = format!("expected value, got Failure({})", e.code.as_str());
                }
            }
        }
        line(ok, name, &detail);
        bump(t, ok);
    }
}

// ── plan ─────────────────────────────────────────────────────────────────────
fn parse_op(o: &J) -> OpSpec {
    let relation_kind = o
        .get("relationKind")
        .and_then(|r| r.as_str())
        .map(|s| match s {
            "connection" => RelationKind::Connection,
            _ => RelationKind::Single,
        });
    OpSpec {
        id: o["id"].as_str().unwrap().to_string(),
        parent: o.get("parent").and_then(|p| p.as_u64()).map(|p| p as usize),
        bind_field: o
            .get("bindField")
            .and_then(|b| b.as_str())
            .map(|s| s.to_string()),
        relation_kind,
        policy: o
            .get("policy")
            .and_then(|p| p.as_str())
            .map(|s| s.to_string()),
    }
}

fn parse_plan(p: &J) -> Option<ExecutionPlanSpec> {
    if p.is_null() {
        return None;
    }
    let groups = p["groups"]
        .as_array()
        .unwrap()
        .iter()
        .map(|g| {
            g.as_array()
                .unwrap()
                .iter()
                .map(|i| i.as_u64().unwrap() as usize)
                .collect()
        })
        .collect();
    let concurrency = p.get("concurrency").and_then(|c| c.as_i64()).unwrap_or(1);
    Some(ExecutionPlanSpec {
        groups,
        concurrency,
    })
}

fn same_set(a: &[String], b: &[J]) -> bool {
    let mut sa: Vec<&str> = a.iter().map(|s| s.as_str()).collect();
    let mut sb: Vec<&str> = b.iter().map(|s| s.as_str().unwrap()).collect();
    sa.sort_unstable();
    sb.sort_unstable();
    sa == sb
}

fn run_plan_suite(t: &mut Tally, doc: &J) {
    let vectors = doc["vectors"].as_array().unwrap();
    println!(
        "\nplan.json (v{}) — {} vectors",
        doc["planVersion"],
        vectors.len()
    );
    for v in vectors {
        let name = v["name"].as_str().unwrap_or("?");
        let plan = parse_plan(v.get("plan").unwrap_or(&J::Null));
        let ops: Vec<OpSpec> = v["ops"].as_array().unwrap().iter().map(parse_op).collect();
        let exec_map = v["exec"].as_object().unwrap();
        let expect = &v["expect"];
        let (mut ok, mut detail) = (false, String::new());

        let exec = |op: &OpSpec, _bound: Option<&Value>| -> ExecOutcome {
            let o = exec_map
                .get(&op.id)
                .unwrap_or_else(|| panic!("no mock outcome for op '{}'", op.id));
            if let Some(okv) = o.get("ok") {
                ExecOutcome::Ok(decode_value(okv).expect("decode exec.ok"))
            } else {
                ExecOutcome::Error(
                    o["error"].as_str().unwrap_or("").to_string(),
                    decode_error_detail(o.get("detail")),
                )
            }
        };

        // bc#23: every vector must be observation-identical through the bounded
        // parallel path (run_plan_parallel) — the sequential run stays the
        // normative expect comparison below; a divergence fails the vector.
        let par = run_plan_parallel(plan.as_ref(), &ops, exec);
        let seq = run_plan(plan.as_ref(), &ops, |op: &OpSpec, b: Option<&Value>| {
            exec(op, b)
        });
        let paths_agree = match (&seq, &par) {
            (Ok(a), Ok(b)) => {
                let ta = canonical_json(&Value::Obj(a.final_tree())).expect("canonical seq tree");
                let tb = canonical_json(&Value::Obj(b.final_tree())).expect("canonical par tree");
                ta == tb && a.executed == b.executed && a.skipped == b.skipped
            }
            (Err(a), Err(b)) => a.code == b.code && a.message == b.message,
            _ => false,
        };
        if !paths_agree {
            line(false, name, "run_plan_parallel diverged from run_plan");
            bump(t, false);
            continue;
        }

        match seq {
            Ok(res) => {
                if let Some(f) = expect.get("failure") {
                    detail = format!("expected Failure({f}), got a full run");
                } else {
                    let tree = Value::Obj(res.final_tree());
                    let exp_tree_pairs: Vec<(String, Value)> = expect["tree"]
                        .as_object()
                        .unwrap()
                        .iter()
                        .map(|(k, val)| (k.clone(), decode_value(val).expect("decode expect.tree")))
                        .collect();
                    let exp_tree = Value::Obj(exp_tree_pairs);
                    let got_c = canonical_json(&tree).expect("canonical tree");
                    let want_c = canonical_json(&exp_tree).expect("canonical exp tree");
                    let tree_ok = got_c == want_c;
                    let exec_ok = same_set(&res.executed, expect["executed"].as_array().unwrap());
                    let skip_ok = same_set(&res.skipped, expect["skipped"].as_array().unwrap());
                    ok = tree_ok && exec_ok && skip_ok;
                    if !ok {
                        let mut parts = Vec::new();
                        if !tree_ok {
                            parts.push(format!("tree {got_c} != {want_c}"));
                        }
                        if !exec_ok {
                            parts.push(format!(
                                "executed {:?} != {}",
                                res.executed, expect["executed"]
                            ));
                        }
                        if !skip_ok {
                            parts.push(format!(
                                "skipped {:?} != {}",
                                res.skipped, expect["skipped"]
                            ));
                        }
                        detail = parts.join("; ");
                    }
                }
            }
            Err(e) => {
                let e: PlanFailure = e;
                if let Some(f) = expect.get("failure").and_then(|f| f.as_str()) {
                    ok = e.code.as_str() == f;
                    if !ok {
                        detail = format!("expected Failure({f}), got Failure({})", e.code.as_str());
                    }
                } else {
                    detail = format!("expected a full run, got Failure({})", e.code.as_str());
                }
            }
        }
        line(ok, name, &detail);
        bump(t, ok);
    }
}

// ── behavior ─────────────────────────────────────────────────────────────────
/// Data-driven handler registry: `handlers[name]` = FIFO queue of scripted
/// outcomes (a non-array bare `{ok}`/`{error}` is the "same element every call"
/// shorthand). Each call pops the next outcome for that component.
struct ScriptedHandlers {
    // name -> (queue of raw outcome JSON, is_single)
    queues: HashMap<String, (Vec<J>, bool)>,
}

impl ScriptedHandlers {
    fn from_spec(spec: &serde_json::Map<String, J>) -> Self {
        let mut queues = HashMap::new();
        for (name, raw) in spec {
            let (items, single) = match raw {
                J::Array(a) => (a.clone(), false),
                other => (vec![other.clone()], true),
            };
            queues.insert(name.clone(), (items, single));
        }
        ScriptedHandlers { queues }
    }
}

impl ComponentExec for ScriptedHandlers {
    fn exec(
        &mut self,
        component: &str,
        ports: &[(String, Value)],
        bound: Option<&Value>,
    ) -> Option<ExecOutcome> {
        self.exec_ctx("", component, ports, bound)
    }

    // v2 observation outcomes (PROTOCOL.md §3.5):
    //   {"echo":"ctx"}   -> {ok: {nodeId, component}} (echoes the handler ctx)
    //   {"echo":"items"} -> {ok: ports["items"]} (what a batched handler received)
    //   {"echo":"port","port":"<name>"} -> {ok: ports["<name>"]} (the value that reached the named
    //                       port — makes the port plane observable; a port not received echoes null)
    fn exec_ctx(
        &mut self,
        node_id: &str,
        component: &str,
        ports: &[(String, Value)],
        _bound: Option<&Value>,
    ) -> Option<ExecOutcome> {
        let (queue, single) = self.queues.get_mut(component)?;
        let raw = if *single || queue.len() <= 1 {
            queue[0].clone()
        } else {
            queue.remove(0)
        };
        match raw.get("echo").and_then(|e| e.as_str()) {
            Some("ctx") => {
                return Some(ExecOutcome::Ok(Value::Obj(vec![
                    ("nodeId".to_string(), Value::Str(node_id.to_string())),
                    ("component".to_string(), Value::Str(component.to_string())),
                ])));
            }
            Some("items") => {
                let items = ports
                    .iter()
                    .find(|(k, _)| k == "items")
                    .map(|(_, v)| v.clone())
                    .unwrap_or(Value::Null);
                return Some(ExecOutcome::Ok(items));
            }
            Some("port") => {
                let name = raw.get("port").and_then(|p| p.as_str()).unwrap_or("");
                let v = ports
                    .iter()
                    .find(|(k, _)| k == name)
                    .map(|(_, v)| v.clone())
                    .unwrap_or(Value::Null);
                // wrap:"v" (#141 fixtures) returns the echoed port INSIDE a single-field record
                // {v: ports[X]}, so a de-box node whose result WRAPS an input port stays non-vacuous.
                match raw.get("wrap").and_then(|w| w.as_str()) {
                    Some(wrap) => return Some(ExecOutcome::Ok(Value::Obj(vec![(wrap.to_string(), v)]))),
                    None => return Some(ExecOutcome::Ok(v)),
                }
            }
            // an echo outside the closed set is a VECTOR-AUTHORING error — fail LOUD (PROTOCOL.md
            // §3.5), never fall through to the ok/error reading and judge the vector on a silent misread.
            Some(other) => panic!(
                "conformance: unknown echo directive {other:?} (expected \"ctx\" | \"items\" | \"port\")"
            ),
            None => {}
        }
        if let Some(okv) = raw.get("ok") {
            Some(ExecOutcome::Ok(
                decode_value(okv).expect("decode handler ok"),
            ))
        } else {
            Some(ExecOutcome::Error(
                raw.get("error")
                    .and_then(|e| e.as_str())
                    .unwrap_or("")
                    .to_string(),
                decode_error_detail(raw.get("detail")),
            ))
        }
    }
}

fn run_behavior_suite(t: &mut Tally, doc: &J) {
    let vectors = doc["vectors"].as_array().unwrap();
    println!(
        "\nbehavior.json (v{}) — {} vectors",
        doc["behaviorVersion"],
        vectors.len()
    );
    for v in vectors {
        let name = v["name"].as_str().unwrap_or("?");
        let ir = &v["ir"];
        let input: Vec<(String, Value)> = match v.get("input") {
            Some(J::Object(o)) => o
                .iter()
                .map(|(k, val)| (k.clone(), decode_value(val).expect("decode input")))
                .collect(),
            _ => Vec::new(),
        };
        let empty = serde_json::Map::new();
        let handlers_spec = v
            .get("handlers")
            .and_then(|h| h.as_object())
            .unwrap_or(&empty);
        let mut handlers = ScriptedHandlers::from_spec(handlers_spec);
        let entry = v.get("entry").and_then(|e| e.as_str());
        let expect = &v["expect"];
        let (mut ok, mut detail) = (false, String::new());
        match run_behavior(ir, &mut handlers, &input, entry) {
            Ok(result) => {
                if let Some(exp) = expect.get("value") {
                    let want = decode_value(exp).expect("decode expect.value");
                    ok = deep_equals(&result, &want);
                    if !ok {
                        detail = format!("expected value {}, got {}", exp, encode_value(&result));
                    }
                } else {
                    detail = format!("expected Failure({}), got a value", expect["failure"]);
                }
            }
            Err(e) => {
                if let Some(f) = expect.get("failure").and_then(|f| f.as_str()) {
                    ok = e.code() == f;
                    if !ok {
                        detail = format!("expected Failure({f}), got Failure({})", e.code());
                    } else if let Some(dexp) = expect.get("detail") {
                        // The structured Error Value (scp-error.md): compare the present fields.
                        match detail_matches(e.detail(), dexp) {
                            Ok(()) => {}
                            Err(msg) => {
                                ok = false;
                                detail = msg;
                            }
                        }
                    }
                } else {
                    detail = format!("expected a value, got Failure({})", e.code());
                }
            }
        }
        line(ok, name, &detail);
        bump(t, ok);
    }
}

/// Compare a failure's structured detail against a vector's expect.detail (present fields only).
fn detail_matches(got: Option<&ErrorDetail>, expect: &J) -> Result<(), String> {
    let want = expect.as_object().ok_or("expect.detail is not an object")?;
    let g = got.cloned().unwrap_or_default();
    let fields = [
        ("kind", g.kind.map(|k| k.as_str().to_string())),
        ("model", g.model),
        ("field", g.field),
        ("expectedType", g.expected_type),
        ("actualWireType", g.actual_wire_type),
        ("rawValue", g.raw_value),
    ];
    let mut present: std::collections::BTreeMap<&str, String> = std::collections::BTreeMap::new();
    for (k, v) in fields {
        if let Some(s) = v {
            present.insert(k, s);
        }
    }
    for (k, wv) in want {
        if k == "context" {
            continue;
        }
        let ws = wv.as_str().unwrap_or("");
        match present.remove(k.as_str()) {
            Some(gs) if gs == ws => {}
            other => return Err(format!("detail.{k} = {other:?}, want {ws:?}")),
        }
    }
    if !present.is_empty() {
        return Err(format!("detail has extra fields {present:?}"));
    }
    match want.get("context") {
        Some(c) => {
            let cobj = c.as_object().ok_or("expect.detail.context not an object")?;
            if g.context.len() != cobj.len() {
                return Err("detail.context size mismatch".to_string());
            }
            for (k, wv) in cobj {
                if g.context.get(k).map(String::as_str) != wv.as_str() {
                    return Err(format!("detail.context.{k} mismatch"));
                }
            }
        }
        None if !g.context.is_empty() => return Err("detail has unexpected context".to_string()),
        None => {}
    }
    Ok(())
}

// ── guard (assert_portable_component_graph: static portability check, bc#25) ──
// The `ir` field is passed to the guard AS-IS (raw parsed JSON; no §2 typed
// decode — the guard is a static structural check over the JSON itself). A
// reject maps PortabilityError to the fixed code PORTABILITY and compares
// expect.path by exact string equality (message text is NOT compared;
// PROTOCOL.md §3.6). Function-residue rejects cannot ride a JSON vector and
// stay in unit tests (raw JSON node types cannot represent functions in Rust).
fn run_guard_suite(t: &mut Tally, doc: &J) {
    let vectors = doc["vectors"].as_array().unwrap();
    println!(
        "\nguard.json (v{}) — {} vectors",
        doc["guardVersion"],
        vectors.len()
    );
    for v in vectors {
        let name = v["name"].as_str().unwrap_or("?");
        let expect = &v["expect"];
        let (mut ok, mut detail) = (false, String::new());
        match assert_portable_component_graph(&v["ir"]) {
            Ok(()) => {
                if expect.get("ok").is_some() {
                    ok = true;
                } else {
                    detail = format!(
                        "expected Failure({} at {}), guard passed",
                        expect["failure"], expect["path"]
                    );
                }
            }
            Err(e) => {
                if let Some(f) = expect.get("failure").and_then(|f| f.as_str()) {
                    let want_path = expect.get("path").and_then(|p| p.as_str()).unwrap_or("");
                    ok = f == "PORTABILITY" && e.path == want_path;
                    if !ok {
                        detail = format!("expected reject path {want_path}, got {}", e.path);
                    }
                } else {
                    detail = format!("expected guard to pass, got PORTABILITY at {}", e.path);
                }
            }
        }
        line(ok, name, &detail);
        bump(t, ok);
    }
}

// ── provenance (serialization-boundary canonical fingerprint gate, #128/A6) ──
// The token (the process-internal unforgeable compile capability) does NOT cross
// the JSON boundary; on the wire the gate is the canonical fingerprint. The runner
// RECOMPUTES fingerprint_component_graph over the raw `ir` and compares to the
// declared `fingerprint`: equal = accept, unequal (stale/tampered) maps to the
// fixed code NON_COMPILED_IR reject. Key-order / int-vs-integral-float spelling
// don't change the fingerprint (canonical invariance). Non-vacuity
// (CONFORMANCE_MUTATE): a 1-nibble-flipped fingerprint MUST reject, proving the
// runner actually recomputes + compares. (scp-only-authoring-contract §3 SA3/§5.)
fn run_provenance_suite(t: &mut Tally, doc: &J) {
    let vectors = doc["vectors"].as_array().unwrap();
    println!(
        "\nprovenance.json (v{}) — {} vectors",
        doc["provenanceVersion"],
        vectors.len()
    );
    for v in vectors {
        let name = v["name"].as_str().unwrap_or("?");
        let expect = &v["expect"];
        let declared = v["fingerprint"].as_str().unwrap_or("");
        let (mut ok, mut detail) = (false, String::new());
        let recomputed = fingerprint_component_graph(&v["ir"]).expect("fingerprint recompute");
        if recomputed == declared {
            if expect.get("ok").is_some() {
                ok = true;
            } else {
                detail = format!(
                    "expected Failure({}), fingerprint matched",
                    expect["failure"]
                );
            }
        } else if let Some(f) = expect.get("failure").and_then(|f| f.as_str()) {
            // mismatch = boundary-loader NON_COMPILED_IR reject.
            ok = f == "NON_COMPILED_IR";
            if !ok {
                detail = format!("expected Failure({f}), got NON_COMPILED_IR");
            }
        } else {
            detail =
                format!("expected accept, got NON_COMPILED_IR (declared {declared}, recomputed {recomputed})");
        }
        line(ok, name, &detail);
        bump(t, ok);
    }
}

// ── c2 (c2-catalog-swap: catalog-swap execution + IR structural identity, bc#28) ──
// Each consumer's vectors run in the behavior-suite form (the SAME run_behavior
// with the consumer's scripted handler set must yield the consumer's expected
// output), then a structural check proves the two consumers' IRs are equal
// MODULO the catalog name map — and NOT equal before normalization (the catalog
// is observably the only difference). PROTOCOL.md §3.7.
fn c2_normalize(ir: &mut J, role_by_name: &HashMap<String, String>) -> Result<(), String> {
    let comps = ir
        .get_mut("components")
        .and_then(|c| c.as_array_mut())
        .ok_or("c2 ir: components must be an array")?;
    for c in comps {
        let body = c
            .get_mut("body")
            .and_then(|b| b.as_array_mut())
            .ok_or("c2 ir: body must be an array")?;
        for n in body {
            let target = if n.get("map").is_some() {
                n.get_mut("map").unwrap()
            } else {
                n
            };
            if let Some(comp) = target.get("component") {
                let comp_name = comp
                    .as_str()
                    .ok_or("c2 ir: component must be a string")?
                    .to_string();
                let role = role_by_name
                    .get(&comp_name)
                    .ok_or_else(|| format!("unmapped component '{comp_name}'"))?;
                *target.get_mut("component").unwrap() = J::String(role.clone());
            }
        }
    }
    Ok(())
}

fn run_c2_suite(t: &mut Tally, doc: &J) {
    let consumers = doc["consumers"].as_object().unwrap();
    let mut consumer_names: Vec<&String> = consumers.keys().collect();
    consumer_names.sort();
    let n_vec: usize = consumer_names
        .iter()
        .map(|c| consumers[*c]["vectors"].as_array().unwrap().len())
        .sum();
    println!(
        "\nc2-catalog-swap.json (v{}) — {n_vec} vectors + structural",
        doc["c2Version"]
    );

    // 1) execution per consumer.
    for cname in &consumer_names {
        for v in consumers[*cname]["vectors"].as_array().unwrap() {
            let name = format!("{cname}: {}", v["name"].as_str().unwrap_or("?"));
            let (mut ok, mut detail) = (false, String::new());
            if let Err(e) = assert_portable_component_graph(&v["ir"]) {
                line(
                    false,
                    &name,
                    &format!("shared guard rejected consumer IR: {e}"),
                );
                bump(t, false);
                continue;
            }
            let input: Vec<(String, Value)> = match v.get("input") {
                Some(J::Object(o)) => o
                    .iter()
                    .map(|(k, val)| (k.clone(), decode_value(val).expect("decode input")))
                    .collect(),
                _ => Vec::new(),
            };
            let empty = serde_json::Map::new();
            let handlers_spec = v
                .get("handlers")
                .and_then(|h| h.as_object())
                .unwrap_or(&empty);
            let mut handlers = ScriptedHandlers::from_spec(handlers_spec);
            let entry = v.get("entry").and_then(|e| e.as_str());
            match run_behavior(&v["ir"], &mut handlers, &input, entry) {
                Ok(result) => {
                    let want = decode_value(&v["expect"]["value"]).expect("decode expect.value");
                    ok = deep_equals(&result, &want);
                    if !ok {
                        detail = format!(
                            "expected value {}, got {}",
                            v["expect"]["value"],
                            encode_value(&result)
                        );
                    }
                }
                Err(e) => {
                    detail = format!("expected a value, got Failure({})", e.code());
                }
            }
            line(ok, &name, &detail);
            bump(t, ok);
        }
    }

    // 2) structural: equal modulo catalog names; NOT equal raw.
    let (a, b) = (consumer_names[0], consumer_names[1]);
    let role_of = |cname: &str| -> HashMap<String, String> {
        consumers[cname]["catalog"]
            .as_object()
            .unwrap()
            .iter()
            .map(|(role, name)| (name.as_str().unwrap().to_string(), role.clone()))
            .collect()
    };
    let va = consumers[a.as_str()]["vectors"].as_array().unwrap();
    let vb = consumers[b.as_str()]["vectors"].as_array().unwrap();
    for i in 0..va.len().min(vb.len()) {
        let (mut ok, mut detail) = (false, String::new());
        let mut ir_a = va[i]["ir"].clone();
        let mut ir_b = vb[i]["ir"].clone();
        if ir_a == ir_b {
            detail = "raw IRs must differ before normalization".to_string();
        } else {
            match c2_normalize(&mut ir_a, &role_of(a))
                .and_then(|()| c2_normalize(&mut ir_b, &role_of(b)))
            {
                Ok(()) => {
                    ok = ir_a == ir_b;
                    if !ok {
                        detail = "IRs must be equal modulo catalog names".to_string();
                    }
                }
                Err(e) => detail = e,
            }
        }
        line(
            ok,
            &format!(
                "structural[{i}]: IR equal modulo catalog ({})",
                va[i]["name"].as_str().unwrap_or("?")
            ),
            &detail,
        );
        bump(t, ok);
    }
}

fn main() {
    println!("dsl-contracts conformance kit — Rust runner");
    let dir = vectors_dir();
    let docs = preflight(&dir); // STEP 1: fail-closed pre-flight

    let mut t = Tally {
        passed: 0,
        failed: 0,
    };
    run_expression(&mut t, &docs["expression"]);
    run_template(&mut t, &docs["template"]);
    run_plan_suite(&mut t, &docs["plan"]);
    run_canonical(&mut t, &docs["canonical"]);
    run_behavior_suite(&mut t, &docs["behavior"]);
    run_guard_suite(&mut t, &docs["guard"]);
    run_c2_suite(&mut t, &docs["c2"]);
    run_provenance_suite(&mut t, &docs["provenance"]);

    let total = t.passed + t.failed;
    println!(
        "\n{} passed, {} failed / {total} vectors across 8 suites",
        t.passed, t.failed
    );
    exit(if t.failed > 0 { 1 } else { 0 });
}